logic-sdk 0.7.2 → 0.7.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -3
- package/dist/adapters/cloudflare-queue.d.ts +3 -2
- package/dist/adapters/cloudflare-queue.js +14 -4
- package/dist/adapters/drizzle-pg.d.ts +31 -1
- package/dist/adapters/drizzle-pg.js +14 -5
- package/dist/adapters/drizzle-sqlite.d.ts +17 -1
- package/dist/adapters/drizzle-sqlite.js +11 -4
- package/dist/adapters/postgres.d.ts +9 -8
- package/dist/adapters/postgres.js +43 -19
- package/dist/adapters/sqlite.d.ts +1 -1
- package/dist/adapters/sqlite.js +32 -12
- package/dist/adapters/stored-jobs.d.ts +27 -19
- package/dist/adapters/stored-jobs.js +157 -61
- package/dist/core/in-process.js +23 -3
- package/dist/core/jobs.d.ts +12 -6
- package/dist/core/jobs.js +158 -17
- package/dist/core/registry.d.ts +39 -3
- package/dist/core/registry.js +23 -11
- package/dist/core/testing.js +3 -1
- package/dist/core/types.d.ts +96 -34
- package/dist/hosts/cloudflare.d.ts +5 -4
- package/dist/hosts/cloudflare.js +5 -4
- package/dist/hosts/node.d.ts +25 -15
- package/dist/hosts/node.js +61 -34
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/node.d.ts +1 -1
- package/dist/node.js +1 -1
- package/package.json +1 -11
- package/skills/logic-sdk/SKILL.md +4 -4
- package/src/adapters/cloudflare-queue.ts +13 -4
- package/src/adapters/drizzle-pg.ts +14 -5
- package/src/adapters/drizzle-sqlite.ts +11 -4
- package/src/adapters/postgres.ts +43 -19
- package/src/adapters/sqlite.ts +32 -12
- package/src/adapters/stored-jobs.ts +174 -74
- package/src/core/in-process.ts +22 -2
- package/src/core/jobs.ts +146 -19
- package/src/core/registry.ts +62 -14
- package/src/core/testing.ts +3 -1
- package/src/core/types.ts +93 -30
- package/src/hosts/cloudflare.ts +5 -4
- package/src/hosts/node.ts +73 -46
- package/src/index.ts +3 -1
- package/src/node.ts +1 -1
- package/dist/adapters/pg-boss.d.ts +0 -45
- package/dist/adapters/pg-boss.js +0 -180
- package/dist/hosts/pg-boss.d.ts +0 -22
- package/dist/hosts/pg-boss.js +0 -55
- package/dist/pg-boss.d.ts +0 -2
- package/dist/pg-boss.js +0 -2
- package/src/adapters/pg-boss.ts +0 -195
- package/src/hosts/pg-boss.ts +0 -71
- package/src/pg-boss.ts +0 -2
package/dist/core/jobs.js
CHANGED
|
@@ -13,10 +13,13 @@ const canonical = (value) => JSON.stringify(value, (_, v) => (isPlainObject(v) ?
|
|
|
13
13
|
*/
|
|
14
14
|
export const replaceKeyOf = (job) => (job.kind === "call" && job.replace ? `${job.fn}@${canonical(job.input)}` : undefined);
|
|
15
15
|
/**
|
|
16
|
-
*
|
|
17
|
-
* large input still fits an index and the function
|
|
16
|
+
* The key adapters that keep one waiting job per key (`replaces: true`) store: a delivery's `unique` as it is, a call's
|
|
17
|
+
* `replaceKeyOf` as `<function id>@<sha-256 of the input>`, so a large input still fits an index and the function
|
|
18
|
+
* stays readable. Undefined for every other job.
|
|
18
19
|
*/
|
|
19
|
-
export async function
|
|
20
|
+
export async function storedUniqueKey(job) {
|
|
21
|
+
if (job.kind === "delivery")
|
|
22
|
+
return job.unique;
|
|
20
23
|
if (job.kind !== "call" || !job.replace)
|
|
21
24
|
return undefined;
|
|
22
25
|
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(canonical(job.input)));
|
|
@@ -52,6 +55,25 @@ function scopeMatches(filter) {
|
|
|
52
55
|
export const defaultBackoff = (attempt) => Math.exp(Math.min(attempt, 10));
|
|
53
56
|
/** Where the docs list each adapter and what it can do. */
|
|
54
57
|
export const ADAPTERS = "see Jobs, Adapters in the docs";
|
|
58
|
+
/** The loops running each adapter's jobs in this process (`work()`), by adapter: every registry on it shares them. */
|
|
59
|
+
const localWorkers = new WeakMap();
|
|
60
|
+
const workerSet = (adapter) => {
|
|
61
|
+
let set = localWorkers.get(adapter);
|
|
62
|
+
if (!set)
|
|
63
|
+
localWorkers.set(adapter, (set = new Set()));
|
|
64
|
+
return set;
|
|
65
|
+
};
|
|
66
|
+
/** What an adapter's `connect` gets as `setup.workers`: does a loop here take this job, and wake them. */
|
|
67
|
+
export function workersOf(adapter) {
|
|
68
|
+
const set = workerSet(adapter);
|
|
69
|
+
return {
|
|
70
|
+
takes: (job) => [...set].some((w) => !w.queues || w.queues.includes(job.queue ?? "default")),
|
|
71
|
+
wake: (count) => {
|
|
72
|
+
for (const worker of set)
|
|
73
|
+
worker.wake(count);
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
}
|
|
55
77
|
/** The minute `at` falls in, and its stamp for a job id: `20261123T0900Z` (no `:`, which BullMQ rejects). */
|
|
56
78
|
function minuteOf(at, what) {
|
|
57
79
|
if (Number.isNaN(at.getTime()))
|
|
@@ -67,17 +89,58 @@ export const deliveryOf = (l, e) => ({
|
|
|
67
89
|
envelope: e,
|
|
68
90
|
attempts: l.listener.attempts ?? 1,
|
|
69
91
|
});
|
|
92
|
+
/**
|
|
93
|
+
* A try that runs past its timeout: aborts its signal (its `ctx.signal`, and no new `ctx.run` starts) and fails the try,
|
|
94
|
+
* as Laravel's `$timeout` and Oban's `timeout/1` count it. JavaScript can't kill it, so what it still does is ignored.
|
|
95
|
+
*/
|
|
96
|
+
async function stopAfter(work, seconds, stop, why) {
|
|
97
|
+
let timer;
|
|
98
|
+
const timedOut = new Promise((_, reject) => {
|
|
99
|
+
timer = setTimeout(() => {
|
|
100
|
+
const error = new Error(`[logic-sdk] ${why}`);
|
|
101
|
+
stop.abort(error);
|
|
102
|
+
reject(error);
|
|
103
|
+
}, seconds * 1000);
|
|
104
|
+
});
|
|
105
|
+
work.catch(() => { }); // it may still settle after the timeout: not this try's anymore
|
|
106
|
+
try {
|
|
107
|
+
return await Promise.race([work, timedOut]);
|
|
108
|
+
}
|
|
109
|
+
finally {
|
|
110
|
+
clearTimeout(timer);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
70
113
|
/**
|
|
71
114
|
* Jobs, for one registry: a listener's share of an event, a cron's run, a scheduled call. Turns a commit's events and
|
|
72
115
|
* calls into jobs, runs one (with its tries), and is what `registry.jobs` calls.
|
|
73
116
|
*/
|
|
74
117
|
export function makeJobs(deps) {
|
|
75
|
-
const { listeners, crons, functions, idOf, jobsAdapter, database, jobScope, failedStore, maxEventDepth, now, wrap, report, runAs, handlerCtx } = deps;
|
|
76
|
-
// the adapter's own, or the store's: a job that failed for good is kept by whichever there is
|
|
77
|
-
const keepFailed = jobsAdapter.fail?.bind(jobsAdapter) ?? failedStore?.fail.bind(failedStore);
|
|
118
|
+
const { listeners, crons, functions, idOf, jobsAdapter, database, jobScope, failedStore, maxEventDepth, queues, now, wrap, report, runAs, handlerCtx } = deps;
|
|
78
119
|
/** Your adapter, as messages name it: by what it can't do, and by its own name. */
|
|
79
120
|
const yours = jobsAdapter.name ? `your jobs adapter, ${jobsAdapter.name},` : "your jobs adapter";
|
|
80
|
-
|
|
121
|
+
// ── queues ───────────────────────────────────────────────────────────────
|
|
122
|
+
for (const q of queues)
|
|
123
|
+
if (typeof q !== "string" || !q || q === "default")
|
|
124
|
+
throw new Error(`[logic-sdk] jobs.queues takes names besides "default" (got ${JSON.stringify(q)}).`);
|
|
125
|
+
if (new Set(queues).size !== queues.length)
|
|
126
|
+
throw new Error(`[logic-sdk] jobs.queues lists a queue twice: ${queues.join(", ")}.`);
|
|
127
|
+
const queueNames = ["default", ...queues];
|
|
128
|
+
if (queues.length && !jobsAdapter.queues)
|
|
129
|
+
throw new Error(`[logic-sdk] jobs.queues declares ${queues.join(", ")}, but ${yours} keeps every job in one queue. Use one that keeps them apart (${ADAPTERS}).`);
|
|
130
|
+
if (typeof jobsAdapter.queues === "object")
|
|
131
|
+
for (const q of queueNames)
|
|
132
|
+
if (!jobsAdapter.queues.includes(q))
|
|
133
|
+
throw new Error(`[logic-sdk] ${yours} has no queue for "${q}": give it one (it has ${jobsAdapter.queues.join(", ") || "none"}).`);
|
|
134
|
+
/** A queue someone named: one of `jobs.queues`, or `"default"`. */
|
|
135
|
+
function checkQueue(what, queue) {
|
|
136
|
+
if (queue !== undefined && !queueNames.includes(queue))
|
|
137
|
+
throw new Error(`[logic-sdk] ${what} has queue ${JSON.stringify(queue)}, which jobs.queues doesn't declare (${queueNames.join(", ")}).`);
|
|
138
|
+
}
|
|
139
|
+
for (const l of listeners)
|
|
140
|
+
checkQueue(l.id, l.listener.queue);
|
|
141
|
+
for (const c of crons)
|
|
142
|
+
checkQueue(c.id, c.cron.queue);
|
|
143
|
+
if (failedStore && jobsAdapter.failed)
|
|
81
144
|
throw new Error(`[logic-sdk] ${yours} keeps failed jobs itself, so jobs.failed has nothing to keep: drop it.`);
|
|
82
145
|
const enqueue = jobsAdapter.enqueue?.bind(jobsAdapter);
|
|
83
146
|
if (enqueue && crons.length && !database)
|
|
@@ -120,6 +183,13 @@ export function makeJobs(deps) {
|
|
|
120
183
|
checkRetries(l.id, l.listener.attempts ?? 1);
|
|
121
184
|
for (const c of crons)
|
|
122
185
|
checkRetries(c.id, c.cron.attempts ?? 1);
|
|
186
|
+
for (const l of listeners) {
|
|
187
|
+
if (l.listener.key && !jobsAdapter.orders)
|
|
188
|
+
throw new Error(`[logic-sdk] ${l.id} has a key, but ${yours} can't run jobs one at a time by key. Use one that can (see Jobs, "key" in the docs).`);
|
|
189
|
+
// nothing waits on an adapter that runs jobs at once, so there's nothing to drop
|
|
190
|
+
if (l.listener.unique && jobsAdapter.holds && !jobsAdapter.replaces)
|
|
191
|
+
throw new Error(`[logic-sdk] ${l.id} is unique, but ${yours} can't drop a job it already has. Use one that can (see Jobs, "unique" in the docs).`);
|
|
192
|
+
}
|
|
123
193
|
/**
|
|
124
194
|
* What a commit queues: one delivery per listener of each event that its `when` lets through, and the calls it
|
|
125
195
|
* scheduled. Events and calls due now past `maxEventDepth` (a listener loop, a function scheduling itself with no
|
|
@@ -135,6 +205,22 @@ export function makeJobs(deps) {
|
|
|
135
205
|
throw new Error(`[logic-sdk] ${l.id}'s when threw on ${e.name}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
136
206
|
}
|
|
137
207
|
};
|
|
208
|
+
/** Its `key` or `unique`, as `<listener id>@<value>`. A throw or an empty value is a bug in the app: it fails the mutation. */
|
|
209
|
+
const valueOf = (l, option, e, payload) => {
|
|
210
|
+
const of = l.listener[option];
|
|
211
|
+
if (!of)
|
|
212
|
+
return undefined;
|
|
213
|
+
let value;
|
|
214
|
+
try {
|
|
215
|
+
value = of(payload);
|
|
216
|
+
}
|
|
217
|
+
catch (error) {
|
|
218
|
+
throw new Error(`[logic-sdk] ${l.id}'s ${option} threw on ${e.name}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
219
|
+
}
|
|
220
|
+
if (typeof value !== "string" || !value)
|
|
221
|
+
throw new Error(`[logic-sdk] ${l.id}'s ${option} must return a non-empty string (got ${JSON.stringify(value)}) on ${e.name}.`);
|
|
222
|
+
return `${l.id}@${value}`;
|
|
223
|
+
};
|
|
138
224
|
const fits = (job) => job.depth <= maxEventDepth;
|
|
139
225
|
const deepEvent = envelopes.find((e) => !fits(e));
|
|
140
226
|
const deepCall = calls.find((c) => !fits(c));
|
|
@@ -143,12 +229,24 @@ export function makeJobs(deps) {
|
|
|
143
229
|
report(loop(deepEvent.name), { source: deepEvent.name });
|
|
144
230
|
else if (deepCall)
|
|
145
231
|
report(loop(deepCall.fn), infoOf(deepCall));
|
|
146
|
-
const
|
|
232
|
+
const unique = new Set();
|
|
233
|
+
const deliveries = envelopes.filter(fits).flatMap((e) => (byEvent.get(e.name) ?? []).filter((l) => wants(l, e, parsed.get(e))).flatMap((l) => {
|
|
147
234
|
const job = deliveryOf(l, e);
|
|
148
235
|
const delay = l.listener.delay;
|
|
149
236
|
if (delay)
|
|
150
237
|
job.runAt = new Date(Date.parse(e.occurredAt) + delay * 1000).toISOString();
|
|
151
|
-
|
|
238
|
+
const key = valueOf(l, "key", e, parsed.get(e));
|
|
239
|
+
if (key)
|
|
240
|
+
job.key = key;
|
|
241
|
+
if (l.listener.queue)
|
|
242
|
+
job.queue = l.listener.queue;
|
|
243
|
+
job.unique = valueOf(l, "unique", e, parsed.get(e));
|
|
244
|
+
if (!job.unique)
|
|
245
|
+
return [job];
|
|
246
|
+
if (unique.has(job.unique))
|
|
247
|
+
return []; // the same commit's first one waits; adapters drop later commits' ones
|
|
248
|
+
unique.add(job.unique);
|
|
249
|
+
return [job];
|
|
152
250
|
}));
|
|
153
251
|
return [...deliveries, ...calls.filter(fits)];
|
|
154
252
|
}
|
|
@@ -181,9 +279,13 @@ export function makeJobs(deps) {
|
|
|
181
279
|
const info = infoOf(job, attempt);
|
|
182
280
|
// read before narrowing: a job queued by another version can have a kind this one doesn't know
|
|
183
281
|
const { id, kind } = job;
|
|
282
|
+
/** Its definition's `failed`, once its last try failed: after it's kept, at most once. A throw is reported. */
|
|
283
|
+
let afterFailed;
|
|
184
284
|
const failed = async (error) => {
|
|
185
285
|
report(error, { ...info, outcome: "failed" });
|
|
186
286
|
await fail?.(error);
|
|
287
|
+
if (afterFailed)
|
|
288
|
+
await afterFailed(error).catch((e) => report(e, { source: `${info.source} (failed)`, job, attempt }));
|
|
187
289
|
return "failed";
|
|
188
290
|
};
|
|
189
291
|
/** One try of the job's `attempts`. */
|
|
@@ -215,10 +317,13 @@ export function makeJobs(deps) {
|
|
|
215
317
|
const c = cronById.get(job.cron);
|
|
216
318
|
if (!c)
|
|
217
319
|
return missing("cron", job.cron);
|
|
320
|
+
const run = { id: c.id, scheduledAt: job.scheduledAt, attempt };
|
|
321
|
+
const hook = c.cron.failed;
|
|
322
|
+
if (hook)
|
|
323
|
+
afterFailed = (error) => hook({ ...handlerCtx(c.cron.scope, 0, c.id, queued), cron: run }, error); // SAFETY: as below
|
|
218
324
|
return attemptOnce(async () => {
|
|
219
325
|
// its scope comes from the code each time, never stored, so jobs.scope store and load don't apply
|
|
220
326
|
const { scope, meta, handler } = c.cron;
|
|
221
|
-
const run = { id: c.id, scheduledAt: job.scheduledAt, attempt };
|
|
222
327
|
await wrap({ id: c.id, kind: "cron", job: { id: job.id, attempt }, meta, input: undefined, scope, depth: 0 }, () => handler({ ...handlerCtx(scope, 0, c.id, queued), cron: run }));
|
|
223
328
|
return "done";
|
|
224
329
|
});
|
|
@@ -241,11 +346,26 @@ export function makeJobs(deps) {
|
|
|
241
346
|
if (!l)
|
|
242
347
|
return missing("listener", job.listener);
|
|
243
348
|
const { envelope } = job;
|
|
349
|
+
const { timeout } = l.listener;
|
|
350
|
+
const stop = timeout ? new AbortController() : undefined;
|
|
351
|
+
const hook = l.listener.failed;
|
|
352
|
+
// with today's scope and the parsed payload, as its handler would get them; a stale job or a scope that's gone has neither
|
|
353
|
+
if (hook)
|
|
354
|
+
afterFailed = async (error) => {
|
|
355
|
+
if (error instanceof StalePayload)
|
|
356
|
+
return;
|
|
357
|
+
const scope = jobScope?.load ? await jobScope.load(envelope.scope) : envelope.scope;
|
|
358
|
+
const r = await l.event.payload["~standard"].validate(envelope.payload);
|
|
359
|
+
if (!scope || r.issues || idOf(l.event) !== envelope.name)
|
|
360
|
+
return;
|
|
361
|
+
const ctxEvent = { id: envelope.id, name: envelope.name, payload: r.value, occurredAt: envelope.occurredAt, attempt };
|
|
362
|
+
return hook({ ...handlerCtx(scope, envelope.depth, l.id, queued), event: ctxEvent }, r.value, error); // SAFETY: as the handler's
|
|
363
|
+
};
|
|
244
364
|
return attemptOnce(async () => {
|
|
245
365
|
const scope = await scopeOf(job, envelope.scope, attempt);
|
|
246
366
|
if (!scope)
|
|
247
367
|
return "discarded";
|
|
248
|
-
|
|
368
|
+
const handled = wrap({ id: l.id, kind: "listener", job: { id: job.id, attempt }, meta: l.listener.meta, input: envelope.payload, scope, depth: 0 }, async () => {
|
|
249
369
|
// its listener's event now: one renamed without an `id`, or a listener moved to another event, leaves stale jobs
|
|
250
370
|
if (idOf(l.event) !== envelope.name)
|
|
251
371
|
throw new StalePayload(`[logic-sdk] ${l.id} now listens to ${idOf(l.event)}, and this job is for ${envelope.name}.`);
|
|
@@ -254,8 +374,9 @@ export function makeJobs(deps) {
|
|
|
254
374
|
throw new StalePayload(`[logic-sdk] ${envelope.name} payload no longer matches its schema: ${JSON.stringify(describeIssues(r.issues))}`);
|
|
255
375
|
const payload = r.value;
|
|
256
376
|
const ctxEvent = { id: envelope.id, name: envelope.name, payload, occurredAt: envelope.occurredAt, attempt };
|
|
257
|
-
return l.listener.handler({ ...handlerCtx(scope, envelope.depth, l.id, queued), event: ctxEvent }, payload); // SAFETY: as in registry.ts's invoke: the ctx was built for a listener
|
|
377
|
+
return l.listener.handler({ ...handlerCtx(scope, envelope.depth, l.id, queued, stop?.signal), event: ctxEvent }, payload); // SAFETY: as in registry.ts's invoke: the ctx was built for a listener
|
|
258
378
|
});
|
|
379
|
+
await (timeout && stop ? stopAfter(handled, timeout, stop, `${l.id} ran past its timeout of ${timeout}s, so this try was stopped.`) : handled);
|
|
259
380
|
return "done";
|
|
260
381
|
});
|
|
261
382
|
}
|
|
@@ -284,11 +405,22 @@ export function makeJobs(deps) {
|
|
|
284
405
|
const { minute, stamp } = minuteOf(at, "tick");
|
|
285
406
|
return scheduled
|
|
286
407
|
.filter((c) => (only === undefined ? isDue(c.schedule, minute, c.cron.timezone) : c.id === only))
|
|
287
|
-
.map((c) => ({ kind: "cron", id: `${c.id}@${stamp}`, cron: c.id, scheduledAt: minute.toISOString(), attempts: c.cron.attempts ?? 1 }));
|
|
408
|
+
.map((c) => ({ kind: "cron", id: `${c.id}@${stamp}`, cron: c.id, scheduledAt: minute.toISOString(), attempts: c.cron.attempts ?? 1, ...(c.cron.queue ? { queue: c.cron.queue } : {}) }));
|
|
288
409
|
}
|
|
289
410
|
const jobs = {
|
|
290
|
-
|
|
291
|
-
|
|
411
|
+
async run(job, options) {
|
|
412
|
+
// a signal: the adapter's row says what runs, and records how it went
|
|
413
|
+
if (jobsAdapter.consume) {
|
|
414
|
+
const queued = [];
|
|
415
|
+
await jobsAdapter.consume(job, runnerInto(queued)).catch((error) => {
|
|
416
|
+
report(error, { source: "(jobs adapter)", job }); // the consumer retries the message: nothing else hears of it
|
|
417
|
+
throw error;
|
|
418
|
+
});
|
|
419
|
+
await deliver(queued);
|
|
420
|
+
return "done";
|
|
421
|
+
}
|
|
422
|
+
return runJob(job, { attempt: options?.attempt, fail: failedStore && ((error) => failedStore.fail(job, error)) });
|
|
423
|
+
},
|
|
292
424
|
async tick(at = now()) {
|
|
293
425
|
const jobs = due(at);
|
|
294
426
|
if (!jobs.length)
|
|
@@ -298,11 +430,20 @@ export function makeJobs(deps) {
|
|
|
298
430
|
return jobs.map((job) => job.cron);
|
|
299
431
|
},
|
|
300
432
|
async sweep(options) {
|
|
433
|
+
for (const q of options?.queues ?? [])
|
|
434
|
+
checkQueue("jobs.sweep({ queues })", q);
|
|
301
435
|
const queued = [];
|
|
302
436
|
const result = (await jobsAdapter.sweep?.(runnerInto(queued), options)) ?? { done: 0, failed: 0, discarded: 0, retrying: 0 };
|
|
303
437
|
await deliver(queued);
|
|
304
438
|
return result;
|
|
305
439
|
},
|
|
440
|
+
attach(worker) {
|
|
441
|
+
for (const q of worker.queues ?? [])
|
|
442
|
+
checkQueue("A worker", q);
|
|
443
|
+
const set = workerSet(jobsAdapter);
|
|
444
|
+
set.add(worker);
|
|
445
|
+
return () => void set.delete(worker);
|
|
446
|
+
},
|
|
306
447
|
async retry(id) {
|
|
307
448
|
if (jobsAdapter.retry)
|
|
308
449
|
return jobsAdapter.retry(id);
|
|
@@ -361,7 +502,7 @@ export function makeJobs(deps) {
|
|
|
361
502
|
? `[logic-sdk] jobs.invoke(${JSON.stringify(target)}): no cron has that id (${[...cronById.keys()].join(", ") || "none registered"}).`
|
|
362
503
|
: "[logic-sdk] jobs.invoke got a cron that isn't registered: export it from its module.");
|
|
363
504
|
const { minute, stamp } = minuteOf(options.at ?? now(), "jobs.invoke({ at })");
|
|
364
|
-
const job = { kind: "cron", id: `${c.id}@${stamp}-${crypto.randomUUID()}`, cron: c.id, scheduledAt: minute.toISOString(), attempts: c.cron.attempts ?? 1 };
|
|
505
|
+
const job = { kind: "cron", id: `${c.id}@${stamp}-${crypto.randomUUID()}`, cron: c.id, scheduledAt: minute.toISOString(), attempts: c.cron.attempts ?? 1, ...(c.cron.queue ? { queue: c.cron.queue } : {}) };
|
|
365
506
|
await enqueueAlone([job]);
|
|
366
507
|
const queued = [];
|
|
367
508
|
await jobsAdapter.deliver([job], runnerInto(queued)); // unlike a tick, a hand-off that fails throws: whoever invoked it needs to know
|
|
@@ -369,5 +510,5 @@ export function makeJobs(deps) {
|
|
|
369
510
|
return job.id;
|
|
370
511
|
},
|
|
371
512
|
};
|
|
372
|
-
return { toJobs, deliver, jobs, due, checkHold, checkRetries, yours };
|
|
513
|
+
return { toJobs, deliver, jobs, due, checkHold, checkRetries, checkQueue, yours };
|
|
373
514
|
}
|
package/dist/core/registry.d.ts
CHANGED
|
@@ -69,7 +69,7 @@ export declare function init<C extends Config & OnlyKnownKeys<C>>(): {
|
|
|
69
69
|
event: () => EventDef<unknown, O>;
|
|
70
70
|
/**
|
|
71
71
|
* Tries in total, the first included, like Laravel's `$tries`. Default 1: a retry repeats side effects, so opt in.
|
|
72
|
-
* Once they're used, the job is `failed` (kept by `databaseQueue
|
|
72
|
+
* Once they're used, the job is `failed` (kept by `databaseQueue` and `outbox`, retried with `registry.jobs.retry(id)`).
|
|
73
73
|
*/
|
|
74
74
|
attempts?: number;
|
|
75
75
|
/** Seconds after the event before the first try. Needs an adapter that holds jobs: `inProcess()` is refused. */
|
|
@@ -81,15 +81,47 @@ export declare function init<C extends Config & OnlyKnownKeys<C>>(): {
|
|
|
81
81
|
* mutation, as a bad payload does.
|
|
82
82
|
*/
|
|
83
83
|
when?: (payload: O) => boolean;
|
|
84
|
+
/**
|
|
85
|
+
* Jobs with the same key run one at a time, in the order their events were emitted, like Laravel's message groups
|
|
86
|
+
* on SQS FIFO: `key: (m) => m.conversationId`. Waiting spends no attempt; a try backing off holds the key, a job
|
|
87
|
+
* that failed for good frees it. Per listener. Needs an adapter that runs a key's jobs in order: others are refused.
|
|
88
|
+
* Inside its handler, run functions with `ctx.run`: calling the registry directly for the same key waits on itself.
|
|
89
|
+
*/
|
|
90
|
+
key?: (payload: O) => string;
|
|
91
|
+
/**
|
|
92
|
+
* While a job with the same value hasn't started, later ones are dropped, like Laravel's
|
|
93
|
+
* `ShouldBeUniqueUntilProcessing`: `unique: (p) => p.productId`. **It drops events, so the handler must read
|
|
94
|
+
* current state, never the payload's data**: for "X changed, recompute X". Once the job starts, the next event
|
|
95
|
+
* queues a new one.
|
|
96
|
+
*/
|
|
97
|
+
unique?: (payload: O) => string;
|
|
98
|
+
/**
|
|
99
|
+
* Seconds a try may run, like Laravel's `$timeout`. Past it, `ctx.signal` aborts, no new `ctx.run` starts, and
|
|
100
|
+
* the try counts as failed (retried while `attempts` are left). JavaScript can't stop code mid-flight: a mutation
|
|
101
|
+
* already running still commits.
|
|
102
|
+
*/
|
|
103
|
+
timeout?: number;
|
|
104
|
+
/**
|
|
105
|
+
* Its queue, one of `jobs.queues`: `queue: "mail"`. Default `"default"`. A worker takes its queues in the order it
|
|
106
|
+
* lists them: `work(registry, { queues: ["mail", "default"] })`.
|
|
107
|
+
*/
|
|
108
|
+
queue?: string;
|
|
84
109
|
meta?: ListenerMetaOf<C>;
|
|
85
110
|
handler: (ctx: ListenerCtx<C, O>, payload: O) => Promise<unknown>;
|
|
111
|
+
/**
|
|
112
|
+
* Runs once its last try has failed, with the handler's ctx and payload, and the error: undo or flag what the
|
|
113
|
+
* handler started (`await ctx.run(orders.flagReceipt, { orderId })`). Not in a transaction: run mutations. At most
|
|
114
|
+
* once (a crash right after the failure skips it), and not for a job that can't run anymore (its payload or event
|
|
115
|
+
* changed, or `scope.load` returned null). A throw is reported to `onError`; the job stays failed.
|
|
116
|
+
*/
|
|
117
|
+
failed?: (ctx: ListenerCtx<C, O>, payload: O, error: unknown) => Promise<unknown>;
|
|
86
118
|
}) => Listener<O, C>;
|
|
87
119
|
};
|
|
88
120
|
/** `cron({...})`: its handler's `ctx.scope` is the scope it declares, so a policy-free read of it is typed. */
|
|
89
121
|
type CronDef<C extends Config, Sc> = {
|
|
90
122
|
/**
|
|
91
|
-
* Stable id, local to its module, like every definer's. Defaults to the export name. Jobs
|
|
92
|
-
*
|
|
123
|
+
* Stable id, local to its module, like every definer's. Defaults to the export name. Jobs store it, so set it before you
|
|
124
|
+
* rename the export.
|
|
93
125
|
*/
|
|
94
126
|
id?: string;
|
|
95
127
|
/** Five fields: minute hour day-of-month month day-of-week. `"*\/15 * * * *"`, `"0 9 * * MON"`. */
|
|
@@ -100,9 +132,13 @@ type CronDef<C extends Config, Sc> = {
|
|
|
100
132
|
scope: Sc;
|
|
101
133
|
/** Tries in total, like a listener's. Default 1: a retry runs the whole handler again. */
|
|
102
134
|
attempts?: number;
|
|
135
|
+
/** Its queue, one of `jobs.queues`, like a listener's. Default `"default"`. */
|
|
136
|
+
queue?: string;
|
|
103
137
|
meta?: ListenerMetaOf<C>;
|
|
104
138
|
/** The work, like a listener's handler: an action's ctx, plus `ctx.cron` (`scheduledAt`, `attempt`). */
|
|
105
139
|
handler: (ctx: CronCtx<C, Sc>) => Promise<unknown>;
|
|
140
|
+
/** Runs once its last try has failed, like a listener's `failed`: the handler's ctx, and the error. */
|
|
141
|
+
failed?: (ctx: CronCtx<C, Sc>, error: unknown) => Promise<unknown>;
|
|
106
142
|
};
|
|
107
143
|
/** Create the registry once at startup. Prefer the `createRegistry` returned by `init()`: it's typed with your config. */
|
|
108
144
|
export declare function createRegistry<S extends object = object, const Mods extends Record<string, object> = Record<string, object>>(options: RegistryOptions<Mods>): Registry<S, Mods, unknown>;
|
package/dist/core/registry.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { CaughtNestedFailure, describeIssues, DomainError, errorsFor, forbiddenOf, moduleOf, PRIVATE } from "./errors.js";
|
|
2
2
|
import { inProcess, runsNow } from "./in-process.js";
|
|
3
|
-
import { ADAPTERS, isPlainObject, makeJobs, replaceKeyOf } from "./jobs.js";
|
|
3
|
+
import { ADAPTERS, isPlainObject, makeJobs, replaceKeyOf, workersOf } from "./jobs.js";
|
|
4
4
|
import { assertTimeZone, parseSchedule } from "./schedule.js";
|
|
5
5
|
import { BRAND, INTERNAL } from "./types.js";
|
|
6
6
|
/**
|
|
@@ -31,25 +31,30 @@ export function init() {
|
|
|
31
31
|
* `cron({ schedule: "0 9 * * MON", scope: { kind: "system", job: "reports.weekly" }, async handler(ctx) { await ctx.run(send) } })`.
|
|
32
32
|
*/
|
|
33
33
|
cron: (def) => {
|
|
34
|
-
const { id, schedule, timezone, scope, attempts, meta, handler } = def;
|
|
34
|
+
const { id, schedule, timezone, scope, attempts, queue, meta, handler, failed } = def;
|
|
35
35
|
parseSchedule(schedule);
|
|
36
36
|
if (timezone !== undefined)
|
|
37
37
|
assertTimeZone(timezone);
|
|
38
38
|
checkAttempts("cron", attempts);
|
|
39
39
|
// meta is checked against ListenerMetaOf<C> above and stored loose, like a listener's, for wrap and adapters
|
|
40
|
-
return Object.freeze({ [BRAND]: "cron", kind: "cron", id, schedule, timezone, scope, attempts, meta: meta, handler });
|
|
40
|
+
return Object.freeze({ [BRAND]: "cron", kind: "cron", id, schedule, timezone, scope, attempts, queue, meta: meta, handler, failed });
|
|
41
41
|
},
|
|
42
42
|
/**
|
|
43
43
|
* React to an event after commit, like an action. Must be idempotent.
|
|
44
44
|
* `listener({ event: () => bookings.confirmed, async handler(ctx, payload) {…} })`
|
|
45
45
|
*/
|
|
46
46
|
listener: (def) => {
|
|
47
|
-
const { id, event, attempts, delay, when, meta, handler } = def;
|
|
47
|
+
const { id, event, attempts, delay, when, key, unique, timeout, queue, meta, handler, failed } = def;
|
|
48
48
|
checkAttempts("listener", attempts);
|
|
49
49
|
if (delay !== undefined && !(Number.isFinite(delay) && delay >= 0))
|
|
50
50
|
throw new Error(`[logic-sdk] listener delay must be seconds, 0 or more (got ${delay}).`);
|
|
51
|
+
if (timeout !== undefined && !(Number.isFinite(timeout) && timeout > 0))
|
|
52
|
+
throw new Error(`[logic-sdk] listener timeout must be seconds, more than 0 (got ${timeout}).`);
|
|
53
|
+
// two jobs of one key with different values would be inserted in `unique` order (the lock order), not emit order
|
|
54
|
+
if (key && unique)
|
|
55
|
+
throw new Error("[logic-sdk] a listener takes key or unique, not both: key runs every job in order, unique drops the ones waiting.");
|
|
51
56
|
// meta is checked against ListenerMetaOf<C> above and stored loose, like Fn.meta, for wrap and adapters
|
|
52
|
-
return Object.freeze({ [BRAND]: "listener", kind: "listener", id, event, attempts, delay, when, meta: meta, handler });
|
|
57
|
+
return Object.freeze({ [BRAND]: "listener", kind: "listener", id, event, attempts, delay, when, key, unique, timeout, queue, meta: meta, handler, failed });
|
|
53
58
|
},
|
|
54
59
|
};
|
|
55
60
|
}
|
|
@@ -212,8 +217,9 @@ function build(options, o) {
|
|
|
212
217
|
if (adapter?.sql && !sql)
|
|
213
218
|
throw new Error(`[logic-sdk] ${adapter.name ?? "Your jobs adapter"} writes in your mutation's transaction with SQL, so it needs ` +
|
|
214
219
|
"createRegistry({ database: { adapter } }) with an adapter that runs SQL (`query`). See Adapters, Other ORMs in the docs.");
|
|
215
|
-
|
|
216
|
-
|
|
220
|
+
const setup = { sql, workers: workersOf(jobsAdapter) };
|
|
221
|
+
jobsAdapter.connect?.(setup);
|
|
222
|
+
failedStore?.connect?.(setup);
|
|
217
223
|
const idOf = (x) => {
|
|
218
224
|
const id = ids.get(x);
|
|
219
225
|
if (!id)
|
|
@@ -276,7 +282,7 @@ function build(options, o) {
|
|
|
276
282
|
// a copy: changing it can't change what's delivered
|
|
277
283
|
return Object.freeze({ id: envelope.id, name: envelope.name, payload: structuredClone(envelope.payload), occurredAt: envelope.occurredAt });
|
|
278
284
|
},
|
|
279
|
-
schedule: (fn, input, { at, delay, attempts = 1, replace, scope }) => {
|
|
285
|
+
schedule: (fn, input, { at, delay, attempts = 1, replace, scope, queue }) => {
|
|
280
286
|
const fnId = ids.get(fn);
|
|
281
287
|
if (!fnId)
|
|
282
288
|
throw new Error("[logic-sdk] ctx.schedule needs a function its module's index.ts exports: a scheduled call waits as a name, and a worker finds the code by it. " +
|
|
@@ -286,6 +292,7 @@ function build(options, o) {
|
|
|
286
292
|
throw new Error(`[logic-sdk] ctx.schedule(${fnId}) needs an \`at\` date or a \`delay\` in seconds, 0 or more.`);
|
|
287
293
|
checkAttempts(`ctx.schedule(${fnId})`, attempts);
|
|
288
294
|
checkRetries(`ctx.schedule(${fnId})`, attempts);
|
|
295
|
+
checkQueue(`ctx.schedule(${fnId})`, queue);
|
|
289
296
|
if (replace !== undefined) {
|
|
290
297
|
if (!jobsAdapter.replaces)
|
|
291
298
|
throw new Error(`[logic-sdk] ctx.schedule(${fnId}) replaces a waiting call, but ${yours} can't replace one it already has. Use one that can (${ADAPTERS}).`);
|
|
@@ -306,6 +313,8 @@ function build(options, o) {
|
|
|
306
313
|
};
|
|
307
314
|
if (waits)
|
|
308
315
|
job.runAt = new Date(now().getTime() + seconds * 1000).toISOString();
|
|
316
|
+
if (queue)
|
|
317
|
+
job.queue = queue;
|
|
309
318
|
if (replace) {
|
|
310
319
|
job.replace = true;
|
|
311
320
|
// scheduled twice in this transaction: the later one wins here too (the dropped one's input is still checked:
|
|
@@ -339,7 +348,7 @@ function build(options, o) {
|
|
|
339
348
|
signal: frame.signal,
|
|
340
349
|
services,
|
|
341
350
|
});
|
|
342
|
-
const { toJobs, deliver, jobs, due, checkHold, checkRetries, yours } = makeJobs({
|
|
351
|
+
const { toJobs, deliver, jobs, due, checkHold, checkRetries, checkQueue, yours } = makeJobs({
|
|
343
352
|
listeners,
|
|
344
353
|
crons,
|
|
345
354
|
functions,
|
|
@@ -349,11 +358,12 @@ function build(options, o) {
|
|
|
349
358
|
jobScope,
|
|
350
359
|
failedStore,
|
|
351
360
|
maxEventDepth,
|
|
361
|
+
queues: options.jobs?.queues ?? [],
|
|
352
362
|
now,
|
|
353
363
|
wrap,
|
|
354
364
|
report,
|
|
355
365
|
runAs: (fn, input, scope, eventDepth, queued, job) => invoke(fn, input, enter({ scope, trail: [], eventDepth, queued, job }, undefined), ["query", "mutation", "action"]),
|
|
356
|
-
handlerCtx: (scope, eventDepth, id, queued) => actionCtx({ scope, trail: [id], eventDepth, queued }, id),
|
|
366
|
+
handlerCtx: (scope, eventDepth, id, queued, stop) => actionCtx({ scope, trail: [id], eventDepth, queued, signal: stop, stop }, id),
|
|
357
367
|
});
|
|
358
368
|
// ── invoke ───────────────────────────────────────────────────────────────
|
|
359
369
|
/** `callerModule`: set by ctx.run, so a private function (its index doesn't export it) runs as part of the module running it. */
|
|
@@ -374,6 +384,7 @@ function build(options, o) {
|
|
|
374
384
|
/** Authorize, then validate, before any transaction opens: denied or bad calls never touch the database. */
|
|
375
385
|
const prepare = async () => {
|
|
376
386
|
frame.abortOn?.throwIfAborted();
|
|
387
|
+
frame.stop?.throwIfAborted();
|
|
377
388
|
if (fn.authorize) {
|
|
378
389
|
// SAFETY: the registry erases each policy's scope type; the caller's scope is the app's Scope by construction
|
|
379
390
|
if (fn.authorize(frame.scope) !== true)
|
|
@@ -416,7 +427,8 @@ function build(options, o) {
|
|
|
416
427
|
const input = await prepare();
|
|
417
428
|
const committed = await commitWithRetries(database, frame, id, (tx) => execute(input, mutationCtx({ ...frame, tx }, tx, id)));
|
|
418
429
|
// committed. Nothing below may fail the caller.
|
|
419
|
-
|
|
430
|
+
// a try past its timeout is settled already: what it still commits is delivered now, not after it
|
|
431
|
+
await afterCommit(committed.events, committed.jobs, frame.stop?.aborted ? undefined : frame.queued);
|
|
420
432
|
return committed.out;
|
|
421
433
|
});
|
|
422
434
|
}
|
package/dist/core/testing.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import {} from "./types.js";
|
|
2
|
+
import { inProcess } from "./in-process.js";
|
|
2
3
|
import { deliveryOf, replaceKeyOf } from "./jobs.js";
|
|
3
4
|
import { INTERNAL } from "./types.js";
|
|
4
5
|
class Rollback extends Error {
|
|
@@ -13,6 +14,7 @@ const testJobs = (mode, app, queued, scheduled) => ({
|
|
|
13
14
|
holds: app?.holds,
|
|
14
15
|
replaces: app?.replaces,
|
|
15
16
|
retries: app?.retries,
|
|
17
|
+
orders: (app ?? inProcess()).orders, // inline, jobs run one by one: in order
|
|
16
18
|
async deliver(jobs, runner) {
|
|
17
19
|
for (const job of jobs) {
|
|
18
20
|
const key = replaceKeyOf(job);
|
|
@@ -26,7 +28,7 @@ const testJobs = (mode, app, queued, scheduled) => ({
|
|
|
26
28
|
await runner.run({ ...job, attempts: 1 }); // one try, like inProcess(): reported, so the test sees it
|
|
27
29
|
else if (job.kind === "call")
|
|
28
30
|
scheduled.push(job);
|
|
29
|
-
else if (job.kind === "delivery")
|
|
31
|
+
else if (job.kind === "delivery" && !(job.unique && queued.some((q) => q.unique === job.unique)))
|
|
30
32
|
queued.push(job);
|
|
31
33
|
}
|
|
32
34
|
},
|