From cef1a48b693ca8283abd9b7698655c18c7d4ede4 Mon Sep 17 00:00:00 2001 From: Torben Nehmer Date: Thu, 3 Dec 2026 23:26:16 +0100 Subject: [PATCH] Add Job domain type and JobQueue port Job lifecycle states, JSON types and the queue protocol with its errors. Co-Authored-By: Claude Sonnet 5.5 --- src/chemenu/domain/job.py | 28 ++++++++++++++++++++++++ src/chemenu/ports/job_queue.py | 40 ++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 src/chemenu/domain/job.py create mode 100644 src/chemenu/ports/job_queue.py diff --git a/src/chemenu/domain/job.py b/src/chemenu/domain/job.py new file mode 100644 index 0000000..1f1ad8f --- /dev/null +++ b/src/chemenu/domain/job.py @@ -0,0 +1,28 @@ +"""Job: a unit of queued work and its lifecycle state.""" + +from dataclasses import dataclass +from datetime import datetime +from enum import StrEnum +from uuid import UUID + +type JsonValue = str | int | float | bool | list[JsonValue] | dict[str, JsonValue] | None +type JsonObject = dict[str, JsonValue] + + +class JobState(StrEnum): + QUEUED = "queued" + RUNNING = "running" + DONE = "done" + FAILED = "failed" + + +@dataclass(frozen=True, slots=True, kw_only=True) +class Job: + id: UUID + kind: str + payload: JsonObject + state: JobState + attempts: int + enqueued_at: datetime # aware, UTC + result: JsonObject | None = None + reason: str | None = None diff --git a/src/chemenu/ports/job_queue.py b/src/chemenu/ports/job_queue.py new file mode 100644 index 0000000..6d9f65f --- /dev/null +++ b/src/chemenu/ports/job_queue.py @@ -0,0 +1,40 @@ +"""Port: a durable queue of jobs.""" + +from typing import Protocol +from uuid import UUID + +from chemenu.domain.job import Job, JsonObject + + +class JobNotFoundError(Exception): + """No job with the given id exists.""" + + +class InvalidTransitionError(Exception): + """The job is not in a state that allows the requested change.""" + + +class JobQueue(Protocol): + def enqueue(self, kind: str, payload: JsonObject) -> Job: + """Add a queued job; ValueError if the payload is not valid JSON.""" + ... + + def claim(self) -> Job | None: + """Atomically move the oldest queued job to running; None if there is none.""" + ... + + def complete(self, job_id: UUID, result: JsonObject) -> Job: + """Move a running job to done. + + ValueError if the result is not valid JSON; the job stays running, so the + caller must call `fail`. + """ + ... + + def fail(self, job_id: UUID, reason: str) -> Job: ... + + def get(self, job_id: UUID) -> Job: ... + + def recover(self) -> list[Job]: + """Requeue or fail jobs left running; only a starting worker calls this.""" + ...