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.
Files changed (99) hide show
  1. package/README.md +7 -7
  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/{jobs.d.ts → core/jobs.d.ts} +23 -10
  23. package/dist/{jobs.js → core/jobs.js} +152 -39
  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} +203 -40
  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 -122
  42. package/dist/index.js +4 -492
  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 -53
  54. package/dist/pg-boss.js +2 -213
  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 -75
  60. package/dist/testing.js +1 -227
  61. package/package.json +2 -2
  62. package/skills/logic-sdk/SKILL.md +4 -3
  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} +152 -38
  74. package/src/core/registry.ts +671 -0
  75. package/src/core/testing.ts +307 -0
  76. package/src/{types.ts → core/types.ts} +197 -40
  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 +15 -652
  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 -241
  90. package/src/postgres.ts +2 -90
  91. package/src/sqlite.ts +2 -74
  92. package/src/testing.ts +1 -305
  93. /package/dist/{errors.d.ts → core/errors.d.ts} +0 -0
  94. /package/dist/{errors.js → core/errors.js} +0 -0
  95. /package/dist/{schedule.d.ts → core/schedule.d.ts} +0 -0
  96. /package/dist/{schedule.js → core/schedule.js} +0 -0
  97. /package/dist/{types.js → core/types.js} +0 -0
  98. /package/src/{errors.ts → core/errors.ts} +0 -0
  99. /package/src/{schedule.ts → core/schedule.ts} +0 -0
