logic-sdk 0.3.0 → 0.5.0

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 (57) hide show
  1. package/README.md +47 -22
  2. package/dist/ai.d.ts +16 -29
  3. package/dist/ai.js +13 -24
  4. package/dist/cloudflare.d.ts +55 -0
  5. package/dist/cloudflare.js +85 -0
  6. package/dist/drizzle/pg.d.ts +237 -0
  7. package/dist/drizzle/pg.js +67 -0
  8. package/dist/drizzle/sqlite.d.ts +242 -0
  9. package/dist/drizzle/sqlite.js +194 -0
  10. package/dist/errors.d.ts +33 -0
  11. package/dist/errors.js +45 -0
  12. package/dist/fetch.d.ts +15 -18
  13. package/dist/fetch.js +18 -55
  14. package/dist/index.d.ts +80 -443
  15. package/dist/index.js +261 -229
  16. package/dist/jobs.d.ts +44 -0
  17. package/dist/jobs.js +252 -0
  18. package/dist/node.d.ts +26 -0
  19. package/dist/node.js +76 -0
  20. package/dist/orpc.d.ts +10 -20
  21. package/dist/orpc.js +19 -28
  22. package/dist/pg-boss.d.ts +55 -0
  23. package/dist/pg-boss.js +211 -0
  24. package/dist/postgres.d.ts +28 -0
  25. package/dist/postgres.js +82 -0
  26. package/dist/schedule.d.ts +23 -0
  27. package/dist/schedule.js +109 -0
  28. package/dist/sqlite.d.ts +9 -0
  29. package/dist/sqlite.js +65 -0
  30. package/dist/stored-jobs.d.ts +64 -0
  31. package/dist/stored-jobs.js +188 -0
  32. package/dist/testing.d.ts +51 -15
  33. package/dist/testing.js +198 -46
  34. package/dist/types.d.ts +653 -0
  35. package/dist/types.js +6 -0
  36. package/package.json +45 -7
  37. package/skills/logic-sdk/SKILL.md +114 -0
  38. package/src/ai.ts +29 -51
  39. package/src/cloudflare.ts +107 -0
  40. package/src/drizzle/pg.ts +111 -0
  41. package/src/drizzle/sqlite.ts +236 -0
  42. package/src/errors.ts +59 -0
  43. package/src/fetch.ts +17 -65
  44. package/src/index.ts +422 -572
  45. package/src/jobs.ts +296 -0
  46. package/src/node.ts +99 -0
  47. package/src/orpc.ts +24 -43
  48. package/src/pg-boss.ts +242 -0
  49. package/src/postgres.ts +90 -0
  50. package/src/schedule.ts +129 -0
  51. package/src/sqlite.ts +74 -0
  52. package/src/stored-jobs.ts +260 -0
  53. package/src/testing.ts +253 -56
  54. package/src/types.ts +683 -0
  55. package/dist/drizzle.d.ts +0 -18
  56. package/dist/drizzle.js +0 -23
  57. package/src/drizzle.ts +0 -39
