feat: add worker job-claim logic
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
import psycopg
|
||||
|
||||
|
||||
def claim_next(conn: psycopg.Connection) -> str | None:
|
||||
"""Atomically claim the oldest queued job. Returns its id or None."""
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id FROM "Job"
|
||||
WHERE state = 'requested'
|
||||
ORDER BY "createdAt" ASC
|
||||
FOR UPDATE SKIP LOCKED
|
||||
LIMIT 1
|
||||
"""
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
conn.rollback()
|
||||
return None
|
||||
job_id = row[0]
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE "Job"
|
||||
SET state = 'matching',
|
||||
"currentStage" = 'match',
|
||||
"claimedAt" = now(),
|
||||
attempts = attempts + 1,
|
||||
"updatedAt" = now()
|
||||
WHERE id = %s
|
||||
""",
|
||||
(job_id,),
|
||||
)
|
||||
conn.commit()
|
||||
return job_id
|
||||
@@ -0,0 +1,8 @@
|
||||
import os
|
||||
|
||||
import psycopg
|
||||
|
||||
|
||||
def connect() -> psycopg.Connection:
|
||||
dsn = os.environ["DATABASE_URL"]
|
||||
return psycopg.connect(dsn)
|
||||
Reference in New Issue
Block a user