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