logic-sdk 0.7.0 → 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.
Files changed (100) hide show
  1. package/README.md +9 -9
  2. package/dist/adapters/cloudflare-queue.d.ts +14 -0
  3. package/dist/adapters/cloudflare-queue.js +48 -0
  4. package/dist/adapters/drizzle-pg.d.ts +250 -0
  5. package/dist/adapters/drizzle-pg.js +69 -0
  6. package/dist/adapters/drizzle-sqlite.d.ts +257 -0
  7. package/dist/adapters/drizzle-sqlite.js +196 -0
  8. package/dist/adapters/pg-boss.d.ts +45 -0
  9. package/dist/adapters/pg-boss.js +180 -0
  10. package/dist/adapters/postgres.d.ts +32 -0
  11. package/dist/adapters/postgres.js +105 -0
  12. package/dist/adapters/sqlite.d.ts +13 -0
  13. package/dist/adapters/sqlite.js +88 -0
  14. package/dist/{stored-jobs.d.ts → adapters/stored-jobs.d.ts} +27 -10
  15. package/dist/{stored-jobs.js → adapters/stored-jobs.js} +106 -20
  16. package/dist/ai.d.ts +1 -32
  17. package/dist/ai.js +1 -40
  18. package/dist/cloudflare.d.ts +2 -55
  19. package/dist/cloudflare.js +2 -85
  20. package/dist/core/in-process.d.ts +9 -0
  21. package/dist/core/in-process.js +17 -0
  22. package/dist/core/jobs.d.ts +57 -0
  23. package/dist/{jobs.js → core/jobs.js} +161 -42
  24. package/dist/core/registry.d.ts +120 -0
  25. package/dist/core/registry.js +503 -0
  26. package/dist/core/testing.d.ts +75 -0
  27. package/dist/core/testing.js +230 -0
  28. package/dist/{types.d.ts → core/types.d.ts} +224 -49
  29. package/dist/drizzle/pg.d.ts +3 -236
  30. package/dist/drizzle/pg.js +2 -67
  31. package/dist/drizzle/sqlite.d.ts +3 -242
  32. package/dist/drizzle/sqlite.js +2 -194
  33. package/dist/fetch.d.ts +1 -19
  34. package/dist/fetch.js +1 -30
  35. package/dist/hosts/cloudflare.d.ts +42 -0
  36. package/dist/hosts/cloudflare.js +39 -0
  37. package/dist/hosts/node.d.ts +26 -0
  38. package/dist/hosts/node.js +76 -0
  39. package/dist/hosts/pg-boss.d.ts +22 -0
  40. package/dist/hosts/pg-boss.js +55 -0
  41. package/dist/index.d.ts +5 -124
  42. package/dist/index.js +4 -495
  43. package/dist/integrations/ai.d.ts +32 -0
  44. package/dist/integrations/ai.js +40 -0
  45. package/dist/integrations/fetch.d.ts +19 -0
  46. package/dist/integrations/fetch.js +30 -0
  47. package/dist/integrations/orpc.d.ts +22 -0
  48. package/dist/integrations/orpc.js +37 -0
  49. package/dist/node.d.ts +1 -26
  50. package/dist/node.js +1 -76
  51. package/dist/orpc.d.ts +1 -21
  52. package/dist/orpc.js +1 -37
  53. package/dist/pg-boss.d.ts +2 -55
  54. package/dist/pg-boss.js +2 -211
  55. package/dist/postgres.d.ts +2 -28
  56. package/dist/postgres.js +1 -82
  57. package/dist/sqlite.d.ts +2 -9
  58. package/dist/sqlite.js +1 -65
  59. package/dist/testing.d.ts +1 -67
  60. package/dist/testing.js +1 -214
  61. package/package.json +2 -2
  62. package/skills/logic-sdk/SKILL.md +7 -6
  63. package/src/adapters/cloudflare-queue.ts +56 -0
  64. package/src/adapters/drizzle-pg.ts +108 -0
  65. package/src/adapters/drizzle-sqlite.ts +234 -0
  66. package/src/adapters/pg-boss.ts +195 -0
  67. package/src/adapters/postgres.ts +112 -0
  68. package/src/adapters/sqlite.ts +96 -0
  69. package/src/{stored-jobs.ts → adapters/stored-jobs.ts} +133 -30
  70. package/src/ai.ts +1 -62
  71. package/src/cloudflare.ts +2 -107
  72. package/src/core/in-process.ts +18 -0
  73. package/src/{jobs.ts → core/jobs.ts} +166 -43
  74. package/src/core/registry.ts +671 -0
  75. package/src/core/testing.ts +307 -0
  76. package/src/{types.ts → core/types.ts} +219 -46
  77. package/src/drizzle/pg.ts +3 -110
  78. package/src/drizzle/sqlite.ts +3 -236
  79. package/src/fetch.ts +1 -31
  80. package/src/hosts/cloudflare.ts +54 -0
  81. package/src/hosts/node.ts +99 -0
  82. package/src/hosts/pg-boss.ts +71 -0
  83. package/src/index.ts +17 -655
  84. package/src/integrations/ai.ts +63 -0
  85. package/src/integrations/fetch.ts +31 -0
  86. package/src/integrations/orpc.ts +47 -0
  87. package/src/node.ts +1 -99
  88. package/src/orpc.ts +1 -46
  89. package/src/pg-boss.ts +2 -242
  90. package/src/postgres.ts +2 -90
  91. package/src/sqlite.ts +2 -74
  92. package/src/testing.ts +1 -288
  93. package/dist/jobs.d.ts +0 -44
  94. /package/dist/{errors.d.ts → core/errors.d.ts} +0 -0
  95. /package/dist/{errors.js → core/errors.js} +0 -0
  96. /package/dist/{schedule.d.ts → core/schedule.d.ts} +0 -0
  97. /package/dist/{schedule.js → core/schedule.js} +0 -0
  98. /package/dist/{types.js → core/types.js} +0 -0
  99. /package/src/{errors.ts → core/errors.ts} +0 -0
  100. /package/src/{schedule.ts → core/schedule.ts} +0 -0
