logic-sdk 0.7.1 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/README.md +7 -7
  2. package/dist/adapters/cloudflare-queue.d.ts +14 -0
  3. package/dist/adapters/cloudflare-queue.js +48 -0
  4. package/dist/adapters/drizzle-pg.d.ts +250 -0
  5. package/dist/adapters/drizzle-pg.js +69 -0
  6. package/dist/adapters/drizzle-sqlite.d.ts +257 -0
  7. package/dist/adapters/drizzle-sqlite.js +196 -0
  8. package/dist/adapters/pg-boss.d.ts +45 -0
  9. package/dist/adapters/pg-boss.js +180 -0
  10. package/dist/adapters/postgres.d.ts +32 -0
  11. package/dist/adapters/postgres.js +105 -0
  12. package/dist/adapters/sqlite.d.ts +13 -0
  13. package/dist/adapters/sqlite.js +88 -0
  14. package/dist/{stored-jobs.d.ts → adapters/stored-jobs.d.ts} +27 -10
  15. package/dist/{stored-jobs.js → adapters/stored-jobs.js} +106 -20
  16. package/dist/ai.d.ts +1 -32
  17. package/dist/ai.js +1 -40
  18. package/dist/cloudflare.d.ts +2 -55
  19. package/dist/cloudflare.js +2 -85
  20. package/dist/core/in-process.d.ts +9 -0
  21. package/dist/core/in-process.js +17 -0
  22. package/dist/{jobs.d.ts → core/jobs.d.ts} +23 -10
  23. package/dist/{jobs.js → core/jobs.js} +152 -39
  24. package/dist/core/registry.d.ts +120 -0
  25. package/dist/core/registry.js +503 -0
  26. package/dist/core/testing.d.ts +75 -0
  27. package/dist/core/testing.js +230 -0
  28. package/dist/{types.d.ts → core/types.d.ts} +203 -40
  29. package/dist/drizzle/pg.d.ts +3 -236
  30. package/dist/drizzle/pg.js +2 -67
  31. package/dist/drizzle/sqlite.d.ts +3 -242
  32. package/dist/drizzle/sqlite.js +2 -194
  33. package/dist/fetch.d.ts +1 -19
  34. package/dist/fetch.js +1 -30
  35. package/dist/hosts/cloudflare.d.ts +42 -0
  36. package/dist/hosts/cloudflare.js +39 -0
  37. package/dist/hosts/node.d.ts +26 -0
  38. package/dist/hosts/node.js +76 -0
  39. package/dist/hosts/pg-boss.d.ts +22 -0
  40. package/dist/hosts/pg-boss.js +55 -0
  41. package/dist/index.d.ts +5 -122
  42. package/dist/index.js +4 -492
  43. package/dist/integrations/ai.d.ts +32 -0
  44. package/dist/integrations/ai.js +40 -0
  45. package/dist/integrations/fetch.d.ts +19 -0
  46. package/dist/integrations/fetch.js +30 -0
  47. package/dist/integrations/orpc.d.ts +22 -0
  48. package/dist/integrations/orpc.js +37 -0
  49. package/dist/node.d.ts +1 -26
  50. package/dist/node.js +1 -76
  51. package/dist/orpc.d.ts +1 -21
  52. package/dist/orpc.js +1 -37
  53. package/dist/pg-boss.d.ts +2 -53
  54. package/dist/pg-boss.js +2 -213
  55. package/dist/postgres.d.ts +2 -28
  56. package/dist/postgres.js +1 -82
  57. package/dist/sqlite.d.ts +2 -9
  58. package/dist/sqlite.js +1 -65
  59. package/dist/testing.d.ts +1 -75
  60. package/dist/testing.js +1 -227
  61. package/package.json +2 -2
  62. package/skills/logic-sdk/SKILL.md +4 -3
  63. package/src/adapters/cloudflare-queue.ts +56 -0
  64. package/src/adapters/drizzle-pg.ts +108 -0
  65. package/src/adapters/drizzle-sqlite.ts +234 -0
  66. package/src/adapters/pg-boss.ts +195 -0
  67. package/src/adapters/postgres.ts +112 -0
  68. package/src/adapters/sqlite.ts +96 -0
  69. package/src/{stored-jobs.ts → adapters/stored-jobs.ts} +133 -30
  70. package/src/ai.ts +1 -62
  71. package/src/cloudflare.ts +2 -107
  72. package/src/core/in-process.ts +18 -0
  73. package/src/{jobs.ts → core/jobs.ts} +152 -38
  74. package/src/core/registry.ts +671 -0
  75. package/src/core/testing.ts +307 -0
  76. package/src/{types.ts → core/types.ts} +197 -40
  77. package/src/drizzle/pg.ts +3 -110
  78. package/src/drizzle/sqlite.ts +3 -236
  79. package/src/fetch.ts +1 -31
  80. package/src/hosts/cloudflare.ts +54 -0
  81. package/src/hosts/node.ts +99 -0
  82. package/src/hosts/pg-boss.ts +71 -0
  83. package/src/index.ts +15 -652
  84. package/src/integrations/ai.ts +63 -0
  85. package/src/integrations/fetch.ts +31 -0
  86. package/src/integrations/orpc.ts +47 -0
  87. package/src/node.ts +1 -99
  88. package/src/orpc.ts +1 -46
  89. package/src/pg-boss.ts +2 -241
  90. package/src/postgres.ts +2 -90
  91. package/src/sqlite.ts +2 -74
  92. package/src/testing.ts +1 -305
  93. /package/dist/{errors.d.ts → core/errors.d.ts} +0 -0
  94. /package/dist/{errors.js → core/errors.js} +0 -0
  95. /package/dist/{schedule.d.ts → core/schedule.d.ts} +0 -0
  96. /package/dist/{schedule.js → core/schedule.js} +0 -0
  97. /package/dist/{types.js → core/types.js} +0 -0
  98. /package/src/{errors.ts → core/errors.ts} +0 -0
  99. /package/src/{schedule.ts → core/schedule.ts} +0 -0
