logic-sdk 0.7.1 → 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.
Files changed (99) hide show
  1. package/README.md +9 -10
  2. package/dist/adapters/cloudflare-queue.d.ts +15 -0
  3. package/dist/adapters/cloudflare-queue.js +58 -0
  4. package/dist/adapters/drizzle-pg.d.ts +280 -0
  5. package/dist/adapters/drizzle-pg.js +78 -0
  6. package/dist/adapters/drizzle-sqlite.d.ts +273 -0
  7. package/dist/adapters/drizzle-sqlite.js +203 -0
  8. package/dist/adapters/postgres.d.ts +33 -0
  9. package/dist/adapters/postgres.js +129 -0
  10. package/dist/adapters/sqlite.d.ts +13 -0
  11. package/dist/adapters/sqlite.js +108 -0
  12. package/dist/adapters/stored-jobs.d.ts +89 -0
  13. package/dist/adapters/stored-jobs.js +370 -0
  14. package/dist/ai.d.ts +1 -32
  15. package/dist/ai.js +1 -40
  16. package/dist/cloudflare.d.ts +2 -55
  17. package/dist/cloudflare.js +2 -85
  18. package/dist/core/in-process.d.ts +9 -0
  19. package/dist/core/in-process.js +37 -0
  20. package/dist/core/jobs.d.ts +63 -0
  21. package/dist/core/jobs.js +514 -0
  22. package/dist/core/registry.d.ts +156 -0
  23. package/dist/core/registry.js +515 -0
  24. package/dist/core/testing.d.ts +75 -0
  25. package/dist/core/testing.js +232 -0
  26. package/dist/{types.d.ts → core/types.d.ts} +289 -64
  27. package/dist/drizzle/pg.d.ts +3 -236
  28. package/dist/drizzle/pg.js +2 -67
  29. package/dist/drizzle/sqlite.d.ts +3 -242
  30. package/dist/drizzle/sqlite.js +2 -194
  31. package/dist/fetch.d.ts +1 -19
  32. package/dist/fetch.js +1 -30
  33. package/dist/hosts/cloudflare.d.ts +43 -0
  34. package/dist/hosts/cloudflare.js +40 -0
  35. package/dist/hosts/node.d.ts +36 -0
  36. package/dist/hosts/node.js +103 -0
  37. package/dist/index.d.ts +5 -122
  38. package/dist/index.js +4 -492
  39. package/dist/integrations/ai.d.ts +32 -0
  40. package/dist/integrations/ai.js +40 -0
  41. package/dist/integrations/fetch.d.ts +19 -0
  42. package/dist/integrations/fetch.js +30 -0
  43. package/dist/integrations/orpc.d.ts +22 -0
  44. package/dist/integrations/orpc.js +37 -0
  45. package/dist/node.d.ts +1 -26
  46. package/dist/node.js +1 -76
  47. package/dist/orpc.d.ts +1 -21
  48. package/dist/orpc.js +1 -37
  49. package/dist/postgres.d.ts +2 -28
  50. package/dist/postgres.js +1 -82
  51. package/dist/sqlite.d.ts +2 -9
  52. package/dist/sqlite.js +1 -65
  53. package/dist/testing.d.ts +1 -75
  54. package/dist/testing.js +1 -227
  55. package/package.json +2 -12
  56. package/skills/logic-sdk/SKILL.md +6 -5
  57. package/src/adapters/cloudflare-queue.ts +65 -0
  58. package/src/adapters/drizzle-pg.ts +117 -0
  59. package/src/adapters/drizzle-sqlite.ts +241 -0
  60. package/src/adapters/postgres.ts +136 -0
  61. package/src/adapters/sqlite.ts +116 -0
  62. package/src/adapters/stored-jobs.ts +463 -0
  63. package/src/ai.ts +1 -62
  64. package/src/cloudflare.ts +2 -107
  65. package/src/core/in-process.ts +38 -0
  66. package/src/core/jobs.ts +548 -0
  67. package/src/core/registry.ts +719 -0
  68. package/src/core/testing.ts +309 -0
  69. package/src/{types.ts → core/types.ts} +280 -60
  70. package/src/drizzle/pg.ts +3 -110
  71. package/src/drizzle/sqlite.ts +3 -236
  72. package/src/fetch.ts +1 -31
  73. package/src/hosts/cloudflare.ts +55 -0
  74. package/src/hosts/node.ts +126 -0
  75. package/src/index.ts +17 -652
  76. package/src/integrations/ai.ts +63 -0
  77. package/src/integrations/fetch.ts +31 -0
  78. package/src/integrations/orpc.ts +47 -0
  79. package/src/node.ts +1 -99
  80. package/src/orpc.ts +1 -46
  81. package/src/postgres.ts +2 -90
  82. package/src/sqlite.ts +2 -74
  83. package/src/testing.ts +1 -305
  84. package/dist/jobs.d.ts +0 -44
  85. package/dist/jobs.js +0 -260
  86. package/dist/pg-boss.d.ts +0 -53
  87. package/dist/pg-boss.js +0 -213
  88. package/dist/stored-jobs.d.ts +0 -64
  89. package/dist/stored-jobs.js +0 -188
  90. package/src/jobs.ts +0 -307
  91. package/src/pg-boss.ts +0 -241
  92. package/src/stored-jobs.ts +0 -260
  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