@@ -0,0 +1,260 @@
1
+ // Jobs in your database, written in the mutation's transaction: run from there (databaseQueue), or kept until a queue
2
+ // has them (outbox). The table's statements are SQL, one set per database (postgres.ts, sqlite.ts), and run through
3
+ // the database adapter's `query`, so this file knows no ORM and no driver.
4
+ import { replaceKeyOf, type Job, type JobOutcome, type JobsAdapter, type Runner, type SqlDatabase, type SweepResult } from "./index.ts";
5
+
6
+ /**
7
+ * The table's statements for one database. Parameters are strings and numbers only, so no driver has to guess a type:
8
+ * lists of ids and rows travel as one JSON string, times as seconds from the database's clock. Each appears once, in
9
+ * the order written here, so a database with positional `?` works too. Each returns the columns named, lowercase.
10
+ */
11
+ export interface JobsSql {
12
+ /** `(pickup, rows)`: rows is JSON `[{ id, job, at, key }]`, `at` in epoch ms or null (due now, a sweep's after `pickup` seconds). A waiting row with the same `key` becomes the new one. */
13
+ insert: string;
14
+ /** `(ids)`: records cron ticks nobody recorded yet. Returns `id`. */
15
+ recordTicks: string;
16
+ /** `()`: forgets ticks older than a day. */
17
+ pruneTicks: string;
18
+ /** `(receipt, lease, ids)`: the first claim, of rows nobody claimed. Returns `id`. */
19
+ claimNew: string;
20
+ /** `(receipt, lease)`: claims the one row due first. Returns `job` (JSON text) and `attempts`. */
21
+ claimDue: string;
22
+ /** `(lease, ids, receipt)`, on rows this receipt still owns, like the three below. */
23
+ extend: string;
24
+ /** `(seconds, error, ids, receipt)` */
25
+ backOff: string;
26
+ /** `(error, ids, receipt)` */
27
+ markFailed: string;
28
+ /** `(ids, receipt)` */
29
+ remove: string;
30
+ /** `(id)`: a failed row back in line. Returns `id`. */
31
+ retry: string;
32
+ /** `(id, job, error)`: a failed row, new or over the one there. */
33
+ fail: string;
34
+ }
35
+
36
+ /** Seconds a job due now waits for the request that queued it, before a sweep may take it: how soon a crash after commit is noticed. */
37
+ const PICKUP = 30;
38
+
39
+ /**
40
+ * Seconds a runner keeps extending a job's lease: the limit of a Workers cron or queue consumer, and pg-boss's default
41
+ * expiry. Past it, a job that hangs is taken over like a crashed one. A longer job needs a `lease` that long.
42
+ */
43
+ const MAX_EXTEND = 15 * 60;
44
+
45
+ /** Who owns a job while it runs. */
46
+ interface Claim {
47
+ receipt: string;
48
+ attempt: number;
49
+ }
50
+
51
+ export interface DatabaseQueueOptions {
52
+ /**
53
+ * Seconds a runner owns a job before a sweep may take it over: how soon a crash is noticed. Default 300. A running
54
+ * job extends it every third of it, for 15 minutes, so it needn't cover your slowest listener, unless one takes
55
+ * longer than that.
56
+ */
57
+ lease?: number;
58
+ /** Seconds to wait after a failed try. Default `Math.exp(Math.min(attempt, 10))`, the curve Graphile Worker uses. */
59
+ backoff?: (attempt: number) => number;
60
+ }
61
+
62
+ export interface OutboxOptions {
63
+ /** Seconds a send owns its jobs: how soon one that crashed is sent again. Default 300. */
64
+ lease?: number;
65
+ /** Seconds to wait after a failed send. Default `Math.exp(Math.min(attempt, 10))`, the curve Graphile Worker uses. */
66
+ backoff?: (attempt: number) => number;
67
+ /**
68
+ * Failed sends before the row is marked failed. Default 10: about 3.5 hours of backoff in all. A listener's own tries
69
+ * are its `attempts`.
70
+ */
71
+ maxAttempts?: number;
72
+ }
73
+
74
+ /** What `databaseQueue` and `outbox` return. You call it through the registry: `registry.jobs.sweep()`, `registry.jobs.retry(id)`. */
75
+ export interface StoredJobs extends JobsAdapter {
76
+ /** What's due (retries, delayed jobs, what a crash left behind), claimed one at a time. */
77
+ sweep(runner: Runner, options?: { limit?: number }): Promise<SweepResult>;
78
+ /** Put a failed row back in line, with a fresh set of attempts. `false` when no failed row has that id. */
79
+ retry(id: string): Promise<boolean>;
80
+ }
81
+
82
+ /** Both: rows in `logic_jobs`, claimed by receipt. Without `via` they run here; with it they're sent. */
83
+ /** Seconds to wait after a failed try: e^attempt, capped at e^10 (about 6 hours), the curve Graphile Worker uses. */
84
+ export const defaultBackoff = (attempt: number) => Math.exp(Math.min(attempt, 10));
85
+
86
+ export function storedJobs(sql: JobsSql, database: SqlDatabase, options: OutboxOptions, via?: JobsAdapter): StoredJobs {
87
+ const lease = options.lease ?? 300;
88
+ const maxAttempts = options.maxAttempts ?? 10;
89
+ const backoff = options.backoff ?? defaultBackoff;
90
+ /** Outside a mutation: on the database itself. */
91
+ const query = (text: string, params: unknown[]) => database.query(database.db, text, params);
92
+ const list = (ids: string[]) => JSON.stringify(ids);
93
+
94
+ // These three only land on rows still pending under this claim (each statement says so): a slow runner can't undo a
95
+ // newer runner's work, and a handoff that finishes late can't delete the failure a consumer already recorded. By
96
+ // receipt, not attempt number: `retry(id)` starts those again at 1.
97
+ const markFailed = (ids: string[], claim: Claim, error: unknown) => query(sql.markFailed, [describe(error), list(ids), claim.receipt]);
98
+ const backOff = (ids: string[], claim: Claim, error: unknown) => query(sql.backOff, [backoff(claim.attempt), describe(error), list(ids), claim.receipt]);
99
+ const remove = (ids: string[], claim: Claim) => query(sql.remove, [list(ids), claim.receipt]);
100
+
101
+ /**
102
+ * While a job runs, its lease is extended, as Laravel Cloud does on SQS: a slow job stays its runner's, and a dead
103
+ * runner's job is free a lease later. Returns the stop, which waits for the extension on its way: landing after a
104
+ * backoff, it would replace the backoff.
105
+ */
106
+ function keepExtending(job: Job, claim: Claim, runner: Runner): () => Promise<unknown> {
107
+ const until = Date.now() + MAX_EXTEND * 1000;
108
+ let extending: Promise<unknown> = Promise.resolve();
109
+ const timer = setInterval(
110
+ () => {
111
+ if (Date.now() >= until) return clearInterval(timer);
112
+ extending = extending
113
+ .then(() => query(sql.extend, [lease, list([job.id]), claim.receipt]))
114
+ .catch((e) => runner.report(e, job, claim.attempt));
115
+ },
116
+ (lease * 1000) / 3,
117
+ );
118
+ return () => {
119
+ clearInterval(timer);
120
+ return extending;
121
+ };
122
+ }
123
+
124
+ /**
125
+ * Run one claimed job here and record how it went. The core decides: `failed` (its `fail` wrote the row), a throw
126
+ * (tries left: back off), or done and discarded (delete the row).
127
+ */
128
+ async function run(job: Job, claim: Claim, runner: Runner): Promise<keyof SweepResult> {
129
+ const stopExtending = keepExtending(job, claim, runner);
130
+ let outcome: JobOutcome;
131
+ try {
132
+ outcome = await runner
133
+ .run(job, {
134
+ attempt: claim.attempt,
135
+ fail: async (error) => {
136
+ await markFailed([job.id], claim, error);
137
+ },
138
+ })
139
+ .finally(stopExtending);
140
+ } catch (e) {
141
+ await backOff([job.id], claim, e);
142
+ return "retrying";
143
+ }
144
+ if (outcome !== "failed") await remove([job.id], claim);
145
+ return outcome;
146
+ }
147
+
148
+ /** Hand claimed jobs to `via` in one send. Done once the queue has them; a failed send keeps them all for a retry. */
149
+ async function handOff(queue: JobsAdapter, jobs: Job[], claim: Claim, runner: Runner): Promise<keyof SweepResult> {
150
+ const ids = jobs.map((j) => j.id);
151
+ try {
152
+ await queue.deliver(jobs, runner);
153
+ } catch (e) {
154
+ for (const job of jobs) runner.report(e, job, claim.attempt); // the queue's failure, not the listener's: run never saw it
155
+ if (claim.attempt >= maxAttempts) {
156
+ await markFailed(ids, claim, e);
157
+ return "failed";
158
+ }
159
+ await backOff(ids, claim, e);
160
+ return "retrying";
161
+ }
162
+ await remove(ids, claim);
163
+ return "done";
164
+ }
165
+
166
+ /** A cron's minute runs once: records the ticks no one recorded yet and returns their ids. Prunes old ones. */
167
+ async function recordTicks(tx: unknown, ticks: Job[]): Promise<Set<unknown>> {
168
+ if (!ticks.length) return new Set();
169
+ const first = await database.query(tx, sql.recordTicks, [list(ticks.map((j) => j.id))]);
170
+ await database.query(tx, sql.pruneTicks, []);
171
+ return new Set(first.map((row) => row.id));
172
+ }
173
+
174
+ const settle = (job: Job, claim: Claim, runner: Runner) => (via ? handOff(via, [job], claim, runner) : run(job, claim, runner));
175
+
176
+ /** The first claim of jobs just committed, by the request that queued them: the ones no sweep took meanwhile. */
177
+ async function claimNew(jobs: Job[]): Promise<{ claim: Claim; won: Job[] }> {
178
+ const claim = { receipt: crypto.randomUUID(), attempt: 1 };
179
+ const rows = await query(sql.claimNew, [claim.receipt, lease, list(jobs.map((j) => j.id))]);
180
+ const ids = new Set(rows.map((row) => row.id));
181
+ return { claim, won: jobs.filter((j) => ids.has(j.id)) }; // in emit order: RETURNING has none
182
+ }
183
+
184
+ return {
185
+ holds: true, // rows wait until they're due, however long, so `via`'s limits on delays don't apply
186
+ replaces: true, // a waiting row is replaced in place; under `via` too, since rows wait here until they're due
187
+ /** Must share the transaction it writes in. */
188
+ check({ database: given }) {
189
+ if (given && given.db !== database.db)
190
+ throw new Error(
191
+ `[logic-sdk] ${via ? "outbox(database, queue)" : "databaseQueue(database)"} must use the same database as \`database\`: jobs are written in your mutation's transaction. ` +
192
+ "A queue in another database goes behind an outbox: outbox(database, queue).",
193
+ );
194
+ },
195
+ /**
196
+ * Inside the mutation's transaction: one unclaimed row per job. Due now: a sweep leaves it `PICKUP` seconds to this
197
+ * request. Delayed: available from `runAt`, for a sweep. A cron's minute runs once: only ticks nobody recorded yet.
198
+ */
199
+ async enqueue(tx, jobs) {
200
+ const firstTicks = await recordTicks(tx, jobs.filter((j) => j.kind === "cron"));
201
+ const rows = jobs
202
+ .filter((j) => j.kind !== "cron" || firstTicks.has(j.id))
203
+ .map((j) => ({ id: j.id, job: j, at: j.runAt ? Date.parse(j.runAt) : null, key: replaceKeyOf(j) ?? null }))
204
+ // in key order, so two transactions replacing the same keys lock them in the same order and can't deadlock
205
+ .sort((a, b) => byText(a.key ?? "", b.key ?? ""));
206
+ if (rows.length) await database.query(tx, sql.insert, [PICKUP, JSON.stringify(rows)]);
207
+ },
208
+ /**
209
+ * After commit, in this request: each job is claimed just before it runs, so a slow or dead one doesn't spend the
210
+ * others' attempt. Under `via` they're claimed together, for one send. What isn't claimed yet when the process dies
211
+ * is a sweep's, as a first try.
212
+ */
213
+ async deliver(jobs, runner) {
214
+ const due = jobs.filter((j) => !j.runAt);
215
+ if (!due.length) return;
216
+ if (via) {
217
+ const { claim, won } = await claimNew(due);
218
+ if (won.length) await handOff(via, won, claim, runner);
219
+ return;
220
+ }
221
+ for (const job of due) {
222
+ try {
223
+ const { claim, won } = await claimNew([job]);
224
+ if (won.length) await run(job, claim, runner);
225
+ } catch (e) {
226
+ runner.report(e, job, 1); // its bookkeeping failed (a lost connection): a sweep sorts it out, and the others still run
227
+ }
228
+ }
229
+ },
230
+ /** One at a time, so every claim gets a full lease and a job the queue rejects (too big) can't hold back the others. */
231
+ async sweep(runner, { limit = 100 } = {}) {
232
+ const result: SweepResult = { done: 0, failed: 0, discarded: 0, retrying: 0 };
233
+ for (let i = 0; i < limit; i++) {
234
+ const receipt = crypto.randomUUID();
235
+ const [row] = await query(sql.claimDue, [receipt, lease]);
236
+ if (!row) break;
237
+ const job: Job = JSON.parse(String(row.job)); // claimDue returns it as JSON text, on every driver
238
+ const attempt = Number(row.attempts);
239
+ try {
240
+ result[await settle(job, { receipt, attempt }, runner)]++;
241
+ } catch (e) {
242
+ runner.report(e, job, attempt); // its bookkeeping failed (a lost connection): its lease brings it back
243
+ }
244
+ }
245
+ return result;
246
+ },
247
+ /** Failed rows only: a pending one belongs to its runner or a sweep, and resetting it could run it twice at once. */
248
+ async retry(id) {
249
+ return (await query(sql.retry, [id])).length > 0;
250
+ },
251
+ /** A job that failed for good in a queue consumer: keep it as a failed row, so you can query it and `retry` it. */
252
+ async fail(job, error) {
253
+ await query(sql.fail, [job.id, JSON.stringify(job), describe(error)]);
254
+ },
255
+ };
256
+ }
257
+
258
+ /** Not `localeCompare`: processes with another locale would lock in another order. */
259
+ const byText = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
260
+ const describe = (e: unknown) => (e instanceof Error ? (e.stack ?? e.message) : String(e)); // a stack starts with the message
package/src/testing.ts CHANGED
@@ -1,4 +1,22 @@
1
- import { internal, type Caller, type DeepPartial, type Envelope, type Fn, type FnIn, type FnOut, type Registry } from "./index.ts";
1
+ import {
2
+ replaceKeyOf,
3
+ type Caller,
4
+ type DatabaseAdapter,
5
+ type DeepPartial,
6
+ type CallJob,
7
+ type Delivery,
8
+ type Envelope,
9
+ type Fn,
10
+ type FnIn,
11
+ type FnOut,
12
+ type Job,
13
+ type JobOutcome,
14
+ type JobsAdapter,
15
+ type Listener,
16
+ type Registry,
17
+ } from "./index.ts";
18
+ import { deliveryOf } from "./jobs.ts";
19
+ import { INTERNAL } from "./types.ts";
2
20
 