@@ -7,44 +7,89 @@ 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,
17
17
  JobScope,
18
18
  Jobs,
19
+ CronRun,
19
20
  ListenerEvent,
20
21
  RegisteredCron,
21
22
  RegisteredFn,
22
23
  RegisteredListener,
23
24
  RunJobOptions,
24
25
  Runner,
26
+ ScopeMatch,
25
27
  } from "./types.ts";
26
- import { RUNS_NOW } from "./types.ts";
27
28
 
28
- const IN_PROCESS: InProcess = {
29
- [RUNS_NOW]: true,
30
- async deliver(jobs, { run }) {
31
- // one try, whatever `attempts` says: what throws has failed, so onError never hears of a retry that won't come
32
- for (const job of jobs) await run({ ...job, attempts: 1 });
33
- },
34
- };
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
+
35
56
  /**
36
- * Default adapter: runs each job right after commit, in this process, one try (like Laravel's sync queue). It can't
37
- * hold a job for later, so a `delay` or a waiting `ctx.schedule` is refused. Lost on crash: use `databaseQueue` when that matters.
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.
38
59
  */
39
- export const inProcess = (): InProcess => IN_PROCESS;
40
- /** `inProcess()`: runs each job right after commit, in this process, so no scope waits at rest. */
41
- export const runsNow = (adapter: JobsAdapter) => adapter === IN_PROCESS;
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
+ }
42
77
 
43
78
  /**
44
- * What makes a scheduled call replaceable, `<function id>@<key>`: a newer call with the same one replaces it while it
45
- * waits. Undefined for every other job. For adapters that replace (`replaces: true`).
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.
46
81
  */
47
- export const replaceKeyOf = (job: Job): string | undefined => (job.kind === "call" && job.replace !== undefined ? `${job.fn}@${job.replace}` : undefined);
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
+ }
48
93
 
49
94
  /** One listener's share of an event, as a job: `<listener id>@<event id>`, with the listener's tries. */