package/src/testing.ts CHANGED
@@ -1,305 +1 @@
1
- import {
2
- replaceKeyOf,
3
- type Caller,
4
- type DatabaseAdapter,
5
- type DeepPartial,
6
- type CallJob,
7
- type Cron,
8
- type Delivery,
9
- type Envelope,
10
- type Fn,
11
- type FnIn,
12
- type FnOut,
13
- type Job,
14
- type JobOutcome,
15
- type JobsAdapter,
16
- type Listener,
17
- type Registry,
18
- } from "./index.ts";
19
- import { deliveryOf } from "./jobs.ts";
20
- import { INTERNAL } from "./types.ts";
21
-
22
- export interface TestOptions<Cf = unknown> {
23
- /** Replace services (e.g. `{ mailer: memoryMailer() }`). */
24
- services?: object;
25
- /** Override parts of `config` (e.g. `{ orders: { maxItems: 1 } }`). Merged over the registry's, section by section. */
26
- config?: DeepPartial<Cf>;
27
- /** Freeze time. */
28
- now?: Date | string | (() => Date);
29
- /**
30
- * `"inline"` (default): listeners run right after each mutation, inside the test. `"manual"`: jobs wait in
31
- * `t.jobs.queued` until you `drain()` them, to test one module without the others reacting. Like Oban's
32
- * `testing: :inline | :manual`. Either way, what waits (a listener's `delay`, `ctx.schedule`) waits for `drain()`, and
33
- * your app's adapter (a database queue, an outbox, Cloudflare) is never used.
34
- */
35
- jobs?: "inline" | "manual";
36
- }
37
-
38
- /** The jobs of the current test, like `registry.jobs` in production. */
39
- export interface TestJobs<S> {
40
- /** Listener jobs waiting: every one in `jobs: "manual"`, and the delayed ones in either mode. */
41
- readonly queued: readonly Delivery[];
42
- /** What `ctx.schedule` asked for, waiting for `drain()`. */
43
- readonly scheduled: readonly CallJob[];
44
- /**
45
- * Run what's due at the test's now (or `until`), and what that queues, until nothing due is left. Throws a failure.
46
- * Like Rails' `perform_enqueued_jobs(at:)` and Oban's `drain_queue(with_scheduled:)`.
47
- */
48
- drain(options?: { until?: Date | string }): Promise<void>;
49
- /** Run one listener by hand, as if its event had been emitted as `scope`. Throws its failure, like `drain()`. */
50
- perform<O>(listener: Listener<O>, payload: O, options: { scope: S; attempt?: number }): Promise<JobOutcome>;
51
- /**
52
- * Run one cron by hand, as its own scope, for the minute `at` (default: the test's now), whatever its schedule. Throws
53
- * its failure. `t.jobs.tick(at)` runs every cron due that minute instead.
54
- */
55
- perform(cron: Cron, options?: { at?: Date | string; attempt?: number }): Promise<JobOutcome>;
56
- /** Run the crons due in `at`'s minute (default: the test's now), here and now. Resolves their ids; throws a failure. */
57
- tick(at?: Date | string): Promise<string[]>;
58
- }
59
-
60
- export interface TestRegistry<S extends object, Mods extends Record<string, object>, Cf> {
61
- /** Open the test's transaction: `beforeEach(() => t.begin())`. */
62
- begin(): Promise<void>;
63
- /** Roll it back: `afterEach(() => t.rollback())`. */
64
- rollback(): Promise<void>;
65
- /** Bind who is calling, like `registry.as(...)`. A listener that fails makes `run` throw, so a test can't pass over it. */
66
- as(scope: S): Caller<S>;
67
- /** Replace a function's implementation for this test. Matched by identity, so `run(availability.hold, …)` hits the stub. */
68
- stub<F extends Fn>(fn: F, impl: (ctx: unknown, input: FnIn<F>) => Promise<FnOut<F>>): void;
69
- /** Every event emitted (and committed) in this test, in order. */
70
- readonly events: readonly Envelope[];
71
- /** The test transaction itself: read rows to assert on them. */
72
- readonly db: any;
73
- /** The registry bound to this test's transaction, for adapters: an oRPC context's `caller: t.registry.as(scope)`. */
74
- readonly registry: Registry<S, Mods, Cf>;
75
- readonly jobs: TestJobs<S>;
76
- }
77
-
78
- /** One test, between `begin` and `rollback`. */
79
- interface Open<S extends object, Mods extends Record<string, object>, Cf> {
80
- registry: Registry<S, Mods, Cf>;
81
- db: unknown;
82
- events: Envelope[];
83
- stubs: Map<Fn, (ctx: never, input: never) => Promise<unknown>>;
84
- queued: Delivery[];
85
- scheduled: CallJob[];
86
- /** Job failures (listeners, crons, scheduled calls) during the current call. */
87
- failures: unknown[];
88
- close(): Promise<void>;
89
- }
90
-
91
- class Rollback extends Error {}
92
-
93
- /**
94
- * The test's jobs adapter. What waits (a delayed listener, `ctx.schedule`) is held for `drain()`, and in `"manual"` so
95
- * is everything else; the rest runs now. It holds and replaces what your app's adapter does, so a test fails where
96
- * production would.
97
- */
98
- const testJobs = (mode: TestOptions["jobs"], app: JobsAdapter | undefined, queued: Delivery[], scheduled: CallJob[]): JobsAdapter => ({
99
- holds: app?.holds,
100
- replaces: app?.replaces,
101
- async deliver(jobs, runner) {
102
- for (const job of jobs) {
103
- const key = replaceKeyOf(job);
104
- if (key) {
105
- const waiting = scheduled.findIndex((c) => replaceKeyOf(c) === key);
106
- if (waiting >= 0) scheduled.splice(waiting, 1);
107
- }
108
- const waits = job.runAt !== undefined || (mode === "manual" && job.kind !== "cron");
109
- if (!waits) await runner.run({ ...job, attempts: 1 }); // one try, like inProcess(): reported, so the test sees it
110
- else if (job.kind === "call") scheduled.push(job);
111
- else if (job.kind === "delivery") queued.push(job);
112
- }
113
- },
114
- });
115
-
116
- /** Removes the jobs that are due from `list` and returns them. */
117
- function takeDue<T extends Job>(list: T[], cutoff: number): T[] {
118
- const due = (job: T) => !job.runAt || Date.parse(job.runAt) <= cutoff;
119
- const ready = list.filter(due);
120
- list.splice(0, list.length, ...list.filter((job) => !due(job)));
121
- return ready;
122
- }
123
-
124
- /**
125
- * Run each test inside a transaction that's rolled back, set up once with hooks:
126
- *
127
- * ```ts
128
- * const t = createTestRegistry(registry);
129
- * beforeEach(() => t.begin());
130
- * afterEach(() => t.rollback());
131
- * ```
132
- *
133
- * Every top-level mutation inside becomes a savepoint, so a failing mutation rolls back just its own writes, like it
134
- * would in production. Tests that share `t` run one at a time (one connection, nested savepoints).
135
- */
136
- export function createTestRegistry<S extends object, Mods extends Record<string, object>, Cf>(
137
- registry: Registry<S, Mods, Cf>,
138
- options: TestOptions<Cf> = {},
139
- ): TestRegistry<S, Mods, Cf> {
140
- const { options: registryOptions } = registry[INTERNAL];
141
- const fixed = options.now;
142
- const now = typeof fixed === "function" ? fixed : fixed === undefined ? undefined : () => new Date(fixed);
143
- /** While `drain()` runs a job that waited, the time it was due: what `ctx.now()` reads then. */
144
- let travelled: number | undefined;
145
- const clock = () => {
146
- const base = (now ?? registryOptions.now ?? (() => new Date()))();
147
- return travelled !== undefined && travelled > base.getTime() ? new Date(travelled) : base;
148
- };
149
- let open: Open<S, Mods, Cf> | undefined;
150
-
151
- const current = () => {
152
- if (!open) throw new Error("[logic-sdk] No test transaction. Add beforeEach(() => t.begin()) and afterEach(() => t.rollback()).");
153
- return open;
154
- };
155
-
156
- /** `db` is the test's transaction, and `database` the adapter nested in it (none without a database). */
157
- function start(db: unknown, database: DatabaseAdapter<unknown, unknown> | undefined, close: () => Promise<void>): Open<S, Mods, Cf> {
158
- const events: Envelope[] = [];
159
- const stubs: Open<S, Mods, Cf>["stubs"] = new Map();
160
- const queued: Delivery[] = [];
161
- const scheduled: CallJob[] = [];
162
- const failures: unknown[] = [];
163
- const derived = registry[INTERNAL].derive({
164
- database,
165
- services: options.services,
166
- config: options.config,
167
- now: clock,
168
- stubs,
169
- record: (e) => events.push(e),
170
- adapter: testJobs(options.jobs, registryOptions.jobs?.adapter, queued, scheduled),
171
- waitUntil: undefined, // listeners finish before a call returns, inside the test
172
- onError(error, info) {
173
- if (info.outcome !== "discarded") failures.push(error);
174
- registryOptions.onError?.(error, info);
175
- },
176
- });
177
- return { registry: derived, db, events, stubs, queued, scheduled, failures, close };
178
- }
179
-
180
- /** Run `work`, then throw the first listener failure since the last one thrown (calls through `t.registry` included). */
181
- async function settle<T>(state: Open<S, Mods, Cf>, work: () => Promise<T>): Promise<T> {
182
- let out: T;
183
- try {
184
- out = await work();
185
- } catch (e) {
186
- state.failures.length = 0; // what it threw is the failure: don't report it again on the next call
187
- throw e;
188
- }
189
- throwFailures(state);
190
- return out;
191
- }
192
- function throwFailures(state: Open<S, Mods, Cf>) {
193
- if (!state.failures.length) return;
194
- const [first] = state.failures.splice(0);
195
- throw first;
196
- }
197
-
198
- return {
199
- async begin() {
200
- if (open)
201
- throw new Error(
202
- "[logic-sdk] t.begin() ran again before t.rollback(). Roll back in afterEach, and don't run tests that share `t` at the same time (test.concurrent).",
203
- );
204
- const database = registryOptions.database;
205
- if (!database) {
206
- open = start(undefined, undefined, async () => {});
207
- return;
208
- }
209
- if (!database.nest) throw new Error("[logic-sdk] This database adapter can't nest transactions, so tests can't roll back.");
210
- // Drizzle transactions live inside a callback: park it there until rollback.
211
- const opened = Promise.withResolvers<unknown>();
212
- const released = Promise.withResolvers<void>();
213
- const done = database
214
- .transaction(async (tx) => {
215
- opened.resolve(tx);
216
- await released.promise;
217
- throw new Rollback();
218
- })
219
- .catch((e) => {
220
- if (!(e instanceof Rollback)) throw e;
221
- });
222
- const tx = await Promise.race([opened.promise, done]); // `done` settles first only if the transaction failed to open
223
- open = start(tx, database.nest(tx), async () => {
224
- released.resolve();
225
- await done;
226
- });
227
- },
228
- /** Also throws a listener failure nothing surfaced yet (a call through `t.registry`), so the test fails. */
229
- async rollback() {
230
- const state = open;
231
- open = undefined;
232
- await state?.close();
233
- if (state) throwFailures(state);
234
- },
235
- as: (scope) => ({
236
- scope,
237
- run: (fn, ...args) => {
238
- const state = current();
239
- return settle(state, () => state.registry.as(scope).run(fn, ...args));
240
- },
241
- }),
242
- stub: (fn, impl) => void current().stubs.set(fn, impl),
243
- get events() {
244
- return current().events;
245
- },
246
- get db() {
247
- return current().db;
248
- },
249
- get registry() {
250
- return current().registry;
251
- },
252
- jobs: {
253
- get queued() {
254
- return current().queued;
255
- },
256
- get scheduled() {
257
- return current().scheduled;
258
- },
259
- async drain({ until } = {}) {
260
- const state = current();
261
- const end = until === undefined ? clock() : new Date(until);
262
- if (Number.isNaN(end.getTime())) throw new Error(`[logic-sdk] drain({ until }) needs a valid date (got ${String(until)}).`);
263
- try {
264
- for (let round = 1; ; round++) {
265
- const ready = [...takeDue(state.queued, end.getTime()), ...takeDue(state.scheduled, end.getTime())];
266
- if (!ready.length) return;
267
- if (round > 100) throw new Error("[logic-sdk] drain() ran 100 rounds and jobs are still due: does one reschedule itself, inside `until`, more often than you meant?");
268
- ready.sort((a, b) => (a.runAt ?? "").localeCompare(b.runAt ?? ""));
269
- for (const job of ready) {
270
- // the job runs at the time it was due, so a self-rescheduling one moves forward and its checks see that time
271
- if (job.runAt) travelled = Math.max(travelled ?? 0, Date.parse(job.runAt));
272
- await settle(state, () => state.registry.jobs.run(job));
273
- }
274
- }
275
- } finally {
276
- travelled = undefined;
277
- }
278
- },
279
- perform(target: Listener<any> | Cron, ...rest: any[]) {
280
- const state = current();
281
- if (target.kind === "cron") {
282
- const { at, attempt } = (rest[0] ?? {}) as { at?: Date | string; attempt?: number };
283
- const cron = state.registry.definitions.crons.find((c) => c.cron === target);
284
- if (!cron) throw new Error("[logic-sdk] t.jobs.perform got a cron that isn't registered: export it from its module.");
285
- const when = at === undefined ? clock() : new Date(at);
286
- if (Number.isNaN(when.getTime())) throw new Error(`[logic-sdk] t.jobs.perform({ at }) needs a valid date (got ${String(at)}).`);
287
- const [job] = state.registry[INTERNAL].due(when, cron.id);
288
- return settle(state, () => state.registry.jobs.run(job!, { attempt }));
289
- }
290
- const listener = target;
291
- const [payload, { scope, attempt }] = rest as [unknown, { scope: S; attempt?: number }];
292
- const registered = state.registry.definitions.listeners.find((l) => l.listener === listener);
293
- if (!registered) throw new Error("[logic-sdk] t.jobs.perform got a listener that isn't registered: export it from its module.");
294
- const envelope = state.registry[INTERNAL].envelope(registered.event, payload, scope);
295
- return settle(state, () => state.registry.jobs.run(deliveryOf(registered, envelope), { attempt }));
296
- },
297
- async tick(at) {
298
- const state = current();
299
- const jobs = state.registry[INTERNAL].due(at === undefined ? clock() : new Date(at));
300
- for (const job of jobs) await settle(state, () => state.registry.jobs.run(job));
301
- return jobs.map((job) => job.cron);
302
- },
303
- },
304
- };
305
- }
1
+ export { createTestRegistry, type TestJobs, type TestOptions, type TestRegistry } from "./core/testing.ts";
package/dist/jobs.d.ts DELETED
@@ -1,44 +0,0 @@
1
- import type { ActionCtx, Call, CallJob, CronJob, DatabaseAdapter, Delivery, Envelope, FailureInfo, Fn, InProcess, Job, JobsAdapter, JobScope, Jobs, RegisteredCron, RegisteredFn, RegisteredListener } from "./types.ts";
2
- /**
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.
5
- */
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;
9
- /**
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`).
12
- */
13
- export declare const replaceKeyOf: (job: Job) => string | undefined;
14
- /** One listener's share of an event, as a job: `<listener id>@<event id>`, with the listener's tries. */
15
- export declare const deliveryOf: (l: RegisteredListener, e: Envelope) => Delivery;
16
- /** What running jobs needs from the registry: its definitions, and how it runs a function or a listener's handler. */
17
- export interface JobsDeps {
18
- listeners: readonly RegisteredListener[];
19
- crons: readonly RegisteredCron[];
20
- functions: readonly RegisteredFn[];
21
- idOf(x: object): string;
22
- jobsAdapter: JobsAdapter;
23
- database: DatabaseAdapter<unknown, unknown> | undefined;
24
- jobScope: JobScope | undefined;
25
- maxEventDepth: number;
26
- now(): Date;
27
- wrap(call: Call, next: () => Promise<unknown>): Promise<unknown>;
28
- report(error: unknown, info: FailureInfo): void;
29
- /** 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>;
31
- /** The ctx a listener's or cron's handler gets, as `scope`, in an event chain `eventDepth` deep. */
32
- handlerCtx(scope: object, eventDepth: number, id: string, queued: Job[] | undefined): ActionCtx<any>;
33
- }
34
- /**
35
- * Jobs, for one registry: a listener's share of an event, a cron's run, a scheduled call. Turns a commit's events and
36
- * calls into jobs, runs one (with its tries), and is what `registry.jobs` calls.
37
- */
38
- export declare function makeJobs(deps: JobsDeps): {
39
- toJobs: (envelopes: Envelope[], calls: CallJob[], parsed: Map<Envelope, unknown>) => Job[];
40
- deliver: (jobs: Job[]) => Promise<void>;
41
- jobs: Jobs;
42
- due: (at: Date, only?: string) => CronJob[];
43
- checkHold: (what: string, seconds: number) => void;
44
- };
package/dist/jobs.js DELETED
@@ -1,260 +0,0 @@
1
- import { CaughtNestedFailure, describeIssues, isDomainError, StalePayload } from "./errors.js";
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
- };
12
- /**
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.
15
- */
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
- /**
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`).
22
- */
23
- export const replaceKeyOf = (job) => (job.kind === "call" && job.replace !== undefined ? `${job.fn}@${job.replace}` : undefined);
24
- /** One listener's share of an event, as a job: `<listener id>@<event id>`, with the listener's tries. */
25
- export const deliveryOf = (l, e) => ({
26
- kind: "delivery",
27
- id: `${l.id}@${e.id}`,
28
- listener: l.id,
29
- envelope: e,
30
- attempts: l.listener.attempts ?? 1,
31
- });
32
- /**
33
- * Jobs, for one registry: a listener's share of an event, a cron's run, a scheduled call. Turns a commit's events and
34
- * calls into jobs, runs one (with its tries), and is what `registry.jobs` calls.
35
- */
36
- 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);
39
- const enqueue = jobsAdapter.enqueue?.bind(jobsAdapter);
40
- // ── listeners ────────────────────────────────────────────────────────────
41
- const byEvent = new Map();
42
- for (const l of listeners) {
43
- const name = idOf(l.event);
44
- byEvent.set(name, [...(byEvent.get(name) ?? []), l]);
45
- }
46
- const listenerById = new Map(listeners.map((l) => [l.id, l]));
47
- const scheduled = crons.map((c) => ({ ...c, schedule: parseSchedule(c.cron.schedule) }));
48
- const cronById = new Map(crons.map((c) => [c.id, c]));
49
- const fnById = new Map(functions.map((f) => [f.id, f]));
50
- /**
51
- * A job that waits (a listener's `delay`, `ctx.schedule`) needs an adapter that holds it: run early it'd be wrong,
52
- * kept in memory it'd be lost on restart. Laravel's sync queue drops the delay; we refuse instead.
53
- */
54
- function checkHold(what, seconds) {
55
- const { holds } = jobsAdapter;
56
- 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).`);
58
- 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.`);
60
- }
61
- for (const l of listeners)
62
- if (l.listener.delay)
63
- checkHold(l.id, l.listener.delay);
64
- /**
65
- * What a commit queues: one delivery per listener of each event that its `when` lets through, and the calls it
66
- * scheduled. Events and calls due now past `maxEventDepth` (a listener loop, a function scheduling itself with no
67
- * delay) are dropped, reported once.
68
- */
69
- function toJobs(envelopes, calls, parsed) {
70
- /** Its `when`, if any. A throw is a bug in the app: it fails the mutation, naming the listener. */
71
- const wants = (l, e, payload) => {
72
- try {
73
- return !l.listener.when || l.listener.when(payload);
74
- }
75
- catch (error) {
76
- throw new Error(`[logic-sdk] ${l.id}'s when threw on ${e.name}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
77
- }
78
- };
79
- const fits = (job) => job.depth <= maxEventDepth;
80
- const deepEvent = envelopes.find((e) => !fits(e));
81
- const deepCall = calls.find((c) => !fits(c));
82
- const loop = (what) => new Error(`[logic-sdk] chain of events and calls deeper than ${maxEventDepth} (jobs.maxEventDepth): stopped queueing ${what} (a loop?)`);
83
- if (deepEvent)
84
- report(loop(deepEvent.name), { source: deepEvent.name });
85
- else if (deepCall)
86
- report(loop(deepCall.fn), infoOf(deepCall));
87
- const deliveries = envelopes.filter(fits).flatMap((e) => (byEvent.get(e.name) ?? []).filter((l) => wants(l, e, parsed.get(e))).map((l) => {
88
- const job = deliveryOf(l, e);
89
- const delay = l.listener.delay;
90
- if (delay)
91
- job.runAt = new Date(Date.parse(e.occurredAt) + delay * 1000).toISOString();
92
- return job;
93
- }));
94
- return [...deliveries, ...calls.filter(fits)];
95
- }
96
- /** An adapter that couldn't take a commit's jobs: each one may be lost, so each is reported. */
97
- const reportEach = (error, jobs) => {
98
- for (const job of jobs)
99
- report(error, { source: "(jobs adapter)", job });
100
- };
101
- /** What `onError` hears about a job. */
102
- const infoOf = (job, attempt) => job.kind === "delivery"
103
- ? { source: job.listener, job, attempt }
104
- : { source: job.kind === "cron" ? job.cron : job.fn, job, attempt };
105
- /** Who a stored job runs as: `jobs.scope.load` rebuilds it; null means discard it (reported). */
106
- async function scopeOf(job, stored, attempt) {
107
- if (!jobScope?.load)
108
- return stored;
109
- const loaded = await jobScope.load(stored);
110
- if (loaded === undefined)
111
- throw new Error(`[logic-sdk] jobs.scope.load returned undefined for ${job.id}. Return the scope, or null to discard the job.`);
112
- if (loaded === null)
113
- report(new Error(`[logic-sdk] jobs.scope.load returned null for ${job.id}, so it was discarded.`), { ...infoOf(job, attempt), outcome: "discarded" });
114
- return loaded;
115
- }
116
- /**
117
- * Run one job: a listener's share of an event, a cron's run, or a scheduled call. Reports every failure; throws only when a retry might
118
- * help and there are tries left. `fail` keeps a job that failed for good. The jobs it queues land in `queued`, for
119
- * `deliver` to run once this one is settled; without it (`registry.jobs.run`, in a consumer) they're delivered at once.
120
- */
121
- async function runJob(job, { attempt = 1, fail } = {}, queued) {
122
- const info = infoOf(job, attempt);
123
- // read before narrowing: a job queued by another version can have a kind this one doesn't know
124
- const { id, kind } = job;
125
- const failed = async (error) => {
126
- report(error, { ...info, outcome: "failed" });
127
- await fail?.(error);
128
- return "failed";
129
- };
130
- /** One try of the job's `attempts`. */
131
- const attemptOnce = async (work) => {
132
- const { attempts } = job;
133
- // its last try was claimed but never finished: a crash, or slower than the lease (Laravel checks this too)
134
- if (attempt > attempts)
135
- return failed(new Error(`[logic-sdk] ${job.id} has used its ${attempts} attempt(s): the last one never finished (crashed or outlived the lease), or its result wasn't recorded.`));
136
- try {
137
- return await work();
138
- }
139
- catch (error) {
140
- // a caught nested failure is retried as its cause would be: a swallowed `reject` still fails at once
141
- const decisive = error instanceof CaughtNestedFailure ? error.cause : error;
142
- const retrying = attempt < attempts && !(decisive instanceof StalePayload) && !(isDomainError(decisive) && decisive.kind !== "conflict");
143
- if (!retrying)
144
- return failed(error);
145
- report(error, { ...info, outcome: "retry" });
146
- throw error;
147
- }
148
- };
149
- // code this process doesn't have (renamed, removed, or not deployed here yet) is a try like any other, as Laravel
150
- // treats a missing class: in a rolling deploy the new code gets a later one.
151
- const cantRun = (why) => attemptOnce(async () => {
152
- throw new Error(`[logic-sdk] ${why}`);
153
- });
154
- const missing = (what, id) => cantRun(`${id} isn't a registered ${what} (renamed, removed or not deployed here yet?), so job ${job.id} can't run.`);
155
- if (job.kind === "cron") {
156
- const c = cronById.get(job.cron);
157
- if (!c)
158
- return missing("cron", job.cron);
159
- return attemptOnce(async () => {
160
- // its scope comes from the code each time, never stored, so jobs.scope store and load don't apply
161
- const { scope, meta, handler } = c.cron;
162
- 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 }));
164
- return "done";
165
- });
166
- }
167
- if (job.kind === "call") {
168
- const f = fnById.get(job.fn);
169
- if (!f)
170
- return missing("function", job.fn);
171
- return attemptOnce(async () => {
172
- const scope = await scopeOf(job, job.scope, attempt);
173
- if (!scope)
174
- return "discarded";
175
- await runAs(f.fn, job.input, scope, job.depth, queued);
176
- return "done";
177
- });
178
- }
179
- if (job.kind !== "delivery")
180
- return cantRun(`job ${id} has kind ${JSON.stringify(kind)}, which this version can't run.`);
181
- const l = listenerById.get(job.listener);
182
- if (!l)
183
- return missing("listener", job.listener);
184
- const { envelope } = job;
185
- return attemptOnce(async () => {
186
- const scope = await scopeOf(job, envelope.scope, attempt);
187
- if (!scope)
188
- return "discarded";
189
- await wrap({ id: l.id, kind: "listener", meta: l.listener.meta, input: envelope.payload, scope, depth: 0 }, async () => {
190
- // its listener's event now: one renamed without an `id`, or a listener moved to another event, leaves stale jobs
191
- if (idOf(l.event) !== envelope.name)
192
- throw new StalePayload(`[logic-sdk] ${l.id} now listens to ${idOf(l.event)}, and this job is for ${envelope.name}.`);
193
- const r = await l.event.payload["~standard"].validate(envelope.payload);
194
- if (r.issues)
195
- throw new StalePayload(`[logic-sdk] ${envelope.name} payload no longer matches its schema: ${JSON.stringify(describeIssues(r.issues))}`);
196
- const payload = r.value;
197
- 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
199
- });
200
- return "done";
201
- });
202
- }
203
- /** A runner whose jobs' own jobs are collected in `queued`. */
204
- const runnerInto = (queued) => ({
205
- run: (job, options) => runJob(job, options, queued),
206
- report: (e, job, attempt) => report(e, infoOf(job, attempt)),
207
- });
208
- /**
209
- * Deliver jobs, then the jobs those queued, and so on. A job is settled before what it queued starts, as a Laravel
210
- * worker deletes a job before it pops the ones it pushed: a crash in a follow-up can't run the job again.
211
- */
212
- async function deliver(jobs) {
213
- while (jobs.length) {
214
- const batch = jobs;
215
- jobs = [];
216
- await jobsAdapter.deliver(batch, runnerInto(jobs)).catch((e) => reportEach(e, batch));
217
- }
218
- }
219
- /**
220
- * 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.
221
- * With `only`, that cron's run for the minute, due or not (`t.jobs.perform`).
222
- */
223
- 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
228
- return scheduled
229
- .filter((c) => (only === undefined ? isDue(c.schedule, minute, c.cron.timezone) : c.id === only))
230
- .map((c) => ({ kind: "cron", id: `${c.id}@${stamp}`, cron: c.id, scheduledAt: minute.toISOString(), attempts: c.cron.attempts ?? 1 }));
231
- }
232
- const jobs = {
233
- // a consumer's own `fail` (pg-boss's work(), which records the reason itself) wins over the adapter's
234
- run: (job, options) => runJob(job, { ...options, fail: options?.fail ?? (keepFailed && ((error) => keepFailed(job, error))) }),
235
- async tick(at = now()) {
236
- const jobs = due(at);
237
- if (!jobs.length)
238
- 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
- }
244
- await deliver(jobs);
245
- return jobs.map((job) => job.cron);
246
- },
247
- async sweep(options) {
248
- const queued = [];
249
- const result = (await jobsAdapter.sweep?.(runnerInto(queued), options)) ?? { done: 0, failed: 0, discarded: 0, retrying: 0 };
250
- await deliver(queued);
251
- return result;
252
- },
253
- 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);
257
- },
258
- };
259
- return { toJobs, deliver, jobs, due, checkHold };
260
- }
package/dist/pg-boss.d.ts DELETED
@@ -1,53 +0,0 @@
1
- import { type PgBoss, type Queue, type WorkOptions } from "pg-boss";
2
- import { type ForListeners, type Jobs, type JobsAdapter, type Registry } from "./index.ts";
3
- /** One queue's tuning: a listener's or cron's `meta.pgBoss`, and `work()`'s `calls`. */
4
- export interface PgBossTuning {
5
- /** The listener's queue (`expireInSeconds`, `retryDelay`, `deadLetter`…), applied by `work()`. `partition` only when it's created. */
6
- queue?: Omit<Queue, "name" | "retryLimit" | "retryBackoff" | "policy">;
7
- /** Its workers in each process that calls `work()`: `localConcurrency`, `batchSize`, `pollingIntervalSeconds`… */
8
- worker?: Omit<WorkOptions, "includeMetadata" | "perJobResults" | "transactional" | "transactionTimeoutSeconds">;
9
- }
10
- /**
11
- * What this adapter reads from a listener's or cron's `meta` (not a function's): `init<{ meta: PgBossMeta & AppMeta }>()`, then
12
- * `meta: { pgBoss: { queue: { expireInSeconds: 120 }, worker: { localConcurrency: 5 } } }`. Tuning only: retries are the
13
- * listener's `attempts`, and the other adapters ignore it.
14
- */
15
- export type PgBossMeta = ForListeners<{
16
- pgBoss?: PgBossTuning;
17
- }>;
18
- /**
19
- * The pg-boss id of a job: a UUID v5 of its logic-sdk id (pg-boss ids are UUIDs). The same job is the same row, so a
20
- * minute ticked by several servers inserts once. Use it to find a job in pg-boss: `boss.findJobs(queue, { id: pgBossId(id) })`.
21
- */
22
- export declare function pgBossId(id: string): string;
23
- /**
24
- * Jobs in pg-boss, inserted in your mutation's transaction, so a rollback leaves none and a commit always has them,
25
- * like Oban. Run them with `work(registry, boss)` in a worker process. Every process that enqueues calls
26
- * `await boss.start()` first.
27
- *
28
- * ```ts
29
- * const boss = new PgBoss(process.env.DATABASE_URL!);
30
- * boss.on("error", console.error);
31
- * const registry = createRegistry({ modules, database: drizzleAdapter(db), jobs: { adapter: pgBoss(boss), scope: { store, load } } });
32
- * ```
33
- */
34
- export declare function pgBoss(boss: PgBoss): JobsAdapter;
35
- export interface PgBossWorkOptions {
36
- /** The shared queue of scheduled calls, tuned like a listener's `meta.pgBoss`: `{ worker: { localConcurrency: 10 } }`. */
37
- calls?: PgBossTuning;
38
- /** Where a failed cron tick goes, and a queue left with jobs but no listener. Default `console.error`. */
39
- onError?: (error: unknown) => void;
40
- }
41
- /**
42
- * Your worker process: a queue and its workers for every listener and cron, one for scheduled calls, and the cron tick
43
- * every minute. `boss.stop()` stops all of it. Applies each listener's and cron's `meta.pgBoss`.
44
- *
45
- * ```ts
46
- * await boss.start();
47
- * await work(registry, boss);
48
- * process.on("SIGTERM", () => boss.stop()); // waits for running jobs, 30 s at most
49
- * ```
50
- */
51
- export declare function work(registry: Pick<Registry, "definitions"> & {
52
- jobs: Pick<Jobs, "run" | "tick" | "sweep">;
53
- }, boss: PgBoss, options?: PgBossWorkOptions): Promise<void>;