SPB Git

Repository Public

jobs.test.ts 7.9 KB 109 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : Note SPBoucher AI8 * File             : tests/unit/jobs.test.ts9 * Module           : tests10 * Repository       : https://git.spboucher.ai/note-spboucher-ai11 * Project Website  : https://note.spboucher.ai12 * Created          : 2026-11-1713 * Last Modified    : 2026-11-1914 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development      : dev@spboucher.ai24 * Support          : support@spboucher.ai25 * Security/Admin   : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License          : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243/**44 * Background jobs: policy, de-duplication, retry → dead letter, orphaned job after a killed worker, timeout.45 * Uses throw-away queues (prefix t-) in the scratch database's pgboss schema.46 */47import "../helpers/testdb";48import { test, before, after } from "node:test";49import assert from "node:assert/strict";50import { PgBoss } from "pg-boss";51import { ensureQueues } from "../../src/lib/jobs/index";52import { QUEUES, QUEUE_POLICY, DEAD_LETTER } from "../../src/lib/jobs/queues";53import { wrap, withTimeout, safeSummary, JobTimeout } from "../../src/worker/run";5455const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));56const until = async (fn: () => Promise<boolean>, ms: number) => { const t0 = Date.now(); while (Date.now() - t0 < ms) { if (await fn()) return true; await sleep(250); } return false; };57const mk = () => new PgBoss({ connectionString: process.env.DATABASE_URL!, schema: "pgboss", max: Math.max(1, Math.min(3, Number(process.env.DB_POOL_MAX ?? 3) || 3)), superviseIntervalSeconds: 1, monitorIntervalSeconds: 1, maintenanceIntervalSeconds: 1 } as any);58let boss: PgBoss; const tag = `t-${Date.now().toString(36)}`; const queues: string[] = [];59const q = async (name: string, opts: Record<string, unknown>) => { const n = `${tag}-${name}`; queues.push(n); await boss.createQueue(n, opts as any); return n; };60before(async () => { boss = mk(); boss.on("error", () => {}); await boss.start(); await ensureQueues(boss); });61after(async () => { for (const n of queues) await boss.deleteQueue(n).catch(() => {}); await boss.stop({ graceful: false, timeout: 2000 } as any).catch(() => {}); });6263test("queue policy is applied: safe work retries with backoff, paid or long work does not", async () => {64  const idx = await boss.getQueue(QUEUES.index); assert.equal(idx?.retryLimit, 4); assert.equal(idx?.retryBackoff, true); assert.equal(idx?.deadLetter, DEAD_LETTER);65  for (const name of [QUEUES.agent, QUEUES.backup, QUEUES.suggestLinks]) assert.equal((await boss.getQueue(name))?.retryLimit, 0, name);66  for (const [name, p] of Object.entries(QUEUE_POLICY)) { assert.ok(p.timeoutMs < p.expireInSeconds * 1000, `${name}: in-process timeout must be below the expiry`); assert.equal((await boss.getQueue(name))?.expireInSeconds, p.expireInSeconds, name); }67});68test("the same singleton key cannot be queued twice in its window (no duplicate job)", async () => {69  const name = await q("dedupe", { retryLimit: 0 });70  const a = await boss.send(name, { n: 1 }, { singletonKey: "page:1", singletonSeconds: 60 }); const b = await boss.send(name, { n: 1 }, { singletonKey: "page:1", singletonSeconds: 60 }); const c = await boss.send(name, { n: 2 }, { singletonKey: "page:2", singletonSeconds: 60 });71  assert.ok(a); assert.equal(b, null); assert.ok(c);72});73test("throttled indexing is deferred to the next slot, never dropped (an edit right after an indexing still gets indexed)", async () => {74  const name = await q("slot", { retryLimit: 0 }); const o = { singletonKey: "page:9", singletonSeconds: 20, singletonNextSlot: true };75  const a = await boss.send(name, {}, o); const b = await boss.send(name, {}, o); const c = await boss.send(name, {}, o);76  assert.ok(a); assert.ok(b, "second send is scheduled for the next slot"); assert.equal(c, null, "a third one in the same window adds nothing");77  const jb = await boss.getJobById(name, b!); assert.ok(jb && new Date(jb.startAfter).getTime() > Date.now(), "the deferred job starts later");78});79test("a failing job is retried, then fails for good and is copied to the dead-letter queue", async () => {80  const dlq = await q("dead", { retryLimit: 0 }); const name = await q("fail", { retryLimit: 2, retryDelay: 1, deadLetter: dlq });81  let attempts = 0; await boss.work(name, { batchSize: 1, pollingIntervalSeconds: 0.5, includeMetadata: true } as any, wrap(name, async () => { attempts++; throw new Error("provider unreachable"); }, 5000) as any);82  const id = await boss.send(name, { sourceId: "x" }); assert.ok(id);83  assert.ok(await until(async () => (await boss.getJobById(name, id!))?.state === "failed", 25_000), "job ends in failed");84  assert.equal(attempts, 3, "1 try + 2 retries");85  assert.ok(await until(async () => (await boss.findJobs(dlq)).length === 1, 10_000), "dead-letter copy exists");86  await boss.offWork(name);87});88test("a job that succeeds on a later attempt is not lost and runs to completion once", async () => {89  const name = await q("flaky", { retryLimit: 3, retryDelay: 1 }); let attempts = 0, done = 0;90  await boss.work(name, { batchSize: 1, pollingIntervalSeconds: 0.5, includeMetadata: true } as any, wrap(name, async () => { if (++attempts < 2) throw new Error("network interrupted"); done++; return { indexed: 1 }; }, 5000) as any);91  const id = await boss.send(name, {});92  assert.ok(await until(async () => (await boss.getJobById(name, id!))?.state === "completed", 20_000)); assert.equal(done, 1); assert.equal(attempts, 2);93  await boss.offWork(name);94});95test("a job left active by a killed worker is released at expiry and picked up again", async () => {96  const name = await q("orphan", { retryLimit: 2, retryDelay: 1, expireInSeconds: 2 });97  const id = await boss.send(name, {}); const dead = mk(); dead.on("error", () => {}); await dead.start();98  const taken = await dead.fetch(name); assert.equal(taken.length, 1); // "worker" takes the job …99  await dead.stop({ graceful: false, timeout: 500 } as any).catch(() => {});       // … and dies without completing it100  let ran = 0; await boss.work(name, { batchSize: 1, pollingIntervalSeconds: 0.5, includeMetadata: true } as any, wrap(name, async () => { ran++; return { ok: true }; }, 5000) as any);101  assert.ok(await until(async () => (await boss.getJobById(name, id!))?.state === "completed", 40_000), "the orphaned job completes on the surviving worker"); assert.equal(ran, 1);102  await boss.offWork(name);103});104test("in-process timeout fails a job that hangs; log summaries never carry text", async () => {105  await assert.rejects(withTimeout(new Promise(() => {}), 50, "test"), JobTimeout);106  assert.equal(await withTimeout(Promise.resolve(7), 50, "test"), 7);107  assert.deepEqual(safeSummary({ indexed: 3, skipped: true, pageId: "7d3c2b1a-0000-4000-8000-000000000000", title: "My private note", message: "secret text" }), { indexed: 3, skipped: true, pageId: "7d3c2b1a-0000-4000-8000-000000000000" });108});109
Files main
Menu

Theme