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/src/core/jobs.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { CaughtNestedFailure, describeIssues, isDomainError, StalePayload } from
|
|
|
2
2
|
import { isDue, parseSchedule } from "./schedule.ts";
|
|
3
3
|
import type {
|
|
4
4
|
ActionCtx,
|
|
5
|
+
AdapterSetup,
|
|
5
6
|
Call,
|
|
6
7
|
CallJob,
|
|
7
8
|
CronJob,
|
|
@@ -18,6 +19,7 @@ import type {
|
|
|
18
19
|
Jobs,
|
|
19
20
|
CronRun,
|
|
20
21
|
ListenerEvent,
|
|
22
|
+
LocalWorker,
|
|
21
23
|
RegisteredCron,
|
|
22
24
|
RegisteredFn,
|
|
23
25
|
RegisteredListener,
|
|
@@ -44,10 +46,12 @@ const canonical = (value: unknown): string =>
|
|
|
44
46
|
export const replaceKeyOf = (job: Job): string | undefined => (job.kind === "call" && job.replace ? `${job.fn}@${canonical(job.input)}` : undefined);
|
|
45
47
|
|
|
46
48
|
/**
|
|
47
|
-
*
|
|
48
|
-
* large input still fits an index and the function
|
|
49
|
+
* The key adapters that keep one waiting job per key (`replaces: true`) store: a delivery's `unique` as it is, a call's
|
|
50
|
+
* `replaceKeyOf` as `<function id>@<sha-256 of the input>`, so a large input still fits an index and the function
|
|
51
|
+
* stays readable. Undefined for every other job.
|
|
49
52
|
*/
|
|
50
|
-
export async function
|
|
53
|
+
export async function storedUniqueKey(job: Job): Promise<string | undefined> {
|
|
54
|
+
if (job.kind === "delivery") return job.unique;
|
|
51
55
|
if (job.kind !== "call" || !job.replace) return undefined;
|
|
52
56
|
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(canonical(job.input)));
|
|
53
57
|
return `${job.fn}@${Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("")}`;
|
|
@@ -84,6 +88,24 @@ export const defaultBackoff = (attempt: number) => Math.exp(Math.min(attempt, 10
|
|
|
84
88
|
/** Where the docs list each adapter and what it can do. */
|
|
85
89
|
export const ADAPTERS = "see Jobs, Adapters in the docs";
|
|
86
90
|
|
|
91
|
+
/** The loops running each adapter's jobs in this process (`work()`), by adapter: every registry on it shares them. */
|
|
92
|
+
const localWorkers = new WeakMap<JobsAdapter, Set<LocalWorker>>();
|
|
93
|
+
const workerSet = (adapter: JobsAdapter) => {
|
|
94
|
+
let set = localWorkers.get(adapter);
|
|
95
|
+
if (!set) localWorkers.set(adapter, (set = new Set()));
|
|
96
|
+
return set;
|
|
97
|
+
};
|
|
98
|
+
/** What an adapter's `connect` gets as `setup.workers`: does a loop here take this job, and wake them. */
|
|
99
|
+
export function workersOf(adapter: JobsAdapter): AdapterSetup["workers"] {
|
|
100
|
+
const set = workerSet(adapter);
|
|
101
|
+
return {
|
|
102
|
+
takes: (job) => [...set].some((w) => !w.queues || w.queues.includes(job.queue ?? "default")),
|
|
103
|
+
wake: (count) => {
|
|
104
|
+
for (const worker of set) worker.wake(count);
|
|
105
|
+
},
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
87
109
|
/** The minute `at` falls in, and its stamp for a job id: `20261123T0900Z` (no `:`, which BullMQ rejects). */
|
|
88
110
|
function minuteOf(at: Date, what: string) {
|
|
89
111
|
if (Number.isNaN(at.getTime())) throw new Error(`[logic-sdk] ${what} needs a valid date (got ${String(at)}).`);
|
|
@@ -100,6 +122,27 @@ export const deliveryOf = (l: RegisteredListener, e: Envelope): Delivery => ({
|
|
|
100
122
|
attempts: l.listener.attempts ?? 1,
|
|
101
123
|
});
|
|
102
124
|
|
|
125
|
+
/**
|
|
126
|
+
* A try that runs past its timeout: aborts its signal (its `ctx.signal`, and no new `ctx.run` starts) and fails the try,
|
|
127
|
+
* as Laravel's `$timeout` and Oban's `timeout/1` count it. JavaScript can't kill it, so what it still does is ignored.
|
|
128
|
+
*/
|
|
129
|
+
async function stopAfter<T>(work: Promise<T>, seconds: number, stop: AbortController, why: string): Promise<T> {
|
|
130
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
131
|
+
const timedOut = new Promise<never>((_, reject) => {
|
|
132
|
+
timer = setTimeout(() => {
|
|
133
|
+
const error = new Error(`[logic-sdk] ${why}`);
|
|
134
|
+
stop.abort(error);
|
|
135
|
+
reject(error);
|
|
136
|
+
}, seconds * 1000);
|
|
137
|
+
});
|
|
138
|
+
work.catch(() => {}); // it may still settle after the timeout: not this try's anymore
|
|
139
|
+
try {
|
|
140
|
+
return await Promise.race([work, timedOut]);
|
|
141
|
+
} finally {
|
|
142
|
+
clearTimeout(timer);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
103
146
|
/** What running jobs needs from the registry: its definitions, and how it runs a function or a listener's handler. */
|
|
104
147
|
export interface JobsDeps {
|
|
105
148
|
listeners: readonly RegisteredListener[];
|
|
@@ -112,13 +155,15 @@ export interface JobsDeps {
|
|
|
112
155
|
/** `jobs.failed`: where failed jobs are kept when the adapter keeps none. */
|
|
113
156
|
failedStore: FailedJobs | undefined;
|
|
114
157
|
maxEventDepth: number;
|
|
158
|
+
/** `jobs.queues`: the queues besides `"default"`. */
|
|
159
|
+
queues: readonly string[];
|
|
115
160
|
now(): Date;
|
|
116
161
|
wrap(call: Call, next: () => Promise<unknown>): Promise<unknown>;
|
|
117
162
|
report(error: unknown, info: FailureInfo): void;
|
|
118
163
|
/** Run a function as `scope`, like `registry.as(scope).run`. `eventDepth`: the chain's hops so far (a scheduled call's `depth`). */
|
|
119
164
|
runAs(fn: Fn, input: unknown, scope: object, eventDepth: number, queued: Job[] | undefined, job: { id: string; attempt: number }): Promise<unknown>;
|
|
120
|
-
/** The ctx a listener's or cron's handler gets, as `scope`, in an event chain `eventDepth` deep. */
|
|
121
|
-
handlerCtx(scope: object, eventDepth: number, id: string, queued: Job[] | undefined): ActionCtx<any>;
|
|
165
|
+
/** The ctx a listener's or cron's handler gets, as `scope`, in an event chain `eventDepth` deep. `stop`: its timeout. */
|
|
166
|
+
handlerCtx(scope: object, eventDepth: number, id: string, queued: Job[] | undefined, stop?: AbortSignal): ActionCtx<any>;
|
|
122
167
|
}
|
|
123
168
|
|
|
124
169
|
/**
|
|
@@ -126,12 +171,28 @@ export interface JobsDeps {
|
|
|
126
171
|
* calls into jobs, runs one (with its tries), and is what `registry.jobs` calls.
|
|
127
172
|
*/
|
|
128
173
|
export function makeJobs(deps: JobsDeps) {
|
|
129
|
-
const { listeners, crons, functions, idOf, jobsAdapter, database, jobScope, failedStore, maxEventDepth, now, wrap, report, runAs, handlerCtx } = deps;
|
|
130
|
-
// the adapter's own, or the store's: a job that failed for good is kept by whichever there is
|
|
131
|
-
const keepFailed = jobsAdapter.fail?.bind(jobsAdapter) ?? failedStore?.fail.bind(failedStore);
|
|
174
|
+
const { listeners, crons, functions, idOf, jobsAdapter, database, jobScope, failedStore, maxEventDepth, queues, now, wrap, report, runAs, handlerCtx } = deps;
|
|
132
175
|
/** Your adapter, as messages name it: by what it can't do, and by its own name. */
|
|
133
176
|
const yours = jobsAdapter.name ? `your jobs adapter, ${jobsAdapter.name},` : "your jobs adapter";
|
|
134
|
-
|
|
177
|
+
|
|
178
|
+
// ── queues ───────────────────────────────────────────────────────────────
|
|
179
|
+
for (const q of queues)
|
|
180
|
+
if (typeof q !== "string" || !q || q === "default") throw new Error(`[logic-sdk] jobs.queues takes names besides "default" (got ${JSON.stringify(q)}).`);
|
|
181
|
+
if (new Set(queues).size !== queues.length) throw new Error(`[logic-sdk] jobs.queues lists a queue twice: ${queues.join(", ")}.`);
|
|
182
|
+
const queueNames = ["default", ...queues];
|
|
183
|
+
if (queues.length && !jobsAdapter.queues)
|
|
184
|
+
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}).`);
|
|
185
|
+
if (typeof jobsAdapter.queues === "object")
|
|
186
|
+
for (const q of queueNames)
|
|
187
|
+
if (!jobsAdapter.queues.includes(q)) throw new Error(`[logic-sdk] ${yours} has no queue for "${q}": give it one (it has ${jobsAdapter.queues.join(", ") || "none"}).`);
|
|
188
|
+
/** A queue someone named: one of `jobs.queues`, or `"default"`. */
|
|
189
|
+
function checkQueue(what: string, queue: string | undefined) {
|
|
190
|
+
if (queue !== undefined && !queueNames.includes(queue))
|
|
191
|
+
throw new Error(`[logic-sdk] ${what} has queue ${JSON.stringify(queue)}, which jobs.queues doesn't declare (${queueNames.join(", ")}).`);
|
|
192
|
+
}
|
|
193
|
+
for (const l of listeners) checkQueue(l.id, l.listener.queue);
|
|
194
|
+
for (const c of crons) checkQueue(c.id, c.cron.queue);
|
|
195
|
+
if (failedStore && jobsAdapter.failed) throw new Error(`[logic-sdk] ${yours} keeps failed jobs itself, so jobs.failed has nothing to keep: drop it.`);
|
|
135
196
|
const enqueue = jobsAdapter.enqueue?.bind(jobsAdapter);
|
|
136
197
|
if (enqueue && crons.length && !database)
|
|
137
198
|
throw new Error(`[logic-sdk] Crons need \`database\` with ${yours}: their runs are written in a transaction of their own.`);
|
|
@@ -171,6 +232,13 @@ export function makeJobs(deps: JobsDeps) {
|
|
|
171
232
|
for (const l of listeners) if (l.listener.delay) checkHold(l.id, l.listener.delay);
|
|
172
233
|
for (const l of listeners) checkRetries(l.id, l.listener.attempts ?? 1);
|
|
173
234
|
for (const c of crons) checkRetries(c.id, c.cron.attempts ?? 1);
|
|
235
|
+
for (const l of listeners) {
|
|
236
|
+
if (l.listener.key && !jobsAdapter.orders)
|
|
237
|
+
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).`);
|
|
238
|
+
// nothing waits on an adapter that runs jobs at once, so there's nothing to drop
|
|
239
|
+
if (l.listener.unique && jobsAdapter.holds && !jobsAdapter.replaces)
|
|
240
|
+
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).`);
|
|
241
|
+
}
|
|
174
242
|
|
|
175
243
|
/**
|
|
176
244
|
* What a commit queues: one delivery per listener of each event that its `when` lets through, and the calls it
|
|
@@ -186,18 +254,39 @@ export function makeJobs(deps: JobsDeps) {
|
|
|
186
254
|
throw new Error(`[logic-sdk] ${l.id}'s when threw on ${e.name}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
187
255
|
}
|
|
188
256
|
};
|
|
257
|
+
/** Its `key` or `unique`, as `<listener id>@<value>`. A throw or an empty value is a bug in the app: it fails the mutation. */
|
|
258
|
+
const valueOf = (l: RegisteredListener, option: "key" | "unique", e: Envelope, payload: unknown) => {
|
|
259
|
+
const of = l.listener[option];
|
|
260
|
+
if (!of) return undefined;
|
|
261
|
+
let value: unknown;
|
|
262
|
+
try {
|
|
263
|
+
value = of(payload);
|
|
264
|
+
} catch (error) {
|
|
265
|
+
throw new Error(`[logic-sdk] ${l.id}'s ${option} threw on ${e.name}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
266
|
+
}
|
|
267
|
+
if (typeof value !== "string" || !value) throw new Error(`[logic-sdk] ${l.id}'s ${option} must return a non-empty string (got ${JSON.stringify(value)}) on ${e.name}.`);
|
|
268
|
+
return `${l.id}@${value}`;
|
|
269
|
+
};
|
|
189
270
|
const fits = (job: { depth: number }) => job.depth <= maxEventDepth;
|
|
190
271
|
const deepEvent = envelopes.find((e) => !fits(e));
|
|
191
272
|
const deepCall = calls.find((c) => !fits(c));
|
|
192
273
|
const loop = (what: string) => new Error(`[logic-sdk] chain of events and calls deeper than ${maxEventDepth} (jobs.maxEventDepth): stopped queueing ${what} (a loop?)`);
|
|
193
274
|
if (deepEvent) report(loop(deepEvent.name), { source: deepEvent.name });
|
|
194
275
|
else if (deepCall) report(loop(deepCall.fn), infoOf(deepCall));
|
|
276
|
+
const unique = new Set<string>();
|
|
195
277
|
const deliveries = envelopes.filter(fits).flatMap((e) =>
|
|
196
|
-
(byEvent.get(e.name) ?? []).filter((l) => wants(l, e, parsed.get(e))).
|
|
278
|
+
(byEvent.get(e.name) ?? []).filter((l) => wants(l, e, parsed.get(e))).flatMap((l): Delivery[] => {
|
|
197
279
|
const job = deliveryOf(l, e);
|
|
198
280
|
const delay = l.listener.delay;
|
|
199
281
|
if (delay) job.runAt = new Date(Date.parse(e.occurredAt) + delay * 1000).toISOString();
|
|
200
|
-
|
|
282
|
+
const key = valueOf(l, "key", e, parsed.get(e));
|
|
283
|
+
if (key) job.key = key;
|
|
284
|
+
if (l.listener.queue) job.queue = l.listener.queue;
|
|
285
|
+
job.unique = valueOf(l, "unique", e, parsed.get(e));
|
|
286
|
+
if (!job.unique) return [job];
|
|
287
|
+
if (unique.has(job.unique)) return []; // the same commit's first one waits; adapters drop later commits' ones
|
|
288
|
+
unique.add(job.unique);
|
|
289
|
+
return [job];
|
|
201
290
|
}),
|
|
202
291
|
);
|
|
203
292
|
return [...deliveries, ...calls.filter(fits)];
|
|
@@ -232,9 +321,13 @@ export function makeJobs(deps: JobsDeps) {
|
|
|
232
321
|
const info = infoOf(job, attempt);
|
|
233
322
|
// read before narrowing: a job queued by another version can have a kind this one doesn't know
|
|
234
323
|
const { id, kind }: { id: string; kind: string } = job;
|
|
324
|
+
/** Its definition's `failed`, once its last try failed: after it's kept, at most once. A throw is reported. */
|
|
325
|
+
let afterFailed: ((error: unknown) => Promise<unknown>) | undefined;
|
|
235
326
|
const failed = async (error: unknown) => {
|
|
236
327
|
report(error, { ...info, outcome: "failed" });
|
|
237
328
|
await fail?.(error);
|
|
329
|
+
if (afterFailed)
|
|
330
|
+
await afterFailed(error).catch((e) => report(e, { source: `${info.source} (failed)`, job, attempt }));
|
|
238
331
|
return "failed" as const;
|
|
239
332
|
};
|
|
240
333
|
/** One try of the job's `attempts`. */
|
|
@@ -268,10 +361,12 @@ export function makeJobs(deps: JobsDeps) {
|
|
|
268
361
|
if (job.kind === "cron") {
|
|
269
362
|
const c = cronById.get(job.cron);
|
|
270
363
|
if (!c) return missing("cron", job.cron);
|
|
364
|
+
const run: CronRun = { id: c.id, scheduledAt: job.scheduledAt, attempt };
|
|
365
|
+
const hook = c.cron.failed;
|
|
366
|
+
if (hook) afterFailed = (error) => hook({ ...handlerCtx(c.cron.scope, 0, c.id, queued), cron: run } as never, error); // SAFETY: as below
|
|
271
367
|
return attemptOnce(async () => {
|
|
272
368
|
// its scope comes from the code each time, never stored, so jobs.scope store and load don't apply
|
|
273
369
|
const { scope, meta, handler } = c.cron;
|
|
274
|
-
const run: CronRun = { id: c.id, scheduledAt: job.scheduledAt, attempt };
|
|
275
370
|
await wrap({ id: c.id, kind: "cron", job: { id: job.id, attempt }, meta, input: undefined, scope, depth: 0 }, () =>
|
|
276
371
|
handler({ ...handlerCtx(scope, 0, c.id, queued), cron: run } as never), // SAFETY: as for listeners: the ctx was built for a cron
|
|
277
372
|
);
|
|
@@ -292,10 +387,23 @@ export function makeJobs(deps: JobsDeps) {
|
|
|
292
387
|
const l = listenerById.get(job.listener);
|
|
293
388
|
if (!l) return missing("listener", job.listener);
|
|
294
389
|
const { envelope } = job;
|
|
390
|
+
const { timeout } = l.listener;
|
|
391
|
+
const stop = timeout ? new AbortController() : undefined;
|
|
392
|
+
const hook = l.listener.failed;
|
|
393
|
+
// 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
|
|
394
|
+
if (hook)
|
|
395
|
+
afterFailed = async (error) => {
|
|
396
|
+
if (error instanceof StalePayload) return;
|
|
397
|
+
const scope = jobScope?.load ? await jobScope.load(envelope.scope) : envelope.scope;
|
|
398
|
+
const r = await l.event.payload["~standard"].validate(envelope.payload);
|
|
399
|
+
if (!scope || r.issues || idOf(l.event) !== envelope.name) return;
|
|
400
|
+
const ctxEvent: ListenerEvent = { id: envelope.id, name: envelope.name, payload: r.value, occurredAt: envelope.occurredAt, attempt };
|
|
401
|
+
return hook({ ...handlerCtx(scope, envelope.depth, l.id, queued), event: ctxEvent } as never, r.value, error); // SAFETY: as the handler's
|
|
402
|
+
};
|
|
295
403
|
return attemptOnce(async () => {
|
|
296
404
|
const scope = await scopeOf(job, envelope.scope, attempt);
|
|
297
405
|
if (!scope) return "discarded";
|
|
298
|
-
|
|
406
|
+
const handled = wrap({ id: l.id, kind: "listener", job: { id: job.id, attempt }, meta: l.listener.meta, input: envelope.payload, scope, depth: 0 }, async () => {
|
|
299
407
|
// its listener's event now: one renamed without an `id`, or a listener moved to another event, leaves stale jobs
|
|
300
408
|
if (idOf(l.event) !== envelope.name)
|
|
301
409
|
throw new StalePayload(`[logic-sdk] ${l.id} now listens to ${idOf(l.event)}, and this job is for ${envelope.name}.`);
|
|
@@ -303,8 +411,9 @@ export function makeJobs(deps: JobsDeps) {
|
|
|
303
411
|
if (r.issues) throw new StalePayload(`[logic-sdk] ${envelope.name} payload no longer matches its schema: ${JSON.stringify(describeIssues(r.issues))}`);
|
|
304
412
|
const payload = r.value;
|
|
305
413
|
const ctxEvent: ListenerEvent = { id: envelope.id, name: envelope.name, payload, occurredAt: envelope.occurredAt, attempt };
|
|
306
|
-
return l.listener.handler({ ...handlerCtx(scope, envelope.depth, l.id, queued), event: ctxEvent } as never, payload); // SAFETY: as in registry.ts's invoke: the ctx was built for a listener
|
|
414
|
+
return l.listener.handler({ ...handlerCtx(scope, envelope.depth, l.id, queued, stop?.signal), event: ctxEvent } as never, payload); // SAFETY: as in registry.ts's invoke: the ctx was built for a listener
|
|
307
415
|
});
|
|
416
|
+
await (timeout && stop ? stopAfter(handled, timeout, stop, `${l.id} ran past its timeout of ${timeout}s, so this try was stopped.`) : handled);
|
|
308
417
|
return "done";
|
|
309
418
|
});
|
|
310
419
|
}
|
|
@@ -336,12 +445,23 @@ export function makeJobs(deps: JobsDeps) {
|
|
|
336
445
|
const { minute, stamp } = minuteOf(at, "tick");
|
|
337
446
|
return scheduled
|
|
338
447
|
.filter((c) => (only === undefined ? isDue(c.schedule, minute, c.cron.timezone) : c.id === only))
|
|
339
|
-
.map((c) => ({ kind: "cron", id: `${c.id}@${stamp}`, cron: c.id, scheduledAt: minute.toISOString(), attempts: c.cron.attempts ?? 1 }));
|
|
448
|
+
.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 } : {}) }));
|
|
340
449
|
}
|
|
341
450
|
|
|
342
451
|
const jobs: Jobs = {
|
|
343
|
-
|
|
344
|
-
|
|
452
|
+
async run(job, options) {
|
|
453
|
+
// a signal: the adapter's row says what runs, and records how it went
|
|
454
|
+
if (jobsAdapter.consume) {
|
|
455
|
+
const queued: Job[] = [];
|
|
456
|
+
await jobsAdapter.consume(job, runnerInto(queued)).catch((error) => {
|
|
457
|
+
report(error, { source: "(jobs adapter)", job }); // the consumer retries the message: nothing else hears of it
|
|
458
|
+
throw error;
|
|
459
|
+
});
|
|
460
|
+
await deliver(queued);
|
|
461
|
+
return "done";
|
|
462
|
+
}
|
|
463
|
+
return runJob(job, { attempt: options?.attempt, fail: failedStore && ((error) => failedStore.fail(job, error)) });
|
|
464
|
+
},
|
|
345
465
|
async tick(at = now()) {
|
|
346
466
|
const jobs = due(at);
|
|
347
467
|
if (!jobs.length) return [];
|
|
@@ -350,11 +470,18 @@ export function makeJobs(deps: JobsDeps) {
|
|
|
350
470
|
return jobs.map((job) => job.cron);
|
|
351
471
|
},
|
|
352
472
|
async sweep(options) {
|
|
473
|
+
for (const q of options?.queues ?? []) checkQueue("jobs.sweep({ queues })", q);
|
|
353
474
|
const queued: Job[] = [];
|
|
354
475
|
const result = (await jobsAdapter.sweep?.(runnerInto(queued), options)) ?? { done: 0, failed: 0, discarded: 0, retrying: 0 };
|
|
355
476
|
await deliver(queued);
|
|
356
477
|
return result;
|
|
357
478
|
},
|
|
479
|
+
attach(worker) {
|
|
480
|
+
for (const q of worker.queues ?? []) checkQueue("A worker", q);
|
|
481
|
+
const set = workerSet(jobsAdapter);
|
|
482
|
+
set.add(worker);
|
|
483
|
+
return () => void set.delete(worker);
|
|
484
|
+
},
|
|
358
485
|
async retry(id) {
|
|
359
486
|
if (jobsAdapter.retry) return jobsAdapter.retry(id);
|
|
360
487
|
if (!failedStore) throw new Error(`[logic-sdk] ${yours} keeps no failed jobs, so there's nothing to retry (${id}). Use one that keeps them, or jobs.failed (${ADAPTERS}).`);
|
|
@@ -408,7 +535,7 @@ export function makeJobs(deps: JobsDeps) {
|
|
|
408
535
|
: "[logic-sdk] jobs.invoke got a cron that isn't registered: export it from its module.",
|
|
409
536
|
);
|
|
410
537
|
const { minute, stamp } = minuteOf(options.at ?? now(), "jobs.invoke({ at })");
|
|
411
|
-
const job: CronJob = { kind: "cron", id: `${c.id}@${stamp}-${crypto.randomUUID()}`, cron: c.id, scheduledAt: minute.toISOString(), attempts: c.cron.attempts ?? 1 };
|
|
538
|
+
const job: CronJob = { 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 } : {}) };
|
|
412
539
|
await enqueueAlone([job]);
|
|
413
540
|
const queued: Job[] = [];
|
|
414
541
|
await jobsAdapter.deliver([job], runnerInto(queued)); // unlike a tick, a hand-off that fails throws: whoever invoked it needs to know
|
|
@@ -417,5 +544,5 @@ export function makeJobs(deps: JobsDeps) {
|
|
|
417
544
|
},
|
|
418
545
|
};
|
|
419
546
|
|
|
420
|
-
return { toJobs, deliver, jobs, due, checkHold, checkRetries, yours };
|
|
547
|
+
return { toJobs, deliver, jobs, due, checkHold, checkRetries, checkQueue, yours };
|
|
421
548
|
}
|
package/src/core/registry.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { CaughtNestedFailure, describeIssues, DomainError, errorsFor, forbiddenOf, moduleOf, PRIVATE } from "./errors.ts";
|
|
2
2
|
import { inProcess, runsNow } from "./in-process.ts";
|
|
3
|
-
import { ADAPTERS, isPlainObject, makeJobs, replaceKeyOf } from "./jobs.ts";
|
|
3
|
+
import { ADAPTERS, isPlainObject, makeJobs, replaceKeyOf, workersOf } from "./jobs.ts";
|
|
4
4
|
import { assertTimeZone, parseSchedule } from "./schedule.ts";
|
|
5
5
|
import { BRAND, INTERNAL } from "./types.ts";
|
|
6
6
|
import type {
|
|
@@ -105,12 +105,12 @@ export function init<C extends Config & OnlyKnownKeys<C>>() {
|
|
|
105
105
|
* `cron({ schedule: "0 9 * * MON", scope: { kind: "system", job: "reports.weekly" }, async handler(ctx) { await ctx.run(send) } })`.
|
|
106
106
|
*/
|
|
107
107
|
cron: <const Sc extends ScopeOf<C>>(def: CronDef<C, Sc>): Cron<C> => {
|
|
108
|
-
const { id, schedule, timezone, scope, attempts, meta, handler } = def;
|
|
108
|
+
const { id, schedule, timezone, scope, attempts, queue, meta, handler, failed } = def;
|
|
109
109
|
parseSchedule(schedule);
|
|
110
110
|
if (timezone !== undefined) assertTimeZone(timezone);
|
|
111
111
|
checkAttempts("cron", attempts);
|
|
112
112
|
// meta is checked against ListenerMetaOf<C> above and stored loose, like a listener's, for wrap and adapters
|
|
113
|
-
return Object.freeze({ [BRAND]: "cron" as const, kind: "cron" as const, id, schedule, timezone, scope, attempts, meta: meta as Cron["meta"], handler });
|
|
113
|
+
return Object.freeze({ [BRAND]: "cron" as const, kind: "cron" as const, id, schedule, timezone, scope, attempts, queue, meta: meta as Cron["meta"], handler, failed });
|
|
114
114
|
},
|
|
115
115
|
/**
|
|
116
116
|
* React to an event after commit, like an action. Must be idempotent.
|
|
@@ -126,7 +126,7 @@ export function init<C extends Config & OnlyKnownKeys<C>>() {
|
|
|
126
126
|
event: () => EventDef<unknown, O>;
|
|
127
127
|
/**
|
|
128
128
|
* Tries in total, the first included, like Laravel's `$tries`. Default 1: a retry repeats side effects, so opt in.
|
|
129
|
-
* Once they're used, the job is `failed` (kept by `databaseQueue
|
|
129
|
+
* Once they're used, the job is `failed` (kept by `databaseQueue` and `outbox`, retried with `registry.jobs.retry(id)`).
|
|
130
130
|
*/
|
|
131
131
|
attempts?: number;
|
|
132
132
|
/** Seconds after the event before the first try. Needs an adapter that holds jobs: `inProcess()` is refused. */
|
|
@@ -138,15 +138,51 @@ export function init<C extends Config & OnlyKnownKeys<C>>() {
|
|
|
138
138
|
* mutation, as a bad payload does.
|
|
139
139
|
*/
|
|
140
140
|
when?: (payload: O) => boolean;
|
|
141
|
+
/**
|
|
142
|
+
* Jobs with the same key run one at a time, in the order their events were emitted, like Laravel's message groups
|
|
143
|
+
* on SQS FIFO: `key: (m) => m.conversationId`. Waiting spends no attempt; a try backing off holds the key, a job
|
|
144
|
+
* that failed for good frees it. Per listener. Needs an adapter that runs a key's jobs in order: others are refused.
|
|
145
|
+
* Inside its handler, run functions with `ctx.run`: calling the registry directly for the same key waits on itself.
|
|
146
|
+
*/
|
|
147
|
+
key?: (payload: O) => string;
|
|
148
|
+
/**
|
|
149
|
+
* While a job with the same value hasn't started, later ones are dropped, like Laravel's
|
|
150
|
+
* `ShouldBeUniqueUntilProcessing`: `unique: (p) => p.productId`. **It drops events, so the handler must read
|
|
151
|
+
* current state, never the payload's data**: for "X changed, recompute X". Once the job starts, the next event
|
|
152
|
+
* queues a new one.
|
|
153
|
+
*/
|
|
154
|
+
unique?: (payload: O) => string;
|
|
155
|
+
/**
|
|
156
|
+
* Seconds a try may run, like Laravel's `$timeout`. Past it, `ctx.signal` aborts, no new `ctx.run` starts, and
|
|
157
|
+
* the try counts as failed (retried while `attempts` are left). JavaScript can't stop code mid-flight: a mutation
|
|
158
|
+
* already running still commits.
|
|
159
|
+
*/
|
|
160
|
+
timeout?: number;
|
|
161
|
+
/**
|
|
162
|
+
* Its queue, one of `jobs.queues`: `queue: "mail"`. Default `"default"`. A worker takes its queues in the order it
|
|
163
|
+
* lists them: `work(registry, { queues: ["mail", "default"] })`.
|
|
164
|
+
*/
|
|
165
|
+
queue?: string;
|
|
141
166
|
meta?: ListenerMetaOf<C>;
|
|
142
167
|
handler: (ctx: ListenerCtx<C, O>, payload: O) => Promise<unknown>;
|
|
168
|
+
/**
|
|
169
|
+
* Runs once its last try has failed, with the handler's ctx and payload, and the error: undo or flag what the
|
|
170
|
+
* handler started (`await ctx.run(orders.flagReceipt, { orderId })`). Not in a transaction: run mutations. At most
|
|
171
|
+
* once (a crash right after the failure skips it), and not for a job that can't run anymore (its payload or event
|
|
172
|
+
* changed, or `scope.load` returned null). A throw is reported to `onError`; the job stays failed.
|
|
173
|
+
*/
|
|
174
|
+
failed?: (ctx: ListenerCtx<C, O>, payload: O, error: unknown) => Promise<unknown>;
|
|
143
175
|
}): Listener<O, C> => {
|
|
144
|
-
const { id, event, attempts, delay, when, meta, handler } = def;
|
|
176
|
+
const { id, event, attempts, delay, when, key, unique, timeout, queue, meta, handler, failed } = def;
|
|
145
177
|
checkAttempts("listener", attempts);
|
|
146
178
|
if (delay !== undefined && !(Number.isFinite(delay) && delay >= 0))
|
|
147
179
|
throw new Error(`[logic-sdk] listener delay must be seconds, 0 or more (got ${delay}).`);
|
|
180
|
+
if (timeout !== undefined && !(Number.isFinite(timeout) && timeout > 0))
|
|
181
|
+
throw new Error(`[logic-sdk] listener timeout must be seconds, more than 0 (got ${timeout}).`);
|
|
182
|
+
// two jobs of one key with different values would be inserted in `unique` order (the lock order), not emit order
|
|
183
|
+
if (key && unique) throw new Error("[logic-sdk] a listener takes key or unique, not both: key runs every job in order, unique drops the ones waiting.");
|
|
148
184
|
// meta is checked against ListenerMetaOf<C> above and stored loose, like Fn.meta, for wrap and adapters
|
|
149
|
-
return Object.freeze({ [BRAND]: "listener" as const, kind: "listener" as const, id, event, attempts, delay, when, meta: meta as Listener["meta"], handler });
|
|
185
|
+
return Object.freeze({ [BRAND]: "listener" as const, kind: "listener" as const, id, event, attempts, delay, when, key, unique, timeout, queue, meta: meta as Listener["meta"], handler, failed });
|
|
150
186
|
},
|
|
151
187
|
};
|
|
152
188
|
}
|
|
@@ -154,8 +190,8 @@ export function init<C extends Config & OnlyKnownKeys<C>>() {
|
|
|
154
190
|
/** `cron({...})`: its handler's `ctx.scope` is the scope it declares, so a policy-free read of it is typed. */
|
|
155
191
|
type CronDef<C extends Config, Sc> = {
|
|
156
192
|
/**
|
|
157
|
-
* Stable id, local to its module, like every definer's. Defaults to the export name. Jobs
|
|
158
|
-
*
|
|
193
|
+
* Stable id, local to its module, like every definer's. Defaults to the export name. Jobs store it, so set it before you
|
|
194
|
+
* rename the export.
|
|
159
195
|
*/
|
|
160
196
|
id?: string;
|
|
161
197
|
/** Five fields: minute hour day-of-month month day-of-week. `"*\/15 * * * *"`, `"0 9 * * MON"`. */
|
|
@@ -166,9 +202,13 @@ type CronDef<C extends Config, Sc> = {
|
|
|
166
202
|
scope: Sc;
|
|
167
203
|
/** Tries in total, like a listener's. Default 1: a retry runs the whole handler again. */
|
|
168
204
|
attempts?: number;
|
|
205
|
+
/** Its queue, one of `jobs.queues`, like a listener's. Default `"default"`. */
|
|
206
|
+
queue?: string;
|
|
169
207
|
meta?: ListenerMetaOf<C>;
|
|
170
208
|
/** The work, like a listener's handler: an action's ctx, plus `ctx.cron` (`scheduledAt`, `attempt`). */
|
|
171
209
|
handler: (ctx: CronCtx<C, Sc>) => Promise<unknown>;
|
|
210
|
+
/** Runs once its last try has failed, like a listener's `failed`: the handler's ctx, and the error. */
|
|
211
|
+
failed?: (ctx: CronCtx<C, Sc>, error: unknown) => Promise<unknown>;
|
|
172
212
|
};
|
|
173
213
|
|
|
174
214
|
/** How deep `ctx.run` calls may nest. Past it, a function is running itself without end. */
|
|
@@ -206,6 +246,8 @@ interface Frame {
|
|
|
206
246
|
signal?: AbortSignal;
|
|
207
247
|
/** Passed to this very call: checked before it starts. */
|
|
208
248
|
abortOn?: AbortSignal;
|
|
249
|
+
/** A listener's `timeout`: once it's aborted, no call from here starts. */
|
|
250
|
+
stop?: AbortSignal;
|
|
209
251
|
/** Hops in the chain of events and calls due now that led here: 0 for a call from outside. */
|
|
210
252
|
eventDepth: number;
|
|
211
253
|
/** Inside a job: where the jobs it queues wait until it's settled. */
|
|
@@ -373,8 +415,9 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
|
|
|
373
415
|
`[logic-sdk] ${adapter.name ?? "Your jobs adapter"} writes in your mutation's transaction with SQL, so it needs ` +
|
|
374
416
|
"createRegistry({ database: { adapter } }) with an adapter that runs SQL (`query`). See Adapters, Other ORMs in the docs.",
|
|
375
417
|
);
|
|
376
|
-
|
|
377
|
-
|
|
418
|
+
const setup = { sql, workers: workersOf(jobsAdapter) };
|
|
419
|
+
jobsAdapter.connect?.(setup);
|
|
420
|
+
failedStore?.connect?.(setup);
|
|
378
421
|
|
|
379
422
|
const idOf = (x: object) => {
|
|
380
423
|
const id = ids.get(x);
|
|
@@ -440,7 +483,7 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
|
|
|
440
483
|
// a copy: changing it can't change what's delivered
|
|
441
484
|
return Object.freeze({ id: envelope.id, name: envelope.name, payload: structuredClone(envelope.payload) as typeof payload, occurredAt: envelope.occurredAt });
|
|
442
485
|
},
|
|
443
|
-
schedule: (fn, input, { at, delay, attempts = 1, replace, scope }) => {
|
|
486
|
+
schedule: (fn, input, { at, delay, attempts = 1, replace, scope, queue }) => {
|
|
444
487
|
const fnId = ids.get(fn);
|
|
445
488
|
if (!fnId)
|
|
446
489
|
throw new Error(
|
|
@@ -452,6 +495,7 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
|
|
|
452
495
|
throw new Error(`[logic-sdk] ctx.schedule(${fnId}) needs an \`at\` date or a \`delay\` in seconds, 0 or more.`);
|
|
453
496
|
checkAttempts(`ctx.schedule(${fnId})`, attempts);
|
|
454
497
|
checkRetries(`ctx.schedule(${fnId})`, attempts);
|
|
498
|
+
checkQueue(`ctx.schedule(${fnId})`, queue);
|
|
455
499
|
if (replace !== undefined) {
|
|
456
500
|
if (!jobsAdapter.replaces)
|
|
457
501
|
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}).`);
|
|
@@ -470,6 +514,7 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
|
|
|
470
514
|
depth: waits ? 0 : frame.eventDepth + 1, // due now, it's the next hop of this chain; a real wait starts a new one
|
|
471
515
|
};
|
|
472
516
|
if (waits) job.runAt = new Date(now().getTime() + seconds * 1000).toISOString();
|
|
517
|
+
if (queue) job.queue = queue;
|
|
473
518
|
if (replace) {
|
|
474
519
|
job.replace = true;
|
|
475
520
|
// scheduled twice in this transaction: the later one wins here too (the dropped one's input is still checked:
|
|
@@ -503,7 +548,7 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
|
|
|
503
548
|
services,
|
|
504
549
|
});
|
|
505
550
|
|
|
506
|
-
const { toJobs, deliver, jobs, due, checkHold, checkRetries, yours } = makeJobs({
|
|
551
|
+
const { toJobs, deliver, jobs, due, checkHold, checkRetries, checkQueue, yours } = makeJobs({
|
|
507
552
|
listeners,
|
|
508
553
|
crons,
|
|
509
554
|
functions,
|
|
@@ -513,11 +558,12 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
|
|
|
513
558
|
jobScope,
|
|
514
559
|
failedStore,
|
|
515
560
|
maxEventDepth,
|
|
561
|
+
queues: options.jobs?.queues ?? [],
|
|
516
562
|
now,
|
|
517
563
|
wrap,
|
|
518
564
|
report,
|
|
519
565
|
runAs: (fn, input, scope, eventDepth, queued, job) => invoke(fn, input, enter({ scope, trail: [], eventDepth, queued, job }, undefined), ["query", "mutation", "action"]),
|
|
520
|
-
handlerCtx: (scope, eventDepth, id, queued) => actionCtx({ scope, trail: [id], eventDepth, queued }, id),
|
|
566
|
+
handlerCtx: (scope, eventDepth, id, queued, stop) => actionCtx({ scope, trail: [id], eventDepth, queued, signal: stop, stop }, id),
|
|
521
567
|
});
|
|
522
568
|
|
|
523
569
|
// ── invoke ───────────────────────────────────────────────────────────────
|
|
@@ -542,6 +588,7 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
|
|
|
542
588
|
/** Authorize, then validate, before any transaction opens: denied or bad calls never touch the database. */
|
|
543
589
|
const prepare = async () => {
|
|
544
590
|
frame.abortOn?.throwIfAborted();
|
|
591
|
+
frame.stop?.throwIfAborted();
|
|
545
592
|
if (fn.authorize) {
|
|
546
593
|
// SAFETY: the registry erases each policy's scope type; the caller's scope is the app's Scope by construction
|
|
547
594
|
if (fn.authorize(frame.scope as never) !== true) throw new DomainError("forbidden", forbiddenOf(id));
|
|
@@ -583,7 +630,8 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
|
|
|
583
630
|
const committed = await commitWithRetries(database, frame, id, (tx) => execute(input, mutationCtx({ ...frame, tx }, tx, id)));
|
|
584
631
|
|
|
585
632
|
// committed. Nothing below may fail the caller.
|
|
586
|
-
|
|
633
|
+
// a try past its timeout is settled already: what it still commits is delivered now, not after it
|
|
634
|
+
await afterCommit(committed.events, committed.jobs, frame.stop?.aborted ? undefined : frame.queued);
|
|
587
635
|
return committed.out;
|
|
588
636
|
});
|
|
589
637
|
}
|
package/src/core/testing.ts
CHANGED
|
@@ -15,6 +15,7 @@ import {
|
|
|
15
15
|
type Listener,
|
|
16
16
|
type Registry,
|
|
17
17
|
} from "./types.ts";
|
|
18
|
+
import { inProcess } from "./in-process.ts";
|
|
18
19
|
import { deliveryOf, replaceKeyOf } from "./jobs.ts";
|
|
19
20
|
import { INTERNAL } from "./types.ts";
|
|
20
21
|
|
|
@@ -99,6 +100,7 @@ const testJobs = (mode: TestOptions["jobs"], app: JobsAdapter | undefined, queue
|
|
|
99
100
|
holds: app?.holds,
|
|
100
101
|
replaces: app?.replaces,
|
|
101
102
|
retries: app?.retries,
|
|
103
|
+
orders: (app ?? inProcess()).orders, // inline, jobs run one by one: in order
|
|
102
104
|
async deliver(jobs, runner) {
|
|
103
105
|
for (const job of jobs) {
|
|
104
106
|
const key = replaceKeyOf(job);
|
|
@@ -109,7 +111,7 @@ const testJobs = (mode: TestOptions["jobs"], app: JobsAdapter | undefined, queue
|
|
|
109
111
|
const waits = job.runAt !== undefined || (mode === "manual" && job.kind !== "cron");
|
|
110
112
|
if (!waits) await runner.run({ ...job, attempts: 1 }); // one try, like inProcess(): reported, so the test sees it
|
|
111
113
|
else if (job.kind === "call") scheduled.push(job);
|
|
112
|
-
else if (job.kind === "delivery") queued.push(job);
|
|
114
|
+
else if (job.kind === "delivery" && !(job.unique && queued.some((q) => q.unique === job.unique))) queued.push(job);
|
|
113
115
|
}
|
|
114
116
|
},
|
|
115
117
|
});
|