Fix worker db

This commit is contained in:
2026-09-29 05:39:45 +00:00
parent 73c51ed1cd
commit 498a22ab61
8 changed files with 241 additions and 43 deletions

View File

@@ -4,6 +4,7 @@ import sqlite3
import time
from contextlib import contextmanager
from pathlib import Path
from threading import Lock
from uuid import uuid4
@@ -14,6 +15,9 @@ def retry_delay(attempt: int) -> int:
class Store:
def __init__(self, path: Path):
self.path = path
# Worker threads share this Store. Serialize their write transactions so
# idle queue polling does not make dozens of SQLite writers contend.
self._tx_lock = Lock()
path.parent.mkdir(parents=True, exist_ok=True)
self.init()
@@ -81,19 +85,20 @@ class Store:
@contextmanager
def tx(self):
db = self.connect()
try:
db.execute("BEGIN IMMEDIATE")
yield db
db.execute("COMMIT")
except BaseException:
# BEGIN IMMEDIATE hết busy_timeout thì chưa có transaction: ROLLBACK lúc đó
# sẽ ném "no transaction is active" và che mất lỗi "database is locked" gốc.
if db.in_transaction:
db.execute("ROLLBACK")
raise
finally:
db.close()
with self._tx_lock:
db = self.connect()
try:
db.execute("BEGIN IMMEDIATE")
yield db
db.execute("COMMIT")
except BaseException:
# BEGIN IMMEDIATE hết busy_timeout thì chưa có transaction: ROLLBACK lúc đó
# sẽ ném "no transaction is active" và che mất lỗi "database is locked" gốc.
if db.in_transaction:
db.execute("ROLLBACK")
raise
finally:
db.close()
@staticmethod
def as_dict(row):