3
21
  export interface TestOptions<Cf = unknown> {
4
22
  /** Replace services (e.g. `{ mailer: memoryMailer() }`). */
@@ -7,85 +25,264 @@ export interface TestOptions<Cf = unknown> {
7
25
  config?: DeepPartial<Cf>;
8
26
  /** Freeze time. */
9
27
  now?: Date | string | (() => Date);
10
- /** Run listeners inline after each mutation (default), or not at all to test one module in isolation. */
11
- listeners?: boolean;
28
+ /**
29
+ * `"inline"` (default): listeners run right after each mutation, inside the test. `"manual"`: jobs wait in
30
+ * `t.jobs.queued` until you `drain()` them, to test one module without the others reacting. Like Oban's
31
+ * `testing: :inline | :manual`. Either way, what waits (a listener's `delay`, `ctx.schedule`) waits for `drain()`, and
32
+ * your app's adapter (a database queue, an outbox, Cloudflare) is never used.
33
+ */
34
+ jobs?: "inline" | "manual";
12
35
  }
13
36
 
14
- export interface TestTransaction<S extends object, Mods extends Record<string, object> = Record<string, object>, Cf = unknown> {
15
- /** Bind who is calling, exactly like `registry.as(...)`. */
37
+ /** The jobs of the current test, like `registry.jobs` in production. */
38
+ export interface TestJobs<S> {
39
+ /** Listener jobs waiting: every one in `jobs: "manual"`, and the delayed ones in either mode. */
40
+ readonly queued: readonly Delivery[];
41
+ /** What `ctx.schedule` asked for, waiting for `drain()`. */
42
+ readonly scheduled: readonly CallJob[];
43
+ /**
44
+ * Run what's due at the test's now (or `until`), and what that queues, until nothing due is left. Throws a failure.
45
+ * Like Rails' `perform_enqueued_jobs(at:)` and Oban's `drain_queue(with_scheduled:)`.
46
+ */
47
+ drain(options?: { until?: Date | string }): Promise<void>;
48
+ /** Run one listener by hand, as if its event had been emitted as `scope`. Throws its failure, like `drain()`. */
49
+ perform<O>(listener: Listener<O>, payload: O, options: { scope: S; attempt?: number }): Promise<JobOutcome>;
50
+ /** Run the crons due in `at`'s minute (default: the test's now), here and now. Resolves their ids; throws a failure. */
51
+ tick(at?: Date | string): Promise<string[]>;
52
+ }
53
+
54
+ export interface TestRegistry<S extends object, Mods extends Record<string, object>, Cf> {
55
+ /** Open the test's transaction: `beforeEach(() => t.begin())`. */
56
+ begin(): Promise<void>;
57
+ /** Roll it back: `afterEach(() => t.rollback())`. */
58
+ rollback(): Promise<void>;
59
+ /** Bind who is calling, like `registry.as(...)`. A listener that fails makes `run` throw, so a test can't pass over it. */
16
60
  as(scope: S): Caller<S>;
17
61
  /** Replace a function's implementation for this test. Matched by identity, so `run(availability.hold, …)` hits the stub. */
18
- stub<F extends Fn>(fn: F, impl: (input: FnIn<F>, ctx: any) => Promise<FnOut<F>>): void;
19
- /** Every event emitted (and committed) so far, in order. */
20
- readonly events: Envelope[];
62
+ stub<F extends Fn>(fn: F, impl: (ctx: unknown, input: FnIn<F>) => Promise<FnOut<F>>): void;
63
+ /** Every event emitted (and committed) in this test, in order. */
64
+ readonly events: readonly Envelope[];
21
65
  /** The test transaction itself: read rows to assert on them. */
22
66
  readonly db: any;
23
- /** The registry bound to this test transaction, for adapters: `toFetchHandler(tx.registry, …)`. */
67
+ /** The registry bound to this test's transaction, for adapters: an oRPC context's `caller: t.registry.as(scope)`. */
24
68
  readonly registry: Registry<S, Mods, Cf>;
69
+ readonly jobs: TestJobs<S>;
70
+ }
71
+
72
+ /** One test, between `begin` and `rollback`. */
73
+ interface Open<S extends object, Mods extends Record<string, object>, Cf> {
74
+ registry: Registry<S, Mods, Cf>;
75
+ db: unknown;
76
+ events: Envelope[];
77
+ stubs: Map<Fn, (ctx: never, input: never) => Promise<unknown>>;
78
+ queued: Delivery[];
79
+ scheduled: CallJob[];
80
+ /** Job failures (listeners, crons, scheduled calls) during the current call. */
81
+ failures: unknown[];
82
+ close(): Promise<void>;
25
83
  }
26
84
 
27
85
  class Rollback extends Error {}
28
86
 
29
87
  /**
30
- * Run each test inside a transaction that is always rolled back.
31
- * Every top-level mutation inside becomes a savepoint, so a failing mutation rolls back just its own writes,
32
- * like it would in production. Run top-level mutations one at a time inside a test (one connection, nested savepoints).
88
+ * The test's jobs adapter. What waits (a delayed listener, `ctx.schedule`) is held for `drain()`, and in `"manual"` so
89
+ * is everything else; the rest runs now. It holds and replaces what your app's adapter does, so a test fails where
90
+ * production would.
91
+ */
92
+ const testJobs = (mode: TestOptions["jobs"], app: JobsAdapter | undefined, queued: Delivery[], scheduled: CallJob[]): JobsAdapter => ({
93
+ holds: app?.holds,
94
+ replaces: app?.replaces,
95
+ async deliver(jobs, runner) {
96
+ for (const job of jobs) {
97
+ const key = replaceKeyOf(job);
98
+ if (key) {
99
+ const waiting = scheduled.findIndex((c) => replaceKeyOf(c) === key);
100
+ if (waiting >= 0) scheduled.splice(waiting, 1);
101
+ }
102
+ const waits = job.runAt !== undefined || (mode === "manual" && job.kind !== "cron");
103
+ if (!waits) await runner.run({ ...job, attempts: 1 }); // one try, like inProcess(): reported, so the test sees it
104
+ else if (job.kind === "call") scheduled.push(job);
105
+ else if (job.kind === "delivery") queued.push(job);
106
+ }
107
+ },
108
+ });
109
+
110
+ /** Removes the jobs that are due from `list` and returns them. */
111
+ function takeDue<T extends Job>(list: T[], cutoff: number): T[] {
112
+ const due = (job: T) => !job.runAt || Date.parse(job.runAt) <= cutoff;
113
+ const ready = list.filter(due);
114
+ list.splice(0, list.length, ...list.filter((job) => !due(job)));
115
+ return ready;
116
+ }
117
+
118
+ /**
119
+ * Run each test inside a transaction that's rolled back, set up once with hooks:
120
+ *
121
+ * ```ts
122
+ * const t = createTestRegistry(registry);
123
+ * beforeEach(() => t.begin());
124
+ * afterEach(() => t.rollback());
125
+ * ```
126
+ *
127
+ * Every top-level mutation inside becomes a savepoint, so a failing mutation rolls back just its own writes, like it
128
+ * would in production. Tests that share `t` run one at a time (one connection, nested savepoints).
33
129
  */
34
130
  export function createTestRegistry<S extends object, Mods extends Record<string, object>, Cf>(
35
131
  registry: Registry<S, Mods, Cf>,
36
132
  options: TestOptions<Cf> = {},
37
- ) {
38
- const { options: registryOptions } = internal(registry);
39
- const now =
40
- options.now === undefined
41
- ? undefined
42
- : typeof options.now === "function"
43
- ? options.now
44
- : (() => {
45
- const fixed = new Date(options.now as Date | string);
46
- return () => new Date(fixed);
47
- })();
133
+ ): TestRegistry<S, Mods, Cf> {
134
+ const { options: registryOptions } = registry[INTERNAL];
135
+ const fixed = options.now;
136
+ const now = typeof fixed === "function" ? fixed : fixed === undefined ? undefined : () => new Date(fixed);
137
+ /** While `drain()` runs a job that waited, the time it was due: what `ctx.now()` reads then. */
138
+ let travelled: number | undefined;
139
+ const clock = () => {
140
+ const base = (now ?? registryOptions.now ?? (() => new Date()))();
141
+ return travelled !== undefined && travelled > base.getTime() ? new Date(travelled) : base;
142
+ };
143
+ let open: Open<S, Mods, Cf> | undefined;
48
144
 
49
- return {
50
- async transaction<T>(fn: (t: TestTransaction<S, Mods, Cf>) => Promise<T>): Promise<T> {
51
- const database = registryOptions.database;
52
- let result!: T;
145
+ const current = () => {
146
+ if (!open) throw new Error("[logic-sdk] No test transaction. Add beforeEach(() => t.begin()) and afterEach(() => t.rollback()).");
147
+ return open;
148
+ };
53
149
 
54
- const body = async (outer: unknown) => {
55
- const stubs = new Map<Fn, (input: any, ctx: any) => Promise<any>>();
56
- const events: Envelope[] = [];
57
- const derived = internal(registry).derive({
58
- database: outer !== undefined && database?.nest ? database.nest(outer) : database,
59
- services: options.services,
60
- config: options.config as object | undefined,
61
- now,
62
- stubs,
63
- record: (e) => events.push(e),
64
- events: options.listeners === false ? { deliver: async () => {} } : undefined,
65
- }) as Registry<S, Mods, Cf>;
66
- result = await fn({
67
- as: (scope) => derived.as(scope),
68
- stub: (f, impl) => void stubs.set(f, impl as (input: any, ctx: any) => Promise<any>),
69
- events,
70
- db: outer,
71
- registry: derived,
72
- });
73
- };
150
+ /** `db` is the test's transaction, and `database` the adapter nested in it (none without a database). */
151
+ function start(db: unknown, database: DatabaseAdapter<unknown, unknown> | undefined, close: () => Promise<void>): Open<S, Mods, Cf> {
152
+ const events: Envelope[] = [];
153
+ const stubs: Open<S, Mods, Cf>["stubs"] = new Map();
154
+ const queued: Delivery[] = [];
155
+ const scheduled: CallJob[] = [];
156
+ const failures: unknown[] = [];
157
+ const derived = registry[INTERNAL].derive({
158
+ database,
159
+ services: options.services,
160
+ config: options.config,
161
+ now: clock,
162
+ stubs,
163
+ record: (e) => events.push(e),
164
+ adapter: testJobs(options.jobs, registryOptions.jobs?.adapter, queued, scheduled),
165
+ waitUntil: undefined, // listeners finish before a call returns, inside the test
166
+ onError(error, info) {
167
+ if (info.outcome !== "discarded") failures.push(error);
168
+ registryOptions.onError?.(error, info);
169
+ },
170
+ });
171
+ return { registry: derived, db, events, stubs, queued, scheduled, failures, close };
172
+ }
74
173
 
174
+ /** Run `work`, then throw the first listener failure since the last one thrown (calls through `t.registry` included). */
175
+ async function settle<T>(state: Open<S, Mods, Cf>, work: () => Promise<T>): Promise<T> {
176
+ let out: T;
177
+ try {
178
+ out = await work();
179
+ } catch (e) {
180
+ state.failures.length = 0; // what it threw is the failure: don't report it again on the next call
181
+ throw e;
182
+ }
183
+ throwFailures(state);
184
+ return out;
185
+ }
186
+ function throwFailures(state: Open<S, Mods, Cf>) {
187
+ if (!state.failures.length) return;
188
+ const [first] = state.failures.splice(0);
189
+ throw first;
190
+ }
191
+
192
+ return {
193
+ async begin() {
194
+ if (open)
195
+ throw new Error(
196
+ "[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).",
197
+ );
198
+ const database = registryOptions.database;
75
199
  if (!database) {
76
- await body(undefined);
77
- return result;
200
+ open = start(undefined, undefined, async () => {});
201
+ return;
78
202
  }
79
203
  if (!database.nest) throw new Error("[logic-sdk] This database adapter can't nest transactions, so tests can't roll back.");
80
- try {
81
- await database.transaction(async (outer) => {
82
- await body(outer);
204
+ // Drizzle transactions live inside a callback: park it there until rollback.
205
+ const opened = Promise.withResolvers<unknown>();
206
+ const released = Promise.withResolvers<void>();
207
+ const done = database
208
+ .transaction(async (tx) => {
209
+ opened.resolve(tx);
210
+ await released.promise;
83
211
  throw new Rollback();
212
+ })
213
+ .catch((e) => {
214
+ if (!(e instanceof Rollback)) throw e;
84
215
  });
85
- } catch (e) {
86
- if (!(e instanceof Rollback)) throw e;
87
- }
88
- return result;
216
+ const tx = await Promise.race([opened.promise, done]); // `done` settles first only if the transaction failed to open
217
+ open = start(tx, database.nest(tx), async () => {
218
+ released.resolve();
219
+ await done;
220
+ });
221
+ },
222
+ /** Also throws a listener failure nothing surfaced yet (a call through `t.registry`), so the test fails. */
223
+ async rollback() {
224
+ const state = open;
225
+ open = undefined;
226
+ await state?.close();
227
+ if (state) throwFailures(state);
228
+ },
229
+ as: (scope) => ({
230
+ scope,
231
+ run: (fn, ...args) => {
232
+ const state = current();
233
+ return settle(state, () => state.registry.as(scope).run(fn, ...args));
234
+ },
235
+ }),
236
+ stub: (fn, impl) => void current().stubs.set(fn, impl),
237
+ get events() {
238
+ return current().events;
239
+ },
240
+ get db() {
241
+ return current().db;
242
+ },
243
+ get registry() {
244
+ return current().registry;
245
+ },
246
+ jobs: {
247
+ get queued() {
248
+ return current().queued;
249
+ },
250
+ get scheduled() {
251
+ return current().scheduled;
252
+ },
253
+ async drain({ until } = {}) {
254
+ const state = current();
255
+ const end = until === undefined ? clock() : new Date(until);
256
+ if (Number.isNaN(end.getTime())) throw new Error(`[logic-sdk] drain({ until }) needs a valid date (got ${String(until)}).`);
257
+ try {
258
+ for (let round = 1; ; round++) {
259
+ const ready = [...takeDue(state.queued, end.getTime()), ...takeDue(state.scheduled, end.getTime())];
260
+ if (!ready.length) return;
261
+ 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?");
262
+ ready.sort((a, b) => (a.runAt ?? "").localeCompare(b.runAt ?? ""));
263
+ for (const job of ready) {
264
+ // the job runs at the time it was due, so a self-rescheduling one moves forward and its checks see that time
265
+ if (job.runAt) travelled = Math.max(travelled ?? 0, Date.parse(job.runAt));
266
+ await settle(state, () => state.registry.jobs.run(job));
267
+ }
268
+ }
269
+ } finally {
270
+ travelled = undefined;
271
+ }
272
+ },
273
+ perform(listener, payload, { scope, attempt }) {
274
+ const state = current();
275
+ const registered = state.registry.definitions.listeners.find((l) => l.listener === listener);
276
+ if (!registered) throw new Error("[logic-sdk] t.jobs.perform got a listener that isn't registered: export it from its module.");
277
+ const envelope = state.registry[INTERNAL].envelope(registered.event, payload, scope);
278
+ return settle(state, () => state.registry.jobs.run(deliveryOf(registered, envelope), { attempt }));
279
+ },
280
+ async tick(at) {
281
+ const state = current();
282
+ const jobs = state.registry[INTERNAL].due(at === undefined ? clock() : new Date(at));
283
+ for (const job of jobs) await settle(state, () => state.registry.jobs.run(job));
284
+ return jobs.map((job) => job.cron);
285
+ },
89
286
  },
90
287
  };
91
288
  }