133 lines
3.8 KiB
Python
133 lines
3.8 KiB
Python
"""The job queue.
|
|
|
|
One statement claims a job: an UPDATE whose WHERE clause is a
|
|
``FOR UPDATE SKIP LOCKED`` subselect. Two workers racing for the same row
|
|
never block each other -- the loser skips to the next row rather than waiting.
|
|
This is the entire reason no Redis is needed (SPEC 6).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import os
|
|
import socket
|
|
from datetime import UTC, datetime, timedelta
|
|
from typing import Any
|
|
|
|
from sqlalchemy import text
|
|
from sqlalchemy.orm import Session
|
|
|
|
from ..models import Job
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
WORKER_ID = f"{socket.gethostname()}:{os.getpid()}"
|
|
|
|
_CLAIM_SQL = text(
|
|
"""
|
|
UPDATE jobs
|
|
SET status = 'running',
|
|
locked_at = now(),
|
|
locked_by = :worker,
|
|
attempts = attempts + 1
|
|
WHERE id = (
|
|
SELECT id
|
|
FROM jobs
|
|
WHERE status = 'queued'
|
|
AND run_at <= now()
|
|
ORDER BY priority DESC, run_at
|
|
FOR UPDATE SKIP LOCKED
|
|
LIMIT 1
|
|
)
|
|
RETURNING id, kind, payload, attempts, max_attempts
|
|
"""
|
|
)
|
|
|
|
|
|
def enqueue(
|
|
session: Session,
|
|
kind: str,
|
|
payload: dict[str, Any] | None = None,
|
|
*,
|
|
priority: int = 0,
|
|
delay_s: float = 0,
|
|
max_attempts: int | None = None,
|
|
) -> Job:
|
|
job = Job(
|
|
kind=kind,
|
|
payload=payload or {},
|
|
priority=priority,
|
|
run_at=datetime.now(UTC) + timedelta(seconds=delay_s),
|
|
)
|
|
if max_attempts is not None:
|
|
job.max_attempts = max_attempts
|
|
session.add(job)
|
|
session.flush()
|
|
return job
|
|
|
|
|
|
def claim(session: Session) -> dict[str, Any] | None:
|
|
"""Claim one job, or return None. Commits so the lock is released promptly."""
|
|
row = session.execute(_CLAIM_SQL, {"worker": WORKER_ID}).mappings().first()
|
|
session.commit()
|
|
return dict(row) if row else None
|
|
|
|
|
|
def complete(session: Session, job_id: int) -> None:
|
|
session.execute(
|
|
text(
|
|
"UPDATE jobs SET status = 'done', finished_at = now(), "
|
|
"last_error = NULL WHERE id = :id"
|
|
),
|
|
{"id": job_id},
|
|
)
|
|
session.commit()
|
|
|
|
|
|
def fail(session: Session, job_id: int, error: str, *, retry_in_s: float = 60) -> None:
|
|
"""Retry with a delay until max_attempts, then park the job as failed."""
|
|
session.execute(
|
|
text(
|
|
"""
|
|
UPDATE jobs
|
|
SET status = CASE WHEN attempts >= max_attempts
|
|
THEN 'failed' ELSE 'queued' END,
|
|
finished_at = CASE WHEN attempts >= max_attempts
|
|
THEN now() ELSE NULL END,
|
|
run_at = CASE WHEN attempts >= max_attempts
|
|
THEN run_at
|
|
ELSE now() + make_interval(secs => :retry) END,
|
|
locked_at = NULL,
|
|
locked_by = NULL,
|
|
last_error = :error
|
|
WHERE id = :id
|
|
"""
|
|
),
|
|
{"id": job_id, "error": error[:4000], "retry": retry_in_s},
|
|
)
|
|
session.commit()
|
|
|
|
|
|
def requeue_stale(session: Session, older_than_s: int = 900) -> int:
|
|
"""Reclaim jobs whose worker died mid-run.
|
|
|
|
A SIGKILL or a power cut leaves rows in 'running' with nobody holding
|
|
them. Nothing else would ever pick those up.
|
|
"""
|
|
result = session.execute(
|
|
text(
|
|
"""
|
|
UPDATE jobs
|
|
SET status = 'queued', locked_at = NULL, locked_by = NULL,
|
|
last_error = 'reclaimed: worker vanished'
|
|
WHERE status = 'running'
|
|
AND locked_at < now() - make_interval(secs => :age)
|
|
"""
|
|
),
|
|
{"age": older_than_s},
|
|
)
|
|
session.commit()
|
|
if result.rowcount:
|
|
log.warning("reclaimed stale jobs", extra={"count": result.rowcount})
|
|
return result.rowcount or 0
|