@@ -1,85 +1,2 @@
1
- import { defaultBackoff } from "./stored-jobs.js";
2
- // Cloudflare's limits, where 1 KB is 1000 bytes: https://developers.cloudflare.com/queues/platform/limits/
3
- const MAX_MESSAGES = 100;
4
- const MAX_BATCH_BYTES = 256_000;
5
- const MAX_MESSAGE_BYTES = 128_000;
6
- /** Cloudflare counts about this much metadata per message toward the limits. */
7
- const OVERHEAD_BYTES = 100;
8
- /** The longest `delaySeconds` Cloudflare takes, for a send and for a retry: 24 hours. */
9
- const MAX_DELAY = 86_400;
10
- const encoder = new TextEncoder();
11
- /**
12
- * Send jobs to a Cloudflare Queue after commit. Alone it's lossy (a Worker that dies between commit and send loses
13
- * them); behind an outbox it's durable: `jobs: { adapter: outbox(database, cloudflareQueue(env.JOBS)), scope: { store, load } }`.
14
- * Run them with `handleQueue(registry, batch)` in your consumer.
15
- */
16
- export function cloudflareQueue(queue) {
17
- return {
18
- holds: { max: MAX_DELAY }, // delaySeconds, up to 24 hours
19
- async deliver(jobs) {
20
- for (const batch of batches(jobs))
21
- await queue.sendBatch(batch);
22
- },
23
- };
24
- }
25
- /** Under Cloudflare's limits per send: 100 messages, 256 KB in all, 128 KB each. Checks every job before sending any. */
26
- function* batches(jobs) {
27
- const sized = jobs.map((body) => {
28
- const size = encoder.encode(JSON.stringify(body)).length + OVERHEAD_BYTES;
29
- if (size > MAX_MESSAGE_BYTES)
30
- throw new Error(`[logic-sdk] job ${body.id} is ${size} bytes; Cloudflare Queues take ${MAX_MESSAGE_BYTES} per message. Keep payloads to ids.`);
31
- return { body, size };
32
- });
33
- let batch = [];
34
- let bytes = 0;
35
- for (const { body, size } of sized) {
36
- if (batch.length && (batch.length === MAX_MESSAGES || bytes + size > MAX_BATCH_BYTES)) {
37
- yield batch;
38
- batch = [];
39
- bytes = 0;
40
- }
41
- batch.push(body.runAt ? { body, delaySeconds: secondsUntil(body.runAt) } : { body });
42
- bytes += size;
43
- }
44
- if (batch.length)
45
- yield batch;
46
- }
47
- const secondsUntil = (iso) => Math.min(MAX_DELAY, Math.max(0, Math.ceil((Date.parse(iso) - Date.now()) / 1000)));
48
- /**
49
- * Your Worker's `queue` handler: runs each message's job, then acknowledges it (`done`, `failed`, `discarded`) or
50
- * retries it with a backoff (it threw and the listener has tries left). One message at a time, each acknowledged on
51
- * its own, so one failure doesn't redeliver the batch.
52
- *
53
- * ```ts
54
- * async queue(batch, env, ctx) {
55
- * await handleQueue(makeRegistry(env, ctx), batch);
56
- * },
57
- * ```
58
- */
59
- export async function handleQueue(registry, batch) {
60
- for (const message of batch.messages) {
61
- try {
62
- await registry.jobs.run(message.body, { attempt: message.attempts });
63
- message.ack();
64
- }
65
- catch {
66
- // already reported to onError. databaseQueue's curve, so a listener's tries aren't spent back to back.
67
- message.retry({ delaySeconds: Math.ceil(defaultBackoff(message.attempts)) });
68
- }
69
- }
70
- }
71
- /**
72
- * Your Worker's `scheduled` handler: runs the crons due at the trigger's time, then sweeps (databaseQueue's retries,
73
- * delayed jobs, and sends a crash left behind). Use `"* * * * *"`, or one trigger per cron: Cloudflare numbers weekdays
74
- * 1 = Sunday, so write them as names (`MON`) in both places.
75
- *
76
- * ```ts
77
- * async scheduled(controller, env, ctx) {
78
- * await handleScheduled(makeRegistry(env, ctx), controller);
79
- * },
80
- * ```
81
- */
82
- export async function handleScheduled(registry, controller) {
83
- await registry.jobs.tick(new Date(controller.scheduledTime));
84
- await registry.jobs.sweep();
85
- }
1
+ export { cloudflareQueue } from "./adapters/cloudflare-queue.js";
2
+ export { handleQueue, handleScheduled } from "./hosts/cloudflare.js";
@@ -0,0 +1,9 @@
1
+ import type { InProcess, JobsAdapter } from "./types.ts";
2
+ import { RUNS_NOW } from "./types.ts";
3
+ /**
4
+ * Default adapter: runs each job right after commit, in this process, one try (like Laravel's sync queue). It can't
5
+ * hold a job for later, so a `delay` or a waiting `ctx.schedule` is refused. Lost on crash: use `databaseQueue` when that matters.
6
+ */
7
+ export declare const inProcess: () => InProcess;
8
+ /** `inProcess()`: runs each job right after commit, in this process, so no scope waits at rest. */
9
+ export declare const runsNow: (adapter: JobsAdapter) => adapter is JobsAdapter & Record<typeof RUNS_NOW, unknown>;
@@ -0,0 +1,17 @@
1
+ import { RUNS_NOW } from "./types.js";
2
+ const IN_PROCESS = {
3
+ [RUNS_NOW]: true,
4
+ name: "inProcess()",
5
+ async deliver(jobs, { run }) {
6
+ // one try, whatever `attempts` says: what throws has failed, so onError never hears of a retry that won't come
7
+ for (const job of jobs)
8
+ await run({ ...job, attempts: 1 });
9
+ },
10
+ };
11
+ /**
12
+ * Default adapter: runs each job right after commit, in this process, one try (like Laravel's sync queue). It can't
13
+ * hold a job for later, so a `delay` or a waiting `ctx.schedule` is refused. Lost on crash: use `databaseQueue` when that matters.
14
+ */
15
+ export const inProcess = () => IN_PROCESS;
16
+ /** `inProcess()`: runs each job right after commit, in this process, so no scope waits at rest. */
17
+ export const runsNow = (adapter) => RUNS_NOW in adapter;
@@ -1,16 +1,22 @@
1
- import type { ActionCtx, Call, CallJob, CronJob, DatabaseAdapter, Delivery, Envelope, FailureInfo, Fn, InProcess, Job, JobsAdapter, JobScope, Jobs, RegisteredCron, RegisteredFn, RegisteredListener } from "./types.ts";
1
+ import type { ActionCtx, Call, CallJob, CronJob, DatabaseAdapter, Delivery, FailedJobs, Envelope, FailureInfo, Fn, Job, JobsAdapter, JobScope, Jobs, RegisteredCron, RegisteredFn, RegisteredListener } from "./types.ts";
2
+ export declare const isPlainObject: (v: unknown) => v is Record<string, unknown>;
2
3
  /**
3
- * Default adapter: runs each job right after commit, in this process, one try (like Laravel's sync queue). It can't
4
- * hold a job for later, so a `delay` or a waiting `ctx.schedule` is refused. Lost on crash: use `databaseQueue` when that matters.
4
+ * What makes a scheduled call with `replace: true` replaceable: its function and its input, `<function id>@<input>`. A
5
+ * newer call with the same one replaces it while it waits. Undefined for every other job.
5
6
  */
6
- export declare const inProcess: () => InProcess;
7
- /** `inProcess()`: runs each job right after commit, in this process, so no scope waits at rest. */
8
- export declare const runsNow: (adapter: JobsAdapter) => boolean;
7
+ export declare const replaceKeyOf: (job: Job) => string | undefined;
9
8
  /**
10
- * What makes a scheduled call replaceable, `<function id>@<key>`: a newer call with the same one replaces it while it
11
- * waits. Undefined for every other job. For adapters that replace (`replaces: true`).
9
+ * `replaceKeyOf`, as adapters that replace (`replaces: true`) store it: `<function id>@<sha-256 of the input>`, so a
10
+ * large input still fits an index and the function stays readable.
12
11
  */
