1.1.2 → 1.1.3
3 arquivos alterados · +25 −4 · eefde32…10f7c8e
Para aplicar essas mudanças mantendo as suas edições, rode no seu projeto: genpm diff @core/jobs --to 1.1.3
src/lib/jobs/genpm.json modificado +1 −1
@@ -1,7 +1,7 @@ { "$": 1, "n": "@core/jobs", - "v": "1.1.2", + "v": "1.1.3", "s": { "en": "Background jobs on Postgres: durable queue, retries with backoff, cron schedules and a serverless cron endpoint", "es": "Tareas en segundo plano sobre Postgres: cola durable, reintentos con backoff, cron y endpoint para serverless",
src/lib/jobs/jobs.test.ts modificado +19 −0
@@ -201,6 +201,25 @@ describe('schedules', () => { expect((await runDue({ now: due })).scheduled).toBe(0); }); + it('a job being run is not claimed again by a concurrent cron that uses the same (future) now', async () => { + let release!: () => void; + const started = new Promise<void>((ok) => { + defineJob('slow', z.object({}), async () => { + seen.push('slow'); + ok(); + await new Promise<void>((r) => (release = r)); + }); + }); + const now = new Date(Date.now() + 3_600_000); // una hora por delante del reloj real + await db.insert(jobs).values({ type: 'slow', payload: {}, runAt: new Date(now.getTime() - 1000) }); + const first = runDue({ now }); + await started; // A ya la reclamó y la está ejecutando (con su bloqueo ajustado al timeout) + expect((await runDue({ now })).claimed).toBe(0); + release(); + await first; + expect(seen).toEqual(['slow']); + }); + it('prunes old done jobs and keeps failed ones', async () => { const j = defineJob('p', z.object({}), async () => {}); await j.enqueue({});
src/lib/jobs/queue.ts modificado +5 −3
@@ -105,7 +105,7 @@ export async function claimJobs(limit: number, now: Date = new Date(), db: Execu return claimed.sort((a, b) => a.runAt.getTime() - b.runAt.getTime()); } -async function runJob(job: Job, db: Executor): Promise<'done' | 'retry' | 'failed'> { +async function runJob(job: Job, db: Executor, claimedAt: Date = new Date()): Promise<'done' | 'retry' | 'failed'> { const def = getJob(job.type); const fail = async (message: string, retry: boolean) => { const final = !retry || job.attempts >= job.maxAttempts; @@ -129,7 +129,9 @@ async function runJob(job: Job, db: Executor): Promise<'done' | 'retry' | 'faile await db .update(jobs) - .set({ lockedUntil: new Date(Date.now() + def.timeoutMs + 30_000) }) + // Desde el mismo instante con el que se reclamó (y nunca antes que el reloj local): si se calculara con otro reloj + // (otra instancia, o un `now` explícito), un cron concurrente podría ver el bloqueo caducado y ejecutarla dos veces. + .set({ lockedUntil: new Date(Math.max(claimedAt.getTime(), Date.now()) + def.timeoutMs + 30_000) }) .where(eq(jobs.id, job.id)); const controller = new AbortController(); const timer = setTimeout(() => controller.abort(new Error(`timeout after ${def.timeoutMs} ms`)), def.timeoutMs); @@ -172,7 +174,7 @@ export async function runDue( const queue = [...claimed]; const worker = async () => { for (let job = queue.shift(); job; job = queue.shift()) { - const r = await runJob(job, db); + const r = await runJob(job, db, now); if (r === 'done') result.done++; else if (r === 'retry') result.retried++; else result.failed++;