package/dist/sqlite.js CHANGED
@@ -1,65 +1 @@
1
- // The jobs table on SQLite (3.42 or later, for `unixepoch('subsec')`), in SQL. With Drizzle, import from
2
- // `logic-sdk/drizzle/sqlite` instead: the same two functions, plus the table for your schema. Times are whole milliseconds since 1970, on SQLite's clock.
3
- // Every statement returns rows: better-sqlite3's `all()` refuses one that doesn't, so one `query` fits every driver.
4
- import { storedJobs } from "./stored-jobs.js";
5
- const now = `cast(unixepoch('subsec') * 1000 as integer)`;
6
- /** The tables behind `databaseQueue` and `outbox`, for your migrations. Drizzle users re-export `jobsTable` instead. */
7
- export const jobsSchema = `
8
- CREATE TABLE logic_jobs (
9
- id text PRIMARY KEY NOT NULL,
10
- job text NOT NULL,
11
- status text NOT NULL DEFAULT 'pending',
12
- attempts integer NOT NULL DEFAULT 0,
13
- available_at integer NOT NULL DEFAULT (${now}),
14
- receipt text,
15
- last_error text,
16
- failed_at integer,
17
- replace_key text,
18
- created_at integer NOT NULL DEFAULT (${now})
19
- );
20
- CREATE INDEX logic_jobs_due ON logic_jobs (available_at) WHERE status = 'pending';
21
- CREATE UNIQUE INDEX logic_jobs_replace ON logic_jobs (replace_key) WHERE status = 'pending' and attempts = 0;
22
- CREATE TABLE logic_cron_runs (
23
- id text PRIMARY KEY NOT NULL,
24
- ran_at integer NOT NULL DEFAULT (${now})
25
- );
26
- `;
27
- const ids = "(SELECT value FROM json_each(?))";
28
- const mine = `id IN ${ids} AND receipt = ? AND status = 'pending'`;
29
- const inSeconds = `${now} + cast(? * 1000 as integer)`;
30
- const statements = {
31
- // the waiting call with this key becomes the new one: its id, job and time (Oban's `replace`). `json_each.key` is
32
- // the row's place in the list. `WHERE true`: SQLite needs it to tell an upsert's ON CONFLICT from a join's ON
33
- insert: `
34
- INSERT INTO logic_jobs (id, job, available_at, replace_key)
35
- SELECT value ->> 'id', value -> 'job', coalesce(value ->> 'at', ${inSeconds}), value ->> 'key'
36
- FROM json_each(?) WHERE true ORDER BY json_each.key
37
- ON CONFLICT (replace_key) WHERE status = 'pending' and attempts = 0
38
- DO UPDATE SET id = excluded.id, job = excluded.job, available_at = excluded.available_at, last_error = NULL
39
- RETURNING id`,
40
- recordTicks: `INSERT INTO logic_cron_runs (id) SELECT value FROM json_each(?) WHERE true ON CONFLICT DO NOTHING RETURNING id`,
41
- pruneTicks: `DELETE FROM logic_cron_runs WHERE ran_at < ${now} - 86400000 RETURNING id`,
42
- claimNew: `
43
- UPDATE logic_jobs SET attempts = 1, receipt = ?, available_at = ${inSeconds}
44
- WHERE id IN ${ids} AND attempts = 0 AND status = 'pending' RETURNING id`,
45
- // no row locks to skip: SQLite has one writer at a time, and this statement is one write
46
- claimDue: `
47
- UPDATE logic_jobs SET attempts = attempts + 1, receipt = ?, available_at = ${inSeconds}
48
- WHERE id = (SELECT id FROM logic_jobs WHERE status = 'pending' AND available_at <= ${now} ORDER BY available_at LIMIT 1)
49
- RETURNING job, attempts`,
50
- extend: `UPDATE logic_jobs SET available_at = ${inSeconds} WHERE ${mine} RETURNING id`,
51
- backOff: `UPDATE logic_jobs SET available_at = ${inSeconds}, last_error = ? WHERE ${mine} RETURNING id`,
52
- markFailed: `UPDATE logic_jobs SET status = 'failed', last_error = ?, failed_at = ${now} WHERE ${mine} RETURNING id`,
53
- remove: `DELETE FROM logic_jobs WHERE ${mine} RETURNING id`,
54
- retry: `
55
- UPDATE logic_jobs SET status = 'pending', attempts = 0, receipt = NULL, available_at = ${now}, last_error = NULL, failed_at = NULL, replace_key = NULL
56
- WHERE id = ? AND status = 'failed' RETURNING id`,
57
- fail: `
58
- INSERT INTO logic_jobs (id, job, status, last_error, failed_at) VALUES (?, ?, 'failed', ?, ${now})
59
- ON CONFLICT (id) DO UPDATE SET status = 'failed', last_error = excluded.last_error, failed_at = excluded.failed_at
60
- RETURNING id`,
61
- };
62
- /** Your database as the queue: see `databaseQueue` in `logic-sdk/postgres`, which this matches. */
63
- export const databaseQueue = (database, options = {}) => storedJobs(statements, database, options);
64
- /** A table in front of another queue: see `outbox` in `logic-sdk/postgres`, which this matches. */
65
- export const outbox = (database, queue, options = {}) => storedJobs(statements, database, options, queue);
1
+ export { databaseQueue, failedJobs, jobsSchema, outbox } from "./adapters/sqlite.js";
package/dist/testing.d.ts CHANGED
@@ -1,75 +1 @@
1
- import { type Caller, type DeepPartial, type CallJob, type Cron, type Delivery, type Envelope, type Fn, type FnIn, type FnOut, type JobOutcome, type Listener, type Registry } from "./index.ts";
2
- export interface TestOptions<Cf = unknown> {
3
- /** Replace services (e.g. `{ mailer: memoryMailer() }`). */
4
- services?: object;
5
- /** Override parts of `config` (e.g. `{ orders: { maxItems: 1 } }`). Merged over the registry's, section by section. */
6
- config?: DeepPartial<Cf>;
7
- /** Freeze time. */
8
- now?: Date | string | (() => Date);
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";
16
- }
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
- /**
36
- * Run one cron by hand, as its own scope, for the minute `at` (default: the test's now), whatever its schedule. Throws
37
- * its failure. `t.jobs.tick(at)` runs every cron due that minute instead.
38
- */
39
- perform(cron: Cron, options?: {
40
- at?: Date | string;
41
- attempt?: number;
42
- }): Promise<JobOutcome>;
43
- /** Run the crons due in `at`'s minute (default: the test's now), here and now. Resolves their ids; throws a failure. */
44
- tick(at?: Date | string): Promise<string[]>;
45
- }
46
- export interface TestRegistry<S extends object, Mods extends Record<string, object>, Cf> {
47
- /** Open the test's transaction: `beforeEach(() => t.begin())`. */
48
- begin(): Promise<void>;
49
- /** Roll it back: `afterEach(() => t.rollback())`. */
50
- rollback(): Promise<void>;
51
- /** Bind who is calling, like `registry.as(...)`. A listener that fails makes `run` throw, so a test can't pass over it. */
52
- as(scope: S): Caller<S>;
53
- /** Replace a function's implementation for this test. Matched by identity, so `run(availability.hold, …)` hits the stub. */
54
- stub<F extends Fn>(fn: F, impl: (ctx: unknown, input: FnIn<F>) => Promise<FnOut<F>>): void;
55
- /** Every event emitted (and committed) in this test, in order. */
56
- readonly events: readonly Envelope[];
57
- /** The test transaction itself: read rows to assert on them. */
58
- readonly db: any;
59
- /** The registry bound to this test's transaction, for adapters: an oRPC context's `caller: t.registry.as(scope)`. */
60
- readonly registry: Registry<S, Mods, Cf>;
61
- readonly jobs: TestJobs<S>;
62
- }
63
- /**
64
- * Run each test inside a transaction that's rolled back, set up once with hooks:
65
- *
66
- * ```ts
67
- * const t = createTestRegistry(registry);
68
- * beforeEach(() => t.begin());
69
- * afterEach(() => t.rollback());
70
- * ```
71
- *
72
- * Every top-level mutation inside becomes a savepoint, so a failing mutation rolls back just its own writes, like it
73
- * would in production. Tests that share `t` run one at a time (one connection, nested savepoints).
74
- */
75
- 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>;
1
+ export { createTestRegistry, type TestJobs, type TestOptions, type TestRegistry } from "./core/testing.ts";
package/dist/testing.js CHANGED
@@ -1,227 +1 @@
1
- import { replaceKeyOf, } from "./index.js";
2
- import { deliveryOf } from "./jobs.js";
3
- import { INTERNAL } from "./types.js";
4
- class Rollback extends Error {
5
- }
6
- /**
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).
50
- */
51
- export function createTestRegistry(registry, options = {}) {
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
- }
110
- return {
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).");
114
- const database = registryOptions.database;
115
- if (!database) {
116
- open = start(undefined, undefined, async () => { });
117
- return;
118
- }
119
- if (!database.nest)
120
- throw new Error("[logic-sdk] This database adapter can't nest transactions, so tests can't roll back.");
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) => {
131
- if (!(e instanceof Rollback))
132
- throw e;
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(target, ...rest) {
198
- const state = current();
199
- if (target.kind === "cron") {
200
- const { at, attempt } = (rest[0] ?? {});
201
- const cron = state.registry.definitions.crons.find((c) => c.cron === target);
202
- if (!cron)
203
- throw new Error("[logic-sdk] t.jobs.perform got a cron that isn't registered: export it from its module.");
204
- const when = at === undefined ? clock() : new Date(at);
205
- if (Number.isNaN(when.getTime()))
206
- throw new Error(`[logic-sdk] t.jobs.perform({ at }) needs a valid date (got ${String(at)}).`);
207
- const [job] = state.registry[INTERNAL].due(when, cron.id);
208
- return settle(state, () => state.registry.jobs.run(job, { attempt }));
209
- }
210
- const listener = target;
211
- const [payload, { scope, attempt }] = rest;
212
- const registered = state.registry.definitions.listeners.find((l) => l.listener === listener);
213
- if (!registered)
214
- throw new Error("[logic-sdk] t.jobs.perform got a listener that isn't registered: export it from its module.");
215
- const envelope = state.registry[INTERNAL].envelope(registered.event, payload, scope);
216
- return settle(state, () => state.registry.jobs.run(deliveryOf(registered, envelope), { attempt }));
217
- },
218
- async tick(at) {
219
- const state = current();
220
- const jobs = state.registry[INTERNAL].due(at === undefined ? clock() : new Date(at));
221
- for (const job of jobs)
222
- await settle(state, () => state.registry.jobs.run(job));
223
- return jobs.map((job) => job.cron);
224
- },
225
- },
226
- };
227
- }
1
+ export { createTestRegistry } from "./core/testing.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "logic-sdk",
3
- "version": "0.7.1",
3
+ "version": "0.7.2",
4
4
  "description": "Queries, mutations, actions and events for TypeScript apps. Transactions, after-commit events and scopes, on any runtime.",
