export const PERMIT_MS = 16 * 60 * 1000; export const QUEUE_POLL_MS = 15000; export class IndexQueueState { constructor(sql, limit = 2, now = Date.now) { if (!Number.isInteger(limit) || limit < 1 || limit > 16) throw new Error("invalid_index_concurrency"); this.sql = sql; this.limit = limit; this.now = now; sql.exec("CREATE TABLE IF NOT EXISTS tickets (sequence INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT UNIQUE NOT NULL, did TEXT NOT NULL, status TEXT NOT NULL, owner TEXT, expires INTEGER, seen INTEGER NOT NULL)"); sql.exec("CREATE TABLE IF NOT EXISTS cooldown (id INTEGER PRIMARY KEY, until_ms INTEGER NOT NULL)"); sql.exec("CREATE INDEX IF NOT EXISTS tickets_status ON tickets(status,sequence)"); } claim(id, did, owner) { const now = this.now(); this.sql.exec("UPDATE tickets SET status='expired' WHERE status IN ('active','draining') AND expires<=?", now); this.sql.exec("UPDATE tickets SET status='expired' WHERE status='queued' AND seen 0) return { granted: false, ahead, delay: this.delay() }; if (ahead >= this.limit - active) return { granted: false, ahead }; this.sql.exec("UPDATE tickets SET status='active',owner=?,expires=? WHERE id=? AND status='queued'", owner, now + PERMIT_MS, id); return { granted: true, expires: now + PERMIT_MS, ahead: 0 }; } delay() { return Math.max(0, ([...this.sql.exec("SELECT until_ms FROM cooldown WHERE id=1")][0]?.until_ms || 0) - this.now()); } backoff(delay) { this.sql.exec("INSERT INTO cooldown(id,until_ms) VALUES(1,?) ON CONFLICT(id) DO UPDATE SET until_ms=MAX(cooldown.until_ms,excluded.until_ms)", this.now() + delay); } valid(id, owner) { return Boolean([...this.sql.exec("SELECT id FROM tickets WHERE id=? AND owner=? AND status='active' AND expires>?", id, owner, this.now())][0]); } release(id, owner) { this.sql.exec("UPDATE tickets SET status='done' WHERE id=? AND owner=? AND status IN ('active','draining')", id, owner); } cancel(id) { this.sql.exec("INSERT INTO tickets(id,did,status,seen) VALUES(?,'','cancelled',?) ON CONFLICT(id) DO UPDATE SET status=CASE WHEN tickets.status='active' THEN 'draining' WHEN tickets.status='queued' THEN 'cancelled' ELSE tickets.status END", id, this.now()); } }