logic-sdk 0.7.1 → 0.7.2
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 +7 -7
- package/dist/adapters/cloudflare-queue.d.ts +14 -0
- package/dist/adapters/cloudflare-queue.js +48 -0
- package/dist/adapters/drizzle-pg.d.ts +250 -0
- package/dist/adapters/drizzle-pg.js +69 -0
- package/dist/adapters/drizzle-sqlite.d.ts +257 -0
- package/dist/adapters/drizzle-sqlite.js +196 -0
- package/dist/adapters/pg-boss.d.ts +45 -0
- package/dist/adapters/pg-boss.js +180 -0
- package/dist/adapters/postgres.d.ts +32 -0
- package/dist/adapters/postgres.js +105 -0
- package/dist/adapters/sqlite.d.ts +13 -0
- package/dist/adapters/sqlite.js +88 -0
- package/dist/{stored-jobs.d.ts → adapters/stored-jobs.d.ts} +27 -10
- package/dist/{stored-jobs.js → adapters/stored-jobs.js} +106 -20
- package/dist/ai.d.ts +1 -32
- package/dist/ai.js +1 -40
- package/dist/cloudflare.d.ts +2 -55
- package/dist/cloudflare.js +2 -85
- package/dist/core/in-process.d.ts +9 -0
- package/dist/core/in-process.js +17 -0
- package/dist/{jobs.d.ts → core/jobs.d.ts} +23 -10
- package/dist/{jobs.js → core/jobs.js} +152 -39
- package/dist/core/registry.d.ts +120 -0
- package/dist/core/registry.js +503 -0
- package/dist/core/testing.d.ts +75 -0
- package/dist/core/testing.js +230 -0
- package/dist/{types.d.ts → core/types.d.ts} +203 -40
- package/dist/drizzle/pg.d.ts +3 -236
- package/dist/drizzle/pg.js +2 -67
- package/dist/drizzle/sqlite.d.ts +3 -242
- package/dist/drizzle/sqlite.js +2 -194
- package/dist/fetch.d.ts +1 -19
- package/dist/fetch.js +1 -30
- package/dist/hosts/cloudflare.d.ts +42 -0
- package/dist/hosts/cloudflare.js +39 -0
- package/dist/hosts/node.d.ts +26 -0
- package/dist/hosts/node.js +76 -0
- package/dist/hosts/pg-boss.d.ts +22 -0
- package/dist/hosts/pg-boss.js +55 -0
- package/dist/index.d.ts +5 -122
- package/dist/index.js +4 -492
- package/dist/integrations/ai.d.ts +32 -0
- package/dist/integrations/ai.js +40 -0
- package/dist/integrations/fetch.d.ts +19 -0
- package/dist/integrations/fetch.js +30 -0
- package/dist/integrations/orpc.d.ts +22 -0
- package/dist/integrations/orpc.js +37 -0
- package/dist/node.d.ts +1 -26
- package/dist/node.js +1 -76
- package/dist/orpc.d.ts +1 -21
- package/dist/orpc.js +1 -37
- package/dist/pg-boss.d.ts +2 -53
- package/dist/pg-boss.js +2 -213
- package/dist/postgres.d.ts +2 -28
- package/dist/postgres.js +1 -82
- package/dist/sqlite.d.ts +2 -9
- package/dist/sqlite.js +1 -65
- package/dist/testing.d.ts +1 -75
- package/dist/testing.js +1 -227
- package/package.json +2 -2
- package/skills/logic-sdk/SKILL.md +4 -3
- package/src/adapters/cloudflare-queue.ts +56 -0
- package/src/adapters/drizzle-pg.ts +108 -0
- package/src/adapters/drizzle-sqlite.ts +234 -0
- package/src/adapters/pg-boss.ts +195 -0
- package/src/adapters/postgres.ts +112 -0
- package/src/adapters/sqlite.ts +96 -0
- package/src/{stored-jobs.ts → adapters/stored-jobs.ts} +133 -30
- package/src/ai.ts +1 -62
- package/src/cloudflare.ts +2 -107
- package/src/core/in-process.ts +18 -0
- package/src/{jobs.ts → core/jobs.ts} +152 -38
- package/src/core/registry.ts +671 -0
- package/src/core/testing.ts +307 -0
- package/src/{types.ts → core/types.ts} +197 -40
- package/src/drizzle/pg.ts +3 -110
- package/src/drizzle/sqlite.ts +3 -236
- package/src/fetch.ts +1 -31
- package/src/hosts/cloudflare.ts +54 -0
- package/src/hosts/node.ts +99 -0
- package/src/hosts/pg-boss.ts +71 -0
- package/src/index.ts +15 -652
- package/src/integrations/ai.ts +63 -0
- package/src/integrations/fetch.ts +31 -0
- package/src/integrations/orpc.ts +47 -0
- package/src/node.ts +1 -99
- package/src/orpc.ts +1 -46
- package/src/pg-boss.ts +2 -241
- package/src/postgres.ts +2 -90
- package/src/sqlite.ts +2 -74
- package/src/testing.ts +1 -305
- /package/dist/{errors.d.ts → core/errors.d.ts} +0 -0
- /package/dist/{errors.js → core/errors.js} +0 -0
- /package/dist/{schedule.d.ts → core/schedule.d.ts} +0 -0
- /package/dist/{schedule.js → core/schedule.js} +0 -0
- /package/dist/{types.js → core/types.js} +0 -0
- /package/src/{errors.ts → core/errors.ts} +0 -0
- /package/src/{schedule.ts → core/schedule.ts} +0 -0
|
@@ -7,10 +7,10 @@ import type {
|
|
|
7
7
|
CronJob,
|
|
8
8
|
DatabaseAdapter,
|
|
9
9
|
Delivery,
|
|
10
|
+
FailedJobs,
|
|
10
11
|
Envelope,
|
|
11
12
|
FailureInfo,
|
|
12
13
|
Fn,
|
|
13
|
-
InProcess,
|
|
14
14
|
Job,
|
|
15
15
|
JobOutcome,
|
|
16
16
|
JobsAdapter,
|
|
@@ -23,29 +23,73 @@ import type {
|
|
|
23
23
|
RegisteredListener,
|
|
24
24
|
RunJobOptions,
|
|
25
25
|
Runner,
|
|
26
|
+
ScopeMatch,
|
|
26
27
|
} from "./types.ts";
|
|
27
|
-
import { RUNS_NOW } from "./types.ts";
|
|
28
28
|
|
|
29
|
-
const
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
29
|
+
export const isPlainObject = (v: unknown): v is Record<string, unknown> =>
|
|
30
|
+
!!v && typeof v === "object" && (Object.getPrototypeOf(v) === Object.prototype || Object.getPrototypeOf(v) === null);
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* JSON with object keys sorted, so `{ a, b }` and `{ b, a }` are one input, like TanStack Query's `hashKey`. Undefined
|
|
34
|
+
* properties drop out, as in JSON; array order counts. The input as passed, before its schema runs (defaults aren't
|
|
35
|
+
* applied), so a schema change doesn't move what's waiting.
|
|
36
|
+
*/
|
|
37
|
+
const canonical = (value: unknown): string =>
|
|
38
|
+
JSON.stringify(value, (_, v) => (isPlainObject(v) ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, v[k]])) : v)) ?? "";
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* What makes a scheduled call with `replace: true` replaceable: its function and its input, `<function id>@<input>`. A
|
|
42
|
+
* newer call with the same one replaces it while it waits. Undefined for every other job.
|
|
43
|
+
*/
|
|
44
|
+
export const replaceKeyOf = (job: Job): string | undefined => (job.kind === "call" && job.replace ? `${job.fn}@${canonical(job.input)}` : undefined);
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* `replaceKeyOf`, as adapters that replace (`replaces: true`) store it: `<function id>@<sha-256 of the input>`, so a
|
|
48
|
+
* large input still fits an index and the function stays readable.
|
|
49
|
+
*/
|
|
50
|
+
export async function storedReplaceKey(job: Job): Promise<string | undefined> {
|
|
51
|
+
if (job.kind !== "call" || !job.replace) return undefined;
|
|
52
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(canonical(job.input)));
|
|
53
|
+
return `${job.fn}@${Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("")}`;
|
|
54
|
+
}
|
|
55
|
+
|
|
36
56
|
/**
|
|
37
|
-
*
|
|
38
|
-
*
|
|
57
|
+
* A `failed({ scope })` filter as the fields it matches: `{ organization: { id: "o1" } }` is `organization.id = "o1"`.
|
|
58
|
+
* Strings, numbers, booleans and null; never an array or an empty object, which two databases would read differently.
|
|
39
59
|
*/
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
60
|
+
function scopeMatches(filter: unknown): ScopeMatch[] {
|
|
61
|
+
const out: ScopeMatch[] = [];
|
|
62
|
+
const walk = (value: unknown, path: string[]) => {
|
|
63
|
+
if (value === null || typeof value === "string" || typeof value === "boolean" || (typeof value === "number" && Number.isFinite(value))) {
|
|
64
|
+
out.push({ path, value });
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
const where = path.length ? path.join(".") : "scope";
|
|
68
|
+
if (!isPlainObject(value))
|
|
69
|
+
throw new Error(`[logic-sdk] jobs.failed({ scope }) matches strings, numbers, booleans and null: ${where} is ${Array.isArray(value) ? "an array" : typeof value}.`);
|
|
70
|
+
const keys = Object.keys(value).filter((k) => value[k] !== undefined);
|
|
71
|
+
if (!keys.length) throw new Error(`[logic-sdk] jobs.failed({ scope }) matches fields: ${where} is an empty object.`);
|
|
72
|
+
for (const k of keys) walk(value[k], [...path, k]);
|
|
73
|
+
};
|
|
74
|
+
walk(filter, []);
|
|
75
|
+
return out;
|
|
76
|
+
}
|
|
43
77
|
|
|
44
78
|
/**
|
|
45
|
-
*
|
|
46
|
-
*
|
|
79
|
+
* Seconds to wait after a failed try: e^attempt, capped at e^10 (about 6 hours), the curve Graphile Worker uses. The
|
|
80
|
+
* core's, so every adapter that backs off (the jobs table, Cloudflare's redelivery) waits the same.
|
|
47
81
|
*/
|
|
48
|
-
export const
|
|
82
|
+
export const defaultBackoff = (attempt: number) => Math.exp(Math.min(attempt, 10));
|
|
83
|
+
|
|
84
|
+
/** Where the docs list each adapter and what it can do. */
|
|
85
|
+
export const ADAPTERS = "see Jobs, Adapters in the docs";
|
|
86
|
+
|
|
87
|
+
/** The minute `at` falls in, and its stamp for a job id: `20261123T0900Z` (no `:`, which BullMQ rejects). */
|
|
88
|
+
function minuteOf(at: Date, what: string) {
|
|
89
|
+
if (Number.isNaN(at.getTime())) throw new Error(`[logic-sdk] ${what} needs a valid date (got ${String(at)}).`);
|
|
90
|
+
const minute = new Date(Math.floor(at.getTime() / 60_000) * 60_000);
|
|
91
|
+
return { minute, stamp: minute.toISOString().slice(0, 16).replaceAll(/[-:]/g, "") + "Z" };
|
|
92
|
+
}
|
|
49
93
|
|
|
50
94
|
/** One listener's share of an event, as a job: `<listener id>@<event id>`, with the listener's tries. */
|
|
51
95
|
export const deliveryOf = (l: RegisteredListener, e: Envelope): Delivery => ({
|
|
@@ -65,12 +109,14 @@ export interface JobsDeps {
|
|
|
65
109
|
jobsAdapter: JobsAdapter;
|
|
66
110
|
database: DatabaseAdapter<unknown, unknown> | undefined;
|
|
67
111
|
jobScope: JobScope | undefined;
|
|
112
|
+
/** `jobs.failed`: where failed jobs are kept when the adapter keeps none. */
|
|
113
|
+
failedStore: FailedJobs | undefined;
|
|
68
114
|
maxEventDepth: number;
|
|
69
115
|
now(): Date;
|
|
70
116
|
wrap(call: Call, next: () => Promise<unknown>): Promise<unknown>;
|
|
71
117
|
report(error: unknown, info: FailureInfo): void;
|
|
72
118
|
/** Run a function as `scope`, like `registry.as(scope).run`. `eventDepth`: the chain's hops so far (a scheduled call's `depth`). */
|
|
73
|
-
runAs(fn: Fn, input: unknown, scope: object, eventDepth: number, queued: Job[] | undefined): Promise<unknown>;
|
|
119
|
+
runAs(fn: Fn, input: unknown, scope: object, eventDepth: number, queued: Job[] | undefined, job: { id: string; attempt: number }): Promise<unknown>;
|
|
74
120
|
/** The ctx a listener's or cron's handler gets, as `scope`, in an event chain `eventDepth` deep. */
|
|
75
121
|
handlerCtx(scope: object, eventDepth: number, id: string, queued: Job[] | undefined): ActionCtx<any>;
|
|
76
122
|
}
|
|
@@ -80,9 +126,19 @@ export interface JobsDeps {
|
|
|
80
126
|
* calls into jobs, runs one (with its tries), and is what `registry.jobs` calls.
|
|
81
127
|
*/
|
|
82
128
|
export function makeJobs(deps: JobsDeps) {
|
|
83
|
-
const { listeners, crons, functions, idOf, jobsAdapter, database, jobScope, maxEventDepth, now, wrap, report, runAs, handlerCtx } = deps;
|
|
84
|
-
|
|
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);
|
|
132
|
+
/** Your adapter, as messages name it: by what it can't do, and by its own name. */
|
|
133
|
+
const yours = jobsAdapter.name ? `your jobs adapter, ${jobsAdapter.name},` : "your jobs adapter";
|
|
134
|
+
if (failedStore && jobsAdapter.fail) throw new Error(`[logic-sdk] ${yours} keeps failed jobs itself, so jobs.failed has nothing to keep: drop it.`);
|
|
85
135
|
const enqueue = jobsAdapter.enqueue?.bind(jobsAdapter);
|
|
136
|
+
if (enqueue && crons.length && !database)
|
|
137
|
+
throw new Error(`[logic-sdk] Crons need \`database\` with ${yours}: their runs are written in a transaction of their own.`);
|
|
138
|
+
/** Cron runs, queued in a transaction of their own (a stored adapter runs each minute once there). */
|
|
139
|
+
const enqueueAlone = async (jobs: Job[]) => {
|
|
140
|
+
if (enqueue && database) await database.transaction((tx) => enqueue(tx, jobs));
|
|
141
|
+
};
|
|
86
142
|
|
|
87
143
|
// ── listeners ────────────────────────────────────────────────────────────
|
|
88
144
|
const byEvent = new Map<string, RegisteredListener[]>();
|
|
@@ -103,12 +159,18 @@ export function makeJobs(deps: JobsDeps) {
|
|
|
103
159
|
*/
|
|
104
160
|
function checkHold(what: string, seconds: number) {
|
|
105
161
|
const { holds } = jobsAdapter;
|
|
106
|
-
if (!holds)
|
|
107
|
-
throw new Error(`[logic-sdk] ${what} waits ${seconds}s, but your jobs adapter can't hold jobs (inProcess() can't). Use databaseQueue(database).`);
|
|
162
|
+
if (!holds) throw new Error(`[logic-sdk] ${what} waits ${seconds}s, but ${yours} can't hold jobs. Use one that holds them (${ADAPTERS}).`);
|
|
108
163
|
if (holds !== true && seconds > holds.max)
|
|
109
|
-
throw new Error(`[logic-sdk] ${what} waits ${seconds}s;
|
|
164
|
+
throw new Error(`[logic-sdk] ${what} waits ${seconds}s; ${yours} holds jobs for at most ${holds.max}s. Use one that holds them longer, or a jobs table in front of it (${ADAPTERS}).`);
|
|
165
|
+
}
|
|
166
|
+
/** `attempts` above 1 need an adapter that runs a job again: ignored, a failure would just be lost. Rails' inline adapter refuses too. */
|
|
167
|
+
function checkRetries(what: string, attempts: number) {
|
|
168
|
+
if (attempts > 1 && !jobsAdapter.retries)
|
|
169
|
+
throw new Error(`[logic-sdk] ${what} has attempts: ${attempts}, but ${yours} runs each job once. Use one that retries (${ADAPTERS}), or attempts: 1.`);
|
|
110
170
|
}
|
|
111
171
|
for (const l of listeners) if (l.listener.delay) checkHold(l.id, l.listener.delay);
|
|
172
|
+
for (const l of listeners) checkRetries(l.id, l.listener.attempts ?? 1);
|
|
173
|
+
for (const c of crons) checkRetries(c.id, c.cron.attempts ?? 1);
|
|
112
174
|
|
|
113
175
|
/**
|
|
114
176
|
* What a commit queues: one delivery per listener of each event that its `when` lets through, and the calls it
|
|
@@ -210,7 +272,7 @@ export function makeJobs(deps: JobsDeps) {
|
|
|
210
272
|
// its scope comes from the code each time, never stored, so jobs.scope store and load don't apply
|
|
211
273
|
const { scope, meta, handler } = c.cron;
|
|
212
274
|
const run: CronRun = { id: c.id, scheduledAt: job.scheduledAt, attempt };
|
|
213
|
-
await wrap({ id: c.id, kind: "cron", meta, input: undefined, scope, depth: 0 }, () =>
|
|
275
|
+
await wrap({ id: c.id, kind: "cron", job: { id: job.id, attempt }, meta, input: undefined, scope, depth: 0 }, () =>
|
|
214
276
|
handler({ ...handlerCtx(scope, 0, c.id, queued), cron: run } as never), // SAFETY: as for listeners: the ctx was built for a cron
|
|
215
277
|
);
|
|
216
278
|
return "done";
|
|
@@ -222,7 +284,7 @@ export function makeJobs(deps: JobsDeps) {
|
|
|
222
284
|
return attemptOnce(async () => {
|
|
223
285
|
const scope = await scopeOf(job, job.scope, attempt);
|
|
224
286
|
if (!scope) return "discarded";
|
|
225
|
-
await runAs(f.fn, job.input, scope, job.depth, queued);
|
|
287
|
+
await runAs(f.fn, job.input, scope, job.depth, queued, { id: job.id, attempt });
|
|
226
288
|
return "done";
|
|
227
289
|
});
|
|
228
290
|
}
|
|
@@ -233,7 +295,7 @@ export function makeJobs(deps: JobsDeps) {
|
|
|
233
295
|
return attemptOnce(async () => {
|
|
234
296
|
const scope = await scopeOf(job, envelope.scope, attempt);
|
|
235
297
|
if (!scope) return "discarded";
|
|
236
|
-
await wrap({ id: l.id, kind: "listener", meta: l.listener.meta, input: envelope.payload, scope, depth: 0 }, async () => {
|
|
298
|
+
await wrap({ id: l.id, kind: "listener", job: { id: job.id, attempt }, meta: l.listener.meta, input: envelope.payload, scope, depth: 0 }, async () => {
|
|
237
299
|
// its listener's event now: one renamed without an `id`, or a listener moved to another event, leaves stale jobs
|
|
238
300
|
if (idOf(l.event) !== envelope.name)
|
|
239
301
|
throw new StalePayload(`[logic-sdk] ${l.id} now listens to ${idOf(l.event)}, and this job is for ${envelope.name}.`);
|
|
@@ -241,7 +303,7 @@ export function makeJobs(deps: JobsDeps) {
|
|
|
241
303
|
if (r.issues) throw new StalePayload(`[logic-sdk] ${envelope.name} payload no longer matches its schema: ${JSON.stringify(describeIssues(r.issues))}`);
|
|
242
304
|
const payload = r.value;
|
|
243
305
|
const ctxEvent: ListenerEvent = { id: envelope.id, name: envelope.name, payload, occurredAt: envelope.occurredAt, attempt };
|
|
244
|
-
return l.listener.handler({ ...handlerCtx(scope, envelope.depth, l.id, queued), event: ctxEvent } as never, payload); // SAFETY: as in
|
|
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
|
|
245
307
|
});
|
|
246
308
|
return "done";
|
|
247
309
|
});
|
|
@@ -249,7 +311,8 @@ export function makeJobs(deps: JobsDeps) {
|
|
|
249
311
|
|
|
250
312
|
/** A runner whose jobs' own jobs are collected in `queued`. */
|
|
251
313
|
const runnerInto = (queued: Job[]): Runner => ({
|
|
252
|
-
|
|
314
|
+
// a job the adapter runs here and doesn't record itself (inProcess) is kept by the store, if there's one
|
|
315
|
+
run: (job, options) => runJob(job, { ...options, fail: options?.fail ?? (failedStore && ((error) => failedStore.fail(job, error))) }, queued),
|
|
253
316
|
report: (e, job, attempt) => report(e, infoOf(job, attempt)),
|
|
254
317
|
});
|
|
255
318
|
|
|
@@ -270,9 +333,7 @@ export function makeJobs(deps: JobsDeps) {
|
|
|
270
333
|
* With `only`, that cron's run for the minute, due or not (`t.jobs.perform`).
|
|
271
334
|
*/
|
|
272
335
|
function due(at: Date, only?: string): CronJob[] {
|
|
273
|
-
|
|
274
|
-
const minute = new Date(Math.floor(at.getTime() / 60_000) * 60_000);
|
|
275
|
-
const stamp = minute.toISOString().slice(0, 16).replaceAll(/[-:]/g, "") + "Z"; // 20261123T0900Z: no `:`, which BullMQ rejects
|
|
336
|
+
const { minute, stamp } = minuteOf(at, "tick");
|
|
276
337
|
return scheduled
|
|
277
338
|
.filter((c) => (only === undefined ? isDue(c.schedule, minute, c.cron.timezone) : c.id === only))
|
|
278
339
|
.map((c) => ({ kind: "cron", id: `${c.id}@${stamp}`, cron: c.id, scheduledAt: minute.toISOString(), attempts: c.cron.attempts ?? 1 }));
|
|
@@ -284,10 +345,7 @@ export function makeJobs(deps: JobsDeps) {
|
|
|
284
345
|
async tick(at = now()) {
|
|
285
346
|
const jobs = due(at);
|
|
286
347
|
if (!jobs.length) return [];
|
|
287
|
-
|
|
288
|
-
if (!database) throw new Error("[logic-sdk] Crons through a jobs adapter that stores them (like databaseQueue(database)) need `database`.");
|
|
289
|
-
await database.transaction((tx) => enqueue(tx, jobs));
|
|
290
|
-
}
|
|
348
|
+
await enqueueAlone(jobs);
|
|
291
349
|
await deliver(jobs);
|
|
292
350
|
return jobs.map((job) => job.cron);
|
|
293
351
|
},
|
|
@@ -298,10 +356,66 @@ export function makeJobs(deps: JobsDeps) {
|
|
|
298
356
|
return result;
|
|
299
357
|
},
|
|
300
358
|
async retry(id) {
|
|
301
|
-
if (
|
|
302
|
-
|
|
359
|
+
if (jobsAdapter.retry) return jobsAdapter.retry(id);
|
|
360
|
+
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}).`);
|
|
361
|
+
// out of the store, back to the queue with a fresh set of tries; a hand-off that fails puts it back and throws
|
|
362
|
+
const job = await failedStore.take(id);
|
|
363
|
+
if (!job) return false;
|
|
364
|
+
const queued: Job[] = [];
|
|
365
|
+
try {
|
|
366
|
+
await jobsAdapter.deliver([job], runnerInto(queued));
|
|
367
|
+
} catch (error) {
|
|
368
|
+
await failedStore.fail(job, error);
|
|
369
|
+
throw error;
|
|
370
|
+
}
|
|
371
|
+
await deliver(queued);
|
|
372
|
+
return true;
|
|
373
|
+
},
|
|
374
|
+
async failed(options = {}) {
|
|
375
|
+
const store = jobsAdapter.failed ? jobsAdapter : failedStore;
|
|
376
|
+
if (!store?.failed) throw new Error(`[logic-sdk] ${yours} can't list failed jobs. Use one that keeps them, or jobs.failed (${ADAPTERS}).`);
|
|
377
|
+
const { source, scope, limit = 100, cursor } = options;
|
|
378
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 1000) throw new Error(`[logic-sdk] jobs.failed({ limit }) takes 1 to 1000 (got ${String(limit)}).`);
|
|
379
|
+
const page = await store.failed({ source, scope: scope === undefined ? undefined : scopeMatches(scope), limit, cursor });
|
|
380
|
+
return {
|
|
381
|
+
jobs: page.rows.map(({ id, job, error, failedAt }) => ({
|
|
382
|
+
id,
|
|
383
|
+
kind: job.kind,
|
|
384
|
+
source: infoOf(job).source,
|
|
385
|
+
scope: (job.kind === "call" ? job.scope : job.kind === "delivery" ? job.envelope.scope : undefined) as never, // what `store` saved, typed by the caller
|
|
386
|
+
error,
|
|
387
|
+
failedAt,
|
|
388
|
+
job,
|
|
389
|
+
})),
|
|
390
|
+
cursor: page.cursor,
|
|
391
|
+
};
|
|
392
|
+
},
|
|
393
|
+
async forget(id) {
|
|
394
|
+
const store = jobsAdapter.forget ? jobsAdapter : failedStore;
|
|
395
|
+
if (!store?.forget) throw new Error(`[logic-sdk] ${yours} keeps no failed jobs, so there's nothing to forget (${id}). Use one that keeps them, or jobs.failed (${ADAPTERS}).`);
|
|
396
|
+
return store.forget(id);
|
|
397
|
+
},
|
|
398
|
+
/**
|
|
399
|
+
* One run of a cron, due or not, through the adapter as a tick's would go. Its id is the minute's plus a uuid, so a
|
|
400
|
+
* tick for that minute still runs (stored adapters run each id once), and so does a second invoke.
|
|
401
|
+
*/
|
|
402
|
+
async invoke(target, options = {}) {
|
|
403
|
+
const c = typeof target === "string" ? cronById.get(target) : crons.find((r) => r.cron === target);
|
|
404
|
+
if (!c)
|
|
405
|
+
throw new Error(
|
|
406
|
+
typeof target === "string"
|
|
407
|
+
? `[logic-sdk] jobs.invoke(${JSON.stringify(target)}): no cron has that id (${[...cronById.keys()].join(", ") || "none registered"}).`
|
|
408
|
+
: "[logic-sdk] jobs.invoke got a cron that isn't registered: export it from its module.",
|
|
409
|
+
);
|
|
410
|
+
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 };
|
|
412
|
+
await enqueueAlone([job]);
|
|
413
|
+
const queued: Job[] = [];
|
|
414
|
+
await jobsAdapter.deliver([job], runnerInto(queued)); // unlike a tick, a hand-off that fails throws: whoever invoked it needs to know
|
|
415
|
+
await deliver(queued);
|
|
416
|
+
return job.id;
|
|
303
417
|
},
|
|
304
418
|
};
|
|
305
419
|
|
|
306
|
-
return { toJobs, deliver, jobs, due, checkHold };
|
|
420
|
+
return { toJobs, deliver, jobs, due, checkHold, checkRetries, yours };
|
|
307
421
|
}
|