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