Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ jqueue/
├── core/ # Business logic
│ ├── broker.py # BrokerQueue (high-throughput with group commit)
│ ├── direct.py # DirectQueue (simple one-operation-per-write)
│ ├── queries.py # StateQueries (pure ops on one QueueState snapshot)
│ ├── group_commit.py # Group commit batching algorithm
│ ├── heartbeat.py # HeartbeatManager for job liveness
│ └── codec.py # JSON serialization
Expand All @@ -98,6 +99,7 @@ jqueue/
- **Dependency injection**: Via constructor parameters
- **Async-first**: All I/O operations use async/await
- **CAS semantics**: Compare-and-set for concurrency safety
- **Queries vs services**: `StateQueries` is pure state logic; services own I/O and CAS (see `queries-and-services.md`)

## Code Style Guidelines

Expand Down Expand Up @@ -246,6 +248,7 @@ class CustomStorage:
## References

- **Architecture**: See `ports-and-adapters.md` for detailed design rationale
- **Queries & Services**: See `queries-and-services.md` for the query/service split
- **README**: Comprehensive usage examples and API documentation
- **Repository**: https://github.com/janbjorge/jqueue
- **License**: MIT
3 changes: 2 additions & 1 deletion jqueue/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@ async def write(content, if_match=None) -> str
Follows the Ports & Adapters pattern:
domain/ — pure value types (Job, QueueState, JobStatus)
ports/ — Protocol interfaces (ObjectStoragePort)
core/ — business logic (DirectQueue, BrokerQueue, GroupCommitLoop)
core/ — services (DirectQueue, BrokerQueue, GroupCommitLoop) and
pure state queries (StateQueries)
adapters/ — concrete storage implementations
"""

Expand Down
89 changes: 26 additions & 63 deletions jqueue/core/direct.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,20 +24,25 @@
from datetime import UTC, datetime, timedelta

from jqueue.core import codec
from jqueue.domain.errors import CASConflictError, JobNotFoundError
from jqueue.domain.models import Job, JobStatus, QueueState
from jqueue.core.queries import StateQueries
from jqueue.domain.errors import CASConflictError
from jqueue.domain.models import Job, QueueState
from jqueue.ports.storage import ObjectStoragePort

MutationFn = Callable[[QueueState], QueueState]


@dataclasses.dataclass
class DirectQueue:
"""
Thin stateless wrapper around ObjectStoragePort.
Thin stateless service around ObjectStoragePort.

All methods are async and safe to call from multiple coroutines;
each operation performs a full CAS cycle independently.
each operation performs a full CAS cycle independently. Each public
method is one unit of work: it either commits entirely or raises.

Parameters
----------
storage : any ObjectStoragePort implementation
max_retries : CAS attempts before CASConflictError is re-raised
"""

storage: ObjectStoragePort
Expand All @@ -55,8 +60,7 @@ async def enqueue(
) -> Job:
"""Add a new job to the queue. Returns the committed Job."""
job = Job.new(entrypoint, payload, priority)
await self._mutate(lambda state: state.with_job_added(job))
return job
return await self._transaction(lambda q: q.add(job))

async def dequeue(
self,
Expand All @@ -70,51 +74,21 @@ async def dequeue(
Optionally filter by entrypoint. Returns the list of claimed jobs.
Returns an empty list if no jobs are available.
"""
claimed: list[Job] = []

def _fn(state: QueueState) -> QueueState:
nonlocal claimed
available = state.queued_jobs(entrypoint)[:batch_size]
claimed = []
new_state = state
for job in available:
updated = job.with_status(JobStatus.IN_PROGRESS).with_heartbeat(
datetime.now(UTC)
)
new_state = new_state.with_job_replaced(updated)
claimed.append(updated)
return new_state

await self._mutate(_fn)
return claimed
return await self._transaction(
lambda q: q.claim(entrypoint, batch_size, datetime.now(UTC))
)

async def ack(self, job_id: str) -> None:
"""Mark a job as done and remove it from the queue."""
await self._mutate(lambda state: state.with_job_removed(job_id))
await self._transaction(lambda q: q.remove(job_id))

async def nack(self, job_id: str) -> None:
"""Return a job to QUEUED status (worker failed or declined it)."""

def _fn(state: QueueState) -> QueueState:
job = state.find(job_id)
if job is None:
raise JobNotFoundError(job_id)
return state.with_job_replaced(
job.with_status(JobStatus.QUEUED).with_heartbeat(None)
)

await self._mutate(_fn)
await self._transaction(lambda q: q.release(job_id))

