Initial commit
This commit is contained in:
242
idp_service/db.py
Normal file
242
idp_service/db.py
Normal file
@@ -0,0 +1,242 @@
|
||||
"""SQLite job and page queue. Each claim is an atomic database transaction."""
|
||||
import json
|
||||
import sqlite3
|
||||
import time
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
|
||||
def retry_delay(attempt: int) -> int:
|
||||
return min(60, 2 ** min(attempt, 6))
|
||||
|
||||
|
||||
class Store:
|
||||
def __init__(self, path: Path):
|
||||
self.path = path
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self.init()
|
||||
|
||||
def connect(self):
|
||||
connection = sqlite3.connect(self.path, timeout=30, isolation_level=None)
|
||||
connection.row_factory = sqlite3.Row
|
||||
connection.execute("PRAGMA busy_timeout=30000")
|
||||
connection.execute("PRAGMA foreign_keys=ON")
|
||||
return connection
|
||||
|
||||
def init(self):
|
||||
with self.connect() as db:
|
||||
db.execute("PRAGMA journal_mode=WAL")
|
||||
db.executescript("""
|
||||
CREATE TABLE IF NOT EXISTS jobs (
|
||||
id TEXT PRIMARY KEY, request_id TEXT NOT NULL UNIQUE,
|
||||
file_path TEXT NOT NULL, callback_url TEXT, batch_id TEXT,
|
||||
status TEXT NOT NULL, created_at REAL NOT NULL, updated_at REAL NOT NULL,
|
||||
total_pages INTEGER NOT NULL DEFAULT 0,
|
||||
attempts INTEGER NOT NULL DEFAULT 0,
|
||||
finalize_attempts INTEGER NOT NULL DEFAULT 0,
|
||||
next_at REAL NOT NULL DEFAULT 0, lease_until REAL NOT NULL DEFAULT 0,
|
||||
error TEXT, result_path TEXT, result_json TEXT,
|
||||
callback_state TEXT NOT NULL DEFAULT 'none',
|
||||
callback_attempts INTEGER NOT NULL DEFAULT 0,
|
||||
callback_next_at REAL NOT NULL DEFAULT 0,
|
||||
callback_lease_until REAL NOT NULL DEFAULT 0,
|
||||
callback_error TEXT
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS pages (
|
||||
job_id TEXT NOT NULL REFERENCES jobs(id) ON DELETE CASCADE,
|
||||
page_no INTEGER NOT NULL, status TEXT NOT NULL,
|
||||
attempts INTEGER NOT NULL DEFAULT 0,
|
||||
next_at REAL NOT NULL DEFAULT 0, lease_until REAL NOT NULL DEFAULT 0,
|
||||
penalize_repetition INTEGER NOT NULL DEFAULT 0,
|
||||
error TEXT, result_json TEXT,
|
||||
PRIMARY KEY (job_id, page_no)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS jobs_queue_idx ON jobs(status, next_at);
|
||||
CREATE INDEX IF NOT EXISTS pages_queue_idx ON pages(status, next_at);
|
||||
""")
|
||||
columns = {row[1] for row in db.execute("PRAGMA table_info(jobs)")}
|
||||
if "result_json" not in columns:
|
||||
db.execute("ALTER TABLE jobs ADD COLUMN result_json TEXT")
|
||||
|
||||
@contextmanager
|
||||
def tx(self):
|
||||
db = self.connect()
|
||||
try:
|
||||
db.execute("BEGIN IMMEDIATE")
|
||||
yield db
|
||||
db.execute("COMMIT")
|
||||
except BaseException:
|
||||
db.execute("ROLLBACK")
|
||||
raise
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
@staticmethod
|
||||
def as_dict(row):
|
||||
return dict(row) if row else None
|
||||
|
||||
def create_job(self, request_id: str, file_path: str, callback_url: str | None,
|
||||
batch_id: str | None, max_queued: int):
|
||||
now = time.time()
|
||||
with self.tx() as db:
|
||||
prior = db.execute("SELECT * FROM jobs WHERE request_id=?", (request_id,)).fetchone()
|
||||
if prior:
|
||||
if (prior["file_path"], prior["callback_url"], prior["batch_id"]) != (file_path, callback_url, batch_id):
|
||||
raise ValueError("request_id already exists with different inputs")
|
||||
return self.as_dict(prior), False
|
||||
queued = db.execute("SELECT count(*) FROM jobs WHERE status IN ('queued','preparing','processing','finalizing')").fetchone()[0]
|
||||
if queued >= max_queued:
|
||||
raise OverflowError("Job queue is full")
|
||||
job_id = "job_" + uuid4().hex
|
||||
db.execute("""INSERT INTO jobs(id,request_id,file_path,callback_url,batch_id,status,created_at,updated_at)
|
||||
VALUES(?,?,?,?,?,'queued',?,?)""",
|
||||
(job_id, request_id, file_path, callback_url, batch_id, now, now))
|
||||
return self.as_dict(db.execute("SELECT * FROM jobs WHERE id=?", (job_id,)).fetchone()), True
|
||||
|
||||
def get_job(self, job_id: str):
|
||||
with self.connect() as db:
|
||||
row = db.execute("""SELECT j.*,
|
||||
(SELECT count(*) FROM pages p WHERE p.job_id=j.id AND p.status='done') AS completed_pages,
|
||||
(SELECT count(*) FROM pages p WHERE p.job_id=j.id AND p.status='failed') AS failed_pages
|
||||
FROM jobs j WHERE j.id=?""", (job_id,)).fetchone()
|
||||
return self.as_dict(row)
|
||||
|
||||
def get_pages(self, job_id: str):
|
||||
with self.connect() as db:
|
||||
rows = db.execute("SELECT page_no,status,attempts,error FROM pages WHERE job_id=? ORDER BY page_no", (job_id,)).fetchall()
|
||||
return [self.as_dict(row) for row in rows]
|
||||
|
||||
def claim_prepare(self, lease_seconds: int):
|
||||
now = time.time()
|
||||
with self.tx() as db:
|
||||
row = db.execute("""SELECT * FROM jobs WHERE
|
||||
(status='queued' AND next_at<=?) OR (status='preparing' AND lease_until<=?)
|
||||
ORDER BY created_at LIMIT 1""", (now, now)).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
db.execute("""UPDATE jobs SET status='preparing',attempts=attempts+1,
|
||||
lease_until=?,updated_at=? WHERE id=?""", (now + lease_seconds, now, row["id"]))
|
||||
return self.as_dict(db.execute("SELECT * FROM jobs WHERE id=?", (row["id"],)).fetchone())
|
||||
|
||||
def prepared(self, job_id: str, attempts: int, page_count: int):
|
||||
now = time.time()
|
||||
with self.tx() as db:
|
||||
row = db.execute("SELECT status,attempts FROM jobs WHERE id=?", (job_id,)).fetchone()
|
||||
if not row or row["status"] != "preparing" or row["attempts"] != attempts:
|
||||
return False
|
||||
db.executemany("INSERT OR IGNORE INTO pages(job_id,page_no,status) VALUES(?,?,'queued')",
|
||||
[(job_id, n) for n in range(1, page_count + 1)])
|
||||
db.execute("UPDATE jobs SET status='processing',total_pages=?,lease_until=0,error=NULL,updated_at=? WHERE id=?",
|
||||
(page_count, now, job_id))
|
||||
return True
|
||||
|
||||
def prepare_failed(self, job_id: str, attempts: int, error: str, max_attempts: int):
|
||||
now = time.time()
|
||||
terminal = attempts >= max_attempts
|
||||
with self.tx() as db:
|
||||
db.execute("""UPDATE jobs SET status=?,error=?,next_at=?,lease_until=0,
|
||||
callback_state=CASE WHEN ? AND callback_url IS NOT NULL THEN 'pending' ELSE callback_state END,
|
||||
updated_at=? WHERE id=? AND status='preparing' AND attempts=?""",
|
||||
("failed" if terminal else "queued", error[:1000], now + retry_delay(attempts),
|
||||
int(terminal), now, job_id, attempts))
|
||||
|
||||
def claim_page(self, lease_seconds: int, global_limit: int):
|
||||
now = time.time()
|
||||
with self.tx() as db:
|
||||
active = db.execute("SELECT count(*) FROM pages WHERE status='running' AND lease_until>?", (now,)).fetchone()[0]
|
||||
if active >= global_limit:
|
||||
return None
|
||||
row = db.execute("""SELECT p.*,j.file_path FROM pages p JOIN jobs j ON j.id=p.job_id
|
||||
WHERE j.status='processing' AND ((p.status='queued' AND p.next_at<=?)
|
||||
OR (p.status='running' AND p.lease_until<=?))
|
||||
ORDER BY (SELECT count(*) FROM pages active
|
||||
WHERE active.job_id=p.job_id AND active.status='running' AND active.lease_until>?),
|
||||
p.next_at,j.created_at,p.page_no LIMIT 1""", (now, now, now)).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
db.execute("""UPDATE pages SET status='running',attempts=attempts+1,lease_until=?
|
||||
WHERE job_id=? AND page_no=?""", (now + lease_seconds, row["job_id"], row["page_no"]))
|
||||
return self.as_dict(db.execute("SELECT * FROM pages WHERE job_id=? AND page_no=?",
|
||||
(row["job_id"], row["page_no"])).fetchone())
|
||||
|
||||
def page_done(self, job_id: str, page_no: int, attempts: int, result: dict):
|
||||
with self.tx() as db:
|
||||
return db.execute("""UPDATE pages SET status='done',result_json=?,error=NULL,lease_until=0
|
||||
WHERE job_id=? AND page_no=? AND status='running' AND attempts=?""",
|
||||
(json.dumps(result, ensure_ascii=False), job_id, page_no, attempts)).rowcount == 1
|
||||
|
||||
def page_failed(self, job_id: str, page_no: int, attempts: int, error: str,
|
||||
truncated: bool, max_attempts: int):
|
||||
now = time.time()
|
||||
terminal = attempts >= max_attempts
|
||||
with self.tx() as db:
|
||||
db.execute("""UPDATE pages SET status=?,error=?,next_at=?,lease_until=0,
|
||||
penalize_repetition=CASE WHEN ? THEN 1 ELSE penalize_repetition END
|
||||
WHERE job_id=? AND page_no=? AND status='running' AND attempts=?""",
|
||||
("failed" if terminal else "queued", error[:1000], now + retry_delay(attempts),
|
||||
int(truncated), job_id, page_no, attempts))
|
||||
|
||||
def claim_finalize(self, lease_seconds: int):
|
||||
now = time.time()
|
||||
with self.tx() as db:
|
||||
row = db.execute("""SELECT * FROM jobs j WHERE
|
||||
((j.status='processing' AND j.next_at<=? AND j.total_pages>0 AND NOT EXISTS
|
||||
(SELECT 1 FROM pages p WHERE p.job_id=j.id AND p.status IN ('queued','running')))
|
||||
OR (j.status='finalizing' AND j.lease_until<=?))
|
||||
ORDER BY j.created_at LIMIT 1""", (now, now)).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
db.execute("""UPDATE jobs SET status='finalizing',finalize_attempts=finalize_attempts+1,
|
||||
lease_until=?,updated_at=? WHERE id=?""", (now + lease_seconds, now, row["id"]))
|
||||
return self.as_dict(db.execute("SELECT * FROM jobs WHERE id=?", (row["id"],)).fetchone())
|
||||
|
||||
def page_results(self, job_id: str):
|
||||
with self.connect() as db:
|
||||
return [self.as_dict(row) for row in db.execute("""SELECT page_no,status,error,result_json
|
||||
FROM pages WHERE job_id=? ORDER BY page_no""", (job_id,))]
|
||||
|
||||
def finalized(self, job_id: str, attempts: int, result_json: str, has_failures: bool):
|
||||
now = time.time()
|
||||
with self.tx() as db:
|
||||
return db.execute("""UPDATE jobs SET status=?,result_path=NULL,result_json=?,error=NULL,lease_until=0,updated_at=?,
|
||||
callback_state=CASE WHEN callback_url IS NOT NULL THEN 'pending' ELSE 'none' END
|
||||
WHERE id=? AND status='finalizing' AND finalize_attempts=?""",
|
||||
("partial_failed" if has_failures else "completed", result_json, now, job_id, attempts)).rowcount == 1
|
||||
|
||||
def finalize_failed(self, job_id: str, attempts: int, error: str, max_attempts: int):
|
||||
now = time.time()
|
||||
terminal = attempts >= max_attempts
|
||||
with self.tx() as db:
|
||||
db.execute("""UPDATE jobs SET status=?,error=?,next_at=?,lease_until=0,updated_at=?,
|
||||
callback_state=CASE WHEN ? AND callback_url IS NOT NULL THEN 'pending' ELSE callback_state END
|
||||
WHERE id=? AND status='finalizing' AND finalize_attempts=?""",
|
||||
("failed" if terminal else "processing", error[:1000], now + retry_delay(attempts),
|
||||
now, int(terminal), job_id, attempts))
|
||||
|
||||
def claim_callback(self, lease_seconds: int):
|
||||
now = time.time()
|
||||
with self.tx() as db:
|
||||
row = db.execute("""SELECT * FROM jobs WHERE status IN ('completed','partial_failed','failed')
|
||||
AND ((callback_state='pending' AND callback_next_at<=?)
|
||||
OR (callback_state='sending' AND callback_lease_until<=?))
|
||||
ORDER BY created_at LIMIT 1""", (now, now)).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
db.execute("""UPDATE jobs SET callback_state='sending',callback_attempts=callback_attempts+1,
|
||||
callback_lease_until=? WHERE id=?""", (now + lease_seconds, row["id"]))
|
||||
return self.as_dict(db.execute("SELECT * FROM jobs WHERE id=?", (row["id"],)).fetchone())
|
||||
|
||||
def callback_done(self, job_id: str, attempts: int):
|
||||
with self.tx() as db:
|
||||
db.execute("""UPDATE jobs SET callback_state='delivered',callback_error=NULL,
|
||||
callback_lease_until=0 WHERE id=? AND callback_state='sending' AND callback_attempts=?""",
|
||||
(job_id, attempts))
|
||||
|
||||
def callback_failed(self, job_id: str, attempts: int, error: str, max_attempts: int):
|
||||
now = time.time()
|
||||
with self.tx() as db:
|
||||
db.execute("""UPDATE jobs SET callback_state=?,callback_error=?,callback_next_at=?,
|
||||
callback_lease_until=0 WHERE id=? AND callback_state='sending' AND callback_attempts=?""",
|
||||
("exhausted" if attempts >= max_attempts else "pending", error[:1000],
|
||||
now + retry_delay(attempts), job_id, attempts))
|
||||
Reference in New Issue
Block a user