Something went wrong. Try again.
Team contribution to sunstead hack in Levi, Finland.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243import { z } from "zod";import type { Redis } from "@upstash/redis";import { getRedis, isStoreConfigured } from "./store";
/** * The job queue contract between the Vercel cron (enqueuer) and the Railway * worker (consumer) — KTD1. A scoring job is one `(prUri, round)` unit of work. * * Backend: a Redis stream on the existing Upstash instance (the implementation- * time choice over QStash — no new credentials, and the Redis claim owns the * at-least-once guarantee anyway, KTD10). The queue is abstracted behind * {@link JobQueue} so the worker and the unit tests depend on the interface, not * the stream; an {@link InMemoryJobQueue} backs the tests and a * {@link RedisStreamQueue} backs production. Mirrors the `RepoSource`-style * isolation the plan uses elsewhere (KTD2). * * Enqueue is unconditional w.r.t. *correctness* — dedup of the actual work * happens at claim-on-consume in the worker (U12). The short-TTL enqueue guard * here only stops two cron ticks from piling duplicate copies onto the stream; * it is a queue-hygiene optimization, never the safety mechanism. */
/** The payload enqueued per unit of scoring work. */export const ScoreJobSchema = z.object({ /** Developer DID the round belongs to (subject of the diagnostic). */ did: z.string().min(1), /** Developer PDS endpoint, carried so the worker can fetch the patch blob. */ pds: z.string().min(1), /** AT-URI of the `sh.tangled.repo.pull` record. */ prUri: z.string().min(1), /** Zero-based round index within the pull. */ round: z.number().int().min(0), /** CID of the round's gzipped patch blob. Required: cid-less rounds aren't enqueued. */ cid: z.string().min(1), prTitle: z.string().optional(), /** * Best-effort source coordinate from the pull's `target.repo` (`owner/repo` * for GitHub anchors/dogfood, or a Tangled DID for live rounds). The worker's * base-commit resolver (U2) decides the authoritative base from this; a DID * source routes to the reduced-context fallback (KTD2). */ sourceRepo: z.string().optional(),});export type ScoreJob = z.infer<typeof ScoreJobSchema>;
/** A job as delivered from the queue, paired with the id needed to ack it. */export interface DeliveredJob { /** Backend message id (stream entry id) used to acknowledge completion. */ id: string; job: ScoreJob;}
export interface ConsumeOptions { /** Max messages to read in one poll. */ count?: number; /** Block up to this long for new messages (ms); 0 returns immediately. */ blockMs?: number;}
/** Backend-agnostic job queue. Production = Redis stream; tests = in-memory. */export interface JobQueue { /** * Enqueues a job. Returns `{ enqueued: false }` when the short-TTL dedup guard * already saw this `(prUri, round)` recently, so callers can count real adds. */ enqueue(job: ScoreJob): Promise<{ enqueued: boolean; id?: string }>; /** Reads a batch of undelivered jobs (does not ack them). */ consume(opts?: ConsumeOptions): Promise<DeliveredJob[]>; /** Acknowledges a delivered job so it is not redelivered. */ ack(id: string): Promise<void>; /** * Re-attaches the backend's subscription so a (re)started consumer is ready * before its first `consume` (U14 restart recovery). For the Redis stream this * (idempotently) ensures the consumer group exists; for the in-memory queue it * is a no-op. Optional so simple backends need not implement it. */ ensureReady?(): Promise<void>;}
export function jobDedupKey(prUri: string, round: number): string { return `enq:${prUri}#${round}`;}
/** * How long a `(prUri, round)` is considered "already enqueued" before the guard * lets it onto the stream again. Long enough to span a few cron ticks plus a * worker run, short enough that a job lost before it was claimed gets another * shot. Correctness does not depend on this value (claim-on-consume does). */export const ENQUEUE_DEDUP_TTL_SECONDS = 30 * 60;
export const JOBS_STREAM_KEY = "slopgotchi:jobs";export const JOBS_CONSUMER_GROUP = "workers";
export function isQueueConfigured(): boolean { return isStoreConfigured();}
// --- in-memory queue (tests / local) ---------------------------------------
/** Deterministic, dependency-free queue for unit tests and local runs. */export class InMemoryJobQueue implements JobQueue { private seq = 0; private readonly pending: DeliveredJob[] = []; private readonly delivered = new Map<string, DeliveredJob>(); private readonly seen = new Set<string>();
async enqueue(job: ScoreJob): Promise<{ enqueued: boolean; id?: string }> { const parsed = ScoreJobSchema.parse(job); const dedup = jobDedupKey(parsed.prUri, parsed.round); if (this.seen.has(dedup)) return { enqueued: false }; this.seen.add(dedup); const id = `m${++this.seq}`; this.pending.push({ id, job: parsed }); return { enqueued: true, id }; }
async consume(opts: ConsumeOptions = {}): Promise<DeliveredJob[]> { const count = opts.count ?? this.pending.length; const batch = this.pending.splice(0, count); for (const d of batch) this.delivered.set(d.id, d); return batch; }
async ack(id: string): Promise<void> { this.delivered.delete(id); }
/** No-op re-attach: the in-memory queue has no subscription to rebuild (U14). */ async ensureReady(): Promise<void> {}
/** Test introspection: jobs delivered but not yet acked (redelivery candidates). */ unacked(): DeliveredJob[] { return [...this.delivered.values()]; }}
// --- Redis stream queue (production) ----------------------------------------
/** * Redis-stream backing for {@link JobQueue} on Upstash. Exercised by the * env-gated integration test; the unit suite uses {@link InMemoryJobQueue}. */export class RedisStreamQueue implements JobQueue { private groupEnsured = false; private _redis?: Redis;
constructor( private readonly consumerName: string = process.env.WORKER_CONSUMER_NAME || process.env.HOSTNAME || "worker-1", redis?: Redis, private readonly streamKey: string = JOBS_STREAM_KEY, private readonly group: string = JOBS_CONSUMER_GROUP, ) { this._redis = redis; }
/** Resolves the Redis client lazily so constructing the queue never throws. */ private redis(): Redis { return (this._redis ??= getRedis()); }
/** Creates the consumer group (and stream) once, ignoring "already exists". */ private async ensureGroup(): Promise<void> { if (this.groupEnsured) return; try { await this.redis().xgroup(this.streamKey, { type: "CREATE", group: this.group, id: "0", options: { MKSTREAM: true }, }); } catch (err) { // BUSYGROUP = group already exists; any other error is real. if (!/BUSYGROUP/i.test((err as Error).message)) throw err; } this.groupEnsured = true; }
/** Public re-attach for restart recovery (U14): idempotently ensure the group. */ async ensureReady(): Promise<void> { await this.ensureGroup(); }
async enqueue(job: ScoreJob): Promise<{ enqueued: boolean; id?: string }> { const parsed = ScoreJobSchema.parse(job); const guard = await this.redis().set( jobDedupKey(parsed.prUri, parsed.round), "1", { nx: true, ex: ENQUEUE_DEDUP_TTL_SECONDS }, ); if (guard !== "OK") return { enqueued: false }; const id = await this.redis().xadd(this.streamKey, "*", { job: JSON.stringify(parsed), }); return { enqueued: true, id: String(id) }; }
async consume(opts: ConsumeOptions = {}): Promise<DeliveredJob[]> { await this.ensureGroup(); const count = opts.count ?? 10; const res = (await this.redis().xreadgroup( this.group, this.consumerName, this.streamKey, ">", { count }, )) as [string, [string, Record<string, string>][]][] | null; if (!res) return []; const out: DeliveredJob[] = []; for (const [, entries] of res) { for (const [id, fields] of entries) { const raw = fields?.job; if (!raw) continue; const parsed = ScoreJobSchema.safeParse(JSON.parse(raw)); if (parsed.success) out.push({ id, job: parsed.data }); else await this.ack(id); // unparseable entry: drop, don't wedge the group } } return out; }
async ack(id: string): Promise<void> { await this.redis().xack(this.streamKey, this.group, id); }}
// --- production queue singleton ---------------------------------------------
let queueSingleton: JobQueue | null = null;
/** Lazily-created production queue. Safe to call when Redis is unconfigured. */export function getJobQueue(): JobQueue { if (!queueSingleton) queueSingleton = new RedisStreamQueue(); return queueSingleton;}
/** Resets the queue singleton (test helper). */export function _resetJobQueue(): void { queueSingleton = null;}