13
- export declare const replaceKeyOf: (job: Job) => string | undefined;
12
+ export declare function storedReplaceKey(job: Job): Promise<string | undefined>;
13
+ /**
14
+ * Seconds to wait after a failed try: e^attempt, capped at e^10 (about 6 hours), the curve Graphile Worker uses. The
15
+ * core's, so every adapter that backs off (the jobs table, Cloudflare's redelivery) waits the same.
16
+ */
17
+ export declare const defaultBackoff: (attempt: number) => number;
18
+ /** Where the docs list each adapter and what it can do. */
19
+ export declare const ADAPTERS = "see Jobs, Adapters in the docs";
14
20
  /** One listener's share of an event, as a job: `<listener id>@<event id>`, with the listener's tries. */
15
21
  export declare const deliveryOf: (l: RegisteredListener, e: Envelope) => Delivery;
16
22
  /** What running jobs needs from the registry: its definitions, and how it runs a function or a listener's handler. */
@@ -22,12 +28,17 @@ export interface JobsDeps {
22
28
  jobsAdapter: JobsAdapter;
23
29
  database: DatabaseAdapter<unknown, unknown> | undefined;
24
30
  jobScope: JobScope | undefined;
31
+ /** `jobs.failed`: where failed jobs are kept when the adapter keeps none. */
32
+ failedStore: FailedJobs | undefined;
25
33
  maxEventDepth: number;
26
34
  now(): Date;
27
35
  wrap(call: Call, next: () => Promise<unknown>): Promise<unknown>;
28
36
  report(error: unknown, info: FailureInfo): void;
29
37
  /** Run a function as `scope`, like `registry.as(scope).run`. `eventDepth`: the chain's hops so far (a scheduled call's `depth`). */
30
- runAs(fn: Fn, input: unknown, scope: object, eventDepth: number, queued: Job[] | undefined): Promise<unknown>;
38
+ runAs(fn: Fn, input: unknown, scope: object, eventDepth: number, queued: Job[] | undefined, job: {
39
+ id: string;
40
+ attempt: number;
41
+ }): Promise<unknown>;
31
42
  /** The ctx a listener's or cron's handler gets, as `scope`, in an event chain `eventDepth` deep. */
32
43
  handlerCtx(scope: object, eventDepth: number, id: string, queued: Job[] | undefined): ActionCtx<any>;
33
44
  }
@@ -41,4 +52,6 @@ export declare function makeJobs(deps: JobsDeps): {
41
52
  jobs: Jobs;
42
53
  due: (at: Date, only?: string) => CronJob[];
43
54
  checkHold: (what: string, seconds: number) => void;
55
+ checkRetries: (what: string, attempts: number) => void;
56
+ yours: string;
44
57
  };
@@ -1,26 +1,64 @@
1
1
  import { CaughtNestedFailure, describeIssues, isDomainError, StalePayload } from "./errors.js";
2
2
  import { isDue, parseSchedule } from "./schedule.js";
3
- import { RUNS_NOW } from "./types.js";
4
- const IN_PROCESS = {
5
- [RUNS_NOW]: true,
6
- async deliver(jobs, { run }) {
7
- // one try, whatever `attempts` says: what throws has failed, so onError never hears of a retry that won't come
8
- for (const job of jobs)
9
- await run({ ...job, attempts: 1 });
10
- },
11
- };
3
+ export const isPlainObject = (v) => !!v && typeof v === "object" && (Object.getPrototypeOf(v) === Object.prototype || Object.getPrototypeOf(v) === null);
4
+ /**
5
+ * JSON with object keys sorted, so `{ a, b }` and `{ b, a }` are one input, like TanStack Query's `hashKey`. Undefined
6
+ * properties drop out, as in JSON; array order counts. The input as passed, before its schema runs (defaults aren't
7
+ * applied), so a schema change doesn't move what's waiting.
8
+ */
9
+ const canonical = (value) => JSON.stringify(value, (_, v) => (isPlainObject(v) ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, v[k]])) : v)) ?? "";
10
+ /**
11
+ * What makes a scheduled call with `replace: true` replaceable: its function and its input, `<function id>@<input>`. A
12
+ * newer call with the same one replaces it while it waits. Undefined for every other job.
13
+ */
14
+ export const replaceKeyOf = (job) => (job.kind === "call" && job.replace ? `${job.fn}@${canonical(job.input)}` : undefined);
12
15
  /**
13
- * Default adapter: runs each job right after commit, in this process, one try (like Laravel's sync queue). It can't
14
- * hold a job for later, so a `delay` or a waiting `ctx.schedule` is refused. Lost on crash: use `databaseQueue` when that matters.
16
+ * `replaceKeyOf`, as adapters that replace (`replaces: true`) store it: `<function id>@<sha-256 of the input>`, so a
17
+ * large input still fits an index and the function stays readable.
15
18
  */