async def heartbeat(self, job_id: str) -> None:
"""Update the heartbeat timestamp of an IN_PROGRESS job."""

def _fn(state: QueueState) -> QueueState:
job = state.find(job_id)
if job is None:
raise JobNotFoundError(job_id)
return state.with_job_replaced(job.with_heartbeat(datetime.now(UTC)))

await self._mutate(_fn)
await self._transaction(lambda q: q.touch(job_id, datetime.now(UTC)))

async def requeue_stale(self, timeout: timedelta) -> int:
"""
Expand All @@ -123,18 +97,7 @@ async def requeue_stale(self, timeout: timedelta) -> int:
Returns the number of jobs re-queued.
"""
cutoff = datetime.now(UTC) - timeout
requeued = 0

def _fn(state: QueueState) -> QueueState:
nonlocal requeued
old_in_progress = {j.id for j in state.in_progress_jobs()}
new_state = state.requeue_stale(cutoff)
new_in_progress = {j.id for j in new_state.in_progress_jobs()}
requeued = len(old_in_progress - new_in_progress)
return new_state

await self._mutate(_fn)
return requeued
return await self._transaction(lambda q: q.requeue_stale(cutoff))

# ------------------------------------------------------------------ #
# Read operations (no CAS needed) #
Expand All @@ -149,22 +112,22 @@ async def read_state(self) -> QueueState:
# Internal CAS loop #
# ------------------------------------------------------------------ #

async def _mutate(self, fn: MutationFn) -> None:
async def _transaction[T](self, fn: Callable[[StateQueries], T]) -> T:
"""
Read-modify-write with CAS retry loop.

fn(state) -> new_state (synchronous)
fn(queries) -> result (synchronous, re-run on a fresh snapshot per retry)
Retries up to self.max_retries on CASConflictError.
"""
for attempt in range(self.max_retries):
content, etag = await self.storage.read()
state = codec.decode(content)
new_state = fn(state)
new_content = codec.encode(new_state)
queries = StateQueries(codec.decode(content))
result = fn(queries)
try:
await self.storage.write(new_content, if_match=etag)
return
await self.storage.write(codec.encode(queries.state), if_match=etag)
return result
except CASConflictError:
if attempt == self.max_retries - 1:
raise
await asyncio.sleep(0.01 * (attempt + 1))
raise CASConflictError("Max CAS retries exceeded")
91 changes: 27 additions & 64 deletions jqueue/core/group_commit.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,23 +30,23 @@
import dataclasses
from collections.abc import Callable
from datetime import UTC, datetime, timedelta
from typing import Any

from jqueue.core import codec
from jqueue.core.queries import StateQueries
from jqueue.domain.errors import CASConflictError, JQueueError
from jqueue.domain.models import Job, JobStatus, QueueState
from jqueue.domain.models import Job, QueueState
from jqueue.ports.storage import ObjectStoragePort

MutationFn = Callable[[QueueState], QueueState]

_MAX_RETRIES: int = 20


@dataclasses.dataclass
class _PendingOp:
"""A buffered mutation waiting to be committed to object storage."""
class _PendingOp[T]:
"""A buffered operation waiting to be committed to object storage."""

fn: MutationFn
future: asyncio.Future[None]
fn: Callable[[StateQueries], T]
future: asyncio.Future[T]


@dataclasses.dataclass
Expand All @@ -68,7 +68,7 @@ class GroupCommitLoop:
storage: ObjectStoragePort
stale_timeout: timedelta = timedelta(minutes=5)