5
5
  "keywords": [
6
6
  "actions",
@@ -113,7 +113,7 @@
113
113
  "drizzle-orm": ">=1.0.0-rc.6 <2",
114
114
  "pg-boss": ">=12.39.0 <13",
115
115
  "ai": ">=7 <8",
116
- "@logic-sdk/cli": ">=0.6.5 <0.7.0"
116
+ "@logic-sdk/cli": ">=0.6.6 <0.7.0"
117
117
  },
118
118
  "peerDependenciesMeta": {
119
119
  "@orpc/server": {
@@ -71,14 +71,15 @@ export const cancel = mutation({
71
71
  8. **Errors:** `throw ctx.errors.reject("snake_reason", details?)` when a rule says no, `ctx.errors.conflict(...)` when someone got there first, `ctx.errors.notFound()`, `ctx.errors.deny()`. Codes are namespaced to your module for you. Never return error objects; never throw plain `Error` for expected cases. Catch only in actions; in a mutation, catch only to rethrow your own error: nested mutations share the caller's transaction, so a caught failure fails the commit with an error naming both. Work over many rows where each must commit or fail alone (a cron over every account) `ctx.run`s the mutation per row inside `try`/`catch`, from a cron's handler or an action: never from a mutation.
72
72
  9. **Need the result? `run` it. Just a consequence? `emit`** and let the owning module react in its `listeners.ts`.
73
73
  10. **A listener that wants only some events says so with `when: (payload) => boolean`** (sync, from the payload only), instead of returning early in its handler: the others get no job. The emitter never filters for its listeners.
74
- 11. **Listeners must be idempotent** (record `ctx.event.id` per listener, since listeners of one event share it, and skip it if seen, when a repeat would charge or email twice). They run with the emitter's scope (or the one `jobs.scope.load` rebuilds, when the app sets it), so they run internal functions. To act as someone else on purpose, pass the whole scope for that call: `ctx.run(fn, input, { scope: { ...ctx.scope, actor: system } })`. It's never merged, so it's always one of your scope's variants.
74
+ 11. **Listeners must be idempotent** (record `ctx.event.id` per listener, since listeners of one event share it, and skip it if seen, when a repeat would charge or email twice). `ctx.emit` returns the event it queued (`{ id, name, payload, occurredAt }`): a row written in the same mutation can carry `event.id`, the id listeners see as `ctx.event.id`. They run with the emitter's scope (or the one `jobs.scope.load` rebuilds, when the app sets it), so they run internal functions. To act as someone else on purpose, pass the whole scope for that call: `ctx.run(fn, input, { scope: { ...ctx.scope, actor: system } })`. It's never merged, so it's always one of your scope's variants.
75
75
  12. **Time** comes from `ctx.now()`, never `new Date()`, so tests can freeze it.
76
76
  13. **Use separate `export const`s**, not functions nested in an object. Name them by verb within the module (`bookings.confirm`, not `bookings.confirmBooking`). Names are unique per module. Renaming a listener, event or function that queued jobs may still reference? Keep its id: `listener({ id: "oldName", ... })`. Put one sentence of JSDoc above each (`/** Cancel a booking and free its dates */`): editors show it on hover, and `logic-sdk list` prints it.
77
77
  14. **`ctx` comes first, everywhere:** `handler(ctx, input)` in functions, `handler(ctx, payload)` in listeners, helpers `findBooking(ctx, id)`. A function that takes nothing leaves out `input`: `handler(ctx)`, called as `run(fn)`. A form's schema comes from the function it submits to (`properties.update.input.pick({ name: true })`), not from a schema the module exports.
78
78
  15. **Settings come from `ctx.config`**, never from env inside a module. Declare its shape in `init<Config>()` (`config: { orders: { maxItems: number } }`), fill it from your env at the entry (`createRegistry({ config })`), and read it in any function: `ctx.config.orders.maxItems`. Plain data only. Clients built from secrets go in `services`. Outside modules (the entry, routes, scripts), read env however you like.
79
- 16. **Listeners that must not be lost run through a durable jobs adapter,** set once in `registry.ts`: `const database = drizzleAdapter(db)` from `logic-sdk/drizzle/pg` (SQLite: `drizzleAdapter(() => drizzle("app.db"))` from `logic-sdk/drizzle/sqlite`, the function, not a connection), then `createRegistry({ database, jobs: { adapter: databaseQueue(database), scope: { store, load } } })` (your database is the queue, like Laravel's `database` driver; export `jobsTable` from the schema and sweep from a cron trigger or `startTicking`), `outbox(database, cloudflareQueue(env.JOBS))` when another queue runs them (the queue alone works too, and can lose a job on a crash), or `pgBoss(boss)` from `logic-sdk/pg-boss` when the app runs pg-boss (`await boss.start()` in every process, `await work(registry, boss)` in the worker, `boss.stop()` on SIGTERM; tune a listener's queue and workers with `meta: { pgBoss: { queue, worker } }`, never its retries). `store` saves ids, `load` rebuilds the scope when the job runs, with today's roles (`null` discards it: check membership there). `createRegistry` requires `load` with every adapter but `inProcess()`; keep the `system` field of a system scope in both. Never pass a jobs adapter per module, and never enqueue background work by hand from a mutation: `emit` an event. A listener tries once; give it `attempts: 5` when retrying is safe, and `delay: 60` (seconds) to run it later.
79
+ 16. **Listeners that must not be lost run through a durable jobs adapter,** set once in `registry.ts`: `const database = drizzleAdapter(db)` from `logic-sdk/drizzle/pg` (SQLite: `drizzleAdapter(() => drizzle("app.db"))` from `logic-sdk/drizzle/sqlite`, the function, not a connection), then `createRegistry({ database: { adapter: database }, jobs: { adapter: databaseQueue(), scope: { store, load } } })` (your database is the queue, like Laravel's `database` driver; export `jobsTable` from the schema and sweep from a cron trigger or `startTicking`), `outbox(cloudflareQueue(env.JOBS))` when another queue runs them (the queue alone works too, and can lose a job on a crash), or `pgBoss(boss)` from `logic-sdk/pg-boss` when the app runs pg-boss (any database adapter that runs SQL) (`await boss.start()` in every process, `await work(registry, boss)` in the worker, `boss.stop()` on SIGTERM; tune a listener's queue and workers with `meta: { pgBoss: { queue, worker } }`, never its retries). `store` saves ids, `load` rebuilds the scope when the job runs, with today's roles (`null` discards it: check membership there). `createRegistry` requires `load` with every adapter but `inProcess()`; keep the `system` field of a system scope in both. Never pass a jobs adapter per module, and never enqueue background work by hand from a mutation: `emit` an event. A listener tries once; give it `attempts: 5` when retrying is safe (`inProcess()` refuses attempts above 1: it runs each job once), and `delay: 60` (seconds) to run it later.
80
80
  17. **Scheduled work is a `cron`,** a listener for the clock, exported from the module: `cron({ schedule: "0 9 * * MON", scope: { kind: "system", job: "reports.weekly" }, async handler(ctx) { await ctx.run(fn) } })`, where `scope` is a system variant of the app's own `Scope` (its own `kind` and the job's name, never built from a request; the library defines no scope fields) and policies grant it explicitly (`staffOrSystem`), never a fake user. With `jobs.scope`, `store` and `load` must keep the system variant: what a cron emits or schedules is stored like anything else. Five-field strings only (weekdays as names: Cloudflare numbers them from Sunday = 1), `timezone` when it isn't UTC. The handler gets an action's ctx plus `ctx.cron` (`scheduledAt`: the minute the run is for; `attempt`), and `ctx.scope` typed as the declared scope; every `ctx.run` checks that function's policy against it. Name a cron after its work, like a listener (`sendDigest`); one that runs shared work, after when it runs (`nightly`). A retry reruns the whole handler: make it idempotent, and put all-or-nothing work in one `ctx.run(mutation)`. `meta` like a listener's (`meta.pgBoss` tunes its queue). On Node, `startTicking(registry)` from `logic-sdk/node` ticks and sweeps (`await stop()` on SIGTERM); with pg-boss, `work(registry, boss)` ticks them; on Cloudflare, `handleScheduled` from a `"* * * * *"` trigger (weekdays as names in `wrangler.jsonc`: Cloudflare counts Sunday as 1). Test with `t.jobs.tick(at)` (every cron due that minute) or `t.jobs.perform(cron, { at })` (that one, due or not).
81
- 18. **Work for later is `ctx.schedule(fn, input, { at } | { delay })`,** from a mutation only, so it commits with it (actions and listeners run a mutation that schedules). The function re-checks its reason when it runs ("still confirmed?"): there's no cancel. Like a cron's, it can run twice, mutations included, so make it idempotent (a unique key and `onConflictDoNothing()`). One try by default: add `attempts: 3` for an action that calls an API. When what it's for can change (a booking's dates), pass `replace: bookingId`: the newer call replaces the waiting one, so it doesn't run twice. It needs `jobs: { adapter: databaseQueue(database), scope: { store, load } }`, an `outbox` or `pgBoss(boss)` (rule 16); tests read `t.jobs.scheduled` and run it with `t.jobs.drain({ until })`.
81
+ 18. **Work for later is `ctx.schedule(fn, input, { at } | { delay })`,** from a mutation only, so it commits with it (actions and listeners run a mutation that schedules). It returns nothing, and there's no cancel: your row is the truth. Cancelling a booking writes `status: "cancelled"`, and the function checks its reason when it runs, in the same transaction as its effect (`update ... where status = 'confirmed' and reminder_sent_at is null returning id`; nothing returned, so `return`). Like a cron's, it can run twice, mutations included, so make it idempotent (a unique key and `onConflictDoNothing()`). One try by default: add `attempts: 3` for an action that calls an API. When what it's for can change (a booking's dates), pass `replace: true`: a newer call to the same function with the same input replaces the waiting one, so it doesn't run twice. Keep the input to ids (`{ bookingId }`), so it names one thing. To run it as someone else, pass the whole scope: `{ at, scope: { kind: "system", job: "tasks.wake", organization } }`. It needs `jobs: { adapter: databaseQueue(), scope: { store, load } }`, an `outbox` or `pgBoss(boss)` (rule 16); tests read `t.jobs.scheduled` and run it with `t.jobs.drain({ until })`.
82
+ 19. **Failed jobs and run-now are for operators,** outside functions, in scripts and staff routes you guard with your own policy: `registry.jobs.failed({ source: "emails.send", scope: { organizationId }, cursor })` (newest first; `scope` matches what `store` saved), then `retry(id)` or `forget(id)` each (a queue on its own keeps them in `jobs: { failed: failedJobs() }`); `registry.jobs.invoke(orders.sendDigest)` runs a cron now (`{ at }` for a missed minute). A user never retries a job: what they want again is a mutation that checks your row and emits again.
82
83
 
83
84
  ## Tests
84
85
 
@@ -0,0 +1,56 @@
1
+ import type { Job, JobsAdapter } from "../core/types.ts";
2
+
3
+ /** What the adapter uses of a Cloudflare Queue binding: `env.JOBS` fits. */
4
+ export interface QueueBinding {
5
+ sendBatch(messages: Iterable<{ body: Job; delaySeconds?: number }>): Promise<unknown>;
6
+ }
7
+
8
+ // Cloudflare's limits, where 1 KB is 1000 bytes: https://developers.cloudflare.com/queues/platform/limits/
9
+ const MAX_MESSAGES = 100;
10
+ const MAX_BATCH_BYTES = 256_000;
11
+ const MAX_MESSAGE_BYTES = 128_000;
12
+ /** Cloudflare counts about this much metadata per message toward the limits. */
13
+ const OVERHEAD_BYTES = 100;
14
+ /** The longest `delaySeconds` Cloudflare takes, for a send and for a retry: 24 hours. */
15
+ const MAX_DELAY = 86_400;
16
+ const encoder = new TextEncoder();
17
+
18
+ /**
19
+ * Send jobs to a Cloudflare Queue after commit. Alone it's lossy (a Worker that dies between commit and send loses
20
+ * them); behind an outbox it's durable: `jobs: { adapter: outbox(cloudflareQueue(env.JOBS)), scope: { store, load } }`.
21
+ * Run them with `handleQueue(registry, batch)` in your consumer.
22
+ */
23
+ export function cloudflareQueue(queue: QueueBinding): JobsAdapter {
24
+ return {
25
+ name: "cloudflareQueue(queue)",
26
+ retries: true, // handleQueue retries a message with a backoff
27
+ holds: { max: MAX_DELAY }, // delaySeconds, up to 24 hours
28
+ async deliver(jobs) {
29
+ for (const batch of batches(jobs)) await queue.sendBatch(batch);
30
+ },
31
+ };
32
+ }
33
+
34
+ /** Under Cloudflare's limits per send: 100 messages, 256 KB in all, 128 KB each. Checks every job before sending any. */
35
+ function* batches(jobs: Job[]) {
36
+ const sized = jobs.map((body) => {
37
+ const size = encoder.encode(JSON.stringify(body)).length + OVERHEAD_BYTES;
38
+ if (size > MAX_MESSAGE_BYTES)
39
+ throw new Error(`[logic-sdk] job ${body.id} is ${size} bytes; Cloudflare Queues take ${MAX_MESSAGE_BYTES} per message. Keep payloads to ids.`);
40
+ return { body, size };
41
+ });
42
+ let batch: { body: Job; delaySeconds?: number }[] = [];
43
+ let bytes = 0;
44
+ for (const { body, size } of sized) {
45
+ if (batch.length && (batch.length === MAX_MESSAGES || bytes + size > MAX_BATCH_BYTES)) {
46
+ yield batch;
47
+ batch = [];
48
+ bytes = 0;
49
+ }
50
+ batch.push(body.runAt ? { body, delaySeconds: secondsUntil(body.runAt) } : { body });
51
+ bytes += size;
52
+ }
53
+ if (batch.length) yield batch;
54
+ }
55
+
56
+ const secondsUntil = (iso: string) => Math.min(MAX_DELAY, Math.max(0, Math.ceil((Date.parse(iso) - Date.now()) / 1000)));
@@ -0,0 +1,108 @@
1
+ import { sql, type SQL } from "drizzle-orm";
2
+ import { index, integer, jsonb, pgTable, text, timestamp, uniqueIndex } from "drizzle-orm/pg-core";
3
+ import type { Job, ReadWrite, SqlDatabase } from "../core/types.ts";
4
+ import { causes } from "../core/errors.ts";
5
+
6
+ /** Anything with Drizzle's `transaction(fn)` and `execute(sql)`: a database or a transaction (nested = savepoint). */
7
+ interface Transactional {
8
+ transaction<T>(fn: (tx: any) => Promise<T>, config?: any): Promise<T>;
9
+ execute(query: SQL, mode: "objects"): PromiseLike<Record<string, unknown>[]>;
10
+ }
11
+
12
+ /** Drizzle's transaction for a database. Nested `transaction` calls on it are savepoints. */
13
+ type Transaction<Db extends Transactional> = Parameters<Parameters<Db["transaction"]>[0]>[0];
14
+
15
+ /**
16
+ * What mutations get: the transaction minus `transaction`, since a savepoint that rolled back would still send the
17
+ * events and calls made inside it. Type helpers with it: `type Tx = DrizzleTx<typeof db>`. A type-level guard.
18
+ */
19
+ export type DrizzleTx<Db extends Transactional> = Omit<Transaction<Db>, "transaction">;
20
+
21
+ /** What queries get: the database minus write methods. A type-level guard, not a runtime one. */
22
+ export type DrizzleReader<Db> = Omit<
23
+ Db,
24
+ "insert" | "update" | "delete" | "execute" | "transaction" | "batch" | "refreshMaterializedView"
25
+ >;
26
+
27
+ /**
28
+ * Your database in `Config`: `db: DrizzleDb<Db>`, where `type Db = typeof db`. Queries get a `DrizzleReader`, mutations
29
+ * the transaction.
30
+ */
31
+ export type DrizzleDb<Db extends Transactional> = ReadWrite<DrizzleReader<DrizzleTx<Db>>, DrizzleTx<Db>>;
32
+
33
+ /**
34
+ * Use a Drizzle database for mutations. Needs a driver with async interactive transactions: node-postgres, postgres.js,
35
+ * PGlite, Neon websocket, Hyperdrive. Not D1 or HTTP drivers. SQLite has its own adapter, `logic-sdk/drizzle/sqlite`.
36
+ * The types reject SQLite and libsql databases here.
37
+ */
38
+ export function drizzleAdapter<Db extends Transactional>(
39
+ db: Db,
40
+ ): SqlDatabase<Db, Transaction<Db>> { // the whole transaction, for `nest`; mutations see it as a DrizzleTx
41
+ return {
42
+ db,
43
+ transaction: (fn) => db.transaction(fn),
44
+ nest: (tx) => drizzleAdapter(tx), // the test registry's savepoints
45
+ retryable: (e) => RETRYABLE.has(sqlState(e) ?? ""),
46
+ query: async (client: Transactional, text, params) => client.execute(toSql(text, params), "objects"),
47
+ };
48
+ }
49
+
50
+ /** SQL text with `$1` parameters as a Drizzle query. Splitting on a captured number leaves them at the odd places. */
51
+ const toSql = (text: string, params: unknown[]) =>
52
+ sql.join(text.split(/\$(\d+)/).map((part, i) => (i % 2 ? sql.param(params[Number(part) - 1]) : sql.raw(part))));
53
+
54
+ /** Postgres: serialization_failure, deadlock_detected. The transaction lost a race; running it again is the fix. */
55
+ const RETRYABLE = new Set(["40001", "40P01"]);
56
+
57
+ /** The SQLSTATE of a driver error, also when Drizzle wraps it (`DrizzleQueryError.cause`). Use it to map constraints. */
58
+ export function sqlState(error: unknown): string | undefined {
59
+ for (const e of causes(error)) if ("code" in e && typeof e.code === "string") return e.code;
60
+ return undefined;
61
+ }
62
+
63
+ /**
64
+ * The table behind `databaseQueue` and `outbox` (Postgres), Laravel's `jobs`. Re-export it from your schema so
65
+ * drizzle-kit adds it to your migrations: `export { jobsTable } from "logic-sdk/drizzle/pg";`. One row per pending job;
66
+ * done rows are deleted, failed ones stay so you can query them and `retry` them.
67
+ */
68
+ export const jobsTable = pgTable(
69
+ "logic_jobs",
70
+ {
71
+ /** The job id: `<listener id>@<event id>`, `<cron id>@<minute>`, or `<function id>@<uuid>`. */
72
+ id: text("id").primaryKey(),
73
+ job: jsonb("job").$type<Job>().notNull(),
74
+ /** `failed`: out of attempts, or a rule said no. Retrying is your call (`registry.jobs.retry(id)`). */
75
+ status: text("status").$type<"pending" | "failed">().notNull().default("pending"),
76
+ /** Incremented when a runner claims it, so a crash still uses an attempt. */
77
+ attempts: integer("attempts").notNull().default(0),
78
+ /** Due from then on. While claimed: when the lease ends and a sweep may take it over. */
79
+ availableAt: timestamp("available_at", { withTimezone: true }).notNull().defaultNow(),
80
+ /** The claim that owns it: a new one each time it's claimed, like SQS's receipt handle. Only it can finish the job. */
81
+ receipt: text("receipt"),
82
+ /** When the claim that owns it started: set while a try runs, empty while it waits (first, or after a backoff). */
83
+ claimedAt: timestamp("claimed_at", { withTimezone: true }),
84
+ /** The last failure, with its stack. */
85
+ lastError: text("last_error"),
86
+ failedAt: timestamp("failed_at", { withTimezone: true }),
87
+ /** A scheduled call's `replace` key, `<function id>@<sha-256 of its input>`: a newer call with it replaces this row while it waits. */
88
+ replaceKey: text("replace_key"),
89
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
90
+ },
91
+ (t) => [
92
+ index("logic_jobs_due").on(t.availableAt).where(sql`${t.status} = 'pending'`),
93
+ // one waiting call per key: a claimed row (attempts > 0) has started, so a newer one doesn't touch it
94
+ uniqueIndex("logic_jobs_replace").on(t.replaceKey).where(sql`status = 'pending' and attempts = 0`),
95
+ // `registry.jobs.failed()` pages newest first by (failed_at, id)
96
+ index("logic_jobs_failed").on(t.failedAt, t.id).where(sql`status = 'failed'`),
97
+ ],
98
+ );
99
+
100
+ /**
101
+ * The cron runs already ticked, so a minute ticked twice (several servers, a redelivered trigger) runs once, like
102
+ * Solid Queue's recurring executions. Re-export it next to `jobsTable` when you have crons. Rows older than a day go.
103
+ */
104
+ export const cronRunsTable = pgTable("logic_cron_runs", {
105
+ /** The cron job's id, `<cron id>@<minute>`. */
106
+ id: text("id").primaryKey(),
107
+ ranAt: timestamp("ran_at", { withTimezone: true }).notNull().defaultNow(),
108
+ }, (t) => [index("logic_cron_runs_ran_at").on(t.ranAt)]);