16
- export const inProcess = () => IN_PROCESS;
17
- /** `inProcess()`: runs each job right after commit, in this process, so no scope waits at rest. */
18
- export const runsNow = (adapter) => adapter === IN_PROCESS;
19
+ export async function storedReplaceKey(job) {
20
+ if (job.kind !== "call" || !job.replace)
21
+ return undefined;
22
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(canonical(job.input)));
23
+ return `${job.fn}@${Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("")}`;
24
+ }
19
25
  /**
20
- * What makes a scheduled call replaceable, `<function id>@<key>`: a newer call with the same one replaces it while it
21
- * waits. Undefined for every other job. For adapters that replace (`replaces: true`).
26
+ * A `failed({ scope })` filter as the fields it matches: `{ organization: { id: "o1" } }` is `organization.id = "o1"`.
27
+ * Strings, numbers, booleans and null; never an array or an empty object, which two databases would read differently.
22
28
  */
23
- export const replaceKeyOf = (job) => (job.kind === "call" && job.replace !== undefined ? `${job.fn}@${job.replace}` : undefined);
29
+ function scopeMatches(filter) {
30
+ const out = [];
31
+ const walk = (value, path) => {
32
+ if (value === null || typeof value === "string" || typeof value === "boolean" || (typeof value === "number" && Number.isFinite(value))) {
33
+ out.push({ path, value });
34
+ return;
35
+ }
36
+ const where = path.length ? path.join(".") : "scope";
37
+ if (!isPlainObject(value))
38
+ throw new Error(`[logic-sdk] jobs.failed({ scope }) matches strings, numbers, booleans and null: ${where} is ${Array.isArray(value) ? "an array" : typeof value}.`);
39
+ const keys = Object.keys(value).filter((k) => value[k] !== undefined);
40
+ if (!keys.length)
41
+ throw new Error(`[logic-sdk] jobs.failed({ scope }) matches fields: ${where} is an empty object.`);
42
+ for (const k of keys)
43
+ walk(value[k], [...path, k]);
44
+ };
45
+ walk(filter, []);
46
+ return out;
47
+ }
48
+ /**
49
+ * Seconds to wait after a failed try: e^attempt, capped at e^10 (about 6 hours), the curve Graphile Worker uses. The
50
+ * core's, so every adapter that backs off (the jobs table, Cloudflare's redelivery) waits the same.
51
+ */
52
+ export const defaultBackoff = (attempt) => Math.exp(Math.min(attempt, 10));
53
+ /** Where the docs list each adapter and what it can do. */
54
+ export const ADAPTERS = "see Jobs, Adapters in the docs";
55
+ /** The minute `at` falls in, and its stamp for a job id: `20261123T0900Z` (no `:`, which BullMQ rejects). */
56
+ function minuteOf(at, what) {
57
+ if (Number.isNaN(at.getTime()))
58
+ throw new Error(`[logic-sdk] ${what} needs a valid date (got ${String(at)}).`);
59
+ const minute = new Date(Math.floor(at.getTime() / 60_000) * 60_000);
60
+ return { minute, stamp: minute.toISOString().slice(0, 16).replaceAll(/[-:]/g, "") + "Z" };
61
+ }
24
62
  /** One listener's share of an event, as a job: `<listener id>@<event id>`, with the listener's tries. */
