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.
- package/README.md +7 -7
- package/dist/adapters/cloudflare-queue.d.ts +14 -0
- package/dist/adapters/cloudflare-queue.js +48 -0
- package/dist/adapters/drizzle-pg.d.ts +250 -0
- package/dist/adapters/drizzle-pg.js +69 -0
- package/dist/adapters/drizzle-sqlite.d.ts +257 -0
- package/dist/adapters/drizzle-sqlite.js +196 -0
- package/dist/adapters/pg-boss.d.ts +45 -0
- package/dist/adapters/pg-boss.js +180 -0
- package/dist/adapters/postgres.d.ts +32 -0
- package/dist/adapters/postgres.js +105 -0
- package/dist/adapters/sqlite.d.ts +13 -0
- package/dist/adapters/sqlite.js +88 -0
- package/dist/{stored-jobs.d.ts → adapters/stored-jobs.d.ts} +27 -10
- package/dist/{stored-jobs.js → adapters/stored-jobs.js} +106 -20
- package/dist/ai.d.ts +1 -32
- package/dist/ai.js +1 -40
- package/dist/cloudflare.d.ts +2 -55
- package/dist/cloudflare.js +2 -85
- package/dist/core/in-process.d.ts +9 -0
- package/dist/core/in-process.js +17 -0
- package/dist/{jobs.d.ts → core/jobs.d.ts} +23 -10
- package/dist/{jobs.js → core/jobs.js} +152 -39
- package/dist/core/registry.d.ts +120 -0
- package/dist/core/registry.js +503 -0
- package/dist/core/testing.d.ts +75 -0
- package/dist/core/testing.js +230 -0
- package/dist/{types.d.ts → core/types.d.ts} +203 -40
- package/dist/drizzle/pg.d.ts +3 -236
- package/dist/drizzle/pg.js +2 -67
- package/dist/drizzle/sqlite.d.ts +3 -242
- package/dist/drizzle/sqlite.js +2 -194
- package/dist/fetch.d.ts +1 -19
- package/dist/fetch.js +1 -30
- package/dist/hosts/cloudflare.d.ts +42 -0
- package/dist/hosts/cloudflare.js +39 -0
- package/dist/hosts/node.d.ts +26 -0
- package/dist/hosts/node.js +76 -0
- package/dist/hosts/pg-boss.d.ts +22 -0
- package/dist/hosts/pg-boss.js +55 -0
- package/dist/index.d.ts +5 -122
- package/dist/index.js +4 -492
- package/dist/integrations/ai.d.ts +32 -0
- package/dist/integrations/ai.js +40 -0
- package/dist/integrations/fetch.d.ts +19 -0
- package/dist/integrations/fetch.js +30 -0
- package/dist/integrations/orpc.d.ts +22 -0
- package/dist/integrations/orpc.js +37 -0
- package/dist/node.d.ts +1 -26
- package/dist/node.js +1 -76
- package/dist/orpc.d.ts +1 -21
- package/dist/orpc.js +1 -37
- package/dist/pg-boss.d.ts +2 -53
- package/dist/pg-boss.js +2 -213
- package/dist/postgres.d.ts +2 -28
- package/dist/postgres.js +1 -82
- package/dist/sqlite.d.ts +2 -9
- package/dist/sqlite.js +1 -65
- package/dist/testing.d.ts +1 -75
- package/dist/testing.js +1 -227
- package/package.json +2 -2
- package/skills/logic-sdk/SKILL.md +4 -3
- package/src/adapters/cloudflare-queue.ts +56 -0
- package/src/adapters/drizzle-pg.ts +108 -0
- package/src/adapters/drizzle-sqlite.ts +234 -0
- package/src/adapters/pg-boss.ts +195 -0
- package/src/adapters/postgres.ts +112 -0
- package/src/adapters/sqlite.ts +96 -0
- package/src/{stored-jobs.ts → adapters/stored-jobs.ts} +133 -30
- package/src/ai.ts +1 -62
- package/src/cloudflare.ts +2 -107
- package/src/core/in-process.ts +18 -0
- package/src/{jobs.ts → core/jobs.ts} +152 -38
- package/src/core/registry.ts +671 -0
- package/src/core/testing.ts +307 -0
- package/src/{types.ts → core/types.ts} +197 -40
- package/src/drizzle/pg.ts +3 -110
- package/src/drizzle/sqlite.ts +3 -236
- package/src/fetch.ts +1 -31
- package/src/hosts/cloudflare.ts +54 -0
- package/src/hosts/node.ts +99 -0
- package/src/hosts/pg-boss.ts +71 -0
- package/src/index.ts +15 -652
- package/src/integrations/ai.ts +63 -0
- package/src/integrations/fetch.ts +31 -0
- package/src/integrations/orpc.ts +47 -0
- package/src/node.ts +1 -99
- package/src/orpc.ts +1 -46
- package/src/pg-boss.ts +2 -241
- package/src/postgres.ts +2 -90
- package/src/sqlite.ts +2 -74
- package/src/testing.ts +1 -305
- /package/dist/{errors.d.ts → core/errors.d.ts} +0 -0
- /package/dist/{errors.js → core/errors.js} +0 -0
- /package/dist/{schedule.d.ts → core/schedule.d.ts} +0 -0
- /package/dist/{schedule.js → core/schedule.js} +0 -0
- /package/dist/{types.js → core/types.js} +0 -0
- /package/src/{errors.ts → core/errors.ts} +0 -0
- /package/src/{schedule.ts → core/schedule.ts} +0 -0
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
import {} from "./types.js";
|
|
2
|
+
import { deliveryOf, replaceKeyOf } 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
|
+
name: app?.name,
|
|
13
|
+
holds: app?.holds,
|
|
14
|
+
replaces: app?.replaces,
|
|
15
|
+
retries: app?.retries,
|
|
16
|
+
async deliver(jobs, runner) {
|
|
17
|
+
for (const job of jobs) {
|
|
18
|
+
const key = replaceKeyOf(job);
|
|
19
|
+
if (key) {
|
|
20
|
+
const waiting = scheduled.findIndex((c) => replaceKeyOf(c) === key);
|
|
21
|
+
if (waiting >= 0)
|
|
22
|
+
scheduled.splice(waiting, 1);
|
|
23
|
+
}
|
|
24
|
+
const waits = job.runAt !== undefined || (mode === "manual" && job.kind !== "cron");
|
|
25
|
+
if (!waits)
|
|
26
|
+
await runner.run({ ...job, attempts: 1 }); // one try, like inProcess(): reported, so the test sees it
|
|
27
|
+
else if (job.kind === "call")
|
|
28
|
+
scheduled.push(job);
|
|
29
|
+
else if (job.kind === "delivery")
|
|
30
|
+
queued.push(job);
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
});
|
|
34
|
+
/** Removes the jobs that are due from `list` and returns them. */
|
|
35
|
+
function takeDue(list, cutoff) {
|
|
36
|
+
const due = (job) => !job.runAt || Date.parse(job.runAt) <= cutoff;
|
|
37
|
+
const ready = list.filter(due);
|
|
38
|
+
list.splice(0, list.length, ...list.filter((job) => !due(job)));
|
|
39
|
+
return ready;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Run each test inside a transaction that's rolled back, set up once with hooks:
|
|
43
|
+
*
|
|
44
|
+
* ```ts
|
|
45
|
+
* const t = createTestRegistry(registry);
|
|
46
|
+
* beforeEach(() => t.begin());
|
|
47
|
+
* afterEach(() => t.rollback());
|
|
48
|
+
* ```
|
|
49
|
+
*
|
|
50
|
+
* Every top-level mutation inside becomes a savepoint, so a failing mutation rolls back just its own writes, like it
|
|
51
|
+
* would in production. Tests that share `t` run one at a time (one connection, nested savepoints).
|
|
52
|
+
*/
|
|
53
|
+
export function createTestRegistry(registry, options = {}) {
|
|
54
|
+
const { options: registryOptions } = registry[INTERNAL];
|
|
55
|
+
const fixed = options.now;
|
|
56
|
+
const now = typeof fixed === "function" ? fixed : fixed === undefined ? undefined : () => new Date(fixed);
|
|
57
|
+
/** While `drain()` runs a job that waited, the time it was due: what `ctx.now()` reads then. */
|
|
58
|
+
let travelled;
|
|
59
|
+
const clock = () => {
|
|
60
|
+
const base = (now ?? registryOptions.now ?? (() => new Date()))();
|
|
61
|
+
return travelled !== undefined && travelled > base.getTime() ? new Date(travelled) : base;
|
|
62
|
+
};
|
|
63
|
+
let open;
|
|
64
|
+
const current = () => {
|
|
65
|
+
if (!open)
|
|
66
|
+
throw new Error("[logic-sdk] No test transaction. Add beforeEach(() => t.begin()) and afterEach(() => t.rollback()).");
|
|
67
|
+
return open;
|
|
68
|
+
};
|
|
69
|
+
/** `db` is the test's transaction, and `database` the adapter nested in it (none without a database). */
|
|
70
|
+
function start(db, database, close) {
|
|
71
|
+
const events = [];
|
|
72
|
+
const stubs = new Map();
|
|
73
|
+
const queued = [];
|
|
74
|
+
const scheduled = [];
|
|
75
|
+
const failures = [];
|
|
76
|
+
const derived = registry[INTERNAL].derive({
|
|
77
|
+
database,
|
|
78
|
+
services: options.services,
|
|
79
|
+
config: options.config,
|
|
80
|
+
now: clock,
|
|
81
|
+
stubs,
|
|
82
|
+
record: (e) => events.push(e),
|
|
83
|
+
adapter: testJobs(options.jobs, registryOptions.jobs?.adapter, queued, scheduled),
|
|
84
|
+
failed: null, // failures throw in the test instead
|
|
85
|
+
waitUntil: undefined, // listeners finish before a call returns, inside the test
|
|
86
|
+
onError(error, info) {
|
|
87
|
+
if (info.outcome !== "discarded")
|
|
88
|
+
failures.push(error);
|
|
89
|
+
registryOptions.onError?.(error, info);
|
|
90
|
+
},
|
|
91
|
+
});
|
|
92
|
+
return { registry: derived, db, events, stubs, queued, scheduled, failures, close };
|
|
93
|
+
}
|
|
94
|
+
/** Run `work`, then throw the first listener failure since the last one thrown (calls through `t.registry` included). */
|
|
95
|
+
async function settle(state, work) {
|
|
96
|
+
let out;
|
|
97
|
+
try {
|
|
98
|
+
out = await work();
|
|
99
|
+
}
|
|
100
|
+
catch (e) {
|
|
101
|
+
state.failures.length = 0; // what it threw is the failure: don't report it again on the next call
|
|
102
|
+
throw e;
|
|
103
|
+
}
|
|
104
|
+
throwFailures(state);
|
|
105
|
+
return out;
|
|
106
|
+
}
|
|
107
|
+
function throwFailures(state) {
|
|
108
|
+
if (!state.failures.length)
|
|
109
|
+
return;
|
|
110
|
+
const [first] = state.failures.splice(0);
|
|
111
|
+
throw first;
|
|
112
|
+
}
|
|
113
|
+
return {
|
|
114
|
+
async begin() {
|
|
115
|
+
if (open)
|
|
116
|
+
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).");
|
|
117
|
+
const database = registryOptions.database?.adapter;
|
|
118
|
+
if (!database) {
|
|
119
|
+
open = start(undefined, undefined, async () => { });
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
if (!database.nest)
|
|
123
|
+
throw new Error("[logic-sdk] This database adapter can't nest transactions, so tests can't roll back.");
|
|
124
|
+
// Drizzle transactions live inside a callback: park it there until rollback.
|
|
125
|
+
const opened = Promise.withResolvers();
|
|
126
|
+
const released = Promise.withResolvers();
|
|
127
|
+
const done = database
|
|
128
|
+
.transaction(async (tx) => {
|
|
129
|
+
opened.resolve(tx);
|
|
130
|
+
await released.promise;
|
|
131
|
+
throw new Rollback();
|
|
132
|
+
})
|
|
133
|
+
.catch((e) => {
|
|
134
|
+
if (!(e instanceof Rollback))
|
|
135
|
+
throw e;
|
|
136
|
+
});
|
|
137
|
+
const tx = await Promise.race([opened.promise, done]); // `done` settles first only if the transaction failed to open
|
|
138
|
+
open = start(tx, database.nest(tx), async () => {
|
|
139
|
+
released.resolve();
|
|
140
|
+
await done;
|
|
141
|
+
});
|
|
142
|
+
},
|
|
143
|
+
/** Also throws a listener failure nothing surfaced yet (a call through `t.registry`), so the test fails. */
|
|
144
|
+
async rollback() {
|
|
145
|
+
const state = open;
|
|
146
|
+
open = undefined;
|
|
147
|
+
await state?.close();
|
|
148
|
+
if (state)
|
|
149
|
+
throwFailures(state);
|
|
150
|
+
},
|
|
151
|
+
as: (scope) => ({
|
|
152
|
+
scope,
|
|
153
|
+
run: (fn, ...args) => {
|
|
154
|
+
const state = current();
|
|
155
|
+
return settle(state, () => state.registry.as(scope).run(fn, ...args));
|
|
156
|
+
},
|
|
157
|
+
}),
|
|
158
|
+
stub: (fn, impl) => void current().stubs.set(fn, impl),
|
|
159
|
+
get events() {
|
|
160
|
+
return current().events;
|
|
161
|
+
},
|
|
162
|
+
get db() {
|
|
163
|
+
return current().db;
|
|
164
|
+
},
|
|
165
|
+
get registry() {
|
|
166
|
+
return current().registry;
|
|
167
|
+
},
|
|
168
|
+
jobs: {
|
|
169
|
+
get queued() {
|
|
170
|
+
return current().queued;
|
|
171
|
+
},
|
|
172
|
+
get scheduled() {
|
|
173
|
+
return current().scheduled;
|
|
174
|
+
},
|
|
175
|
+
async drain({ until } = {}) {
|
|
176
|
+
const state = current();
|
|
177
|
+
const end = until === undefined ? clock() : new Date(until);
|
|
178
|
+
if (Number.isNaN(end.getTime()))
|
|
179
|
+
throw new Error(`[logic-sdk] drain({ until }) needs a valid date (got ${String(until)}).`);
|
|
180
|
+
try {
|
|
181
|
+
for (let round = 1;; round++) {
|
|
182
|
+
const ready = [...takeDue(state.queued, end.getTime()), ...takeDue(state.scheduled, end.getTime())];
|
|
183
|
+
if (!ready.length)
|
|
184
|
+
return;
|
|
185
|
+
if (round > 100)
|
|
186
|
+
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?");
|
|
187
|
+
ready.sort((a, b) => (a.runAt ?? "").localeCompare(b.runAt ?? ""));
|
|
188
|
+
for (const job of ready) {
|
|
189
|
+
// the job runs at the time it was due, so a self-rescheduling one moves forward and its checks see that time
|
|
190
|
+
if (job.runAt)
|
|
191
|
+
travelled = Math.max(travelled ?? 0, Date.parse(job.runAt));
|
|
192
|
+
await settle(state, () => state.registry.jobs.run(job));
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
finally {
|
|
197
|
+
travelled = undefined;
|
|
198
|
+
}
|
|
199
|
+
},
|
|
200
|
+
perform(target, ...rest) {
|
|
201
|
+
const state = current();
|
|
202
|
+
if (target.kind === "cron") {
|
|
203
|
+
const { at, attempt } = (rest[0] ?? {});
|
|
204
|
+
const cron = state.registry.definitions.crons.find((c) => c.cron === target);
|
|
205
|
+
if (!cron)
|
|
206
|
+
throw new Error("[logic-sdk] t.jobs.perform got a cron that isn't registered: export it from its module.");
|
|
207
|
+
const when = at === undefined ? clock() : new Date(at);
|
|
208
|
+
if (Number.isNaN(when.getTime()))
|
|
209
|
+
throw new Error(`[logic-sdk] t.jobs.perform({ at }) needs a valid date (got ${String(at)}).`);
|
|
210
|
+
const [job] = state.registry[INTERNAL].due(when, cron.id);
|
|
211
|
+
return settle(state, () => state.registry.jobs.run(job, { attempt }));
|
|
212
|
+
}
|
|
213
|
+
const listener = target;
|
|
214
|
+
const [payload, { scope, attempt }] = rest;
|
|
215
|
+
const registered = state.registry.definitions.listeners.find((l) => l.listener === listener);
|
|
216
|
+
if (!registered)
|
|
217
|
+
throw new Error("[logic-sdk] t.jobs.perform got a listener that isn't registered: export it from its module.");
|
|
218
|
+
const envelope = state.registry[INTERNAL].envelope(registered.event, payload, scope);
|
|
219
|
+
return settle(state, () => state.registry.jobs.run(deliveryOf(registered, envelope), { attempt }));
|
|
220
|
+
},
|
|
221
|
+
async tick(at) {
|
|
222
|
+
const state = current();
|
|
223
|
+
const jobs = state.registry[INTERNAL].due(at === undefined ? clock() : new Date(at));
|
|
224
|
+
for (const job of jobs)
|
|
225
|
+
await settle(state, () => state.registry.jobs.run(job));
|
|
226
|
+
return jobs.map((job) => job.cron);
|
|
227
|
+
},
|
|
228
|
+
},
|
|
229
|
+
};
|
|
230
|
+
}
|
|
@@ -192,7 +192,7 @@ export interface CronJob {
|
|
|
192
192
|
/** When it may run (ISO), like a delivery's. Absent for crons: they run when ticked. */
|
|
193
193
|
runAt?: string;
|
|
194
194
|
}
|
|
195
|
-
/** A function `ctx.schedule` asked to run later: `id` is `<function id>@<uuid
|
|
195
|
+
/** A function `ctx.schedule` asked to run later: `id` is `<function id>@<uuid>`. */
|
|
196
196
|
export interface CallJob {
|
|
197
197
|
kind: "call";
|
|
198
198
|
id: string;
|
|
@@ -208,8 +208,8 @@ export interface CallJob {
|
|
|
208
208
|
* function that schedules itself with no delay stops like a listener loop. A delayed one starts a new chain (0).
|
|
209
209
|
*/
|
|
210
210
|
depth: number;
|
|
211
|
-
/**
|
|
212
|
-
replace?:
|
|
211
|
+
/** `true`: a newer call to `fn` with the same input replaces this one while it waits (the function and its input are the identity). */
|
|
212
|
+
replace?: true;
|
|
213
213
|
/** When it may run (ISO). */
|
|
214
214
|
runAt?: string;
|
|
215
215
|
}
|
|
@@ -246,6 +246,17 @@ export interface CronRun {
|
|
|
246
246
|
* `discarded`: `jobs.scope.load` returned null (who it ran as is gone). Acknowledge it too; it's been reported.
|
|
247
247
|
*/
|
|
248
248
|
export type JobOutcome = "done" | "failed" | "discarded";
|
|
249
|
+
/**
|
|
250
|
+
* What `ctx.emit` queued: the `id`, `name` and `occurredAt` its listeners see as `ctx.event`. `payload` is a copy of what
|
|
251
|
+
* you passed; listeners get it parsed by the event's schema.
|
|
252
|
+
*/
|
|
253
|
+
export interface EmittedEvent<I = unknown> {
|
|
254
|
+
readonly id: string;
|
|
255
|
+
readonly name: string;
|
|
256
|
+
readonly payload: I;
|
|
257
|
+
/** ISO. */
|
|
258
|
+
readonly occurredAt: string;
|
|
259
|
+
}
|
|
249
260
|
/** The event a listener is handling. No scope here: `ctx.scope` is the one it runs as. */
|
|
250
261
|
export interface ListenerEvent<O = unknown> {
|
|
251
262
|
id: string;
|
|
@@ -324,19 +335,24 @@ export interface MutationCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C
|
|
|
324
335
|
* `await ctx.run(availability.hold, { propertyId })`. If it fails, the whole transaction rolls back.
|
|
325
336
|
*/
|
|
326
337
|
run: Run<"query" | "mutation", ScopeOf<C>>;
|
|
327
|
-
/**
|
|
328
|
-
|
|
338
|
+
/**
|
|
339
|
+
* Queue an event. Delivered to listeners only after the transaction commits. Returns what it queued: the id, name and
|
|
340
|
+
* time its listeners see as `ctx.event`, so a row you write in this transaction can carry `event.id` and a listener
|
|
341
|
+
* finds it by `ctx.event.id`.
|
|
342
|
+
*/
|
|
343
|
+
emit<I>(event: EventDef<I, unknown>, payload: I): EmittedEvent<I>;
|
|
329
344
|
/**
|
|
330
345
|
* Run a mutation or action once, later, as this scope: `ctx.schedule(guests.remind, { bookingId }, { at })` or
|
|
331
|
-
* `{ delay: 3600 }` (seconds). Committed with this transaction, so a rollback never leaves one behind.
|
|
332
|
-
*
|
|
333
|
-
* `attempts`: tries in total, default 1; give an action that calls an API a few.
|
|
334
|
-
* with
|
|
346
|
+
* `{ delay: 3600 }` (seconds). Committed with this transaction, so a rollback never leaves one behind. Nothing to
|
|
347
|
+
* keep: there's no cancel. It runs whatever happens meanwhile, so it checks that its reason still holds ("still
|
|
348
|
+
* confirmed?") against your own row. `attempts`: tries in total, default 1; give an action that calls an API a few.
|
|
349
|
+
* `replace: true`: a newer call to this function with the same input replaces the one still waiting (the dates of
|
|
350
|
+
* `{ bookingId }` changed), like Oban's `replace`. Keep the input to ids, so it names one thing.
|
|
335
351
|
*/
|
|
336
|
-
schedule<F extends Fn<"mutation" | "action">>(fn: F, input: FnIn<F>, options: ScheduleOptions):
|
|
352
|
+
schedule<F extends Fn<"mutation" | "action">>(fn: F, input: FnIn<F>, options: ScheduleOptions<ScopeOf<C>>): void;
|
|
337
353
|
}
|
|
338
354
|
/** When a scheduled call runs (`at` or `delay` in seconds), and how many tries it gets. */
|
|
339
|
-
export type ScheduleOptions = ({
|
|
355
|
+
export type ScheduleOptions<S = object> = ({
|
|
340
356
|
at: Date;
|
|
341
357
|
delay?: never;
|
|
342
358
|
} | {
|
|
@@ -344,8 +360,13 @@ export type ScheduleOptions = ({
|
|
|
344
360
|
at?: never;
|
|
345
361
|
}) & {
|
|
346
362
|
attempts?: number;
|
|
347
|
-
/**
|
|
348
|
-
replace?:
|
|
363
|
+
/** `true`: the call to this function waiting with the same input (not started yet) is replaced by this one. */
|
|
364
|
+
replace?: true;
|
|
365
|
+
/**
|
|
366
|
+
* Who it runs as, whole, never merged, as `ctx.run` takes it: `{ scope: { kind: "system", job: "tasks.wake", organization } }`.
|
|
367
|
+
* Default: this mutation's scope. The function's policy checks it when it runs.
|
|
368
|
+
*/
|
|
369
|
+
scope?: S;
|
|
349
370
|
};
|
|
350
371
|
export interface ActionCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C, S> {
|
|
351
372
|
services: ServicesOf<C>;
|
|
@@ -413,21 +434,24 @@ export interface DatabaseAdapter<Db = unknown, Tx = Db> {
|
|
|
413
434
|
nest?(tx: Tx): DatabaseAdapter<Tx, Tx>;
|
|
414
435
|
/** Did this transaction lose a race the database says to retry (deadlock, serialization failure)? */
|
|
415
436
|
retryable?(error: unknown): boolean;
|
|
416
|
-
/**
|
|
417
|
-
* Tries in total for a top-level mutation whose transaction is `retryable`, each in a fresh one, like Laravel's
|
|
418
|
-
* `DB::transaction(fn, attempts)`. Default 3; 1 turns it off. A job's own tries are its `attempts`.
|
|
419
|
-
*/
|
|
420
|
-
transactionAttempts?: number;
|
|
421
|
-
/**
|
|
422
|
-
* One SQL statement (`$1` parameters on Postgres, `?` on SQLite), on the database or on a transaction of it. Resolves the rows it
|
|
423
|
-
* returns. `databaseQueue` and `outbox` run their table through it, so any ORM that can run SQL has them.
|
|
424
|
-
*/
|
|
425
|
-
query?(client: Db | Tx, text: string, params: unknown[]): Promise<Record<string, unknown>[]>;
|
|
426
437
|
}
|
|
427
|
-
/** A database adapter
|
|
438
|
+
/** A database adapter that runs SQL: what `databaseQueue()`, `outbox(queue)` and `pgBoss(boss)` need. */
|
|
428
439
|
export interface SqlDatabase<Db = any, Tx = any> extends DatabaseAdapter<Db, Tx> {
|
|
440
|
+
/**
|
|
441
|
+
* One SQL statement (`$1` parameters on Postgres, `?` on SQLite), on the database or on a transaction of it. Resolves
|
|
442
|
+
* the rows it returns. The jobs table runs through it, so any ORM that can run SQL has it.
|
|
443
|
+
*/
|
|
429
444
|
query(client: Db | Tx, text: string, params: unknown[]): Promise<Record<string, unknown>[]>;
|
|
430
445
|
}
|
|
446
|
+
/**
|
|
447
|
+
* `createRegistry({ database })`: the adapter, and how the core uses it. `transactionAttempts`: tries in total for a
|
|
448
|
+
* top-level mutation whose transaction lost a race (`retryable`), each in a fresh one, like Laravel's
|
|
449
|
+
* `DB::transaction(fn, attempts)`. Default 3; 1 turns it off. A job's own tries are its `attempts`.
|
|
450
|
+
*/
|
|
451
|
+
export interface DatabaseOptions<A extends DatabaseAdapter<any, any> = DatabaseAdapter<unknown, unknown>> {
|
|
452
|
+
adapter: A;
|
|
453
|
+
transactionAttempts?: number;
|
|
454
|
+
}
|
|
431
455
|
/** Runs one job: resolves when it's done or failed for good (acknowledge it), throws when a retry might help. */
|
|
432
456
|
export type RunJob = (job: Job, options?: RunJobOptions) => Promise<JobOutcome>;
|
|
433
457
|
export interface RunJobOptions {
|
|
@@ -453,6 +477,18 @@ export interface Runner {
|
|
|
453
477
|
report(error: unknown, job: Job, attempt?: number): void;
|
|
454
478
|
}
|
|
455
479
|
export interface JobsAdapter {
|
|
480
|
+
/** How it's set up, for messages: `"databaseQueue()"`. The core names capabilities, the adapter itself. */
|
|
481
|
+
name?: string;
|
|
482
|
+
/**
|
|
483
|
+
* It can run a job again after a failed try: a queue redelivers it, a table backs off. Without it (`inProcess()`),
|
|
484
|
+
* `createRegistry` refuses `attempts` above 1 rather than ignore them, as it refuses a delay it can't hold.
|
|
485
|
+
*/
|
|
486
|
+
retries?: true;
|
|
487
|
+
/**
|
|
488
|
+
* It writes jobs with SQL in the mutation's transaction, through the registry's database: `createRegistry` refuses a
|
|
489
|
+
* registry whose `database.adapter` doesn't run SQL (`query`), and `connect` gets it as `setup.sql`.
|
|
490
|
+
*/
|
|
491
|
+
sql?: true;
|
|
456
492
|
/**
|
|
457
493
|
* It can hold a job until its `runAt` (a listener's `delay`, `ctx.schedule`): `true`, or for at most `max` seconds.
|
|
458
494
|
* Without it (`inProcess()`), `createRegistry` refuses delayed listeners and `ctx.schedule` throws, rather than run
|
|
@@ -462,17 +498,16 @@ export interface JobsAdapter {
|
|
|
462
498
|
max: number;
|
|
463
499
|
};
|
|
464
500
|
/**
|
|
465
|
-
* Can replace a call waiting to run: `enqueue` gets a call with `replace`, and a pending call
|
|
466
|
-
*
|
|
467
|
-
* Without it, `ctx.schedule` with `replace` is refused.
|
|
501
|
+
* Can replace a call waiting to run: `enqueue` gets a call with `replace`, and a pending call with the same key
|
|
502
|
+
* (`storedReplaceKey`) that hasn't started is replaced by it. `databaseQueue` and `outbox` can; a queue that already
|
|
503
|
+
* has the message can't. Without it, `ctx.schedule` with `replace` is refused.
|
|
468
504
|
*/
|
|
469
505
|
replaces?: true;
|
|
470
|
-
/**
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
}): void;
|
|
506
|
+
/**
|
|
507
|
+
* At `createRegistry`, once: take what the adapter needs from the registry (its database, for an adapter that writes
|
|
508
|
+
* jobs in the mutation's transaction), and refuse a setup it can't honour.
|
|
509
|
+
*/
|
|
510
|
+
connect?(setup: AdapterSetup): void;
|
|
476
511
|
/** Inside the transaction, before commit. In-process: nothing. `databaseQueue` and `outbox`: insert one row per job with `tx`. */
|
|
477
512
|
enqueue?(tx: unknown, jobs: Job[]): Promise<void>;
|
|
478
513
|
/** After commit: run them, or hand them to a queue. A throw is reported to `onError`. */
|
|
@@ -483,6 +518,13 @@ export interface JobsAdapter {
|
|
|
483
518
|
}): Promise<SweepResult>;
|
|
484
519
|
/** Put a failed job back in line. `false` when there's no failed job with that id. Only adapters that store them. */
|
|
485
520
|
retry?(id: string): Promise<boolean>;
|
|
521
|
+
/** A page of failed jobs, newest first. Only adapters that store them and can filter them. */
|
|
522
|
+
failed?(options: FailedQuery): Promise<{
|
|
523
|
+
rows: FailedRow[];
|
|
524
|
+
cursor: string | null;
|
|
525
|
+
}>;
|
|
526
|
+
/** Delete one failed job. `false` when there's no failed job with that id: a waiting or running one is never touched. */
|
|
527
|
+
forget?(id: string): Promise<boolean>;
|
|
486
528
|
/**
|
|
487
529
|
* Keep a job that failed for good after it left the adapter: `registry.jobs.run` calls it from a queue consumer, so
|
|
488
530
|
* `outbox` stores the failure Cloudflare would otherwise drop. Not called for jobs the adapter ran itself.
|
|
@@ -502,6 +544,93 @@ export interface FailureInfo {
|
|
|
502
544
|
/** `retry`: tries are left and the adapter may run it again. `failed` and `discarded`: it's over. */
|
|
503
545
|
outcome?: "retry" | "failed" | "discarded";
|
|
504
546
|
}
|
|
547
|
+
/** What `createRegistry` gives an adapter's `connect`. */
|
|
548
|
+
export interface AdapterSetup {
|
|
549
|
+
listeners: readonly RegisteredListener[];
|
|
550
|
+
crons: readonly RegisteredCron[];
|
|
551
|
+
/** The registry's `database.adapter`. */
|
|
552
|
+
database: DatabaseAdapter<unknown, unknown> | undefined;
|
|
553
|
+
/** The same, when it runs SQL: always set for an adapter that declares `sql: true`. */
|
|
554
|
+
sql: SqlDatabase | undefined;
|
|
555
|
+
}
|
|
556
|
+
/**
|
|
557
|
+
* A store for failed jobs, apart from the queue that runs them, like Laravel's `failed` driver. `failedJobs()`
|
|
558
|
+
* keeps them in the jobs table. For adapters that keep their own, it isn't needed.
|
|
559
|
+
*/
|
|
560
|
+
export interface FailedJobs {
|
|
561
|
+
/** For messages: `"failedJobs()"`. */
|
|
562
|
+
name?: string;
|
|
563
|
+
/** Keeps failed jobs with SQL, through the registry's database (`setup.sql`): see `JobsAdapter.sql`. */
|
|
564
|
+
sql?: true;
|
|
565
|
+
/** At `createRegistry`, once: take the registry's database. */
|
|
566
|
+
connect?(setup: AdapterSetup): void;
|
|
567
|
+
/** Keep a job that failed for good. */
|
|
568
|
+
fail(job: Job, error: unknown): Promise<void>;
|
|
569
|
+
/** A page of failed jobs, newest first. */
|
|
570
|
+
failed(query: FailedQuery): Promise<{
|
|
571
|
+
rows: FailedRow[];
|
|
572
|
+
cursor: string | null;
|
|
573
|
+
}>;
|
|
574
|
+
/** Remove a failed job and return it, for `retry` to hand to the queue again. Undefined when there's none with that id. */
|
|
575
|
+
take(id: string): Promise<Job | undefined>;
|
|
576
|
+
/** Delete a failed job. `false` when there's none with that id. */
|
|
577
|
+
forget(id: string): Promise<boolean>;
|
|
578
|
+
}
|
|
579
|
+
/** One field of a stored scope a `failed({ scope })` filter matches exactly: `["organization", "id"]` and `"org_1"`. */
|
|
580
|
+
export interface ScopeMatch {
|
|
581
|
+
path: string[];
|
|
582
|
+
value: string | number | boolean | null;
|
|
583
|
+
}
|
|
584
|
+
/** What `registry.jobs.failed` asks an adapter for. The core checks and flattens the filter first. */
|
|
585
|
+
export interface FailedQuery {
|
|
586
|
+
/** The listener, cron or function id. */
|
|
587
|
+
source?: string;
|
|
588
|
+
/** Every one must equal the stored scope's field at `path` (the job's `scope`, or its envelope's). */
|
|
589
|
+
scope?: ScopeMatch[];
|
|
590
|
+
limit: number;
|
|
591
|
+
/** From the last page: where to go on. */
|
|
592
|
+
cursor?: string;
|
|
593
|
+
}
|
|
594
|
+
/** A failed job as an adapter keeps it. */
|
|
595
|
+
export interface FailedRow {
|
|
596
|
+
id: string;
|
|
597
|
+
job: Job;
|
|
598
|
+
error: string;
|
|
599
|
+
/** ISO. */
|
|
600
|
+
failedAt: string;
|
|
601
|
+
}
|
|
602
|
+
/** A failed job, as `registry.jobs.failed` lists it: pass its `id` to `retry` or `forget`. */
|
|
603
|
+
export interface FailedJob<Stored = Record<string, unknown>> {
|
|
604
|
+
id: string;
|
|
605
|
+
kind: Job["kind"];
|
|
606
|
+
/** The listener, cron or function that failed, as in `FailureInfo`. */
|
|
607
|
+
source: string;
|
|
608
|
+
/** What `jobs.scope.store` saved with it. Undefined for a cron run: it has none. */
|
|
609
|
+
scope: Stored | undefined;
|
|
610
|
+
/** The last error, with its stack. */
|
|
611
|
+
error: string;
|
|
612
|
+
/** ISO. */
|
|
613
|
+
failedAt: string;
|
|
614
|
+
job: Job;
|
|
615
|
+
}
|
|
616
|
+
export interface FailedOptions<Stored = Record<string, unknown>> {
|
|
617
|
+
/** Only this listener's, cron's or function's: `"emails.send"`. */
|
|
618
|
+
source?: string;
|
|
619
|
+
/**
|
|
620
|
+
* Only jobs whose stored scope has these values (what `jobs.scope.store` saved): `{ organizationId: "org_1" }`,
|
|
621
|
+
* nested fields too. Never a cron run: it stores none. Values are strings, numbers, booleans or null.
|
|
622
|
+
*/
|
|
623
|
+
scope?: DeepPartial<Stored>;
|
|
624
|
+
/** 1 to 1000. Default 100. */
|
|
625
|
+
limit?: number;
|
|
626
|
+
/** The `cursor` of the page before. */
|
|
627
|
+
cursor?: string;
|
|
628
|
+
}
|
|
629
|
+
export interface FailedPage<Stored = Record<string, unknown>> {
|
|
630
|
+
jobs: FailedJob<Stored>[];
|
|
631
|
+
/** Pass it back for the next page; null on the last one. */
|
|
632
|
+
cursor: string | null;
|
|
633
|
+
}
|
|
505
634
|
/**
|
|
506
635
|
* Who a job runs as, at rest. `store` picks what's saved with the job (ids, not whole objects); `load` rebuilds the
|
|
507
636
|
* scope when it runs, so policies see today's roles. `load` returning null discards the job (reported to `onError`),
|
|
@@ -524,6 +653,11 @@ export interface InProcess extends JobsAdapter {
|
|
|
524
653
|
* checked at startup: requiring it here would report a missing one as a wrong `store`.
|
|
525
654
|
*/
|
|
526
655
|
export type JobsOptions<S = object, T = any> = {
|
|
656
|
+
/**
|
|
657
|
+
* Where failed jobs are kept when your adapter can't keep them itself (a queue on its own), like Laravel's `failed`
|
|
658
|
+
* driver: `failed: failedJobs()`. `registry.jobs.failed`, `retry` and `forget` then work on it.
|
|
659
|
+
*/
|
|
660
|
+
failed?: FailedJobs;
|
|
527
661
|
/**
|
|
528
662
|
* Max chain of listener → mutation → event → listener… before queueing stops, reported. Calls `ctx.schedule` runs
|
|
529
663
|
* right away count too, so a function that schedules itself with no delay stops the same way. Default 8 (real chains
|
|
@@ -531,12 +665,12 @@ export type JobsOptions<S = object, T = any> = {
|
|
|
531
665
|
*/
|
|
532
666
|
maxEventDepth?: number;
|
|
533
667
|
} & ({
|
|
534
|
-
/** `inProcess()` (default), or a durable one like `databaseQueue(
|
|
668
|
+
/** `inProcess()` (default), or a durable one like `databaseQueue()`. Its own options go in its factory. */
|
|
535
669
|
adapter?: InProcess;
|
|
536
670
|
/** Applied by the registry in every adapter, `inProcess()` and tests included. */
|
|
537
671
|
scope?: JobScope<S, T>;
|
|
538
672
|
} | {
|
|
539
|
-
/** An adapter that keeps jobs to run later, like `databaseQueue(
|
|
673
|
+
/** An adapter that keeps jobs to run later, like `databaseQueue()`. */
|
|
540
674
|
adapter?: JobsAdapter;
|
|
541
675
|
/** Required: such a job runs as the scope `load` rebuilds, with today's roles. */
|
|
542
676
|
scope: JobScope<S, T>;
|
|
@@ -544,6 +678,11 @@ export type JobsOptions<S = object, T = any> = {
|
|
|
544
678
|
export interface Call<M = unknown> {
|
|
545
679
|
id: string;
|
|
546
680
|
kind: Kind | "listener" | "cron";
|
|
681
|
+
/** Set on a job's own run (a listener's, a cron's, a scheduled call's): which job, and which try (1 on the first). */
|
|
682
|
+
job?: {
|
|
683
|
+
id: string;
|
|
684
|
+
attempt: number;
|
|
685
|
+
};
|
|
547
686
|
/** The function's, listener's or cron's `meta` (undefined when it has none). */
|
|
548
687
|
meta: M | undefined;
|
|
549
688
|
/** Raw input as received (before validation). */
|
|
@@ -554,11 +693,12 @@ export interface Call<M = unknown> {
|
|
|
554
693
|
export interface RegistryOptions<Mods extends Record<string, object>> {
|
|
555
694
|
/** One entry per module: `{ bookings, availability }` with `import * as bookings from "./bookings"`. */
|
|
556
695
|
modules: Mods;
|
|
557
|
-
database
|
|
696
|
+
/** `database: { adapter: drizzleAdapter(db) }`, with `transactionAttempts` when 3 isn't right. */
|
|
697
|
+
database?: DatabaseOptions;
|
|
558
698
|
services?: object;
|
|
559
699
|
/** Settings every function reads as `ctx.config`. Plain data: it's copied and frozen. */
|
|
560
700
|
config?: object;
|
|
561
|
-
/** Background work: `jobs: { adapter: databaseQueue(
|
|
701
|
+
/** Background work: `jobs: { adapter: databaseQueue(), scope: { store, load } }`. Default: in-process, scope as-is (nothing waits). */
|
|
562
702
|
jobs?: JobsOptions;
|
|
563
703
|
/** Wraps every call, including ones that fail validation or authorization: logging, tracing, audit. */
|
|
564
704
|
wrap?: (call: Call, next: () => Promise<unknown>) => Promise<unknown>;
|
|
@@ -595,6 +735,8 @@ export interface Overrides {
|
|
|
595
735
|
/** Merged over the registry's config, section by section. */
|
|
596
736
|
config?: unknown;
|
|
597
737
|
adapter?: JobsAdapter;
|
|
738
|
+
/** Where failed jobs go instead of `jobs.failed`; `null` keeps none (a test registry: failures throw). */
|
|
739
|
+
failed?: FailedJobs | null;
|
|
598
740
|
now?: () => Date;
|
|
599
741
|
stubs?: Map<Fn, (ctx: never, input: never) => Promise<unknown>>;
|
|
600
742
|
record?: (envelope: Envelope) => void;
|
|
@@ -612,7 +754,10 @@ export interface RegisteredListener extends Registered {
|
|
|
612
754
|
export interface RegisteredCron extends Registered {
|
|
613
755
|
cron: Cron;
|
|
614
756
|
}
|
|
615
|
-
/**
|
|
757
|
+
/**
|
|
758
|
+
* `registry.jobs`: what you call from a queue consumer, a timer, a script or a staff route. Outside your functions, as
|
|
759
|
+
* Laravel's queue commands are: guard the route yourself. A job a user wants again is a mutation that emits again.
|
|
760
|
+
*/
|
|
616
761
|
export interface Jobs {
|
|
617
762
|
/**
|
|
618
763
|
* Run one stored job (queue consumers): `await registry.jobs.run(message.body, { attempt: message.attempts })`.
|
|
@@ -627,7 +772,7 @@ export interface Jobs {
|
|
|
627
772
|
*/
|
|
628
773
|
tick(at?: Date): Promise<string[]>;
|
|
629
774
|
/**
|
|
630
|
-
* Run what your adapter has due, from a cron or an interval: `await registry.jobs.sweep()`. With `databaseQueue(
|
|
775
|
+
* Run what your adapter has due, from a cron or an interval: `await registry.jobs.sweep()`. With `databaseQueue()`, that's
|
|
631
776
|
* retries whose backoff is over and jobs whose runner crashed. Adapters that keep nothing, or maintain themselves
|
|
632
777
|
* (pg-boss), resolve zeros.
|
|
633
778
|
*/
|
|
@@ -639,6 +784,25 @@ export interface Jobs {
|
|
|
639
784
|
* running, done, or never existed). Throws when your adapter keeps no jobs, like `inProcess()`.
|
|
640
785
|
*/
|
|
641
786
|
retry(id: string): Promise<boolean>;
|
|
787
|
+
/**
|
|
788
|
+
* Failed jobs, newest first, a page at a time: `await registry.jobs.failed({ source: "emails.send", scope: { organizationId } })`.
|
|
789
|
+
* Then `retry` or `forget` each. Pass your stored scope's type to check the filter: `failed<Stored>({ scope })`. Throws
|
|
790
|
+
* when your adapter keeps none (a queue alone without `jobs.failed`) or can't list them: its message says where they are.
|
|
791
|
+
*/
|
|
792
|
+
failed<Stored = Record<string, unknown>>(options?: FailedOptions<Stored>): Promise<FailedPage<Stored>>;
|
|
793
|
+
/**
|
|
794
|
+
* Delete a failed job, like Laravel's `queue:forget`. `false` when no failed job has that id: a waiting or running one
|
|
795
|
+
* is never touched. Throws when your adapter keeps no jobs.
|
|
796
|
+
*/
|
|
797
|
+
forget(id: string): Promise<boolean>;
|
|
798
|
+
/**
|
|
799
|
+
* Run a cron now, outside its schedule, through your jobs adapter like a tick: `await registry.jobs.invoke(orders.sendDigest)`,
|
|
800
|
+
* or its id from a script. `at`: the minute the run is for (`ctx.cron.scheduledAt`), default now, to redo a missed one.
|
|
801
|
+
* Its own job id, so the real tick for that minute still runs. Resolves the id; throws when the hand-off fails.
|
|
802
|
+
*/
|
|
803
|
+
invoke(cron: Cron | string, options?: {
|
|
804
|
+
at?: Date;
|
|
805
|
+
}): Promise<string>;
|
|
642
806
|
}
|
|
643
807
|
/** What `createRegistry` returns. `Cf` is your config's type, so tests can override parts of it. */
|
|
644
808
|
export interface Registry<S extends object = object, Mods extends Record<string, object> = Record<string, object>, Cf = unknown> {
|
|
@@ -658,7 +822,6 @@ export interface Registry<S extends object = object, Mods extends Record<string,
|
|
|
658
822
|
/** @internal used by `logic-sdk/testing` */
|
|
659
823
|
readonly [INTERNAL]: {
|
|
660
824
|
options: RegistryOptions<Mods>;
|
|
661
|
-
config: Frozen<Cf>;
|
|
662
825
|
derive(more: Overrides): Registry<S, Mods, Cf>;
|
|
663
826
|
/** An event as `emit` would make it, for `t.jobs.perform`. */
|
|
664
827
|
envelope(event: EventDef, payload: unknown, scope: S): Envelope;
|