logic-sdk 0.6.3 → 0.7.1
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 +2 -2
- package/dist/errors.d.ts +10 -1
- package/dist/errors.js +11 -2
- package/dist/index.d.ts +21 -23
- package/dist/index.js +41 -19
- package/dist/jobs.d.ts +3 -3
- package/dist/jobs.js +16 -8
- package/dist/pg-boss.d.ts +3 -5
- package/dist/pg-boss.js +5 -3
- package/dist/testing.d.ts +9 -1
- package/dist/testing.js +14 -1
- package/dist/types.d.ts +25 -12
- package/package.json +2 -2
- package/skills/logic-sdk/SKILL.md +4 -4
- package/src/errors.ts +11 -2
- package/src/index.ts +66 -35
- package/src/jobs.ts +21 -10
- package/src/pg-boss.ts +6 -7
- package/src/testing.ts +18 -1
- package/src/types.ts +30 -13
package/README.md
CHANGED
|
@@ -83,8 +83,8 @@ export const registry = createRegistry({
|
|
|
83
83
|
// a listener, with tries
|
|
84
84
|
export const sendConfirmation = listener({ event: () => confirmed, attempts: 3, handler });
|
|
85
85
|
|
|
86
|
-
// a cron
|
|
87
|
-
export const
|
|
86
|
+
// a cron: a listener for the clock
|
|
87
|
+
export const sendDigest = cron({ schedule: "0 8 * * MON-FRI", scope: { kind: "system", job: "digest" }, handler: (ctx) => ctx.run(mailDigest) });
|
|
88
88
|
|
|
89
89
|
// later, from a mutation, committed with it
|
|
90
90
|
ctx.schedule(remindGuest, { bookingId }, { at: dayBefore(booking.checkIn) });
|
package/dist/errors.d.ts
CHANGED
|
@@ -30,10 +30,19 @@ export declare const describeIssues: (issues: readonly StandardSchemaV1.Issue[])
|
|
|
30
30
|
/** A payload that stopped matching its event's schema (a deploy changed it while it waited): delivering again won't help. */
|
|
31
31
|
export declare class StalePayload extends Error {
|
|
32
32
|
}
|
|
33
|
+
/**
|
|
34
|
+
* A mutation's commit after a nested mutation failed and was caught: the transaction they share is doomed. Its
|
|
35
|
+
* `cause` is that failure, and retries (a transaction's, a job's) treat it as the cause would be treated.
|
|
36
|
+
*/
|
|
37
|
+
export declare class CaughtNestedFailure extends Error {
|
|
38
|
+
}
|
|
33
39
|
/**
|
|
34
40
|
* Throw where there's no valid session, outside your functions (a route, a middleware): `toResponse` makes it a 401.
|
|
35
41
|
* Inside a function, a policy answers instead (a scope with no actor, then `forbidden`).
|
|
36
42
|
*/
|
|
37
43
|
export declare const unauthenticated: (code?: string, details?: unknown) => DomainError;
|
|
38
|
-
/**
|
|
44
|
+
/**
|
|
45
|
+
* An error and the ones it wraps (`cause`), six deep at most: a driver's error usually arrives wrapped by the ORM,
|
|
46
|
+
* and a caught nested failure wraps that once more.
|
|
47
|
+
*/
|
|
39
48
|
export declare function causes(error: unknown): Generator<object>;
|
package/dist/errors.js
CHANGED
|
@@ -39,13 +39,22 @@ export const describeIssues = (issues) => issues.map((i) => ({ message: i.messag
|
|
|
39
39
|
/** A payload that stopped matching its event's schema (a deploy changed it while it waited): delivering again won't help. */
|
|
40
40
|
export class StalePayload extends Error {
|
|
41
41
|
}
|
|
42
|
+
/**
|
|
43
|
+
* A mutation's commit after a nested mutation failed and was caught: the transaction they share is doomed. Its
|
|
44
|
+
* `cause` is that failure, and retries (a transaction's, a job's) treat it as the cause would be treated.
|
|
45
|
+
*/
|
|
46
|
+
export class CaughtNestedFailure extends Error {
|
|
47
|
+
}
|
|
42
48
|
/**
|
|
43
49
|
* Throw where there's no valid session, outside your functions (a route, a middleware): `toResponse` makes it a 401.
|
|
44
50
|
* Inside a function, a policy answers instead (a scope with no actor, then `forbidden`).
|
|
45
51
|
*/
|
|
46
52
|
export const unauthenticated = (code = "unauthenticated", details) => new DomainError("unauthenticated", code, details);
|
|
47
|
-
/**
|
|
53
|
+
/**
|
|
54
|
+
* An error and the ones it wraps (`cause`), six deep at most: a driver's error usually arrives wrapped by the ORM,
|
|
55
|
+
* and a caught nested failure wraps that once more.
|
|
56
|
+
*/
|
|
48
57
|
export function* causes(error) {
|
|
49
|
-
for (let e = error, i = 0; typeof e === "object" && e !== null && i <
|
|
58
|
+
for (let e = error, i = 0; typeof e === "object" && e !== null && i < 6; e = "cause" in e ? e.cause : undefined, i++)
|
|
50
59
|
yield e;
|
|
51
60
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { Call, CallMetaOf, Config, ConfigOf, Constructor, Cron, DatabaseAdapter, DbOf, EventDef,
|
|
2
|
-
export type { ActionCtx, Call, CallJob, Caller, Config, Constructor, Cron, CronJob, DatabaseAdapter, DeepPartial, Delivery, Envelope, Errors, EventDef, FailureInfo, Fn, FnIn, FnOut, ForFunctions, ForListeners, Frozen, In, InProcess, Job, JobOutcome, JobsAdapter, JobScope, Jobs, JobsOptions, Kind, Listener, ListenerCtx, ListenerEvent, MutationCtx, Out, Policy, PublishableFn, ScopeOfFn, QueryCtx, ReadWrite, Registered, RegisteredCron, RegisteredEvent, RegisteredFn, RegisteredListener, Registry, RegistryOptions, RunArgs, RunJob, RunJobOptions, RunOptions, Runner, ScheduleOptions, Schema, SqlDatabase, SweepResult, } from "./types.ts";
|
|
1
|
+
import type { Call, CallMetaOf, Config, ConfigOf, Constructor, Cron, CronCtx, DatabaseAdapter, DbOf, EventDef, In, JobsOptions, Listener, ListenerCtx, ListenerMetaOf, Out, OwnModules, RegisteredCron, RegisteredEvent, RegisteredFn, RegisteredListener, Registry, RegistryOptions, Schema, ScopeOf, ServicesOf } from "./types.ts";
|
|
2
|
+
export type { ActionCtx, Call, CallJob, Caller, Config, Constructor, Cron, CronCtx, CronRun, CronJob, DatabaseAdapter, DeepPartial, Delivery, Envelope, Errors, EventDef, FailureInfo, Fn, FnIn, FnOut, ForFunctions, ForListeners, Frozen, In, InProcess, Job, JobOutcome, JobsAdapter, JobScope, Jobs, JobsOptions, Kind, Listener, ListenerCtx, ListenerEvent, MutationCtx, Out, Policy, PublishableFn, ScopeOfFn, QueryCtx, ReadWrite, Registered, RegisteredCron, RegisteredEvent, RegisteredFn, RegisteredListener, Registry, RegistryOptions, RunArgs, RunJob, RunJobOptions, RunOptions, Runner, ScheduleOptions, Schema, SqlDatabase, SweepResult, } from "./types.ts";
|
|
3
3
|
export { DomainError, isDomainError, unauthenticated, type ErrorKind } from "./errors.ts";
|
|
4
4
|
export { inProcess, replaceKeyOf } from "./jobs.ts";
|
|
5
5
|
type TypedOptions<C extends Config, Mods extends Record<string, object>, T> = Omit<RegistryOptions<Mods>, "wrap" | "jobs"> & {
|
|
@@ -52,11 +52,12 @@ export declare function init<C extends Config & OnlyKnownKeys<C>>(): {
|
|
|
52
52
|
payload: S;
|
|
53
53
|
}) => EventDef<In<S>, Out<S>>;
|
|
54
54
|
/**
|
|
55
|
-
*
|
|
56
|
-
* `registry.jobs.tick()` every minute (or from your platform's cron trigger)
|
|
57
|
-
*
|
|
55
|
+
* Work on a schedule, as `scope` (a cron has no caller): a handler, like a listener's, run when the clock says. Export
|
|
56
|
+
* it from a module and call `registry.jobs.tick()` every minute (or from your platform's cron trigger). Must be
|
|
57
|
+
* idempotent: a retry runs the whole handler again.
|
|
58
|
+
* `cron({ schedule: "0 9 * * MON", scope: { kind: "system", job: "reports.weekly" }, async handler(ctx) { await ctx.run(send) } })`.
|
|
58
59
|
*/
|
|
59
|
-
cron: <
|
|
60
|
+
cron: <const Sc extends ScopeOf<C>>(def: CronDef<C, Sc>) => Cron<C>;
|
|
60
61
|
/**
|
|
61
62
|
* React to an event after commit, like an action. Must be idempotent.
|
|
62
63
|
* `listener({ event: () => bookings.confirmed, async handler(ctx, payload) {…} })`
|
|
@@ -87,28 +88,25 @@ export declare function init<C extends Config & OnlyKnownKeys<C>>(): {
|
|
|
87
88
|
handler: (ctx: ListenerCtx<C, O>, payload: O) => Promise<unknown>;
|
|
88
89
|
}) => Listener<O, C>;
|
|
89
90
|
};
|
|
90
|
-
/** `cron({...})`: `
|
|
91
|
-
type CronDef<
|
|
92
|
-
/**
|
|
91
|
+
/** `cron({...})`: its handler's `ctx.scope` is the scope it declares, so a policy-free read of it is typed. */
|
|
92
|
+
type CronDef<C extends Config, Sc> = {
|
|
93
|
+
/**
|
|
94
|
+
* Stable id, local to its module, like every definer's. Defaults to the export name. Jobs and pg-boss's queue store it,
|
|
95
|
+
* so set it before you rename the export.
|
|
96
|
+
*/
|
|
93
97
|
id?: string;
|
|
94
|
-
/** Five fields: minute hour day-of-month month day-of-week. `"*\/15 * * * *"`, `"0 9 * *
|
|
98
|
+
/** Five fields: minute hour day-of-month month day-of-week. `"*\/15 * * * *"`, `"0 9 * * MON"`. */
|
|
95
99
|
schedule: string;
|
|
96
100
|
/** IANA name, like `"Europe/Madrid"`. Default UTC. Matched on the wall clock, like Laravel: mind DST at 1 to 3 am. */
|
|
97
101
|
timezone?: string;
|
|
98
|
-
/**
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
*/
|
|
102
|
-
run: () => F;
|
|
103
|
-
/** Who it runs as: a cron has no caller. */
|
|
104
|
-
scope: S;
|
|
105
|
-
/** Tries in total, like a listener's. Default 1. */
|
|
102
|
+
/** Who it runs as: a cron has no caller. Every function the handler runs checks its policy against it. */
|
|
103
|
+
scope: Sc;
|
|
104
|
+
/** Tries in total, like a listener's. Default 1: a retry runs the whole handler again. */
|
|
106
105
|
attempts?: number;
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
});
|
|
106
|
+
meta?: ListenerMetaOf<C>;
|
|
107
|
+
/** The work, like a listener's handler: an action's ctx, plus `ctx.cron` (`scheduledAt`, `attempt`). */
|
|
108
|
+
handler: (ctx: CronCtx<C, Sc>) => Promise<unknown>;
|
|
109
|
+
};
|
|
112
110
|
/** Create the registry once at startup. Prefer the `createRegistry` returned by `init()`: it's typed with your config. */
|
|
113
111
|
export declare function createRegistry<S extends object = object, const Mods extends Record<string, object> = Record<string, object>>(options: RegistryOptions<Mods>): Registry<S, Mods, unknown>;
|
|
114
112
|
/**
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { describeIssues, DomainError, errorsFor, forbiddenOf, moduleOf, PRIVATE } from "./errors.js";
|
|
1
|
+
import { CaughtNestedFailure, describeIssues, DomainError, errorsFor, forbiddenOf, moduleOf, PRIVATE } from "./errors.js";
|
|
2
2
|
import { inProcess, makeJobs, replaceKeyOf, runsNow } from "./jobs.js";
|
|
3
3
|
import { assertTimeZone, parseSchedule } from "./schedule.js";
|
|
4
4
|
import { BRAND, INTERNAL } from "./types.js";
|
|
@@ -26,17 +26,19 @@ export function init() {
|
|
|
26
26
|
/** Something that happened. Emitted by mutations, delivered after commit. */
|
|
27
27
|
event: (def) => Object.freeze({ [BRAND]: "event", kind: "event", ...def }),
|
|
28
28
|
/**
|
|
29
|
-
*
|
|
30
|
-
* `registry.jobs.tick()` every minute (or from your platform's cron trigger)
|
|
31
|
-
*
|
|
29
|
+
* Work on a schedule, as `scope` (a cron has no caller): a handler, like a listener's, run when the clock says. Export
|
|
30
|
+
* it from a module and call `registry.jobs.tick()` every minute (or from your platform's cron trigger). Must be
|
|
31
|
+
* idempotent: a retry runs the whole handler again.
|
|
32
|
+
* `cron({ schedule: "0 9 * * MON", scope: { kind: "system", job: "reports.weekly" }, async handler(ctx) { await ctx.run(send) } })`.
|
|
32
33
|
*/
|
|
33
34
|
cron: (def) => {
|
|
34
|
-
const { id, schedule, timezone,
|
|
35
|
+
const { id, schedule, timezone, scope, attempts, meta, handler } = def;
|
|
35
36
|
parseSchedule(schedule);
|
|
36
37
|
if (timezone !== undefined)
|
|
37
38
|
assertTimeZone(timezone);
|
|
38
39
|
checkAttempts("cron", attempts);
|
|
39
|
-
|
|
40
|
+
// meta is checked against ListenerMetaOf<C> above and stored loose, like a listener's, for wrap and adapters
|
|
41
|
+
return Object.freeze({ [BRAND]: "cron", kind: "cron", id, schedule, timezone, scope, attempts, meta: meta, handler });
|
|
40
42
|
},
|
|
41
43
|
/**
|
|
42
44
|
* React to an event after commit, like an action. Must be idempotent.
|
|
@@ -58,6 +60,19 @@ function checkAttempts(what, attempts) {
|
|
|
58
60
|
if (attempts !== undefined && !(Number.isInteger(attempts) && attempts >= 1))
|
|
59
61
|
throw new Error(`[logic-sdk] ${what} attempts must be a whole number of tries, 1 or more (got ${attempts}).`);
|
|
60
62
|
}
|
|
63
|
+
/** What a mutation throws at commit when a nested mutation failed and was caught: the transaction they share is doomed. */
|
|
64
|
+
function caughtNestedFailure(id, tx) {
|
|
65
|
+
let why;
|
|
66
|
+
try {
|
|
67
|
+
why = tx.reason instanceof Error ? tx.reason.message : String(tx.reason);
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
why = Object.prototype.toString.call(tx.reason); // an object String() can't print
|
|
71
|
+
}
|
|
72
|
+
return new CaughtNestedFailure(`[logic-sdk] ${tx.doomedBy?.at(-1)} failed inside ${id}'s transaction (${tx.doomedBy?.join(" → ")}) and was ` +
|
|
73
|
+
`caught, so ${id} can't commit: a mutation shares its transaction with the mutations it runs. To let each one ` +
|
|
74
|
+
`commit or fail on its own, run them from an action. The failure (this error's cause): ${why}`, { cause: tx.reason });
|
|
75
|
+
}
|
|
61
76
|
/** Create the registry once at startup. Prefer the `createRegistry` returned by `init()`: it's typed with your config. */
|
|
62
77
|
export function createRegistry(options) {
|
|
63
78
|
return build(options, {});
|
|
@@ -149,7 +164,7 @@ export function describeModules(modules) {
|
|
|
149
164
|
else if (value.kind === "listener")
|
|
150
165
|
listeners.push({ id, module, name, listener: value, event: value.event() });
|
|
151
166
|
else if (value.kind === "cron")
|
|
152
|
-
crons.push({ id, module, name, cron: value
|
|
167
|
+
crons.push({ id, module, name, cron: value });
|
|
153
168
|
else
|
|
154
169
|
functions.push({ id, module, name, kind: value.kind, fn: value });
|
|
155
170
|
}
|
|
@@ -193,7 +208,7 @@ function build(options, o) {
|
|
|
193
208
|
for (const l of listeners)
|
|
194
209
|
if (!ids.has(l.event))
|
|
195
210
|
throw new Error(`[logic-sdk] Listener ${l.id} listens to an event that isn't registered in any module.`);
|
|
196
|
-
jobsAdapter.check?.({ listeners, database });
|
|
211
|
+
jobsAdapter.check?.({ listeners, crons, database });
|
|
197
212
|
const idOf = (x) => {
|
|
198
213
|
const id = ids.get(x);
|
|
199
214
|
if (!id)
|
|
@@ -224,16 +239,11 @@ function build(options, o) {
|
|
|
224
239
|
check.catch(() => { }); // surfaced at commit; never an unhandled rejection
|
|
225
240
|
tx.pending.push(check);
|
|
226
241
|
}
|
|
227
|
-
for (const c of crons) {
|
|
228
|
-
if (!ids.has(c.run))
|
|
229
|
-
throw new Error(`[logic-sdk] Cron ${c.id} runs a function that isn't registered. Export it from its module's index.ts.`);
|
|
230
|
-
assertPlain(c.cron.input, `${c.id} input`, "Cron runs travel through queues as JSON: send an ISO string and let the schema turn it into a Date");
|
|
231
|
-
}
|
|
232
242
|
// ── ctx ──────────────────────────────────────────────────────────────────
|
|
233
|
-
/** The frame for a call from here: its scope
|
|
243
|
+
/** The frame for a call from here: its scope and signal. `invoke` adds the call to the trail. */
|
|
234
244
|
const enter = (frame, options) => ({
|
|
235
245
|
...frame,
|
|
236
|
-
scope: options?.scope
|
|
246
|
+
scope: options?.scope ?? frame.scope,
|
|
237
247
|
signal: options?.signal ?? frame.signal,
|
|
238
248
|
abortOn: options?.signal,
|
|
239
249
|
});
|
|
@@ -337,7 +347,7 @@ function build(options, o) {
|
|
|
337
347
|
wrap,
|
|
338
348
|
report,
|
|
339
349
|
runAs: (fn, input, scope, eventDepth, queued) => invoke(fn, input, enter({ scope, trail: [], eventDepth, queued }, undefined), ["query", "mutation", "action"]),
|
|
340
|
-
|
|
350
|
+
handlerCtx: (scope, eventDepth, id, queued) => actionCtx({ scope, trail: [id], eventDepth, queued }, id),
|
|
341
351
|
});
|
|
342
352
|
// ── invoke ───────────────────────────────────────────────────────────────
|
|
343
353
|
/** `callerModule`: set by ctx.run, so a private function (its index doesn't export it) runs as part of the module running it. */
|
|
@@ -386,6 +396,7 @@ function build(options, o) {
|
|
|
386
396
|
if (!tx.doomed) {
|
|
387
397
|
tx.doomed = true;
|
|
388
398
|
tx.reason = e;
|
|
399
|
+
tx.doomedBy = frame.trail.slice(tx.from);
|
|
389
400
|
}
|
|
390
401
|
throw e;
|
|
391
402
|
}
|
|
@@ -398,14 +409,21 @@ function build(options, o) {
|
|
|
398
409
|
const input = await prepare();
|
|
399
410
|
let committed;
|
|
400
411
|
for (let attempt = 1;; attempt++) {
|
|
412
|
+
const attemptTx = {};
|
|
401
413
|
try {
|
|
402
414
|
committed = await database.transaction(async (txDb) => {
|
|
403
415
|
// fresh per attempt, so a retry never reuses events from a failed attempt
|
|
404
|
-
const tx = {
|
|
416
|
+
const tx = {
|
|
417
|
+
db: txDb, doomed: false, reason: undefined, from: frame.trail.length - 1, doomedBy: undefined,
|
|
418
|
+
events: [], parsed: new Map(), calls: [], pending: [],
|
|
419
|
+
};
|
|
420
|
+
attemptTx.current = tx;
|
|
405
421
|
const out = await execute(input, mutationCtx({ ...frame, tx }, tx, id));
|
|
406
422
|
await Promise.all(tx.pending);
|
|
423
|
+
// a nested failure was caught: a bug, so its own error, with the failure as its cause (Ecto's aborted
|
|
424
|
+
// transaction). Retries still see a deadlock: `retryable` walks causes
|
|
407
425
|
if (tx.doomed)
|
|
408
|
-
throw tx
|
|
426
|
+
throw caughtNestedFailure(id, tx);
|
|
409
427
|
const jobs = toJobs(tx.events, tx.calls, tx.parsed);
|
|
410
428
|
if (jobs.length)
|
|
411
429
|
await jobsAdapter.enqueue?.(txDb, jobs);
|
|
@@ -414,7 +432,11 @@ function build(options, o) {
|
|
|
414
432
|
break;
|
|
415
433
|
}
|
|
416
434
|
catch (e) {
|
|
417
|
-
|
|
435
|
+
// a lost race dooms the transaction even when a caller caught it and went on: Postgres then fails the next
|
|
436
|
+
// statement with 25P02, or the caller throws its own error, and the race is still what to retry
|
|
437
|
+
const doomed = attemptTx.current?.doomed ? attemptTx.current.reason : undefined;
|
|
438
|
+
const lostRace = database.retryable?.(e) || (doomed !== undefined && database.retryable?.(doomed));
|
|
439
|
+
if (attempt < transactionAttempts && lostRace) {
|
|
418
440
|
// a random pause, so transactions that just deadlocked don't retry in lockstep and collide again
|
|
419
441
|
await new Promise((r) => setTimeout(r, Math.random() * 20 * attempt));
|
|
420
442
|
continue;
|
package/dist/jobs.d.ts
CHANGED
|
@@ -28,8 +28,8 @@ export interface JobsDeps {
|
|
|
28
28
|
report(error: unknown, info: FailureInfo): void;
|
|
29
29
|
/** Run a function as `scope`, like `registry.as(scope).run`. `eventDepth`: the chain's hops so far (a scheduled call's `depth`). */
|
|
30
30
|
runAs(fn: Fn, input: unknown, scope: object, eventDepth: number, queued: Job[] | undefined): Promise<unknown>;
|
|
31
|
-
/** The ctx a listener's handler gets, as `scope`, in an event chain `eventDepth` deep. */
|
|
32
|
-
|
|
31
|
+
/** The ctx a listener's or cron's handler gets, as `scope`, in an event chain `eventDepth` deep. */
|
|
32
|
+
handlerCtx(scope: object, eventDepth: number, id: string, queued: Job[] | undefined): ActionCtx<any>;
|
|
33
33
|
}
|
|
34
34
|
/**
|
|
35
35
|
* Jobs, for one registry: a listener's share of an event, a cron's run, a scheduled call. Turns a commit's events and
|
|
@@ -39,6 +39,6 @@ export declare function makeJobs(deps: JobsDeps): {
|
|
|
39
39
|
toJobs: (envelopes: Envelope[], calls: CallJob[], parsed: Map<Envelope, unknown>) => Job[];
|
|
40
40
|
deliver: (jobs: Job[]) => Promise<void>;
|
|
41
41
|
jobs: Jobs;
|
|
42
|
-
due: (at: Date) => CronJob[];
|
|
42
|
+
due: (at: Date, only?: string) => CronJob[];
|
|
43
43
|
checkHold: (what: string, seconds: number) => void;
|
|
44
44
|
};
|
package/dist/jobs.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { describeIssues, isDomainError, StalePayload } from "./errors.js";
|
|
1
|
+
import { CaughtNestedFailure, describeIssues, isDomainError, StalePayload } from "./errors.js";
|
|
2
2
|
import { isDue, parseSchedule } from "./schedule.js";
|
|
3
3
|
import { RUNS_NOW } from "./types.js";
|
|
4
4
|
const IN_PROCESS = {
|
|
@@ -34,7 +34,7 @@ export const deliveryOf = (l, e) => ({
|
|
|
34
34
|
* calls into jobs, runs one (with its tries), and is what `registry.jobs` calls.
|
|
35
35
|
*/
|
|
36
36
|
export function makeJobs(deps) {
|
|
37
|
-
const { listeners, crons, functions, idOf, jobsAdapter, database, jobScope, maxEventDepth, now, wrap, report, runAs,
|
|
37
|
+
const { listeners, crons, functions, idOf, jobsAdapter, database, jobScope, maxEventDepth, now, wrap, report, runAs, handlerCtx } = deps;
|
|
38
38
|
const keepFailed = jobsAdapter.fail?.bind(jobsAdapter);
|
|
39
39
|
const enqueue = jobsAdapter.enqueue?.bind(jobsAdapter);
|
|
40
40
|
// ── listeners ────────────────────────────────────────────────────────────
|
|
@@ -137,7 +137,9 @@ export function makeJobs(deps) {
|
|
|
137
137
|
return await work();
|
|
138
138
|
}
|
|
139
139
|
catch (error) {
|
|
140
|
-
|
|
140
|
+
// a caught nested failure is retried as its cause would be: a swallowed `reject` still fails at once
|
|
141
|
+
const decisive = error instanceof CaughtNestedFailure ? error.cause : error;
|
|
142
|
+
const retrying = attempt < attempts && !(decisive instanceof StalePayload) && !(isDomainError(decisive) && decisive.kind !== "conflict");
|
|
141
143
|
if (!retrying)
|
|
142
144
|
return failed(error);
|
|
143
145
|
report(error, { ...info, outcome: "retry" });
|
|
@@ -155,7 +157,10 @@ export function makeJobs(deps) {
|
|
|
155
157
|
if (!c)
|
|
156
158
|
return missing("cron", job.cron);
|
|
157
159
|
return attemptOnce(async () => {
|
|
158
|
-
|
|
160
|
+
// its scope comes from the code each time, never stored, so jobs.scope store and load don't apply
|
|
161
|
+
const { scope, meta, handler } = c.cron;
|
|
162
|
+
const run = { id: c.id, scheduledAt: job.scheduledAt, attempt };
|
|
163
|
+
await wrap({ id: c.id, kind: "cron", meta, input: undefined, scope, depth: 0 }, () => handler({ ...handlerCtx(scope, 0, c.id, queued), cron: run }));
|
|
159
164
|
return "done";
|
|
160
165
|
});
|
|
161
166
|
}
|
|
@@ -190,7 +195,7 @@ export function makeJobs(deps) {
|
|
|
190
195
|
throw new StalePayload(`[logic-sdk] ${envelope.name} payload no longer matches its schema: ${JSON.stringify(describeIssues(r.issues))}`);
|
|
191
196
|
const payload = r.value;
|
|
192
197
|
const ctxEvent = { id: envelope.id, name: envelope.name, payload, occurredAt: envelope.occurredAt, attempt };
|
|
193
|
-
return l.listener.handler({ ...
|
|
198
|
+
return l.listener.handler({ ...handlerCtx(scope, envelope.depth, l.id, queued), event: ctxEvent }, payload); // SAFETY: as in index.ts's invoke: the ctx was built for a listener
|
|
194
199
|
});
|
|
195
200
|
return "done";
|
|
196
201
|
});
|
|
@@ -211,14 +216,17 @@ export function makeJobs(deps) {
|
|
|
211
216
|
await jobsAdapter.deliver(batch, runnerInto(jobs)).catch((e) => reportEach(e, batch));
|
|
212
217
|
}
|
|
213
218
|
}
|
|
214
|
-
/**
|
|
215
|
-
|
|
219
|
+
/**
|
|
220
|
+
* The runs due in `at`'s minute: one job per cron, with an id per minute, so a tick that's delivered twice runs once.
|
|
221
|
+
* With `only`, that cron's run for the minute, due or not (`t.jobs.perform`).
|
|
222
|
+
*/
|
|
223
|
+
function due(at, only) {
|
|
216
224
|
if (Number.isNaN(at.getTime()))
|
|
217
225
|
throw new Error(`[logic-sdk] tick needs a valid date (got ${String(at)}).`);
|
|
218
226
|
const minute = new Date(Math.floor(at.getTime() / 60_000) * 60_000);
|
|
219
227
|
const stamp = minute.toISOString().slice(0, 16).replaceAll(/[-:]/g, "") + "Z"; // 20261123T0900Z: no `:`, which BullMQ rejects
|
|
220
228
|
return scheduled
|
|
221
|
-
.filter((c) => isDue(c.schedule, minute, c.cron.timezone))
|
|
229
|
+
.filter((c) => (only === undefined ? isDue(c.schedule, minute, c.cron.timezone) : c.id === only))
|
|
222
230
|
.map((c) => ({ kind: "cron", id: `${c.id}@${stamp}`, cron: c.id, scheduledAt: minute.toISOString(), attempts: c.cron.attempts ?? 1 }));
|
|
223
231
|
}
|
|
224
232
|
const jobs = {
|
package/dist/pg-boss.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type PgBoss, type Queue, type WorkOptions } from "pg-boss";
|
|
2
2
|
import { type ForListeners, type Jobs, type JobsAdapter, type Registry } from "./index.ts";
|
|
3
|
-
/** One queue's tuning: `meta.pgBoss`, and `work()`'s `calls
|
|
3
|
+
/** One queue's tuning: a listener's or cron's `meta.pgBoss`, and `work()`'s `calls`. */
|
|
4
4
|
export interface PgBossTuning {
|
|
5
5
|
/** The listener's queue (`expireInSeconds`, `retryDelay`, `deadLetter`…), applied by `work()`. `partition` only when it's created. */
|
|
6
6
|
queue?: Omit<Queue, "name" | "retryLimit" | "retryBackoff" | "policy">;
|
|
@@ -8,7 +8,7 @@ export interface PgBossTuning {
|
|
|
8
8
|
worker?: Omit<WorkOptions, "includeMetadata" | "perJobResults" | "transactional" | "transactionTimeoutSeconds">;
|
|
9
9
|
}
|
|
10
10
|
/**
|
|
11
|
-
* What this adapter reads from a listener's `meta` (not a function's): `init<{ meta: PgBossMeta & AppMeta }>()`, then
|
|
11
|
+
* What this adapter reads from a listener's or cron's `meta` (not a function's): `init<{ meta: PgBossMeta & AppMeta }>()`, then
|
|
12
12
|
* `meta: { pgBoss: { queue: { expireInSeconds: 120 }, worker: { localConcurrency: 5 } } }`. Tuning only: retries are the
|
|
13
13
|
* listener's `attempts`, and the other adapters ignore it.
|
|
14
14
|
*/
|
|
@@ -35,14 +35,12 @@ export declare function pgBoss(boss: PgBoss): JobsAdapter;
|
|
|
35
35
|
export interface PgBossWorkOptions {
|
|
36
36
|
/** The shared queue of scheduled calls, tuned like a listener's `meta.pgBoss`: `{ worker: { localConcurrency: 10 } }`. */
|
|
37
37
|
calls?: PgBossTuning;
|
|
38
|
-
/** Every cron's queue, tuned the same way (crons have no `meta`): `{ queue: { expireInSeconds: 3600 } }` for a long one. */
|
|
39
|
-
crons?: PgBossTuning;
|
|
40
38
|
/** Where a failed cron tick goes, and a queue left with jobs but no listener. Default `console.error`. */
|
|
41
39
|
onError?: (error: unknown) => void;
|
|
42
40
|
}
|
|
43
41
|
/**
|
|
44
42
|
* Your worker process: a queue and its workers for every listener and cron, one for scheduled calls, and the cron tick
|
|
45
|
-
* every minute. `boss.stop()` stops all of it. Applies each listener's `meta.pgBoss`.
|
|
43
|
+
* every minute. `boss.stop()` stops all of it. Applies each listener's and cron's `meta.pgBoss`.
|
|
46
44
|
*
|
|
47
45
|
* ```ts
|
|
48
46
|
* await boss.start();
|
package/dist/pg-boss.js
CHANGED
|
@@ -100,12 +100,14 @@ export function pgBoss(boss) {
|
|
|
100
100
|
holds: true, // `startAfter`, however far ahead
|
|
101
101
|
replaces: true,
|
|
102
102
|
/** Needs `database`: jobs are inserted in the mutation's transaction, and `retry` opens its own through it. */
|
|
103
|
-
check({ listeners, database: given }) {
|
|
103
|
+
check({ listeners, crons, database: given }) {
|
|
104
104
|
if (!given)
|
|
105
105
|
throw new Error("[logic-sdk] pgBoss(boss) needs `database`: jobs are inserted in your mutation's transaction.");
|
|
106
106
|
database = given;
|
|
107
107
|
for (const l of listeners)
|
|
108
108
|
queueOptions.set(queueName(l.id), tuningOf(l.listener.meta)?.queue);
|
|
109
|
+
for (const c of crons)
|
|
110
|
+
queueOptions.set(queueName(c.id), tuningOf(c.cron.meta)?.queue);
|
|
109
111
|
},
|
|
110
112
|
/** Inside the mutation's transaction: one insert per queue. pg-boss skips a row whose id it already has. */
|
|
111
113
|
async enqueue(tx, jobs) {
|
|
@@ -158,7 +160,7 @@ export function pgBoss(boss) {
|
|
|
158
160
|
}
|
|
159
161
|
/**
|
|
160
162
|
* Your worker process: a queue and its workers for every listener and cron, one for scheduled calls, and the cron tick
|
|
161
|
-
* every minute. `boss.stop()` stops all of it. Applies each listener's `meta.pgBoss`.
|
|
163
|
+
* every minute. `boss.stop()` stops all of it. Applies each listener's and cron's `meta.pgBoss`.
|
|
162
164
|
*
|
|
163
165
|
* ```ts
|
|
164
166
|
* await boss.start();
|
|
@@ -171,7 +173,7 @@ export async function work(registry, boss, options = {}) {
|
|
|
171
173
|
const onError = options.onError ?? ((error) => console.error("[logic-sdk]", error));
|
|
172
174
|
const queues = [
|
|
173
175
|
...listeners.map((l) => ({ name: queueName(l.id), tuning: tuningOf(l.listener.meta) })),
|
|
174
|
-
...crons.map((c) => ({ name: queueName(c.id), tuning:
|
|
176
|
+
...crons.map((c) => ({ name: queueName(c.id), tuning: tuningOf(c.cron.meta) })),
|
|
175
177
|
{ name: CALLS_QUEUE, tuning: options.calls },
|
|
176
178
|
];
|
|
177
179
|
/** One job's try. `failed` is over (out of tries, or retrying can't help), so pg-boss mustn't retry it. */
|
package/dist/testing.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
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";
|
|
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
2
|
export interface TestOptions<Cf = unknown> {
|
|
3
3
|
/** Replace services (e.g. `{ mailer: memoryMailer() }`). */
|
|
4
4
|
services?: object;
|
|
@@ -32,6 +32,14 @@ export interface TestJobs<S> {
|
|
|
32
32
|
scope: S;
|
|
33
33
|
attempt?: number;
|
|
34
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>;
|
|
35
43
|
/** Run the crons due in `at`'s minute (default: the test's now), here and now. Resolves their ids; throws a failure. */
|
|
36
44
|
tick(at?: Date | string): Promise<string[]>;
|
|
37
45
|
}
|
package/dist/testing.js
CHANGED
|
@@ -194,8 +194,21 @@ export function createTestRegistry(registry, options = {}) {
|
|
|
194
194
|
travelled = undefined;
|
|
195
195
|
}
|
|
196
196
|
},
|
|
197
|
-
perform(
|
|
197
|
+
perform(target, ...rest) {
|
|
198
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;
|
|
199
212
|
const registered = state.registry.definitions.listeners.find((l) => l.listener === listener);
|
|
200
213
|
if (!registered)
|
|
201
214
|
throw new Error("[logic-sdk] t.jobs.perform got a listener that isn't registered: export it from its module.");
|
package/dist/types.d.ts
CHANGED
|
@@ -218,18 +218,26 @@ export interface CallJob {
|
|
|
218
218
|
* run, or a call `ctx.schedule` asked for.
|
|
219
219
|
*/
|
|
220
220
|
export type Job = Delivery | CronJob | CallJob;
|
|
221
|
-
/**
|
|
221
|
+
/** Work on a schedule, as `scope`: a handler, like a listener's, run when the clock says. Export it from a module. */
|
|
222
222
|
export interface Cron<C extends Config = any> extends FromInit<C> {
|
|
223
223
|
readonly [BRAND]: "cron";
|
|
224
224
|
readonly kind: "cron";
|
|
225
225
|
readonly id?: string;
|
|
226
226
|
readonly schedule: string;
|
|
227
227
|
readonly timezone?: string;
|
|
228
|
-
/** The function it runs, read when the registry is built, like a listener's `event`. */
|
|
229
|
-
readonly run: () => Fn;
|
|
230
|
-
readonly input?: unknown;
|
|
231
228
|
readonly scope: object;
|
|
232
229
|
readonly attempts?: number;
|
|
230
|
+
readonly meta?: Readonly<Record<string, unknown>>;
|
|
231
|
+
readonly handler: (ctx: never) => Promise<unknown>;
|
|
232
|
+
}
|
|
233
|
+
/** The run a cron's handler is doing. No scope here: `ctx.scope` is the one it runs as. */
|
|
234
|
+
export interface CronRun {
|
|
235
|
+
/** The cron's id: `tasks.wakeDue`. */
|
|
236
|
+
id: string;
|
|
237
|
+
/** The minute this run is for (ISO), even when it runs late or again: which day a digest covers. */
|
|
238
|
+
scheduledAt: string;
|
|
239
|
+
/** 1 on the first try. */
|
|
240
|
+
attempt: number;
|
|
233
241
|
}
|
|
234
242
|
/**
|
|
235
243
|
* What running a job resolved to. `failed`: out of attempts (code this process doesn't have uses them too), a rule said
|
|
@@ -266,10 +274,11 @@ export interface Listener<O = unknown, C extends Config = any> extends FromInit<
|
|
|
266
274
|
/** What a single call may change: who it runs as (part of the scope) and when to give up. Nothing else. */
|
|
267
275
|
export interface RunOptions<S = object> {
|
|
268
276
|
/**
|
|
269
|
-
*
|
|
270
|
-
*
|
|
277
|
+
* The whole scope for this call and everything it runs, never merged: `{ scope: { ...ctx.scope, locale: "es" } }`
|
|
278
|
+
* to render in another language, `{ scope: { kind: "system", job: "reports.weekly" } }` to act as someone else on purpose. The
|
|
279
|
+
* callee's policy sees it. Whole, so it's one of your scope's variants: a patch could build one that isn't.
|
|
271
280
|
*/
|
|
272
|
-
scope?:
|
|
281
|
+
scope?: S;
|
|
273
282
|
/**
|
|
274
283
|
* Checked before this call starts. Inside, actions get it as `ctx.signal` to pass on (`fetch(url, { signal })`).
|
|
275
284
|
* Never checked between your steps, so a caller who gives up can't leave a workflow half done.
|
|
@@ -348,6 +357,10 @@ export interface ActionCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C,
|
|
|
348
357
|
export interface ListenerCtx<C extends Config, O = unknown> extends ActionCtx<C> {
|
|
349
358
|
event: ListenerEvent<O>;
|
|
350
359
|
}
|
|
360
|
+
/** A cron's handler's ctx: an action's, as the cron's own scope, plus the run. */
|
|
361
|
+
export interface CronCtx<C extends Config, S = ScopeOf<C>> extends ActionCtx<C, S> {
|
|
362
|
+
cron: CronRun;
|
|
363
|
+
}
|
|
351
364
|
/**
|
|
352
365
|
* Who may call a function at all: signed in, admin, staff. Sync, reads only the scope, returns exactly `true` to allow.
|
|
353
366
|
* Write it as a type guard (`(s): s is Admin => ...`) to narrow `ctx.scope` in `handler`.
|
|
@@ -457,6 +470,7 @@ export interface JobsAdapter {
|
|
|
457
470
|
/** At `createRegistry`: refuse a setup this adapter can't honour (a database it doesn't share). */
|
|
458
471
|
check?(setup: {
|
|
459
472
|
listeners: readonly RegisteredListener[];
|
|
473
|
+
crons: readonly RegisteredCron[];
|
|
460
474
|
database: DatabaseAdapter<unknown, unknown> | undefined;
|
|
461
475
|
}): void;
|
|
462
476
|
/** Inside the transaction, before commit. In-process: nothing. `databaseQueue` and `outbox`: insert one row per job with `tx`. */
|
|
@@ -529,8 +543,8 @@ export type JobsOptions<S = object, T = any> = {
|
|
|
529
543
|
});
|
|
530
544
|
export interface Call<M = unknown> {
|
|
531
545
|
id: string;
|
|
532
|
-
kind: Kind | "listener";
|
|
533
|
-
/** The function's or
|
|
546
|
+
kind: Kind | "listener" | "cron";
|
|
547
|
+
/** The function's, listener's or cron's `meta` (undefined when it has none). */
|
|
534
548
|
meta: M | undefined;
|
|
535
549
|
/** Raw input as received (before validation). */
|
|
536
550
|
input: unknown;
|
|
@@ -597,7 +611,6 @@ export interface RegisteredListener extends Registered {
|
|
|
597
611
|
}
|
|
598
612
|
export interface RegisteredCron extends Registered {
|
|
599
613
|
cron: Cron;
|
|
600
|
-
run: Fn;
|
|
601
614
|
}
|
|
602
615
|
/** `registry.jobs`: what you call from a queue consumer, a cron, or a script. */
|
|
603
616
|
export interface Jobs {
|
|
@@ -649,8 +662,8 @@ export interface Registry<S extends object = object, Mods extends Record<string,
|
|
|
649
662
|
derive(more: Overrides): Registry<S, Mods, Cf>;
|
|
650
663
|
/** An event as `emit` would make it, for `t.jobs.perform`. */
|
|
651
664
|
envelope(event: EventDef, payload: unknown, scope: S): Envelope;
|
|
652
|
-
/** The cron runs due in a minute, for `t.jobs.tick
|
|
653
|
-
due(at: Date): CronJob[];
|
|
665
|
+
/** The cron runs due in a minute, for `t.jobs.tick`; with `only`, that cron's run, due or not (`t.jobs.perform`). */
|
|
666
|
+
due(at: Date, only?: string): CronJob[];
|
|
654
667
|
};
|
|
655
668
|
}
|
|
656
669
|
/** The registry's internals, for `logic-sdk/testing`. */
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "logic-sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.1",
|
|
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.
|
|
116
|
+
"@logic-sdk/cli": ">=0.6.5 <0.7.0"
|
|
117
117
|
},
|
|
118
118
|
"peerDependenciesMeta": {
|
|
119
119
|
"@orpc/server": {
|
|
@@ -64,20 +64,20 @@ export const cancel = mutation({
|
|
|
64
64
|
1. **Pick the kind by what it touches.** Only reads: `query`. Writes to our database: `mutation`. Talks to the network: `action`. Reacts to another module: `listener`.
|
|
65
65
|
2. **Never put side effects in a mutation or query.** No email, HTTP or payments. They don't have `services` on purpose. Emit an event and react in a listener, or write an action that runs the mutation.
|
|
66
66
|
3. **Call other modules only with `run(otherModule.fn, input)`.** Import them as `import * as availability from "../availability"`. Never import their `data.ts` or `schema.ts`, from a module or from routes and pages.
|
|
67
|
-
4. **Within a module, use helpers.** Shared logic is a plain function in `data.ts` taking `ctx`. `ctx.run` your own module's function only when you want its `authorize`, validation and tracing. When an action must write, define the mutation in the action's own file without `export` and `ctx.run` it: nothing outside the file can reach it, so nothing can skip the action's checks. When two files need the same one, put it in `data.ts`, never in `mutations.ts`: exporting it from there for the other file makes `export * from "./mutations"` publish it. A private function can't be scheduled,
|
|
67
|
+
4. **Within a module, use helpers.** Shared logic is a plain function in `data.ts` taking `ctx`. `ctx.run` your own module's function only when you want its `authorize`, validation and tracing. When an action must write, define the mutation in the action's own file without `export` and `ctx.run` it: nothing outside the file can reach it, so nothing can skip the action's checks. When two files need the same one, put it in `data.ts`, never in `mutations.ts`: exporting it from there for the other file makes `export * from "./mutations"` publish it. A private function can't be scheduled, published or run from a test: test it through the action (or the listener or cron whose handler runs it).
|
|
68
68
|
5. **Always filter by `ctx.scope.accountId`** in `data.ts` helpers, writes included. Loading helpers throw `ctx.errors.notFound()`. Scope is who and where (actor, account, locale); input is what.
|
|
69
69
|
6. **Authorize every function a user, client or AI tool may call.** `authorize: member` (a policy from `policies.ts`) says who may call it: sync, reads only scope, runs on every call including nested ones. Publish a function by listing it in `src/rpc.ts` (`toORPCProcedure(fn)`) or an agent's tools (`toAITool(caller, fn)`); both refuse one without `authorize`. A hand-written route or Server Action can `caller.run` anything, nothing stops it: only call functions that have `authorize` from them. Give published functions an `output` so nothing unintended leaves.
|
|
70
70
|
7. **Record rules are `can*` predicates.** Load through a scoped helper, then `if (!canX(ctx.scope.actor, record)) throw ctx.errors.deny();`. `can*` is sync, its result is always used, and the same predicate feeds UI flags in list queries: `can: { cancel: canCancel(actor, b) }`. A rule that must hold at commit goes in the write's `WHERE` or a `FOR UPDATE` re-select.
|
|
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.
|
|
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,
|
|
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.
|
|
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
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.
|
|
80
|
-
17. **Scheduled work is a `cron`,** exported from the module
|
|
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
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 })`.
|
|
82
82
|
|
|
83
83
|
## Tests
|
package/src/errors.ts
CHANGED
|
@@ -56,13 +56,22 @@ export const describeIssues = (issues: readonly StandardSchemaV1.Issue[]) =>
|
|
|
56
56
|
/** A payload that stopped matching its event's schema (a deploy changed it while it waited): delivering again won't help. */
|
|
57
57
|
export class StalePayload extends Error {}
|
|
58
58
|
|
|
59
|
+
/**
|
|
60
|
+
* A mutation's commit after a nested mutation failed and was caught: the transaction they share is doomed. Its
|
|
61
|
+
* `cause` is that failure, and retries (a transaction's, a job's) treat it as the cause would be treated.
|
|
62
|
+
*/
|
|
63
|
+
export class CaughtNestedFailure extends Error {}
|
|
64
|
+
|
|
59
65
|
/**
|
|
60
66
|
* Throw where there's no valid session, outside your functions (a route, a middleware): `toResponse` makes it a 401.
|
|
61
67
|
* Inside a function, a policy answers instead (a scope with no actor, then `forbidden`).
|
|
62
68
|
*/
|
|
63
69
|
export const unauthenticated = (code = "unauthenticated", details?: unknown) => new DomainError("unauthenticated", code, details);
|
|
64
70
|
|
|
65
|
-
/**
|
|
71
|
+
/**
|
|
72
|
+
* An error and the ones it wraps (`cause`), six deep at most: a driver's error usually arrives wrapped by the ORM,
|
|
73
|
+
* and a caught nested failure wraps that once more.
|
|
74
|
+
*/
|
|
66
75
|
export function* causes(error: unknown): Generator<object> {
|
|
67
|
-
for (let e = error, i = 0; typeof e === "object" && e !== null && i <
|
|
76
|
+
for (let e = error, i = 0; typeof e === "object" && e !== null && i < 6; e = "cause" in e ? e.cause : undefined, i++) yield e;
|
|
68
77
|
}
|
package/src/index.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { describeIssues, DomainError, errorsFor, forbiddenOf, moduleOf, PRIVATE } from "./errors.ts";
|
|
1
|
+
import { CaughtNestedFailure, describeIssues, DomainError, errorsFor, forbiddenOf, moduleOf, PRIVATE } from "./errors.ts";
|
|
2
2
|
import { inProcess, makeJobs, replaceKeyOf, runsNow } from "./jobs.ts";
|
|
3
3
|
import { assertTimeZone, parseSchedule } from "./schedule.ts";
|
|
4
4
|
import { BRAND, INTERNAL } from "./types.ts";
|
|
@@ -11,13 +11,13 @@ import type {
|
|
|
11
11
|
ConfigOf,
|
|
12
12
|
Constructor,
|
|
13
13
|
Cron,
|
|
14
|
+
CronCtx,
|
|
14
15
|
DatabaseAdapter,
|
|
15
16
|
DbOf,
|
|
16
17
|
Envelope,
|
|
17
18
|
EventDef,
|
|
18
19
|
FailureInfo,
|
|
19
20
|
Fn,
|
|
20
|
-
FnIn,
|
|
21
21
|
Frozen,
|
|
22
22
|
In,
|
|
23
23
|
Job,
|
|
@@ -51,6 +51,8 @@ export type {
|
|
|
51
51
|
Config,
|
|
52
52
|
Constructor,
|
|
53
53
|
Cron,
|
|
54
|
+
CronCtx,
|
|
55
|
+
CronRun,
|
|
54
56
|
CronJob,
|
|
55
57
|
DatabaseAdapter,
|
|
56
58
|
DeepPartial,
|
|
@@ -157,16 +159,18 @@ export function init<C extends Config & OnlyKnownKeys<C>>() {
|
|
|
157
159
|
}): EventDef<In<S>, Out<S>> =>
|
|
158
160
|
Object.freeze({ [BRAND]: "event" as const, kind: "event" as const, ...def }),
|
|
159
161
|
/**
|
|
160
|
-
*
|
|
161
|
-
* `registry.jobs.tick()` every minute (or from your platform's cron trigger)
|
|
162
|
-
*
|
|
162
|
+
* Work on a schedule, as `scope` (a cron has no caller): a handler, like a listener's, run when the clock says. Export
|
|
163
|
+
* it from a module and call `registry.jobs.tick()` every minute (or from your platform's cron trigger). Must be
|
|
164
|
+
* idempotent: a retry runs the whole handler again.
|
|
165
|
+
* `cron({ schedule: "0 9 * * MON", scope: { kind: "system", job: "reports.weekly" }, async handler(ctx) { await ctx.run(send) } })`.
|
|
163
166
|
*/
|
|
164
|
-
cron: <
|
|
165
|
-
const { id, schedule, timezone,
|
|
167
|
+
cron: <const Sc extends ScopeOf<C>>(def: CronDef<C, Sc>): Cron<C> => {
|
|
168
|
+
const { id, schedule, timezone, scope, attempts, meta, handler } = def;
|
|
166
169
|
parseSchedule(schedule);
|
|
167
170
|
if (timezone !== undefined) assertTimeZone(timezone);
|
|
168
171
|
checkAttempts("cron", attempts);
|
|
169
|
-
|
|
172
|
+
// meta is checked against ListenerMetaOf<C> above and stored loose, like a listener's, for wrap and adapters
|
|
173
|
+
return Object.freeze({ [BRAND]: "cron" as const, kind: "cron" as const, id, schedule, timezone, scope, attempts, meta: meta as Cron["meta"], handler });
|
|
170
174
|
},
|
|
171
175
|
/**
|
|
172
176
|
* React to an event after commit, like an action. Must be idempotent.
|
|
@@ -207,24 +211,25 @@ export function init<C extends Config & OnlyKnownKeys<C>>() {
|
|
|
207
211
|
};
|
|
208
212
|
}
|
|
209
213
|
|
|
210
|
-
/** `cron({...})`: `
|
|
211
|
-
type CronDef<
|
|
212
|
-
/**
|
|
214
|
+
/** `cron({...})`: its handler's `ctx.scope` is the scope it declares, so a policy-free read of it is typed. */
|
|
215
|
+
type CronDef<C extends Config, Sc> = {
|
|
216
|
+
/**
|
|
217
|
+
* Stable id, local to its module, like every definer's. Defaults to the export name. Jobs and pg-boss's queue store it,
|
|
218
|
+
* so set it before you rename the export.
|
|
219
|
+
*/
|
|
213
220
|
id?: string;
|
|
214
|
-
/** Five fields: minute hour day-of-month month day-of-week. `"*\/15 * * * *"`, `"0 9 * *
|
|
221
|
+
/** Five fields: minute hour day-of-month month day-of-week. `"*\/15 * * * *"`, `"0 9 * * MON"`. */
|
|
215
222
|
schedule: string;
|
|
216
223
|
/** IANA name, like `"Europe/Madrid"`. Default UTC. Matched on the wall clock, like Laravel: mind DST at 1 to 3 am. */
|
|
217
224
|
timezone?: string;
|
|
218
|
-
/**
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
*/
|
|
222
|
-
run: () => F;
|
|
223
|
-
/** Who it runs as: a cron has no caller. */
|
|
224
|
-
scope: S;
|
|
225
|
-
/** Tries in total, like a listener's. Default 1. */
|
|
225
|
+
/** Who it runs as: a cron has no caller. Every function the handler runs checks its policy against it. */
|
|
226
|
+
scope: Sc;
|
|
227
|
+
/** Tries in total, like a listener's. Default 1: a retry runs the whole handler again. */
|
|
226
228
|
attempts?: number;
|
|
227
|
-
|
|
229
|
+
meta?: ListenerMetaOf<C>;
|
|
230
|
+
/** The work, like a listener's handler: an action's ctx, plus `ctx.cron` (`scheduledAt`, `attempt`). */
|
|
231
|
+
handler: (ctx: CronCtx<C, Sc>) => Promise<unknown>;
|
|
232
|
+
};
|
|
228
233
|
|
|
229
234
|
/** How deep `ctx.run` calls may nest. Past it, a function is running itself without end. */
|
|
230
235
|
const MAX_RUN_DEPTH = 64;
|
|
@@ -242,6 +247,10 @@ interface TxState {
|
|
|
242
247
|
db: unknown;
|
|
243
248
|
doomed: boolean;
|
|
244
249
|
reason: unknown;
|
|
250
|
+
/** Where the transaction's own mutation sits in the trail: what the error at commit prints starts there. */
|
|
251
|
+
from: number;
|
|
252
|
+
/** The calls down to the nested mutation whose failure doomed it, from the transaction's own mutation. */
|
|
253
|
+
doomedBy: readonly string[] | undefined;
|
|
245
254
|
events: Envelope[];
|
|
246
255
|
/** Each event's payload as its schema parsed it, for listeners' `when`: the value their handler gets. */
|
|
247
256
|
parsed: Map<Envelope, unknown>;
|
|
@@ -264,6 +273,22 @@ interface Frame {
|
|
|
264
273
|
tx?: TxState;
|
|
265
274
|
}
|
|
266
275
|
|
|
276
|
+
/** What a mutation throws at commit when a nested mutation failed and was caught: the transaction they share is doomed. */
|
|
277
|
+
function caughtNestedFailure(id: string, tx: TxState): CaughtNestedFailure {
|
|
278
|
+
let why: string;
|
|
279
|
+
try {
|
|
280
|
+
why = tx.reason instanceof Error ? tx.reason.message : String(tx.reason);
|
|
281
|
+
} catch {
|
|
282
|
+
why = Object.prototype.toString.call(tx.reason); // an object String() can't print
|
|
283
|
+
}
|
|
284
|
+
return new CaughtNestedFailure(
|
|
285
|
+
`[logic-sdk] ${tx.doomedBy?.at(-1)} failed inside ${id}'s transaction (${tx.doomedBy?.join(" → ")}) and was ` +
|
|
286
|
+
`caught, so ${id} can't commit: a mutation shares its transaction with the mutations it runs. To let each one ` +
|
|
287
|
+
`commit or fail on its own, run them from an action. The failure (this error's cause): ${why}`,
|
|
288
|
+
{ cause: tx.reason },
|
|
289
|
+
);
|
|
290
|
+
}
|
|
291
|
+
|
|
267
292
|
/** Create the registry once at startup. Prefer the `createRegistry` returned by `init()`: it's typed with your config. */
|
|
268
293
|
export function createRegistry<S extends object = object, const Mods extends Record<string, object> = Record<string, object>>(
|
|
269
294
|
options: RegistryOptions<Mods>,
|
|
@@ -351,7 +376,7 @@ export function describeModules(modules: Record<string, object>) {
|
|
|
351
376
|
ids.set(value, id);
|
|
352
377
|
if (value.kind === "event") events.push({ id, module, name, event: value });
|
|
353
378
|
else if (value.kind === "listener") listeners.push({ id, module, name, listener: value, event: value.event() });
|
|
354
|
-
else if (value.kind === "cron") crons.push({ id, module, name, cron: value
|
|
379
|
+
else if (value.kind === "cron") crons.push({ id, module, name, cron: value });
|
|
355
380
|
else functions.push({ id, module, name, kind: value.kind, fn: value });
|
|
356
381
|
}
|
|
357
382
|
}
|
|
@@ -401,7 +426,7 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
|
|
|
401
426
|
for (const l of listeners)
|
|
402
427
|
if (!ids.has(l.event))
|
|
403
428
|
throw new Error(`[logic-sdk] Listener ${l.id} listens to an event that isn't registered in any module.`);
|
|
404
|
-
jobsAdapter.check?.({ listeners, database });
|
|
429
|
+
jobsAdapter.check?.({ listeners, crons, database });
|
|
405
430
|
|
|
406
431
|
const idOf = (x: object) => {
|
|
407
432
|
const id = ids.get(x);
|
|
@@ -434,17 +459,11 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
|
|
|
434
459
|
tx.pending.push(check);
|
|
435
460
|
}
|
|
436
461
|
|
|
437
|
-
for (const c of crons) {
|
|
438
|
-
if (!ids.has(c.run))
|
|
439
|
-
throw new Error(`[logic-sdk] Cron ${c.id} runs a function that isn't registered. Export it from its module's index.ts.`);
|
|
440
|
-
assertPlain(c.cron.input, `${c.id} input`, "Cron runs travel through queues as JSON: send an ISO string and let the schema turn it into a Date");
|
|
441
|
-
}
|
|
442
|
-
|
|
443
462
|
// ── ctx ──────────────────────────────────────────────────────────────────
|
|
444
|
-
/** The frame for a call from here: its scope
|
|
463
|
+
/** The frame for a call from here: its scope and signal. `invoke` adds the call to the trail. */
|
|
445
464
|
const enter = (frame: Frame, options: RunOptions | undefined): Frame => ({
|
|
446
465
|
...frame,
|
|
447
|
-
scope: options?.scope
|
|
466
|
+
scope: options?.scope ?? frame.scope,
|
|
448
467
|
signal: options?.signal ?? frame.signal,
|
|
449
468
|
abortOn: options?.signal,
|
|
450
469
|
});
|
|
@@ -548,7 +567,7 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
|
|
|
548
567
|
wrap,
|
|
549
568
|
report,
|
|
550
569
|
runAs: (fn, input, scope, eventDepth, queued) => invoke(fn, input, enter({ scope, trail: [], eventDepth, queued }, undefined), ["query", "mutation", "action"]),
|
|
551
|
-
|
|
570
|
+
handlerCtx: (scope, eventDepth, id, queued) => actionCtx({ scope, trail: [id], eventDepth, queued }, id),
|
|
552
571
|
});
|
|
553
572
|
|
|
554
573
|
// ── invoke ───────────────────────────────────────────────────────────────
|
|
@@ -600,6 +619,7 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
|
|
|
600
619
|
if (!tx.doomed) {
|
|
601
620
|
tx.doomed = true;
|
|
602
621
|
tx.reason = e;
|
|
622
|
+
tx.doomedBy = frame.trail.slice(tx.from);
|
|
603
623
|
}
|
|
604
624
|
throw e;
|
|
605
625
|
}
|
|
@@ -612,20 +632,31 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
|
|
|
612
632
|
const input = await prepare();
|
|
613
633
|
let committed: { out: unknown; events: Envelope[]; jobs: Job[] };
|
|
614
634
|
for (let attempt = 1; ; attempt++) {
|
|
635
|
+
const attemptTx: { current?: TxState } = {};
|
|
615
636
|
try {
|
|
616
637
|
committed = await database.transaction(async (txDb) => {
|
|
617
638
|
// fresh per attempt, so a retry never reuses events from a failed attempt
|
|
618
|
-
const tx: TxState = {
|
|
639
|
+
const tx: TxState = {
|
|
640
|
+
db: txDb, doomed: false, reason: undefined, from: frame.trail.length - 1, doomedBy: undefined,
|
|
641
|
+
events: [], parsed: new Map(), calls: [], pending: [],
|
|
642
|
+
};
|
|
643
|
+
attemptTx.current = tx;
|
|
619
644
|
const out = await execute(input, mutationCtx({ ...frame, tx }, tx, id));
|
|
620
645
|
await Promise.all(tx.pending);
|
|
621
|
-
|
|
646
|
+
// a nested failure was caught: a bug, so its own error, with the failure as its cause (Ecto's aborted
|
|
647
|
+
// transaction). Retries still see a deadlock: `retryable` walks causes
|
|
648
|
+
if (tx.doomed) throw caughtNestedFailure(id, tx);
|
|
622
649
|
const jobs = toJobs(tx.events, tx.calls, tx.parsed);
|
|
623
650
|
if (jobs.length) await jobsAdapter.enqueue?.(txDb, jobs);
|
|
624
651
|
return { out, events: tx.events, jobs };
|
|
625
652
|
});
|
|
626
653
|
break;
|
|
627
654
|
} catch (e) {
|
|
628
|
-
|
|
655
|
+
// a lost race dooms the transaction even when a caller caught it and went on: Postgres then fails the next
|
|
656
|
+
// statement with 25P02, or the caller throws its own error, and the race is still what to retry
|
|
657
|
+
const doomed = attemptTx.current?.doomed ? attemptTx.current.reason : undefined;
|
|
658
|
+
const lostRace = database.retryable?.(e) || (doomed !== undefined && database.retryable?.(doomed));
|
|
659
|
+
if (attempt < transactionAttempts && lostRace) {
|
|
629
660
|
// a random pause, so transactions that just deadlocked don't retry in lockstep and collide again
|
|
630
661
|
await new Promise((r) => setTimeout(r, Math.random() * 20 * attempt));
|
|
631
662
|
continue;
|
package/src/jobs.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { describeIssues, isDomainError, StalePayload } from "./errors.ts";
|
|
1
|
+
import { CaughtNestedFailure, describeIssues, isDomainError, StalePayload } from "./errors.ts";
|
|
2
2
|
import { isDue, parseSchedule } from "./schedule.ts";
|
|
3
3
|
import type {
|
|
4
4
|
ActionCtx,
|
|
@@ -16,6 +16,7 @@ import type {
|
|
|
16
16
|
JobsAdapter,
|
|
17
17
|
JobScope,
|
|
18
18
|
Jobs,
|
|
19
|
+
CronRun,
|
|
19
20
|
ListenerEvent,
|
|
20
21
|
RegisteredCron,
|
|
21
22
|
RegisteredFn,
|
|
@@ -70,8 +71,8 @@ export interface JobsDeps {
|
|
|
70
71
|
report(error: unknown, info: FailureInfo): void;
|
|
71
72
|
/** Run a function as `scope`, like `registry.as(scope).run`. `eventDepth`: the chain's hops so far (a scheduled call's `depth`). */
|
|
72
73
|
runAs(fn: Fn, input: unknown, scope: object, eventDepth: number, queued: Job[] | undefined): Promise<unknown>;
|
|
73
|
-
/** The ctx a listener's handler gets, as `scope`, in an event chain `eventDepth` deep. */
|
|
74
|
-
|
|
74
|
+
/** The ctx a listener's or cron's handler gets, as `scope`, in an event chain `eventDepth` deep. */
|
|
75
|
+
handlerCtx(scope: object, eventDepth: number, id: string, queued: Job[] | undefined): ActionCtx<any>;
|
|
75
76
|
}
|
|
76
77
|
|
|
77
78
|
/**
|
|
@@ -79,7 +80,7 @@ export interface JobsDeps {
|
|
|
79
80
|
* calls into jobs, runs one (with its tries), and is what `registry.jobs` calls.
|
|
80
81
|
*/
|
|
81
82
|
export function makeJobs(deps: JobsDeps) {
|
|
82
|
-
const { listeners, crons, functions, idOf, jobsAdapter, database, jobScope, maxEventDepth, now, wrap, report, runAs,
|
|
83
|
+
const { listeners, crons, functions, idOf, jobsAdapter, database, jobScope, maxEventDepth, now, wrap, report, runAs, handlerCtx } = deps;
|
|
83
84
|
const keepFailed = jobsAdapter.fail?.bind(jobsAdapter);
|
|
84
85
|
const enqueue = jobsAdapter.enqueue?.bind(jobsAdapter);
|
|
85
86
|
|
|
@@ -185,7 +186,9 @@ export function makeJobs(deps: JobsDeps) {
|
|
|
185
186
|
try {
|
|
186
187
|
return await work();
|
|
187
188
|
} catch (error) {
|
|
188
|
-
|
|
189
|
+
// a caught nested failure is retried as its cause would be: a swallowed `reject` still fails at once
|
|
190
|
+
const decisive = error instanceof CaughtNestedFailure ? error.cause : error;
|
|
191
|
+
const retrying = attempt < attempts && !(decisive instanceof StalePayload) && !(isDomainError(decisive) && decisive.kind !== "conflict");
|
|
189
192
|
if (!retrying) return failed(error);
|
|
190
193
|
report(error, { ...info, outcome: "retry" });
|
|
191
194
|
throw error;
|
|
@@ -204,7 +207,12 @@ export function makeJobs(deps: JobsDeps) {
|
|
|
204
207
|
const c = cronById.get(job.cron);
|
|
205
208
|
if (!c) return missing("cron", job.cron);
|
|
206
209
|
return attemptOnce(async () => {
|
|
207
|
-
|
|
210
|
+
// its scope comes from the code each time, never stored, so jobs.scope store and load don't apply
|
|
211
|
+
const { scope, meta, handler } = c.cron;
|
|
212
|
+
const run: CronRun = { id: c.id, scheduledAt: job.scheduledAt, attempt };
|
|
213
|
+
await wrap({ id: c.id, kind: "cron", meta, input: undefined, scope, depth: 0 }, () =>
|
|
214
|
+
handler({ ...handlerCtx(scope, 0, c.id, queued), cron: run } as never), // SAFETY: as for listeners: the ctx was built for a cron
|
|
215
|
+
);
|
|
208
216
|
return "done";
|
|
209
217
|
});
|
|
210
218
|
}
|
|
@@ -233,7 +241,7 @@ export function makeJobs(deps: JobsDeps) {
|
|
|
233
241
|
if (r.issues) throw new StalePayload(`[logic-sdk] ${envelope.name} payload no longer matches its schema: ${JSON.stringify(describeIssues(r.issues))}`);
|
|
234
242
|
const payload = r.value;
|
|
235
243
|
const ctxEvent: ListenerEvent = { id: envelope.id, name: envelope.name, payload, occurredAt: envelope.occurredAt, attempt };
|
|
236
|
-
return l.listener.handler({ ...
|
|
244
|
+
return l.listener.handler({ ...handlerCtx(scope, envelope.depth, l.id, queued), event: ctxEvent } as never, payload); // SAFETY: as in index.ts's invoke: the ctx was built for a listener
|
|
237
245
|
});
|
|
238
246
|
return "done";
|
|
239
247
|
});
|
|
@@ -257,13 +265,16 @@ export function makeJobs(deps: JobsDeps) {
|
|
|
257
265
|
}
|
|
258
266
|
}
|
|
259
267
|
|
|
260
|
-
/**
|
|
261
|
-
|
|
268
|
+
/**
|
|
269
|
+
* The runs due in `at`'s minute: one job per cron, with an id per minute, so a tick that's delivered twice runs once.
|
|
270
|
+
* With `only`, that cron's run for the minute, due or not (`t.jobs.perform`).
|
|
271
|
+
*/
|
|
272
|
+
function due(at: Date, only?: string): CronJob[] {
|
|
262
273
|
if (Number.isNaN(at.getTime())) throw new Error(`[logic-sdk] tick needs a valid date (got ${String(at)}).`);
|
|
263
274
|
const minute = new Date(Math.floor(at.getTime() / 60_000) * 60_000);
|
|
264
275
|
const stamp = minute.toISOString().slice(0, 16).replaceAll(/[-:]/g, "") + "Z"; // 20261123T0900Z: no `:`, which BullMQ rejects
|
|
265
276
|
return scheduled
|
|
266
|
-
.filter((c) => isDue(c.schedule, minute, c.cron.timezone))
|
|
277
|
+
.filter((c) => (only === undefined ? isDue(c.schedule, minute, c.cron.timezone) : c.id === only))
|
|
267
278
|
.map((c) => ({ kind: "cron", id: `${c.id}@${stamp}`, cron: c.id, scheduledAt: minute.toISOString(), attempts: c.cron.attempts ?? 1 }));
|
|
268
279
|
}
|
|
269
280
|
|
package/src/pg-boss.ts
CHANGED
|
@@ -6,7 +6,7 @@ import { fromDrizzle, type Db, type DrizzleTransactionLike, type JobInsert, type
|
|
|
6
6
|
import { replaceKeyOf, type DatabaseAdapter, type ForListeners, type Job, type Jobs, type JobsAdapter, type Registry } from "./index.ts";
|
|
7
7
|
import { startTicking } from "./node.ts";
|
|
8
8
|
|
|
9
|
-
/** One queue's tuning: `meta.pgBoss`, and `work()`'s `calls
|
|
9
|
+
/** One queue's tuning: a listener's or cron's `meta.pgBoss`, and `work()`'s `calls`. */
|
|
10
10
|
export interface PgBossTuning {
|
|
11
11
|
/** The listener's queue (`expireInSeconds`, `retryDelay`, `deadLetter`…), applied by `work()`. `partition` only when it's created. */
|
|
12
12
|
queue?: Omit<Queue, "name" | "retryLimit" | "retryBackoff" | "policy">;
|
|
@@ -15,7 +15,7 @@ export interface PgBossTuning {
|
|
|
15
15
|
}
|
|
16
16
|
|
|
17
17
|
/**
|
|
18
|
-
* What this adapter reads from a listener's `meta` (not a function's): `init<{ meta: PgBossMeta & AppMeta }>()`, then
|
|
18
|
+
* What this adapter reads from a listener's or cron's `meta` (not a function's): `init<{ meta: PgBossMeta & AppMeta }>()`, then
|
|
19
19
|
* `meta: { pgBoss: { queue: { expireInSeconds: 120 }, worker: { localConcurrency: 5 } } }`. Tuning only: retries are the
|
|
20
20
|
* listener's `attempts`, and the other adapters ignore it.
|
|
21
21
|
*/
|
|
@@ -123,10 +123,11 @@ export function pgBoss(boss: PgBoss): JobsAdapter {
|
|
|
123
123
|
holds: true, // `startAfter`, however far ahead
|
|
124
124
|
replaces: true,
|
|
125
125
|
/** Needs `database`: jobs are inserted in the mutation's transaction, and `retry` opens its own through it. */
|
|
126
|
-
check({ listeners, database: given }) {
|
|
126
|
+
check({ listeners, crons, database: given }) {
|
|
127
127
|
if (!given) throw new Error("[logic-sdk] pgBoss(boss) needs `database`: jobs are inserted in your mutation's transaction.");
|
|
128
128
|
database = given;
|
|
129
129
|
for (const l of listeners) queueOptions.set(queueName(l.id), tuningOf(l.listener.meta)?.queue);
|
|
130
|
+
for (const c of crons) queueOptions.set(queueName(c.id), tuningOf(c.cron.meta)?.queue);
|
|
130
131
|
},
|
|
131
132
|
/** Inside the mutation's transaction: one insert per queue. pg-boss skips a row whose id it already has. */
|
|
132
133
|
async enqueue(tx, jobs) {
|
|
@@ -176,15 +177,13 @@ export function pgBoss(boss: PgBoss): JobsAdapter {
|
|
|
176
177
|
export interface PgBossWorkOptions {
|
|
177
178
|
/** The shared queue of scheduled calls, tuned like a listener's `meta.pgBoss`: `{ worker: { localConcurrency: 10 } }`. */
|
|
178
179
|
calls?: PgBossTuning;
|
|
179
|
-
/** Every cron's queue, tuned the same way (crons have no `meta`): `{ queue: { expireInSeconds: 3600 } }` for a long one. */
|
|
180
|
-
crons?: PgBossTuning;
|
|
181
180
|
/** Where a failed cron tick goes, and a queue left with jobs but no listener. Default `console.error`. */
|
|
182
181
|
onError?: (error: unknown) => void;
|
|
183
182
|
}
|
|
184
183
|
|
|
185
184
|
/**
|
|
186
185
|
* Your worker process: a queue and its workers for every listener and cron, one for scheduled calls, and the cron tick
|
|
187
|
-
* every minute. `boss.stop()` stops all of it. Applies each listener's `meta.pgBoss`.
|
|
186
|
+
* every minute. `boss.stop()` stops all of it. Applies each listener's and cron's `meta.pgBoss`.
|
|
188
187
|
*
|
|
189
188
|
* ```ts
|
|
190
189
|
* await boss.start();
|
|
@@ -201,7 +200,7 @@ export async function work(
|
|
|
201
200
|
const onError = options.onError ?? ((error) => console.error("[logic-sdk]", error));
|
|
202
201
|
const queues: { name: string; tuning: PgBossTuning | undefined }[] = [
|
|
203
202
|
...listeners.map((l) => ({ name: queueName(l.id), tuning: tuningOf(l.listener.meta) })),
|
|
204
|
-
...crons.map((c) => ({ name: queueName(c.id), tuning:
|
|
203
|
+
...crons.map((c) => ({ name: queueName(c.id), tuning: tuningOf(c.cron.meta) })),
|
|
205
204
|
{ name: CALLS_QUEUE, tuning: options.calls },
|
|
206
205
|
];
|
|
207
206
|
|
package/src/testing.ts
CHANGED
|
@@ -4,6 +4,7 @@ import {
|
|
|
4
4
|
type DatabaseAdapter,
|
|
5
5
|
type DeepPartial,
|
|
6
6
|
type CallJob,
|
|
7
|
+
type Cron,
|
|
7
8
|
type Delivery,
|
|
8
9
|
type Envelope,
|
|
9
10
|
type Fn,
|
|
@@ -47,6 +48,11 @@ export interface TestJobs<S> {
|
|
|
47
48
|
drain(options?: { until?: Date | string }): Promise<void>;
|
|
48
49
|
/** Run one listener by hand, as if its event had been emitted as `scope`. Throws its failure, like `drain()`. */
|
|
49
50
|
perform<O>(listener: Listener<O>, payload: O, options: { scope: S; attempt?: number }): Promise<JobOutcome>;
|
|
51
|
+
/**
|
|
52
|
+
* Run one cron by hand, as its own scope, for the minute `at` (default: the test's now), whatever its schedule. Throws
|
|
53
|
+
* its failure. `t.jobs.tick(at)` runs every cron due that minute instead.
|
|
54
|
+
*/
|
|
55
|
+
perform(cron: Cron, options?: { at?: Date | string; attempt?: number }): Promise<JobOutcome>;
|
|
50
56
|
/** Run the crons due in `at`'s minute (default: the test's now), here and now. Resolves their ids; throws a failure. */
|
|
51
57
|
tick(at?: Date | string): Promise<string[]>;
|
|
52
58
|
}
|
|
@@ -270,8 +276,19 @@ export function createTestRegistry<S extends object, Mods extends Record<string,
|
|
|
270
276
|
travelled = undefined;
|
|
271
277
|
}
|
|
272
278
|
},
|
|
273
|
-
perform(
|
|
279
|
+
perform(target: Listener<any> | Cron, ...rest: any[]) {
|
|
274
280
|
const state = current();
|
|
281
|
+
if (target.kind === "cron") {
|
|
282
|
+
const { at, attempt } = (rest[0] ?? {}) as { at?: Date | string; attempt?: number };
|
|
283
|
+
const cron = state.registry.definitions.crons.find((c) => c.cron === target);
|
|
284
|
+
if (!cron) throw new Error("[logic-sdk] t.jobs.perform got a cron that isn't registered: export it from its module.");
|
|
285
|
+
const when = at === undefined ? clock() : new Date(at);
|
|
286
|
+
if (Number.isNaN(when.getTime())) throw new Error(`[logic-sdk] t.jobs.perform({ at }) needs a valid date (got ${String(at)}).`);
|
|
287
|
+
const [job] = state.registry[INTERNAL].due(when, cron.id);
|
|
288
|
+
return settle(state, () => state.registry.jobs.run(job!, { attempt }));
|
|
289
|
+
}
|
|
290
|
+
const listener = target;
|
|
291
|
+
const [payload, { scope, attempt }] = rest as [unknown, { scope: S; attempt?: number }];
|
|
275
292
|
const registered = state.registry.definitions.listeners.find((l) => l.listener === listener);
|
|
276
293
|
if (!registered) throw new Error("[logic-sdk] t.jobs.perform got a listener that isn't registered: export it from its module.");
|
|
277
294
|
const envelope = state.registry[INTERNAL].envelope(registered.event, payload, scope);
|
package/src/types.ts
CHANGED
|
@@ -215,18 +215,27 @@ export interface CallJob {
|
|
|
215
215
|
*/
|
|
216
216
|
export type Job = Delivery | CronJob | CallJob;
|
|
217
217
|
|
|
218
|
-
/**
|
|
218
|
+
/** Work on a schedule, as `scope`: a handler, like a listener's, run when the clock says. Export it from a module. */
|
|
219
219
|
export interface Cron<C extends Config = any> extends FromInit<C> {
|
|
220
220
|
readonly [BRAND]: "cron";
|
|
221
221
|
readonly kind: "cron";
|
|
222
222
|
readonly id?: string;
|
|
223
223
|
readonly schedule: string;
|
|
224
224
|
readonly timezone?: string;
|
|
225
|
-
/** The function it runs, read when the registry is built, like a listener's `event`. */
|
|
226
|
-
readonly run: () => Fn;
|
|
227
|
-
readonly input?: unknown;
|
|
228
225
|
readonly scope: object;
|
|
229
226
|
readonly attempts?: number;
|
|
227
|
+
readonly meta?: Readonly<Record<string, unknown>>;
|
|
228
|
+
readonly handler: (ctx: never) => Promise<unknown>;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** The run a cron's handler is doing. No scope here: `ctx.scope` is the one it runs as. */
|
|
232
|
+
export interface CronRun {
|
|
233
|
+
/** The cron's id: `tasks.wakeDue`. */
|
|
234
|
+
id: string;
|
|
235
|
+
/** The minute this run is for (ISO), even when it runs late or again: which day a digest covers. */
|
|
236
|
+
scheduledAt: string;
|
|
237
|
+
/** 1 on the first try. */
|
|
238
|
+
attempt: number;
|
|
230
239
|
}
|
|
231
240
|
|
|
232
241
|
/**
|
|
@@ -267,10 +276,11 @@ export interface Listener<O = unknown, C extends Config = any> extends FromInit<
|
|
|
267
276
|
/** What a single call may change: who it runs as (part of the scope) and when to give up. Nothing else. */
|
|
268
277
|
export interface RunOptions<S = object> {
|
|
269
278
|
/**
|
|
270
|
-
*
|
|
271
|
-
*
|
|
279
|
+
* The whole scope for this call and everything it runs, never merged: `{ scope: { ...ctx.scope, locale: "es" } }`
|
|
280
|
+
* to render in another language, `{ scope: { kind: "system", job: "reports.weekly" } }` to act as someone else on purpose. The
|
|
281
|
+
* callee's policy sees it. Whole, so it's one of your scope's variants: a patch could build one that isn't.
|
|
272
282
|
*/
|
|
273
|
-
scope?:
|
|
283
|
+
scope?: S;
|
|
274
284
|
/**
|
|
275
285
|
* Checked before this call starts. Inside, actions get it as `ctx.signal` to pass on (`fetch(url, { signal })`).
|
|
276
286
|
* Never checked between your steps, so a caller who gives up can't leave a workflow half done.
|
|
@@ -346,6 +356,10 @@ export interface ActionCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C,
|
|
|
346
356
|
export interface ListenerCtx<C extends Config, O = unknown> extends ActionCtx<C> {
|
|
347
357
|
event: ListenerEvent<O>;
|
|
348
358
|
}
|
|
359
|
+
/** A cron's handler's ctx: an action's, as the cron's own scope, plus the run. */
|
|
360
|
+
export interface CronCtx<C extends Config, S = ScopeOf<C>> extends ActionCtx<C, S> {
|
|
361
|
+
cron: CronRun;
|
|
362
|
+
}
|
|
349
363
|
|
|
350
364
|
/**
|
|
351
365
|
* Who may call a function at all: signed in, admin, staff. Sync, reads only the scope, returns exactly `true` to allow.
|
|
@@ -477,7 +491,11 @@ export interface JobsAdapter {
|
|
|
477
491
|
*/
|
|
478
492
|
replaces?: true;
|
|
479
493
|
/** At `createRegistry`: refuse a setup this adapter can't honour (a database it doesn't share). */
|
|
480
|
-
check?(setup: {
|
|
494
|
+
check?(setup: {
|
|
495
|
+
listeners: readonly RegisteredListener[];
|
|
496
|
+
crons: readonly RegisteredCron[];
|
|
497
|
+
database: DatabaseAdapter<unknown, unknown> | undefined;
|
|
498
|
+
}): void;
|
|
481
499
|
/** Inside the transaction, before commit. In-process: nothing. `databaseQueue` and `outbox`: insert one row per job with `tx`. */
|
|
482
500
|
enqueue?(tx: unknown, jobs: Job[]): Promise<void>;
|
|
483
501
|
/** After commit: run them, or hand them to a queue. A throw is reported to `onError`. */
|
|
@@ -554,8 +572,8 @@ export type JobsOptions<S = object, T = any> = {
|
|
|
554
572
|
|
|
555
573
|
export interface Call<M = unknown> {
|
|
556
574
|
id: string;
|
|
557
|
-
kind: Kind | "listener";
|
|
558
|
-
/** The function's or
|
|
575
|
+
kind: Kind | "listener" | "cron";
|
|
576
|
+
/** The function's, listener's or cron's `meta` (undefined when it has none). */
|
|
559
577
|
meta: M | undefined;
|
|
560
578
|
/** Raw input as received (before validation). */
|
|
561
579
|
input: unknown;
|
|
@@ -627,7 +645,6 @@ export interface RegisteredListener extends Registered {
|
|
|
627
645
|
}
|
|
628
646
|
export interface RegisteredCron extends Registered {
|
|
629
647
|
cron: Cron;
|
|
630
|
-
run: Fn;
|
|
631
648
|
}
|
|
632
649
|
|
|
633
650
|
/** `registry.jobs`: what you call from a queue consumer, a cron, or a script. */
|
|
@@ -679,8 +696,8 @@ export interface Registry<S extends object = object, Mods extends Record<string,
|
|
|
679
696
|
derive(more: Overrides): Registry<S, Mods, Cf>;
|
|
680
697
|
/** An event as `emit` would make it, for `t.jobs.perform`. */
|
|
681
698
|
envelope(event: EventDef, payload: unknown, scope: S): Envelope;
|
|
682
|
-
/** The cron runs due in a minute, for `t.jobs.tick
|
|
683
|
-
due(at: Date): CronJob[];
|
|
699
|
+
/** The cron runs due in a minute, for `t.jobs.tick`; with `only`, that cron's run, due or not (`t.jobs.perform`). */
|
|
700
|
+
due(at: Date, only?: string): CronJob[];
|
|
684
701
|
};
|
|
685
702
|
}
|
|
686
703
|
|