50
95
  export const deliveryOf = (l: RegisteredListener, e: Envelope): Delivery => ({
@@ -64,14 +109,16 @@ export interface JobsDeps {
64
109
  jobsAdapter: JobsAdapter;
65
110
  database: DatabaseAdapter<unknown, unknown> | undefined;
66
111
  jobScope: JobScope | undefined;
112
+ /** `jobs.failed`: where failed jobs are kept when the adapter keeps none. */
113
+ failedStore: FailedJobs | undefined;
67
114
  maxEventDepth: number;
68
115
  now(): Date;
69
116
  wrap(call: Call, next: () => Promise<unknown>): Promise<unknown>;
70
117
  report(error: unknown, info: FailureInfo): void;
71
118
  /** Run a function as `scope`, like `registry.as(scope).run`. `eventDepth`: the chain's hops so far (a scheduled call's `depth`). */
72
- runAs(fn: Fn, input: unknown, scope: object, eventDepth: number, queued: Job[] | undefined): Promise<unknown>;
73
- /** The ctx a listener's handler gets, as `scope`, in an event chain `eventDepth` deep. */
74
- listenerCtx(scope: object, eventDepth: number, id: string, queued: Job[] | undefined): ActionCtx<any>;
119
+ 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>;
75
122
  }
76
123
 
77
124
  /**
@@ -79,9 +126,19 @@ export interface JobsDeps {
79
126
  * calls into jobs, runs one (with its tries), and is what `registry.jobs` calls.
80
127
  */
81
128
  export function makeJobs(deps: JobsDeps) {
82
- const { listeners, crons, functions, idOf, jobsAdapter, database, jobScope, maxEventDepth, now, wrap, report, runAs, listenerCtx } = deps;
83
- const keepFailed = jobsAdapter.fail?.bind(jobsAdapter);
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.`);
84
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
+ };
85
142
 
86
143
  // ── listeners ────────────────────────────────────────────────────────────
87
144
  const byEvent = new Map<string, RegisteredListener[]>();
@@ -102,12 +159,18 @@ export function makeJobs(deps: JobsDeps) {
102
159
  */
103
160
  function checkHold(what: string, seconds: number) {
104
161
  const { holds } = jobsAdapter;
105
- if (!holds)
106
- 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}).`);
107
163
  if (holds !== true && seconds > holds.max)
108
- throw new Error(`[logic-sdk] ${what} waits ${seconds}s; your jobs adapter holds jobs for at most ${holds.max}s. Put an outbox in front, outbox(database, queue): it holds them as long as needed.`);
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.`);
109
170
  }
110
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);
111
174
 
112
175
  /**
113
176
  * What a commit queues: one delivery per listener of each event that its `when` lets through, and the calls it
@@ -206,7 +269,12 @@ export function makeJobs(deps: JobsDeps) {
206
269
  const c = cronById.get(job.cron);
207
270
  if (!c) return missing("cron", job.cron);
208
271
  return attemptOnce(async () => {
209
- await runAs(c.run, c.cron.input, c.cron.scope, 0, queued);
272
+ // its scope comes from the code each time, never stored, so jobs.scope store and load don't apply
273
+ const { scope, meta, handler } = c.cron;
274
+ const run: CronRun = { id: c.id, scheduledAt: job.scheduledAt, attempt };
275
+ await wrap({ id: c.id, kind: "cron", job: { id: job.id, attempt }, meta, input: undefined, scope, depth: 0 }, () =>
276
+ handler({ ...handlerCtx(scope, 0, c.id, queued), cron: run } as never), // SAFETY: as for listeners: the ctx was built for a cron
277
+ );
210
278
  return "done";
211
279
  });
212
280
  }
@@ -216,7 +284,7 @@ export function makeJobs(deps: JobsDeps) {
216
284
  return attemptOnce(async () => {
217
285
  const scope = await scopeOf(job, job.scope, attempt);
218
286
  if (!scope) return "discarded";
219
- 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 });
220
288
  return "done";
221
289
  });
222
290
  }
@@ -227,7 +295,7 @@ export function makeJobs(deps: JobsDeps) {
227
295
  return attemptOnce(async () => {
228
296
  const scope = await scopeOf(job, envelope.scope, attempt);
229
297
  if (!scope) return "discarded";
230
- 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 () => {
231
299
  // its listener's event now: one renamed without an `id`, or a listener moved to another event, leaves stale jobs
232
300
  if (idOf(l.event) !== envelope.name)
233
301
  throw new StalePayload(`[logic-sdk] ${l.id} now listens to ${idOf(l.event)}, and this job is for ${envelope.name}.`);
@@ -235,7 +303,7 @@ export function makeJobs(deps: JobsDeps) {
235
303
  if (r.issues) throw new StalePayload(`[logic-sdk] ${envelope.name} payload no longer matches its schema: ${JSON.stringify(describeIssues(r.issues))}`);
236
304
  const payload = r.value;
237
305
  const ctxEvent: ListenerEvent = { id: envelope.id, name: envelope.name, payload, occurredAt: envelope.occurredAt, attempt };
238
- return l.listener.handler({ ...listenerCtx(scope, envelope.depth, l.id, queued), event: ctxEvent } as never, payload); // SAFETY: as in index.ts's invoke: the ctx was built for a listener
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
239
307
  });
240
308
  return "done";
241
309
  });
@@ -243,7 +311,8 @@ export function makeJobs(deps: JobsDeps) {
243
311
 
244
312
  /** A runner whose jobs' own jobs are collected in `queued`. */
245
313
  const runnerInto = (queued: Job[]): Runner => ({
246
- run: (job, options) => runJob(job, options, queued),
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),
247
316
  report: (e, job, attempt) => report(e, infoOf(job, attempt)),
248
317
  });
249
318
 
@@ -259,13 +328,14 @@ export function makeJobs(deps: JobsDeps) {
259
328
  }
260
329
  }
261
330
 
262
- /** The runs due in `at`'s minute: one job per cron, with an id per minute, so a tick that's delivered twice runs once. */
263
- function due(at: Date): CronJob[] {
264
- if (Number.isNaN(at.getTime())) throw new Error(`[logic-sdk] tick needs a valid date (got ${String(at)}).`);
265
- const minute = new Date(Math.floor(at.getTime() / 60_000) * 60_000);
266
- const stamp = minute.toISOString().slice(0, 16).replaceAll(/[-:]/g, "") + "Z"; // 20261123T0900Z: no `:`, which BullMQ rejects
331
+ /**
332
+ * The runs due in `at`'s minute: one job per cron, with an id per minute, so a tick that's delivered twice runs once.
333
+ * With `only`, that cron's run for the minute, due or not (`t.jobs.perform`).
334
+ */
335
+ function due(at: Date, only?: string): CronJob[] {
336
+ const { minute, stamp } = minuteOf(at, "tick");
267
337
  return scheduled
268
- .filter((c) => isDue(c.schedule, minute, c.cron.timezone))
338
+ .filter((c) => (only === undefined ? isDue(c.schedule, minute, c.cron.timezone) : c.id === only))
269
339
  .map((c) => ({ kind: "cron", id: `${c.id}@${stamp}`, cron: c.id, scheduledAt: minute.toISOString(), attempts: c.cron.attempts ?? 1 }));
270
340
  }
271
341
 
@@ -275,10 +345,7 @@ export function makeJobs(deps: JobsDeps) {
275
345
  async tick(at = now()) {
276
346
  const jobs = due(at);
277
347
  if (!jobs.length) return [];
278
- if (enqueue) {
279
- if (!database) throw new Error("[logic-sdk] Crons through a jobs adapter that stores them (like databaseQueue(database)) need `database`.");
280
- await database.transaction((tx) => enqueue(tx, jobs));
281
- }
348
+ await enqueueAlone(jobs);
282
349
  await deliver(jobs);
283
350
  return jobs.map((job) => job.cron);
284
351
  },
@@ -289,10 +356,66 @@ export function makeJobs(deps: JobsDeps) {
289
356
  return result;
290
357
  },
291
358
  async retry(id) {
292
- if (!jobsAdapter.retry) throw new Error(`[logic-sdk] your jobs adapter keeps no jobs, so there's nothing to retry (${id}). databaseQueue(database), outbox(database, queue) and pgBoss(boss) do.`);
293
- return jobsAdapter.retry(id);
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;
294
417
  },
295
418
  };
296
419
 
297
- return { toJobs, deliver, jobs, due, checkHold };
420
+ return { toJobs, deliver, jobs, due, checkHold, checkRetries, yours };
298
421
  }