_pending: list[_PendingOp] = dataclasses.field(
_pending: list[_PendingOp[Any]] = dataclasses.field(
default_factory=list, init=False, repr=False
)
_wakeup: asyncio.Event = dataclasses.field(
Expand Down Expand Up @@ -111,12 +111,7 @@ async def enqueue(
) -> Job:
"""Add a new job. Returns the committed Job (UUID stable across retries)."""
job = Job.new(entrypoint, payload, priority)

def _fn(state: QueueState) -> QueueState:
return state.with_job_added(job)

await self._submit(_fn)
return job
return await self._submit(lambda q: q.add(job))

async def dequeue(
self,
Expand All @@ -125,53 +120,21 @@ async def dequeue(
batch_size: int = 1,
) -> list[Job]:
"""Claim up to batch_size QUEUED jobs and mark them IN_PROGRESS."""
claimed: list[Job] = []

def _fn(state: QueueState) -> QueueState:
nonlocal claimed
available = state.queued_jobs(entrypoint)[:batch_size]
claimed = []
new_state = state
for job in available:
updated = job.with_status(JobStatus.IN_PROGRESS).with_heartbeat(
datetime.now(UTC)
)
new_state = new_state.with_job_replaced(updated)
claimed.append(updated)
return new_state

await self._submit(_fn)
return claimed
return await self._submit(
lambda q: q.claim(entrypoint, batch_size, datetime.now(UTC))
)

async def ack(self, job_id: str) -> None:
"""Remove a completed job from the queue."""
await self._submit(lambda state: state.with_job_removed(job_id))
await self._submit(lambda q: q.remove(job_id))

async def nack(self, job_id: str) -> None:
"""Return a job to QUEUED status."""
from jqueue.domain.errors import JobNotFoundError

def _fn(state: QueueState) -> QueueState:
job = state.find(job_id)
if job is None:
raise JobNotFoundError(job_id)
return state.with_job_replaced(
job.with_status(JobStatus.QUEUED).with_heartbeat(None)
)

await self._submit(_fn)
await self._submit(lambda q: q.release(job_id))

async def heartbeat(self, job_id: str) -> None:
"""Refresh the heartbeat timestamp for an IN_PROGRESS job."""
from jqueue.domain.errors import JobNotFoundError

def _fn(state: QueueState) -> QueueState:
job = state.find(job_id)
if job is None:
raise JobNotFoundError(job_id)
return state.with_job_replaced(job.with_heartbeat(datetime.now(UTC)))

await self._submit(_fn)
await self._submit(lambda q: q.touch(job_id, datetime.now(UTC)))

async def read_state(self) -> QueueState:
"""Read-only snapshot of current queue state (bypasses the write pipeline)."""
Expand All @@ -182,19 +145,19 @@ async def read_state(self) -> QueueState:
# Internal machinery #
# ------------------------------------------------------------------ #

async def _submit(self, fn: MutationFn) -> None:
async def _submit[T](self, fn: Callable[[StateQueries], T]) -> T:
"""
Enqueue a mutation and block until it is committed.
Enqueue an operation and block until it is committed.

Appends the op to _pending, wakes the writer, then awaits the future
that resolves when the batch containing this op successfully commits.
"""
if self._stopped:
raise JQueueError("GroupCommitLoop is stopped")
future: asyncio.Future[None] = asyncio.get_running_loop().create_future()
future: asyncio.Future[T] = asyncio.get_running_loop().create_future()
self._pending.append(_PendingOp(fn=fn, future=future))
self._wakeup.set()
await future
return await future

async def _writer_loop(self) -> None:
"""Background coroutine — runs until stopped and all pending ops drain."""
Expand All @@ -210,7 +173,7 @@ async def _writer_loop(self) -> None:
self._pending.clear()
await self._commit_batch(batch)

async def _commit_batch(self, batch: list[_PendingOp]) -> None:
async def _commit_batch(self, batch: list[_PendingOp[Any]]) -> None:
"""
Apply all ops in `batch` to the current state and CAS write.

Expand All @@ -220,28 +183,28 @@ async def _commit_batch(self, batch: list[_PendingOp]) -> None:
for attempt in range(_MAX_RETRIES):
try:
content, etag = await self.storage.read()
state = codec.decode(content)
queries = StateQueries(codec.decode(content))

# Sweep stale jobs on every write cycle (free — no extra I/O)
cutoff = datetime.now(UTC) - self.stale_timeout
state = state.requeue_stale(cutoff)
queries.requeue_stale(datetime.now(UTC) - self.stale_timeout)

results: dict[int, Any] = {}
per_op_errors: dict[int, Exception] = {}
for i, op in enumerate(batch):
try:
state = op.fn(state)
results[i] = op.fn(queries)
except Exception as exc:
per_op_errors[i] = exc

await self.storage.write(codec.encode(state), if_match=etag)
await self.storage.write(codec.encode(queries.state), if_match=etag)

for i, op in enumerate(batch):
if op.future.done():
continue
if i in per_op_errors:
op.future.set_exception(per_op_errors[i])
else:
op.future.set_result(None)
op.future.set_result(results[i])
return

except CASConflictError:
Expand All @@ -256,7 +219,7 @@ async def _commit_batch(self, batch: list[_PendingOp]) -> None:
return


def _fail_batch(batch: list[_PendingOp], exc: Exception) -> None:
def _fail_batch(batch: list[_PendingOp[Any]], exc: Exception) -> None:
"""Set exception on all unresolved futures in the batch."""
for op in batch:
if not op.future.done():
Expand Down
Loading
Loading