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,671 @@
|
|
|
1
|
+
import { CaughtNestedFailure, describeIssues, DomainError, errorsFor, forbiddenOf, moduleOf, PRIVATE } from "./errors.ts";
|
|
2
|
+
import { inProcess, runsNow } from "./in-process.ts";
|
|
3
|
+
import { ADAPTERS, isPlainObject, makeJobs, replaceKeyOf } from "./jobs.ts";
|
|
4
|
+
import { assertTimeZone, parseSchedule } from "./schedule.ts";
|
|
5
|
+
import { BRAND, INTERNAL } from "./types.ts";
|
|
6
|
+
import type {
|
|
7
|
+
ActionCtx,
|
|
8
|
+
Call,
|
|
9
|
+
CallJob,
|
|
10
|
+
CallMetaOf,
|
|
11
|
+
Config,
|
|
12
|
+
ConfigOf,
|
|
13
|
+
Constructor,
|
|
14
|
+
Cron,
|
|
15
|
+
CronCtx,
|
|
16
|
+
DatabaseAdapter,
|
|
17
|
+
DatabaseOptions,
|
|
18
|
+
DbOf,
|
|
19
|
+
Envelope,
|
|
20
|
+
EventDef,
|
|
21
|
+
FailureInfo,
|
|
22
|
+
Fn,
|
|
23
|
+
Frozen,
|
|
24
|
+
In,
|
|
25
|
+
Job,
|
|
26
|
+
JobsOptions,
|
|
27
|
+
Kind,
|
|
28
|
+
Listener,
|
|
29
|
+
ListenerCtx,
|
|
30
|
+
ListenerMetaOf,
|
|
31
|
+
MutationCtx,
|
|
32
|
+
Out,
|
|
33
|
+
Overrides,
|
|
34
|
+
OwnModules,
|
|
35
|
+
QueryCtx,
|
|
36
|
+
RegisteredCron,
|
|
37
|
+
RegisteredEvent,
|
|
38
|
+
RegisteredFn,
|
|
39
|
+
RegisteredListener,
|
|
40
|
+
Registry,
|
|
41
|
+
RegistryOptions,
|
|
42
|
+
RunOptions,
|
|
43
|
+
Schema,
|
|
44
|
+
ScopeOf,
|
|
45
|
+
ServicesOf,
|
|
46
|
+
SqlDatabase,
|
|
47
|
+
} from "./types.ts";
|
|
48
|
+
|
|
49
|
+
/* ────────────────────────────────────────────────────────────────────────────
|
|
50
|
+
* init: typed constructors
|
|
51
|
+
* ──────────────────────────────────────────────────────────────────────────── */
|
|
52
|
+
|
|
53
|
+
type TypedOptions<C extends Config, Mods extends Record<string, object>, T> = Omit<RegistryOptions<Mods>, "wrap" | "jobs"> & {
|
|
54
|
+
/** Background work: `jobs: { adapter: databaseQueue(), scope: { store, load } }`. Default: in-process, scope as-is (nothing waits). */
|
|
55
|
+
jobs?: JobsOptions<ScopeOf<C>, T>;
|
|
56
|
+
/** Wraps every call, including ones that fail validation or authorization: logging, tracing, audit. */
|
|
57
|
+
wrap?: (call: Call<CallMetaOf<C>>, next: () => Promise<unknown>) => Promise<unknown>;
|
|
58
|
+
} &
|
|
59
|
+
({} extends ServicesOf<C> ? { services?: ServicesOf<C> } : { services: ServicesOf<C> }) &
|
|
60
|
+
({} extends ConfigOf<C> ? { config?: ConfigOf<C> } : { config: ConfigOf<C> }) &
|
|
61
|
+
([DbOf<C>] extends [never] ? { database?: undefined } : { database: DatabaseOptions<DatabaseAdapter<unknown, DbOf<C>>> }) &
|
|
62
|
+
{ modules: OwnModules<C, Mods> };
|
|
63
|
+
|
|
64
|
+
/** Keys `Config` doesn't know are errors, so a typo like `servises` can't be silently ignored. */
|
|
65
|
+
type OnlyKnownKeys<C> = { [K in Exclude<keyof C, keyof Config>]: never };
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Typed constructors for your app:
|
|
69
|
+
*
|
|
70
|
+
* ```ts
|
|
71
|
+
* export const { query, mutation, action, event, listener, createRegistry } = init<Config>();
|
|
72
|
+
* ```
|
|
73
|
+
*/
|
|
74
|
+
export function init<C extends Config & OnlyKnownKeys<C>>() {
|
|
75
|
+
// One implementation behind the typed signature of `Constructor`: the types are the contract, the adapters check `authorize`.
|
|
76
|
+
const make =
|
|
77
|
+
<K extends Kind>(kind: K) =>
|
|
78
|
+
(def: object) =>
|
|
79
|
+
Object.freeze({ [BRAND]: kind, kind, ...def });
|
|
80
|
+
|
|
81
|
+
return {
|
|
82
|
+
/** Create the registry once at startup: `createRegistry({ modules, database, services })`. */
|
|
83
|
+
createRegistry: <const Mods extends Record<string, object>, T = ScopeOf<C>>(options: TypedOptions<C, Mods, T>) =>
|
|
84
|
+
build<ScopeOf<C>, Mods, ConfigOf<C>>(options as RegistryOptions<Mods>, {}), // meta in wrap is typed by CallMetaOf<C>; the values come from typed defs
|
|
85
|
+
/** Reads data. Can run other queries. No writes, no events, no services. */
|
|
86
|
+
query: make("query") as Constructor<C, "query">,
|
|
87
|
+
/** Changes data inside one transaction. Can run queries and mutations (same transaction) and emit events. */
|
|
88
|
+
mutation: make("mutation") as Constructor<C, "mutation">,
|
|
89
|
+
/** Talks to the outside world (payments, email, AI). No transaction; each mutation it runs commits on its own. */
|
|
90
|
+
action: make("action") as Constructor<C, "action">,
|
|
91
|
+
/** Something that happened. Emitted by mutations, delivered after commit. */
|
|
92
|
+
event: <S extends Schema>(def: {
|
|
93
|
+
/**
|
|
94
|
+
* Stable id, local to its module: in a `notifications` module, `id: "send"` is `notifications.send`. Jobs store it,
|
|
95
|
+
* so set it before you rename the export and queued jobs keep finding this code. Defaults to the export name.
|
|
96
|
+
*/
|
|
97
|
+
id?: string;
|
|
98
|
+
payload: S;
|
|
99
|
+
}): EventDef<In<S>, Out<S>> =>
|
|
100
|
+
Object.freeze({ [BRAND]: "event" as const, kind: "event" as const, ...def }),
|
|
101
|
+
/**
|
|
102
|
+
* Work on a schedule, as `scope` (a cron has no caller): a handler, like a listener's, run when the clock says. Export
|
|
103
|
+
* it from a module and call `registry.jobs.tick()` every minute (or from your platform's cron trigger). Must be
|
|
104
|
+
* idempotent: a retry runs the whole handler again.
|
|
105
|
+
* `cron({ schedule: "0 9 * * MON", scope: { kind: "system", job: "reports.weekly" }, async handler(ctx) { await ctx.run(send) } })`.
|
|
106
|
+
*/
|
|
107
|
+
cron: <const Sc extends ScopeOf<C>>(def: CronDef<C, Sc>): Cron<C> => {
|
|
108
|
+
const { id, schedule, timezone, scope, attempts, meta, handler } = def;
|
|
109
|
+
parseSchedule(schedule);
|
|
110
|
+
if (timezone !== undefined) assertTimeZone(timezone);
|
|
111
|
+
checkAttempts("cron", attempts);
|
|
112
|
+
// meta is checked against ListenerMetaOf<C> above and stored loose, like a listener's, for wrap and adapters
|
|
113
|
+
return Object.freeze({ [BRAND]: "cron" as const, kind: "cron" as const, id, schedule, timezone, scope, attempts, meta: meta as Cron["meta"], handler });
|
|
114
|
+
},
|
|
115
|
+
/**
|
|
116
|
+
* React to an event after commit, like an action. Must be idempotent.
|
|
117
|
+
* `listener({ event: () => bookings.confirmed, async handler(ctx, payload) {…} })`
|
|
118
|
+
*/
|
|
119
|
+
listener: <O>(def: {
|
|
120
|
+
/**
|
|
121
|
+
* Stable id, local to its module: in a `notifications` module, `id: "send"` is `notifications.send`. Jobs store it,
|
|
122
|
+
* so set it before you rename the export and queued jobs keep finding this code. Defaults to the export name.
|
|
123
|
+
*/
|
|
124
|
+
id?: string;
|
|
125
|
+
/** The event it reacts to, as a thunk so modules can import each other's barrels without cycles. */
|
|
126
|
+
event: () => EventDef<unknown, O>;
|
|
127
|
+
/**
|
|
128
|
+
* Tries in total, the first included, like Laravel's `$tries`. Default 1: a retry repeats side effects, so opt in.
|
|
129
|
+
* Once they're used, the job is `failed` (kept by `databaseQueue`, `outbox` and pg-boss, retried with `registry.jobs.retry(id)`).
|
|
130
|
+
*/
|
|
131
|
+
attempts?: number;
|
|
132
|
+
/** Seconds after the event before the first try. Needs an adapter that holds jobs: `inProcess()` is refused. */
|
|
133
|
+
delay?: number;
|
|
134
|
+
/**
|
|
135
|
+
* Whether this event gets a job for this listener, like Laravel's `shouldQueue($event)`: false, and nothing is
|
|
136
|
+
* stored, run or counted. From the payload the handler gets (parsed), at commit, so sync and from the event only:
|
|
137
|
+
* a condition on the database belongs in the handler, since it can change before the job runs. A throw fails the
|
|
138
|
+
* mutation, as a bad payload does.
|
|
139
|
+
*/
|
|
140
|
+
when?: (payload: O) => boolean;
|
|
141
|
+
meta?: ListenerMetaOf<C>;
|
|
142
|
+
handler: (ctx: ListenerCtx<C, O>, payload: O) => Promise<unknown>;
|
|
143
|
+
}): Listener<O, C> => {
|
|
144
|
+
const { id, event, attempts, delay, when, meta, handler } = def;
|
|
145
|
+
checkAttempts("listener", attempts);
|
|
146
|
+
if (delay !== undefined && !(Number.isFinite(delay) && delay >= 0))
|
|
147
|
+
throw new Error(`[logic-sdk] listener delay must be seconds, 0 or more (got ${delay}).`);
|
|
148
|
+
// meta is checked against ListenerMetaOf<C> above and stored loose, like Fn.meta, for wrap and adapters
|
|
149
|
+
return Object.freeze({ [BRAND]: "listener" as const, kind: "listener" as const, id, event, attempts, delay, when, meta: meta as Listener["meta"], handler });
|
|
150
|
+
},
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** `cron({...})`: its handler's `ctx.scope` is the scope it declares, so a policy-free read of it is typed. */
|
|
155
|
+
type CronDef<C extends Config, Sc> = {
|
|
156
|
+
/**
|
|
157
|
+
* Stable id, local to its module, like every definer's. Defaults to the export name. Jobs and pg-boss's queue store it,
|
|
158
|
+
* so set it before you rename the export.
|
|
159
|
+
*/
|
|
160
|
+
id?: string;
|
|
161
|
+
/** Five fields: minute hour day-of-month month day-of-week. `"*\/15 * * * *"`, `"0 9 * * MON"`. */
|
|
162
|
+
schedule: string;
|
|
163
|
+
/** IANA name, like `"Europe/Madrid"`. Default UTC. Matched on the wall clock, like Laravel: mind DST at 1 to 3 am. */
|
|
164
|
+
timezone?: string;
|
|
165
|
+
/** Who it runs as: a cron has no caller. Every function the handler runs checks its policy against it. */
|
|
166
|
+
scope: Sc;
|
|
167
|
+
/** Tries in total, like a listener's. Default 1: a retry runs the whole handler again. */
|
|
168
|
+
attempts?: number;
|
|
169
|
+
meta?: ListenerMetaOf<C>;
|
|
170
|
+
/** The work, like a listener's handler: an action's ctx, plus `ctx.cron` (`scheduledAt`, `attempt`). */
|
|
171
|
+
handler: (ctx: CronCtx<C, Sc>) => Promise<unknown>;
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
/** How deep `ctx.run` calls may nest. Past it, a function is running itself without end. */
|
|
175
|
+
const MAX_RUN_DEPTH = 64;
|
|
176
|
+
|
|
177
|
+
function checkAttempts(what: string, attempts: number | undefined) {
|
|
178
|
+
if (attempts !== undefined && !(Number.isInteger(attempts) && attempts >= 1))
|
|
179
|
+
throw new Error(`[logic-sdk] ${what} attempts must be a whole number of tries, 1 or more (got ${attempts}).`);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/* ────────────────────────────────────────────────────────────────────────────
|
|
183
|
+
* createRegistry
|
|
184
|
+
* ──────────────────────────────────────────────────────────────────────────── */
|
|
185
|
+
|
|
186
|
+
interface TxState {
|
|
187
|
+
db: unknown;
|
|
188
|
+
doomed: boolean;
|
|
189
|
+
reason: unknown;
|
|
190
|
+
/** Where the transaction's own mutation sits in the trail: what the error at commit prints starts there. */
|
|
191
|
+
from: number;
|
|
192
|
+
/** The calls down to the nested mutation whose failure doomed it, from the transaction's own mutation. */
|
|
193
|
+
doomedBy: readonly string[] | undefined;
|
|
194
|
+
events: Envelope[];
|
|
195
|
+
/** Each event's payload as its schema parsed it, for listeners' `when`: the value their handler gets. */
|
|
196
|
+
parsed: Map<Envelope, unknown>;
|
|
197
|
+
/** What `ctx.schedule` asked for, enqueued with the events at commit. */
|
|
198
|
+
calls: CallJob[];
|
|
199
|
+
pending: Promise<void>[];
|
|
200
|
+
}
|
|
201
|
+
interface Frame {
|
|
202
|
+
scope: object;
|
|
203
|
+
/** The calls that led here, outermost first. How many there are is the next call's depth. */
|
|
204
|
+
trail: readonly string[];
|
|
205
|
+
/** Inherited, for actions to pass on as ctx.signal. */
|
|
206
|
+
signal?: AbortSignal;
|
|
207
|
+
/** Passed to this very call: checked before it starts. */
|
|
208
|
+
abortOn?: AbortSignal;
|
|
209
|
+
/** Hops in the chain of events and calls due now that led here: 0 for a call from outside. */
|
|
210
|
+
eventDepth: number;
|
|
211
|
+
/** Inside a job: where the jobs it queues wait until it's settled. */
|
|
212
|
+
queued?: Job[];
|
|
213
|
+
/** A scheduled call's own run: which job and try, for `wrap`'s call. */
|
|
214
|
+
job?: { id: string; attempt: number };
|
|
215
|
+
tx?: TxState;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** What a mutation throws at commit when a nested mutation failed and was caught: the transaction they share is doomed. */
|
|
219
|
+
function caughtNestedFailure(id: string, tx: TxState): CaughtNestedFailure {
|
|
220
|
+
let why: string;
|
|
221
|
+
try {
|
|
222
|
+
why = tx.reason instanceof Error ? tx.reason.message : String(tx.reason);
|
|
223
|
+
} catch {
|
|
224
|
+
why = Object.prototype.toString.call(tx.reason); // an object String() can't print
|
|
225
|
+
}
|
|
226
|
+
return new CaughtNestedFailure(
|
|
227
|
+
`[logic-sdk] ${tx.doomedBy?.at(-1)} failed inside ${id}'s transaction (${tx.doomedBy?.join(" → ")}) and was ` +
|
|
228
|
+
`caught, so ${id} can't commit: a mutation shares its transaction with the mutations it runs. To let each one ` +
|
|
229
|
+
`commit or fail on its own, run them from an action. The failure (this error's cause): ${why}`,
|
|
230
|
+
{ cause: tx.reason },
|
|
231
|
+
);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** Create the registry once at startup. Prefer the `createRegistry` returned by `init()`: it's typed with your config. */
|
|
235
|
+
export function createRegistry<S extends object = object, const Mods extends Record<string, object> = Record<string, object>>(
|
|
236
|
+
options: RegistryOptions<Mods>,
|
|
237
|
+
) {
|
|
238
|
+
return build<S, Mods>(options, {});
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** Plain objects merge key by key; anything else (values, arrays, null) replaces. `undefined` keeps the base. */
|
|
242
|
+
function mergeConfig(base: unknown, patch: unknown): unknown {
|
|
243
|
+
if (patch === undefined) return base;
|
|
244
|
+
if (!isPlainObject(base) || !isPlainObject(patch)) return patch;
|
|
245
|
+
const keys = new Set([...Object.keys(base), ...Object.keys(patch)]);
|
|
246
|
+
return Object.fromEntries([...keys].map((k) => [k, mergeConfig(base[k], patch[k])])); // fromEntries: `__proto__` stays a key
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** A frozen copy of plain data, so settings can't change under everyone else or hide behavior (a client, a class). */
|
|
250
|
+
function freezeConfig(value: unknown): unknown {
|
|
251
|
+
assertPlain(value, "config", "config holds plain data: pass a Date as an ISO string, and put clients in services");
|
|
252
|
+
const freeze = (v: unknown): unknown => {
|
|
253
|
+
if (v && typeof v === "object") {
|
|
254
|
+
for (const item of Object.values(v)) freeze(item);
|
|
255
|
+
Object.freeze(v);
|
|
256
|
+
}
|
|
257
|
+
return v;
|
|
258
|
+
};
|
|
259
|
+
return freeze(structuredClone(value));
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* Plain data, what survives JSON: plain objects, arrays, strings, finite numbers, booleans, null (undefined is dropped).
|
|
264
|
+
* Anything else (a Date, a Map, a class instance, a function, a cycle) is rejected with its path.
|
|
265
|
+
*/
|
|
266
|
+
function assertPlain(value: unknown, what: string, hint: string): void {
|
|
267
|
+
const seen = new Set<object>();
|
|
268
|
+
const check = (v: unknown, path: string): void => {
|
|
269
|
+
const fail = (found: string): never => {
|
|
270
|
+
throw new Error(`[logic-sdk] ${what} isn't plain data${path ? ` at ${path}` : ""}: ${found}. ${hint}.`);
|
|
271
|
+
};
|
|
272
|
+
if (v === null || v === undefined || typeof v === "string" || typeof v === "boolean") return;
|
|
273
|
+
if (typeof v === "number") {
|
|
274
|
+
if (!Number.isFinite(v)) fail(String(v));
|
|
275
|
+
return;
|
|
276
|
+
}
|
|
277
|
+
if (typeof v !== "object") return fail(`a ${typeof v}`);
|
|
278
|
+
if (seen.has(v)) fail("a circular reference");
|
|
279
|
+
seen.add(v);
|
|
280
|
+
if (Array.isArray(v)) v.forEach((item, i) => check(item, `${path}[${i}]`));
|
|
281
|
+
else {
|
|
282
|
+
if (!isPlainObject(v)) fail(`a ${v.constructor?.name ?? "class instance"}`);
|
|
283
|
+
for (const [k, item] of Object.entries(v)) check(item, path ? `${path}.${k}` : k);
|
|
284
|
+
}
|
|
285
|
+
seen.delete(v);
|
|
286
|
+
};
|
|
287
|
+
check(value, "");
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
const isBranded = (v: unknown): v is Fn | EventDef | Listener | Cron => !!v && typeof v === "object" && BRAND in v;
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* What `createRegistry` finds in your modules, without a database or services: every function, event, listener and
|
|
294
|
+
* cron with its id. For tools (the CLI, docs generators) that inspect an app without running it.
|
|
295
|
+
*/
|
|
296
|
+
export function describeModules(modules: Record<string, object>) {
|
|
297
|
+
const ids = new Map<object, string>();
|
|
298
|
+
const functions: RegisteredFn[] = [];
|
|
299
|
+
const events: RegisteredEvent[] = [];
|
|
300
|
+
const listeners: RegisteredListener[] = [];
|
|
301
|
+
const crons: RegisteredCron[] = [];
|
|
302
|
+
|
|
303
|
+
const taken = new Map<string, string>();
|
|
304
|
+
|
|
305
|
+
for (const [module, ns] of Object.entries(modules)) {
|
|
306
|
+
for (const [name, value] of Object.entries(ns)) {
|
|
307
|
+
if (!isBranded(value) || ids.has(value)) continue;
|
|
308
|
+
const local = value.id ?? name;
|
|
309
|
+
if (value.id !== undefined && (typeof value.id !== "string" || !/^[A-Za-z0-9_-]+$/.test(value.id)))
|
|
310
|
+
throw new Error(`[logic-sdk] ${module}.${name} has id ${JSON.stringify(value.id)}. Give the local name ("send"): the module key is added, so it's ${module}.<id>.`);
|
|
311
|
+
const id = `${module}.${local}`;
|
|
312
|
+
const other = taken.get(id);
|
|
313
|
+
if (other) throw new Error(`[logic-sdk] ${module}.${other} and ${module}.${name} both have the id ${id}. Ids must be unique: jobs find their code by it.`);
|
|
314
|
+
taken.set(id, name);
|
|
315
|
+
ids.set(value, id);
|
|
316
|
+
if (value.kind === "event") events.push({ id, module, name, event: value });
|
|
317
|
+
else if (value.kind === "listener") listeners.push({ id, module, name, listener: value, event: value.event() });
|
|
318
|
+
else if (value.kind === "cron") crons.push({ id, module, name, cron: value });
|
|
319
|
+
else functions.push({ id, module, name, kind: value.kind, fn: value });
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
return { ids, functions, events, listeners, crons };
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function build<S extends object, Mods extends Record<string, object>, Cf = unknown>(
|
|
326
|
+
options: RegistryOptions<Mods>,
|
|
327
|
+
o: Overrides,
|
|
328
|
+
): Registry<S, Mods, Cf> {
|
|
329
|
+
const { ids, functions, events, listeners, crons } = describeModules(options.modules);
|
|
330
|
+
|
|
331
|
+
const database = o.database ?? options.database?.adapter;
|
|
332
|
+
const services = o.services ?? options.services ?? {};
|
|
333
|
+
const config = freezeConfig(mergeConfig(options.config ?? {}, o.config)) as Frozen<Cf>;
|
|
334
|
+
const jobsAdapter = o.adapter ?? options.jobs?.adapter ?? inProcess();
|
|
335
|
+
const jobScope = options.jobs?.scope;
|
|
336
|
+
if (jobScope?.store && !jobScope.load) throw new Error("[logic-sdk] jobs.scope has store but no load. Jobs run as a scope, so rebuild it from what store saved.");
|
|
337
|
+
// a job any adapter but inProcess() keeps runs as a scope saved earlier: rebuild it, or its roles are the ones from
|
|
338
|
+
// back then (AshOban's actor_persister). The app's adapter, so a test registry agrees with the app it wraps.
|
|
339
|
+
const appAdapter = options.jobs?.adapter;
|
|
340
|
+
if (appAdapter && !runsNow(appAdapter) && !jobScope?.load)
|
|
341
|
+
throw new Error(
|
|
342
|
+
"[logic-sdk] Your jobs adapter keeps jobs to run later, so set jobs.scope.load: it rebuilds the scope when a job runs, with today's " +
|
|
343
|
+
"roles (null discards the job). Add `store` to save only ids. To keep the scope as it was, `load: (saved) => saved`.",
|
|
344
|
+
);
|
|
345
|
+
const now = o.now ?? options.now ?? (() => new Date());
|
|
346
|
+
const wrap = options.wrap ?? ((_c, next) => next());
|
|
347
|
+
const maxEventDepth = options.jobs?.maxEventDepth ?? 8;
|
|
348
|
+
checkAttempts("database transaction", options.database?.transactionAttempts);
|
|
349
|
+
const transactionAttempts = options.database?.transactionAttempts ?? 3; // the app's, so a test's nested adapter keeps it
|
|
350
|
+
const waitUntil = "waitUntil" in o ? o.waitUntil : options.waitUntil; // tests turn it off: listeners finish inside the test
|
|
351
|
+
const reportRaw =
|
|
352
|
+
o.onError ?? options.onError ?? ((e, info) => console.error(`[logic-sdk] ${info.source} failed`, e));
|
|
353
|
+
const report = (e: unknown, info: FailureInfo) => {
|
|
354
|
+
try {
|
|
355
|
+
reportRaw(e, info);
|
|
356
|
+
} catch (inner) {
|
|
357
|
+
console.error("[logic-sdk] onError threw", inner, "while reporting", e);
|
|
358
|
+
}
|
|
359
|
+
};
|
|
360
|
+
|
|
361
|
+
const noDatabase =
|
|
362
|
+
"[logic-sdk] Mutations need a database: createRegistry({ database: { adapter } }), on a driver with interactive " +
|
|
363
|
+
"transactions (see Adapters in the docs).";
|
|
364
|
+
if (!database && functions.some((f) => f.kind === "mutation")) throw new Error(noDatabase);
|
|
365
|
+
for (const l of listeners)
|
|
366
|
+
if (!ids.has(l.event))
|
|
367
|
+
throw new Error(`[logic-sdk] Listener ${l.id} listens to an event that isn't registered in any module.`);
|
|
368
|
+
const failedStore = o.failed === null ? undefined : (o.failed ?? options.jobs?.failed);
|
|
369
|
+
const sql = database && "query" in database ? (database as SqlDatabase) : undefined;
|
|
370
|
+
for (const adapter of [jobsAdapter, failedStore])
|
|
371
|
+
if (adapter?.sql && !sql)
|
|
372
|
+
throw new Error(
|
|
373
|
+
`[logic-sdk] ${adapter.name ?? "Your jobs adapter"} writes in your mutation's transaction with SQL, so it needs ` +
|
|
374
|
+
"createRegistry({ database: { adapter } }) with an adapter that runs SQL (`query`). See Adapters, Other ORMs in the docs.",
|
|
375
|
+
);
|
|
376
|
+
jobsAdapter.connect?.({ listeners, crons, database, sql });
|
|
377
|
+
failedStore?.connect?.({ listeners, crons, database, sql });
|
|
378
|
+
|
|
379
|
+
const idOf = (x: object) => {
|
|
380
|
+
const id = ids.get(x);
|
|
381
|
+
if (!id)
|
|
382
|
+
throw new Error(
|
|
383
|
+
"[logic-sdk] This function or event isn't registered. Export it from its module's index.ts, and add the module to createRegistry({ modules }). " +
|
|
384
|
+
"A private function (one the index doesn't export) runs only through ctx.run, from its own module.",
|
|
385
|
+
);
|
|
386
|
+
return id;
|
|
387
|
+
};
|
|
388
|
+
|
|
389
|
+
/** Bad input from a caller is their error. Bad input from your own code (a nested call) is a bug. */
|
|
390
|
+
async function parseInput(schema: Schema, value: unknown, id: string, nested: boolean) {
|
|
391
|
+
const r = await schema["~standard"].validate(value);
|
|
392
|
+
if (!r.issues) return r.value;
|
|
393
|
+
const issues = describeIssues(r.issues);
|
|
394
|
+
if (nested) throw new Error(`[logic-sdk] ${id} was run with invalid input: ${JSON.stringify(issues)}`);
|
|
395
|
+
throw new DomainError("invalid", `${id}.invalid_input`, { issues });
|
|
396
|
+
}
|
|
397
|
+
/** Output and event payloads are produced by our own code: invalid means a bug, not a bad request. */
|
|
398
|
+
async function parseOwn(schema: Schema, value: unknown, what: string) {
|
|
399
|
+
const r = await schema["~standard"].validate(value);
|
|
400
|
+
if (r.issues) throw new Error(`[logic-sdk] ${what} is invalid: ${JSON.stringify(describeIssues(r.issues))}`);
|
|
401
|
+
return r.value;
|
|
402
|
+
}
|
|
403
|
+
/** What our own code passed a mutation's ctx, checked by the time it commits: a bad value fails the commit. */
|
|
404
|
+
function checkAtCommit(tx: TxState, schema: Schema, value: unknown, what: string, keep?: (parsed: unknown) => void) {
|
|
405
|
+
const check = parseOwn(schema, value, what).then((parsed) => keep?.(parsed));
|
|
406
|
+
check.catch(() => {}); // surfaced at commit; never an unhandled rejection
|
|
407
|
+
tx.pending.push(check);
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
// ── ctx ──────────────────────────────────────────────────────────────────
|
|
411
|
+
/** The frame for a call from here: its scope and signal. `invoke` adds the call to the trail. */
|
|
412
|
+
const enter = (frame: Frame, options: RunOptions | undefined): Frame => ({
|
|
413
|
+
...frame,
|
|
414
|
+
scope: options?.scope ?? frame.scope,
|
|
415
|
+
signal: options?.signal ?? frame.signal,
|
|
416
|
+
abortOn: options?.signal,
|
|
417
|
+
});
|
|
418
|
+
|
|
419
|
+
/** What every ctx has. `allowed`: the kinds its `run` may call. */
|
|
420
|
+
const baseCtx = (frame: Frame, id: string, allowed: Kind[]) => ({
|
|
421
|
+
errors: errorsFor(id),
|
|
422
|
+
scope: frame.scope,
|
|
423
|
+
config: config as any, // Frozen<Cf> here; each app's ctx types it from its own Config
|
|
424
|
+
now,
|
|
425
|
+
run: (fn: Fn, input?: unknown, options?: RunOptions) => invoke(fn, input, enter(frame, options), allowed, moduleOf(id)),
|
|
426
|
+
});
|
|
427
|
+
const queryCtx = (frame: Frame, id: string): QueryCtx<any> => ({
|
|
428
|
+
...baseCtx(frame, id, ["query"]),
|
|
429
|
+
db: frame.tx ? frame.tx.db : database?.db,
|
|
430
|
+
});
|
|
431
|
+
function mutationCtx(frame: Frame, tx: TxState, id: string): MutationCtx<any> {
|
|
432
|
+
return {
|
|
433
|
+
...baseCtx(frame, id, ["query", "mutation"]),
|
|
434
|
+
db: tx.db,
|
|
435
|
+
emit: (event, payload) => {
|
|
436
|
+
// reserve the slot now so events keep emit order, even with async schemas
|
|
437
|
+
const envelope = envelopeOf(event, payload, frame.scope, frame.eventDepth + 1);
|
|
438
|
+
tx.events.push(envelope);
|
|
439
|
+
checkAtCommit(tx, event.payload, envelope.payload, `${envelope.name} payload`, (parsed) => tx.parsed.set(envelope, parsed));
|
|
440
|
+
// a copy: changing it can't change what's delivered
|
|
441
|
+
return Object.freeze({ id: envelope.id, name: envelope.name, payload: structuredClone(envelope.payload) as typeof payload, occurredAt: envelope.occurredAt });
|
|
442
|
+
},
|
|
443
|
+
schedule: (fn, input, { at, delay, attempts = 1, replace, scope }) => {
|
|
444
|
+
const fnId = ids.get(fn);
|
|
445
|
+
if (!fnId)
|
|
446
|
+
throw new Error(
|
|
447
|
+
"[logic-sdk] ctx.schedule needs a function its module's index.ts exports: a scheduled call waits as a name, and a worker finds the code by it. " +
|
|
448
|
+
"A private function runs only through ctx.run.",
|
|
449
|
+
);
|
|
450
|
+
const seconds = at ? (at.getTime() - now().getTime()) / 1000 : (delay ?? NaN);
|
|
451
|
+
if (!Number.isFinite(seconds) || (!at && seconds < 0))
|
|
452
|
+
throw new Error(`[logic-sdk] ctx.schedule(${fnId}) needs an \`at\` date or a \`delay\` in seconds, 0 or more.`);
|
|
453
|
+
checkAttempts(`ctx.schedule(${fnId})`, attempts);
|
|
454
|
+
checkRetries(`ctx.schedule(${fnId})`, attempts);
|
|
455
|
+
if (replace !== undefined) {
|
|
456
|
+
if (!jobsAdapter.replaces)
|
|
457
|
+
throw new Error(`[logic-sdk] ctx.schedule(${fnId}) replaces a waiting call, but ${yours} can't replace one it already has. Use one that can (${ADAPTERS}).`);
|
|
458
|
+
}
|
|
459
|
+
// due now (no delay, or an `at` already past): runs after commit like a listener, no holding needed
|
|
460
|
+
const waits = seconds > 0;
|
|
461
|
+
if (waits) checkHold(`ctx.schedule(${fnId})`, seconds);
|
|
462
|
+
assertPlain(input, `${fnId} input`, "Scheduled calls wait as JSON: send an ISO string and let the schema turn it into a Date");
|
|
463
|
+
const job: CallJob = {
|
|
464
|
+
kind: "call",
|
|
465
|
+
id: `${fnId}@${crypto.randomUUID()}`,
|
|
466
|
+
fn: fnId,
|
|
467
|
+
input: structuredClone(input),
|
|
468
|
+
scope: storedScope(scope ?? frame.scope, `the scope scheduling ${fnId}`), // `scope`: whole, as ctx.run takes it
|
|
469
|
+
attempts,
|
|
470
|
+
depth: waits ? 0 : frame.eventDepth + 1, // due now, it's the next hop of this chain; a real wait starts a new one
|
|
471
|
+
};
|
|
472
|
+
if (waits) job.runAt = new Date(now().getTime() + seconds * 1000).toISOString();
|
|
473
|
+
if (replace) {
|
|
474
|
+
job.replace = true;
|
|
475
|
+
// scheduled twice in this transaction: the later one wins here too (the dropped one's input is still checked:
|
|
476
|
+
// a bad input is a bug wherever it is)
|
|
477
|
+
const earlier = tx.calls.findIndex((c) => replaceKeyOf(c) === replaceKeyOf(job));
|
|
478
|
+
if (earlier >= 0) tx.calls.splice(earlier, 1);
|
|
479
|
+
}
|
|
480
|
+
tx.calls.push(job);
|
|
481
|
+
// our own code passed it: a bad input is a bug, surfaced at commit like an event's payload
|
|
482
|
+
if (fn.input) checkAtCommit(tx, fn.input, job.input, `${fnId} input`);
|
|
483
|
+
},
|
|
484
|
+
};
|
|
485
|
+
}
|
|
486
|
+
/** An emitted event as jobs carry it: plain JSON, and copied, so what was emitted is what gets delivered. */
|
|
487
|
+
function envelopeOf(event: EventDef, payload: unknown, scope: object, depth: number): Envelope {
|
|
488
|
+
const name = idOf(event);
|
|
489
|
+
// a queue carries JSON: a Date or a class instance would work in-process and break only in production
|
|
490
|
+
assertPlain(payload, `${name} payload`, "Events travel through queues as JSON: send an ISO string and let the schema turn it into a Date");
|
|
491
|
+
return { id: crypto.randomUUID(), name, payload: structuredClone(payload), scope: storedScope(scope, `the scope emitting ${name}`), occurredAt: now().toISOString(), depth };
|
|
492
|
+
}
|
|
493
|
+
/** What a job keeps of the scope it runs as: `jobs.scope.store`'s pick, as a JSON copy. */
|
|
494
|
+
function storedScope(scope: object, what: string): object {
|
|
495
|
+
const stored = jobScope?.store ? jobScope.store(scope) : scope;
|
|
496
|
+
assertPlain(stored, what, "Jobs carry the scope through queues as JSON: keep it to ids (jobs.scope.store picks what's saved)");
|
|
497
|
+
return structuredClone(stored);
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
const actionCtx = (frame: Frame, id: string): ActionCtx<any> => ({
|
|
501
|
+
...baseCtx(frame, id, ["query", "mutation", "action"]),
|
|
502
|
+
signal: frame.signal,
|
|
503
|
+
services,
|
|
504
|
+
});
|
|
505
|
+
|
|
506
|
+
const { toJobs, deliver, jobs, due, checkHold, checkRetries, yours } = makeJobs({
|
|
507
|
+
listeners,
|
|
508
|
+
crons,
|
|
509
|
+
functions,
|
|
510
|
+
idOf,
|
|
511
|
+
jobsAdapter,
|
|
512
|
+
database,
|
|
513
|
+
jobScope,
|
|
514
|
+
failedStore,
|
|
515
|
+
maxEventDepth,
|
|
516
|
+
now,
|
|
517
|
+
wrap,
|
|
518
|
+
report,
|
|
519
|
+
runAs: (fn, input, scope, eventDepth, queued, job) => invoke(fn, input, enter({ scope, trail: [], eventDepth, queued, job }, undefined), ["query", "mutation", "action"]),
|
|
520
|
+
handlerCtx: (scope, eventDepth, id, queued) => actionCtx({ scope, trail: [id], eventDepth, queued }, id),
|
|
521
|
+
});
|
|
522
|
+
|
|
523
|
+
// ── invoke ───────────────────────────────────────────────────────────────
|
|
524
|
+
/** `callerModule`: set by ctx.run, so a private function (its index doesn't export it) runs as part of the module running it. */
|
|
525
|
+
async function invoke(fn: Fn, rawInput: unknown, outer: Frame, allowed: Kind[], callerModule?: string): Promise<any> {
|
|
526
|
+
// anything else that runs one finds it by name, and it has none: idOf throws, saying so
|
|
527
|
+
const id = ids.get(fn) ?? (callerModule ? `${callerModule}.${fn.id ?? PRIVATE}` : idOf(fn));
|
|
528
|
+
if (!allowed.includes(fn.kind))
|
|
529
|
+
throw new Error(`[logic-sdk] ${id} is a ${fn.kind}; it can't be run from here (allowed: ${allowed.join(", ")}).`);
|
|
530
|
+
const depth = outer.trail.length;
|
|
531
|
+
// a function that runs itself, through other modules or not, never returns: stop it with the path, not run out of memory
|
|
532
|
+
if (depth > MAX_RUN_DEPTH)
|
|
533
|
+
throw new Error(
|
|
534
|
+
`[logic-sdk] ctx.run nested past ${MAX_RUN_DEPTH} calls: … → ${[...outer.trail.slice(-6), id].join(" → ")}. ` +
|
|
535
|
+
"Recurse in a plain helper that takes ctx, or make each step separate work (an event, or ctx.schedule).",
|
|
536
|
+
);
|
|
537
|
+
const frame: Frame = { ...outer, trail: [...outer.trail, id] };
|
|
538
|
+
|
|
539
|
+
const call: Call = { id, kind: fn.kind, meta: fn.meta, input: rawInput, scope: frame.scope, depth };
|
|
540
|
+
if (depth === 0 && outer.job) call.job = outer.job; // the job's own call, not what it runs
|
|
541
|
+
|
|
542
|
+
/** Authorize, then validate, before any transaction opens: denied or bad calls never touch the database. */
|
|
543
|
+
const prepare = async () => {
|
|
544
|
+
frame.abortOn?.throwIfAborted();
|
|
545
|
+
if (fn.authorize) {
|
|
546
|
+
// SAFETY: the registry erases each policy's scope type; the caller's scope is the app's Scope by construction
|
|
547
|
+
if (fn.authorize(frame.scope as never) !== true) throw new DomainError("forbidden", forbiddenOf(id));
|
|
548
|
+
}
|
|
549
|
+
// no `input`: the function takes nothing, whatever an adapter sends (AI tools send `{}`)
|
|
550
|
+
return fn.input ? parseInput(fn.input, rawInput, id, depth > 0) : undefined;
|
|
551
|
+
};
|
|
552
|
+
const execute = async (input: unknown, ctx: unknown) => {
|
|
553
|
+
// SAFETY: the handler's types were erased when it was registered. `ctx` was built for its kind,
|
|
554
|
+
// and `input` just passed its own schema (or it takes none).
|
|
555
|
+
const handler = o.stubs?.get(fn) ?? fn.handler;
|
|
556
|
+
const out = await handler(ctx as never, input as never);
|
|
557
|
+
return fn.output ? parseOwn(fn.output, out, `${id} output`) : out;
|
|
558
|
+
};
|
|
559
|
+
|
|
560
|
+
return wrap(call, async () => {
|
|
561
|
+
if (fn.kind === "query") return execute(await prepare(), queryCtx(frame, id));
|
|
562
|
+
if (fn.kind === "action") return execute(await prepare(), actionCtx(frame, id));
|
|
563
|
+
|
|
564
|
+
// mutation joining an open transaction: any failure dooms it, even if the caller catches
|
|
565
|
+
if (frame.tx) {
|
|
566
|
+
const tx = frame.tx;
|
|
567
|
+
try {
|
|
568
|
+
return await execute(await prepare(), mutationCtx(frame, tx, id));
|
|
569
|
+
} catch (e) {
|
|
570
|
+
if (!tx.doomed) {
|
|
571
|
+
tx.doomed = true;
|
|
572
|
+
tx.reason = e;
|
|
573
|
+
tx.doomedBy = frame.trail.slice(tx.from);
|
|
574
|
+
}
|
|
575
|
+
throw e;
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
// top-level mutation: open the transaction, commit, then deliver events.
|
|
580
|
+
// createRegistry checks for one, but a private mutation isn't registered, so it can only be checked here
|
|
581
|
+
if (!database) throw new Error(noDatabase);
|
|
582
|
+
const input = await prepare();
|
|
583
|
+
const committed = await commitWithRetries(database, frame, id, (tx) => execute(input, mutationCtx({ ...frame, tx }, tx, id)));
|
|
584
|
+
|
|
585
|
+
// committed. Nothing below may fail the caller.
|
|
586
|
+
await afterCommit(committed.events, committed.jobs, frame.queued);
|
|
587
|
+
return committed.out;
|
|
588
|
+
});
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
/**
|
|
592
|
+
* A top-level mutation's transaction: run it, check nothing inside was caught and ignored, queue its jobs, commit. A
|
|
593
|
+
* lost race (deadlock, serialization failure) re-runs it in a fresh transaction, up to `transactionAttempts`.
|
|
594
|
+
*/
|
|
595
|
+
async function commitWithRetries(
|
|
596
|
+
database: DatabaseAdapter<unknown, unknown>,
|
|
597
|
+
frame: Frame,
|
|
598
|
+
id: string,
|
|
599
|
+
run: (tx: TxState) => Promise<unknown>,
|
|
600
|
+
): Promise<{ out: unknown; events: Envelope[]; jobs: Job[] }> {
|
|
601
|
+
for (let attempt = 1; ; attempt++) {
|
|
602
|
+
const attemptTx: { current?: TxState } = {};
|
|
603
|
+
try {
|
|
604
|
+
return await database.transaction(async (txDb) => {
|
|
605
|
+
// fresh per attempt, so a retry never reuses events from a failed attempt
|
|
606
|
+
const tx: TxState = {
|
|
607
|
+
db: txDb, doomed: false, reason: undefined, from: frame.trail.length - 1, doomedBy: undefined,
|
|
608
|
+
events: [], parsed: new Map(), calls: [], pending: [],
|
|
609
|
+
};
|
|
610
|
+
attemptTx.current = tx;
|
|
611
|
+
const out = await run(tx);
|
|
612
|
+
await Promise.all(tx.pending);
|
|
613
|
+
// a nested failure was caught: a bug, so its own error, with the failure as its cause (Ecto's aborted
|
|
614
|
+
// transaction). Retries still see a deadlock: `retryable` walks causes
|
|
615
|
+
if (tx.doomed) throw caughtNestedFailure(id, tx);
|
|
616
|
+
const jobs = toJobs(tx.events, tx.calls, tx.parsed);
|
|
617
|
+
if (jobs.length) await jobsAdapter.enqueue?.(txDb, jobs);
|
|
618
|
+
return { out, events: tx.events, jobs };
|
|
619
|
+
});
|
|
620
|
+
} catch (e) {
|
|
621
|
+
// a lost race dooms the transaction even when a caller caught it and went on: Postgres then fails the next
|
|
622
|
+
// statement with 25P02, or the caller throws its own error, and the race is still what to retry
|
|
623
|
+
const doomed = attemptTx.current?.doomed ? attemptTx.current.reason : undefined;
|
|
624
|
+
const lostRace = database.retryable?.(e) || (doomed !== undefined && database.retryable?.(doomed));
|
|
625
|
+
if (attempt < transactionAttempts && lostRace) {
|
|
626
|
+
// a random pause, so transactions that just deadlocked don't retry in lockstep and collide again
|
|
627
|
+
await new Promise((r) => setTimeout(r, Math.random() * 20 * attempt));
|
|
628
|
+
continue;
|
|
629
|
+
}
|
|
630
|
+
throw e;
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
async function afterCommit(emitted: Envelope[], jobs: Job[], queued: Job[] | undefined) {
|
|
636
|
+
try {
|
|
637
|
+
for (const e of emitted) o.record?.(e);
|
|
638
|
+
if (!jobs.length) return;
|
|
639
|
+
if (queued) return void queued.push(...jobs); // queued by a job: delivered once that job is settled
|
|
640
|
+
const delivery = deliver(jobs);
|
|
641
|
+
if (waitUntil) {
|
|
642
|
+
try {
|
|
643
|
+
waitUntil(delivery);
|
|
644
|
+
return;
|
|
645
|
+
} catch (e) {
|
|
646
|
+
report(e, { source: "(waitUntil)" });
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
await delivery;
|
|
650
|
+
} catch (e) {
|
|
651
|
+
report(e, { source: "(after commit)" });
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
return {
|
|
656
|
+
as: (scope) => ({
|
|
657
|
+
scope,
|
|
658
|
+
run: (fn: Fn, input?: unknown, options?: RunOptions) =>
|
|
659
|
+
invoke(fn, input, enter({ scope, trail: [], eventDepth: 0 }, options), ["query", "mutation", "action"]),
|
|
660
|
+
}),
|
|
661
|
+
definitions: { functions, events, listeners, crons },
|
|
662
|
+
idOf,
|
|
663
|
+
jobs,
|
|
664
|
+
[INTERNAL]: {
|
|
665
|
+
options,
|
|
666
|
+
derive: (more: Overrides) => build<S, Mods, Cf>(options, { ...o, ...more, config: mergeConfig(o.config, more.config) }),
|
|
667
|
+
envelope: (event, payload, scope) => envelopeOf(event, payload, scope, 1),
|
|
668
|
+
due,
|
|
669
|
+
},
|
|
670
|
+
};
|
|
671
|
+
}
|