Add SQLite job queue with jobs migration
CI / checks (pull_request) Successful in 1m15s

Atomic claim, terminal transitions and recover() that requeues at the old place.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
torbenandClaude Sonnet 5.5 committed 2026-12-04 20:06:04 +01:00
1 parent 3e001e5ae4
commit 8b55072677
3 files changed
+388 -1

No files matched your search

+136
View File
@@ -0,0 +1,136 @@
"""SQLite implementation of the job queue port."""
import json
import sqlite3
import uuid
from collections.abc import Callable
from datetime import UTC, datetime
from typing import Any, cast
from uuid import UUID
from chemenu.adapters.sqlite.database import Database
from chemenu.domain.job import Job, JobState, JsonObject
from chemenu.ports.job_queue import InvalidTransitionError, JobNotFoundError
_SELECT_JOB = (
"SELECT id, kind, payload, state, attempts, enqueued_at, result, reason FROM jobs WHERE id = ?"
)
def utc_now() -> datetime:
return datetime.now(UTC)
def _dumps(value: JsonObject) -> str:
return json.dumps(value, allow_nan=False)
def _loads(text: str) -> JsonObject:
return cast("JsonObject", json.loads(text))
def _to_job(row: tuple[Any, ...]) -> Job:
return Job(
id=UUID(row[0]),
kind=row[1],
payload=_loads(row[2]),
state=JobState(row[3]),
attempts=row[4],
enqueued_at=datetime.fromisoformat(row[5]),
result=None if row[6] is None else _loads(row[6]),
reason=row[7],
)
def _select(conn: sqlite3.Connection, job_id: UUID) -> Job:
row = conn.execute(_SELECT_JOB, (str(job_id),)).fetchone()
if row is None:
raise JobNotFoundError(str(job_id))
return _to_job(row)
class SqliteJobQueue:
def __init__(
self,
database: Database,
*,
max_attempts: int = 3,
clock: Callable[[], datetime] = utc_now,
) -> None:
if max_attempts < 1:
raise ValueError("max_attempts must be at least 1")
self._database = database
self._max_attempts = max_attempts
self._clock = clock
def enqueue(self, kind: str, payload: JsonObject) -> Job:
text = _dumps(payload)
now = self._clock()
if now.tzinfo is None or now.utcoffset() is None:
raise ValueError("clock must return an aware datetime")
job_id = uuid.uuid7()
with self._database.transaction() as conn:
conn.execute(
"INSERT INTO jobs (id, kind, payload, state, attempts, enqueued_at)"
" VALUES (?, ?, ?, ?, 0, ?)",
(str(job_id), kind, text, JobState.QUEUED.value, now.astimezone(UTC).isoformat()),
)
return _select(conn, job_id)
def claim(self) -> Job | None:
with self._database.transaction() as conn:
row = conn.execute(
"SELECT id FROM jobs WHERE state = ? ORDER BY seq LIMIT 1",
(JobState.QUEUED.value,),
).fetchone()
if row is None:
return None
conn.execute(
"UPDATE jobs SET state = ?, attempts = attempts + 1 WHERE id = ?",
(JobState.RUNNING.value, row[0]),
)
return _select(conn, UUID(row[0]))
def _finish(self, job_id: UUID, state: JobState, result: str | None, reason: str | None) -> Job:
with self._database.transaction() as conn:
current = _select(conn, job_id)
if current.state is not JobState.RUNNING:
raise InvalidTransitionError(f"job {job_id} is {current.state}, not running")
conn.execute(
"UPDATE jobs SET state = ?, result = ?, reason = ? WHERE id = ?",
(state.value, result, reason, str(job_id)),
)
return _select(conn, job_id)
def complete(self, job_id: UUID, result: JsonObject) -> Job:
return self._finish(job_id, JobState.DONE, _dumps(result), None)
def fail(self, job_id: UUID, reason: str) -> Job:
# SQLite rejects lone surrogates, as in undecodable file names; a failure
# that cannot be stored would leave the job running and repeat it.
text = reason.encode("utf-8", "backslashreplace").decode("utf-8")
return self._finish(job_id, JobState.FAILED, None, text)
def get(self, job_id: UUID) -> Job:
with self._database.transaction() as conn:
return _select(conn, job_id)
def recover(self) -> list[Job]:
reason = f"aborted after {self._max_attempts} attempts"
with self._database.transaction() as conn:
rows = conn.execute(
"SELECT id, attempts FROM jobs WHERE state = ? ORDER BY seq",
(JobState.RUNNING.value,),
).fetchall()
for job_id, attempts in rows:
if attempts < self._max_attempts:
conn.execute(
"UPDATE jobs SET state = ? WHERE id = ?",
(JobState.QUEUED.value, job_id),
)
else:
conn.execute(
"UPDATE jobs SET state = ?, reason = ? WHERE id = ?",
(JobState.FAILED.value, reason, job_id),
)
return [_select(conn, UUID(job_id)) for job_id, _ in rows]
+19 -1
View File
@@ -6,4 +6,22 @@ from typing import Final
type Migration = Sequence[str]
"""One migration: SQL statements, applied together in one transaction."""
MIGRATIONS: Final[tuple[Migration, ...]] = ()
# No CHECK on jobs.state: changing it later would mean rebuilding the table.
MIGRATIONS: Final[tuple[Migration, ...]] = (
(
"""
CREATE TABLE jobs (
seq INTEGER PRIMARY KEY AUTOINCREMENT,
id TEXT NOT NULL UNIQUE,
kind TEXT NOT NULL,
payload TEXT NOT NULL,
state TEXT NOT NULL,
attempts INTEGER NOT NULL,
enqueued_at TEXT NOT NULL,
result TEXT,
reason TEXT
) STRICT
""",
"CREATE INDEX jobs_state_seq ON jobs (state, seq)",
),
)