25
63
  export const deliveryOf = (l, e) => ({
26
64
  kind: "delivery",
@@ -34,9 +72,21 @@ export const deliveryOf = (l, e) => ({
34
72
  * calls into jobs, runs one (with its tries), and is what `registry.jobs` calls.
35
73
  */
36
74
  export function makeJobs(deps) {
37
- const { listeners, crons, functions, idOf, jobsAdapter, database, jobScope, maxEventDepth, now, wrap, report, runAs, handlerCtx } = deps;
38
- const keepFailed = jobsAdapter.fail?.bind(jobsAdapter);
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);
78
+ /** Your adapter, as messages name it: by what it can't do, and by its own name. */
79
+ const yours = jobsAdapter.name ? `your jobs adapter, ${jobsAdapter.name},` : "your jobs adapter";
80
+ if (failedStore && jobsAdapter.fail)
81
+ throw new Error(`[logic-sdk] ${yours} keeps failed jobs itself, so jobs.failed has nothing to keep: drop it.`);
39
82
  const enqueue = jobsAdapter.enqueue?.bind(jobsAdapter);
83
+ if (enqueue && crons.length && !database)
84
+ throw new Error(`[logic-sdk] Crons need \`database\` with ${yours}: their runs are written in a transaction of their own.`);
85
+ /** Cron runs, queued in a transaction of their own (a stored adapter runs each minute once there). */
86
+ const enqueueAlone = async (jobs) => {
87
+ if (enqueue && database)
88
+ await database.transaction((tx) => enqueue(tx, jobs));
89
+ };
40
90
  // ── listeners ────────────────────────────────────────────────────────────
41
91
  const byEvent = new Map();
42
92
  for (const l of listeners) {
@@ -54,13 +104,22 @@ export function makeJobs(deps) {
54
104
  function checkHold(what, seconds) {
55
105
  const { holds } = jobsAdapter;
56
106
  if (!holds)
57
- throw new Error(`[logic-sdk] ${what} waits ${seconds}s, but your jobs adapter can't hold jobs (inProcess() can't). Use databaseQueue(database).`);
107
+ throw new Error(`[logic-sdk] ${what} waits ${seconds}s, but ${yours} can't hold jobs. Use one that holds them (${ADAPTERS}).`);
58
108
  if (holds !== true && seconds > holds.max)
59
- 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.`);
109
+ 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}).`);
110
+ }
111
+ /** `attempts` above 1 need an adapter that runs a job again: ignored, a failure would just be lost. Rails' inline adapter refuses too. */
112
+ function checkRetries(what, attempts) {
113
+ if (attempts > 1 && !jobsAdapter.retries)
114
+ throw new Error(`[logic-sdk] ${what} has attempts: ${attempts}, but ${yours} runs each job once. Use one that retries (${ADAPTERS}), or attempts: 1.`);
60
115
  }
61
116
  for (const l of listeners)
62
117
  if (l.listener.delay)
63
118
  checkHold(l.id, l.listener.delay);
119
+ for (const l of listeners)
120
+ checkRetries(l.id, l.listener.attempts ?? 1);
121
+ for (const c of crons)
122
+ checkRetries(c.id, c.cron.attempts ?? 1);
64
123
  /**
65
124
  * What a commit queues: one delivery per listener of each event that its `when` lets through, and the calls it
66
125
  * scheduled. Events and calls due now past `maxEventDepth` (a listener loop, a function scheduling itself with no
@@ -160,7 +219,7 @@ export function makeJobs(deps) {
160
219
  // its scope comes from the code each time, never stored, so jobs.scope store and load don't apply
161
220
  const { scope, meta, handler } = c.cron;
162
221
  const run = { id: c.id, scheduledAt: job.scheduledAt, attempt };
163
- await wrap({ id: c.id, kind: "cron", meta, input: undefined, scope, depth: 0 }, () => handler({ ...handlerCtx(scope, 0, c.id, queued), cron: run }));
222
+ 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 }));
164
223
  return "done";
165
224
  });
166
225
  }
@@ -172,7 +231,7 @@ export function makeJobs(deps) {
172
231
  const scope = await scopeOf(job, job.scope, attempt);
173
232
  if (!scope)
174
233
  return "discarded";
175
- await runAs(f.fn, job.input, scope, job.depth, queued);
234
+ await runAs(f.fn, job.input, scope, job.depth, queued, { id: job.id, attempt });
176
235
  return "done";
177
236
  });
178
237
  }
@@ -186,7 +245,7 @@ export function makeJobs(deps) {
186
245
  const scope = await scopeOf(job, envelope.scope, attempt);
187
246
  if (!scope)
188
247
  return "discarded";
189
- await wrap({ id: l.id, kind: "listener", meta: l.listener.meta, input: envelope.payload, scope, depth: 0 }, async () => {
248
+ await wrap({ id: l.id, kind: "listener", job: { id: job.id, attempt }, meta: l.listener.meta, input: envelope.payload, scope, depth: 0 }, async () => {
190
249
  // its listener's event now: one renamed without an `id`, or a listener moved to another event, leaves stale jobs
191
250
  if (idOf(l.event) !== envelope.name)
192
251
  throw new StalePayload(`[logic-sdk] ${l.id} now listens to ${idOf(l.event)}, and this job is for ${envelope.name}.`);
@@ -195,14 +254,15 @@ export function makeJobs(deps) {
195
254
  throw new StalePayload(`[logic-sdk] ${envelope.name} payload no longer matches its schema: ${JSON.stringify(describeIssues(r.issues))}`);
196
255
  const payload = r.value;
197
256
  const ctxEvent = { id: envelope.id, name: envelope.name, payload, occurredAt: envelope.occurredAt, attempt };
198
- return l.listener.handler({ ...handlerCtx(scope, envelope.depth, l.id, queued), event: ctxEvent }, payload); // SAFETY: as in index.ts's invoke: the ctx was built for a listener
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
199
258
  });
200
259
  return "done";
201
260
  });
202
261
  }
203
262
  /** A runner whose jobs' own jobs are collected in `queued`. */
204
263
  const runnerInto = (queued) => ({
205
- run: (job, options) => runJob(job, options, queued),
264
+ // a job the adapter runs here and doesn't record itself (inProcess) is kept by the store, if there's one
265
+ run: (job, options) => runJob(job, { ...options, fail: options?.fail ?? (failedStore && ((error) => failedStore.fail(job, error))) }, queued),
206
266
  report: (e, job, attempt) => report(e, infoOf(job, attempt)),
207
267
  });
208
268
  /**
@@ -221,10 +281,7 @@ export function makeJobs(deps) {
221
281
  * With `only`, that cron's run for the minute, due or not (`t.jobs.perform`).
222
282
  */
223
283
  function due(at, only) {
224
- if (Number.isNaN(at.getTime()))
225
- throw new Error(`[logic-sdk] tick needs a valid date (got ${String(at)}).`);
226
- const minute = new Date(Math.floor(at.getTime() / 60_000) * 60_000);
227
- const stamp = minute.toISOString().slice(0, 16).replaceAll(/[-:]/g, "") + "Z"; // 20261123T0900Z: no `:`, which BullMQ rejects
284
+ const { minute, stamp } = minuteOf(at, "tick");
228
285
  return scheduled
229
286
  .filter((c) => (only === undefined ? isDue(c.schedule, minute, c.cron.timezone) : c.id === only))
230
287
  .map((c) => ({ kind: "cron", id: `${c.id}@${stamp}`, cron: c.id, scheduledAt: minute.toISOString(), attempts: c.cron.attempts ?? 1 }));
@@ -236,11 +293,7 @@ export function makeJobs(deps) {
236
293
  const jobs = due(at);
237
294
  if (!jobs.length)
238
295
  return [];
239
- if (enqueue) {
240
- if (!database)
241
- throw new Error("[logic-sdk] Crons through a jobs adapter that stores them (like databaseQueue(database)) need `database`.");
242
- await database.transaction((tx) => enqueue(tx, jobs));
243
- }
296
+ await enqueueAlone(jobs);
244
297
  await deliver(jobs);
245
298
  return jobs.map((job) => job.cron);
246
299
  },
@@ -251,10 +304,70 @@ export function makeJobs(deps) {
251
304
  return result;
252
305
  },
253
306
  async retry(id) {
254
- if (!jobsAdapter.retry)
255
- 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.`);
256
- return jobsAdapter.retry(id);
307
+ if (jobsAdapter.retry)
308
+ return jobsAdapter.retry(id);
309
+ if (!failedStore)
310
+ 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}).`);
311
+ // out of the store, back to the queue with a fresh set of tries; a hand-off that fails puts it back and throws
312
+ const job = await failedStore.take(id);
313
+ if (!job)
314
+ return false;
315
+ const queued = [];
316
+ try {
317
+ await jobsAdapter.deliver([job], runnerInto(queued));
318
+ }
319
+ catch (error) {
320
+ await failedStore.fail(job, error);
321
+ throw error;
322
+ }
323
+ await deliver(queued);
324
+ return true;
325
+ },
326
+ async failed(options = {}) {
327
+ const store = jobsAdapter.failed ? jobsAdapter : failedStore;
328
+ if (!store?.failed)
329
+ throw new Error(`[logic-sdk] ${yours} can't list failed jobs. Use one that keeps them, or jobs.failed (${ADAPTERS}).`);
330
+ const { source, scope, limit = 100, cursor } = options;
331
+ if (!Number.isInteger(limit) || limit < 1 || limit > 1000)
332
+ throw new Error(`[logic-sdk] jobs.failed({ limit }) takes 1 to 1000 (got ${String(limit)}).`);
333
+ const page = await store.failed({ source, scope: scope === undefined ? undefined : scopeMatches(scope), limit, cursor });
334
+ return {
335
+ jobs: page.rows.map(({ id, job, error, failedAt }) => ({
336
+ id,
337
+ kind: job.kind,
338
+ source: infoOf(job).source,
339
+ scope: (job.kind === "call" ? job.scope : job.kind === "delivery" ? job.envelope.scope : undefined), // what `store` saved, typed by the caller
340
+ error,
341
+ failedAt,
342
+ job,
343
+ })),
344
+ cursor: page.cursor,
345
+ };
346
+ },
347
+ async forget(id) {
348
+ const store = jobsAdapter.forget ? jobsAdapter : failedStore;
349
+ if (!store?.forget)
350
+ 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}).`);
351
+ return store.forget(id);
352
+ },
353
+ /**
354
+ * 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
355
+ * tick for that minute still runs (stored adapters run each id once), and so does a second invoke.
356
+ */
357
+ async invoke(target, options = {}) {
358
+ const c = typeof target === "string" ? cronById.get(target) : crons.find((r) => r.cron === target);
359
+ if (!c)
360
+ throw new Error(typeof target === "string"
361
+ ? `[logic-sdk] jobs.invoke(${JSON.stringify(target)}): no cron has that id (${[...cronById.keys()].join(", ") || "none registered"}).`
362
+ : "[logic-sdk] jobs.invoke got a cron that isn't registered: export it from its module.");
363
+ 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 };
365
+ await enqueueAlone([job]);
366
+ const queued = [];
367
+ await jobsAdapter.deliver([job], runnerInto(queued)); // unlike a tick, a hand-off that fails throws: whoever invoked it needs to know
368
+ await deliver(queued);
369
+ return job.id;
257
370
  },
258
371
  };
259
- return { toJobs, deliver, jobs, due, checkHold };
372
+ return { toJobs, deliver, jobs, due, checkHold, checkRetries, yours };
260
373
  }
@@ -0,0 +1,120 @@
1
+ import type { Call, CallMetaOf, Config, ConfigOf, Constructor, Cron, CronCtx, DatabaseAdapter, DatabaseOptions, DbOf, EventDef, In, JobsOptions, Listener, ListenerCtx, ListenerMetaOf, Out, OwnModules, RegisteredCron, RegisteredEvent, RegisteredFn, RegisteredListener, Registry, RegistryOptions, Schema, ScopeOf, ServicesOf } from "./types.ts";
2
+ type TypedOptions<C extends Config, Mods extends Record<string, object>, T> = Omit<RegistryOptions<Mods>, "wrap" | "jobs"> & {
3
+ /** Background work: `jobs: { adapter: databaseQueue(), scope: { store, load } }`. Default: in-process, scope as-is (nothing waits). */
4
+ jobs?: JobsOptions<ScopeOf<C>, T>;
5
+ /** Wraps every call, including ones that fail validation or authorization: logging, tracing, audit. */
6
+ wrap?: (call: Call<CallMetaOf<C>>, next: () => Promise<unknown>) => Promise<unknown>;
7
+ } & ({} extends ServicesOf<C> ? {
8
+ services?: ServicesOf<C>;
9
+ } : {
10
+ services: ServicesOf<C>;
11
+ }) & ({} extends ConfigOf<C> ? {
12
+ config?: ConfigOf<C>;
13
+ } : {
14
+ config: ConfigOf<C>;
15
+ }) & ([DbOf<C>] extends [never] ? {
16
+ database?: undefined;
17
+ } : {
18
+ database: DatabaseOptions<DatabaseAdapter<unknown, DbOf<C>>>;
19
+ }) & {
20
+ modules: OwnModules<C, Mods>;
21
+ };
22
+ /** Keys `Config` doesn't know are errors, so a typo like `servises` can't be silently ignored. */
23
+ type OnlyKnownKeys<C> = {
24
+ [K in Exclude<keyof C, keyof Config>]: never;
25
+ };
26
+ /**
27
+ * Typed constructors for your app:
28
+ *
29
+ * ```ts
30
+ * export const { query, mutation, action, event, listener, createRegistry } = init<Config>();
31
+ * ```
32
+ */
33
+ export declare function init<C extends Config & OnlyKnownKeys<C>>(): {
34
+ /** Create the registry once at startup: `createRegistry({ modules, database, services })`. */
35
+ createRegistry: <const Mods extends Record<string, object>, T = ScopeOf<C>>(options: TypedOptions<C, Mods, T>) => Registry<ScopeOf<C>, Mods, ConfigOf<C>>;
36
+ /** Reads data. Can run other queries. No writes, no events, no services. */
37
+ query: Constructor<C, "query">;
38
+ /** Changes data inside one transaction. Can run queries and mutations (same transaction) and emit events. */
39
+ mutation: Constructor<C, "mutation">;
40
+ /** Talks to the outside world (payments, email, AI). No transaction; each mutation it runs commits on its own. */
41
+ action: Constructor<C, "action">;
42
+ /** Something that happened. Emitted by mutations, delivered after commit. */
43
+ event: <S extends Schema>(def: {
44
+ /**
45
+ * Stable id, local to its module: in a `notifications` module, `id: "send"` is `notifications.send`. Jobs store it,
46
+ * so set it before you rename the export and queued jobs keep finding this code. Defaults to the export name.
47
+ */
48
+ id?: string;
49
+ payload: S;
50
+ }) => EventDef<In<S>, Out<S>>;
51
+ /**
52
+ * Work on a schedule, as `scope` (a cron has no caller): a handler, like a listener's, run when the clock says. Export
53
+ * it from a module and call `registry.jobs.tick()` every minute (or from your platform's cron trigger). Must be
54
+ * idempotent: a retry runs the whole handler again.
55
+ * `cron({ schedule: "0 9 * * MON", scope: { kind: "system", job: "reports.weekly" }, async handler(ctx) { await ctx.run(send) } })`.
56
+ */
57
+ cron: <const Sc extends ScopeOf<C>>(def: CronDef<C, Sc>) => Cron<C>;
58
+ /**
59
+ * React to an event after commit, like an action. Must be idempotent.
60
+ * `listener({ event: () => bookings.confirmed, async handler(ctx, payload) {…} })`
61
+ */
62
+ listener: <O>(def: {
63
+ /**
64
+ * Stable id, local to its module: in a `notifications` module, `id: "send"` is `notifications.send`. Jobs store it,
65
+ * so set it before you rename the export and queued jobs keep finding this code. Defaults to the export name.
66
+ */
67
+ id?: string;
68
+ /** The event it reacts to, as a thunk so modules can import each other's barrels without cycles. */
69
+ event: () => EventDef<unknown, O>;
70
+ /**
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`, `outbox` and pg-boss, retried with `registry.jobs.retry(id)`).
73
+ */
74
+ attempts?: number;
75
+ /** Seconds after the event before the first try. Needs an adapter that holds jobs: `inProcess()` is refused. */
76
+ delay?: number;
77
+ /**
78
+ * Whether this event gets a job for this listener, like Laravel's `shouldQueue($event)`: false, and nothing is
79
+ * stored, run or counted. From the payload the handler gets (parsed), at commit, so sync and from the event only:
80
+ * a condition on the database belongs in the handler, since it can change before the job runs. A throw fails the
81
+ * mutation, as a bad payload does.
82
+ */
83
+ when?: (payload: O) => boolean;
84
+ meta?: ListenerMetaOf<C>;
85
+ handler: (ctx: ListenerCtx<C, O>, payload: O) => Promise<unknown>;
86
+ }) => Listener<O, C>;
87
+ };
88
+ /** `cron({...})`: its handler's `ctx.scope` is the scope it declares, so a policy-free read of it is typed. */
89
+ type CronDef<C extends Config, Sc> = {
90
+ /**
91
+ * Stable id, local to its module, like every definer's. Defaults to the export name. Jobs and pg-boss's queue store it,
92
+ * so set it before you rename the export.
93
+ */
94
+ id?: string;
95
+ /** Five fields: minute hour day-of-month month day-of-week. `"*\/15 * * * *"`, `"0 9 * * MON"`. */
96
+ schedule: string;
97
+ /** IANA name, like `"Europe/Madrid"`. Default UTC. Matched on the wall clock, like Laravel: mind DST at 1 to 3 am. */
98
+ timezone?: string;
99
+ /** Who it runs as: a cron has no caller. Every function the handler runs checks its policy against it. */
100
+ scope: Sc;
101
+ /** Tries in total, like a listener's. Default 1: a retry runs the whole handler again. */
102
+ attempts?: number;
103
+ meta?: ListenerMetaOf<C>;
104
+ /** The work, like a listener's handler: an action's ctx, plus `ctx.cron` (`scheduledAt`, `attempt`). */
105
+ handler: (ctx: CronCtx<C, Sc>) => Promise<unknown>;
106
+ };
107
+ /** Create the registry once at startup. Prefer the `createRegistry` returned by `init()`: it's typed with your config. */
108
+ export declare function createRegistry<S extends object = object, const Mods extends Record<string, object> = Record<string, object>>(options: RegistryOptions<Mods>): Registry<S, Mods, unknown>;
109
+ /**
110
+ * What `createRegistry` finds in your modules, without a database or services: every function, event, listener and
111
+ * cron with its id. For tools (the CLI, docs generators) that inspect an app without running it.
112
+ */
113
+ export declare function describeModules(modules: Record<string, object>): {
114
+ ids: Map<object, string>;
115
+ functions: RegisteredFn[];
116
+ events: RegisteredEvent[];
117
+ listeners: RegisteredListener[];
118
+ crons: RegisteredCron[];
119
+ };
120
+ export {};