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 <noreply@anthropic.com>
This commit is contained in:
1 parent
776cef7bc3
commit
cef1a48b69
2 files changed
+68
No files matched your search
@@ -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
|
||||
@@ -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."""
|
||||
...
|
||||
Reference in new issue
Block a user