logic-sdk 0.4.0 → 0.6.0
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 +40 -15
- package/bin/logic-sdk.js +1 -1
- package/dist/ai.d.ts +16 -26
- package/dist/ai.js +8 -21
- package/dist/cloudflare.d.ts +55 -0
- package/dist/cloudflare.js +85 -0
- package/dist/drizzle/pg.d.ts +236 -0
- package/dist/drizzle/pg.js +67 -0
- package/dist/drizzle/sqlite.d.ts +242 -0
- package/dist/drizzle/sqlite.js +194 -0
- package/dist/errors.d.ts +33 -0
- package/dist/errors.js +45 -0
- package/dist/fetch.d.ts +15 -18
- package/dist/fetch.js +18 -55
- package/dist/index.d.ts +78 -379
- package/dist/index.js +240 -186
- package/dist/jobs.d.ts +44 -0
- package/dist/jobs.js +252 -0
- package/dist/node.d.ts +26 -0
- package/dist/node.js +76 -0
- package/dist/orpc.d.ts +10 -17
- package/dist/orpc.js +19 -28
- package/dist/pg-boss.d.ts +55 -0
- package/dist/pg-boss.js +211 -0
- package/dist/postgres.d.ts +28 -0
- package/dist/postgres.js +82 -0
- package/dist/schedule.d.ts +23 -0
- package/dist/schedule.js +109 -0
- package/dist/sqlite.d.ts +9 -0
- package/dist/sqlite.js +65 -0
- package/dist/stored-jobs.d.ts +64 -0
- package/dist/stored-jobs.js +188 -0
- package/dist/testing.d.ts +50 -14
- package/dist/testing.js +198 -46
- package/dist/types.d.ts +655 -0
- package/dist/types.js +6 -0
- package/package.json +45 -7
- package/skills/logic-sdk/SKILL.md +114 -0
- package/src/ai.ts +23 -46
- package/src/cloudflare.ts +107 -0
- package/src/drizzle/pg.ts +110 -0
- package/src/drizzle/sqlite.ts +236 -0
- package/src/errors.ts +59 -0
- package/src/fetch.ts +17 -65
- package/src/index.ts +404 -564
- package/src/jobs.ts +296 -0
- package/src/node.ts +99 -0
- package/src/orpc.ts +24 -42
- package/src/pg-boss.ts +242 -0
- package/src/postgres.ts +90 -0
- package/src/schedule.ts +129 -0
- package/src/sqlite.ts +74 -0
- package/src/stored-jobs.ts +260 -0
- package/src/testing.ts +252 -55
- package/src/types.ts +685 -0
- package/dist/drizzle.d.ts +0 -18
- package/dist/drizzle.js +0 -23
- package/src/drizzle.ts +0 -39
package/dist/index.js
CHANGED
|
@@ -1,67 +1,22 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
export class DomainError extends Error {
|
|
8
|
-
kind;
|
|
9
|
-
code;
|
|
10
|
-
details;
|
|
11
|
-
constructor(kind, code, details) {
|
|
12
|
-
// the details are in the message too: logs and AI tool errors (which show only the message) stay useful
|
|
13
|
-
super(details === undefined ? code : `${code} ${JSON.stringify(details)}`);
|
|
14
|
-
this.name = "DomainError";
|
|
15
|
-
this.kind = kind;
|
|
16
|
-
this.code = code;
|
|
17
|
-
this.details = details;
|
|
18
|
-
}
|
|
19
|
-
}
|
|
20
|
-
/** `isDomainError(e)`, or with a code: `isDomainError(e, "availability.dates_unavailable")`. */
|
|
21
|
-
export const isDomainError = (e, code) => e instanceof DomainError && (code === undefined || e.code === code);
|
|
22
|
-
/** `ctx.errors` for one function or listener (`id` like "bookings.confirm"). */
|
|
23
|
-
const errorsFor = (id) => {
|
|
24
|
-
const module = id.slice(0, id.indexOf("."));
|
|
25
|
-
return {
|
|
26
|
-
reject: (code, details) => new DomainError("rejected", `${module}.${code}`, details),
|
|
27
|
-
conflict: (code, details) => new DomainError("conflict", `${module}.${code}`, details),
|
|
28
|
-
notFound: (code = "not_found", details) => new DomainError("not_found", `${module}.${code}`, details),
|
|
29
|
-
deny: (code, details) => new DomainError("forbidden", code ? `${module}.${code}` : `${id}.forbidden`, details),
|
|
30
|
-
};
|
|
31
|
-
};
|
|
32
|
-
/** Default dispatcher: delivers right after commit, in this process. Lost on crash: use an outbox when that matters. */
|
|
33
|
-
export const inProcess = () => ({
|
|
34
|
-
async deliver(envelopes, dispatch) {
|
|
35
|
-
for (const e of envelopes)
|
|
36
|
-
await dispatch(e);
|
|
37
|
-
},
|
|
38
|
-
});
|
|
1
|
+
import { describeIssues, DomainError, errorsFor } from "./errors.js";
|
|
2
|
+
import { inProcess, makeJobs, replaceKeyOf, runsNow } from "./jobs.js";
|
|
3
|
+
import { assertTimeZone, parseSchedule } from "./schedule.js";
|
|
4
|
+
import { BRAND, INTERNAL } from "./types.js";
|
|
5
|
+
export { DomainError, isDomainError, unauthenticated } from "./errors.js";
|
|
6
|
+
export { inProcess, replaceKeyOf } from "./jobs.js";
|
|
39
7
|
/**
|
|
40
8
|
* Typed constructors for your app:
|
|
41
9
|
*
|
|
42
10
|
* ```ts
|
|
43
|
-
* export const { query, mutation, action, event,
|
|
11
|
+
* export const { query, mutation, action, event, listener, createRegistry } = init<Config>();
|
|
44
12
|
* ```
|
|
45
13
|
*/
|
|
46
14
|
export function init() {
|
|
47
|
-
// One implementation behind the typed
|
|
48
|
-
const make = (kind) => (def) => {
|
|
49
|
-
const where = def?.description ? `"${def.description}"` : `a ${kind}`;
|
|
50
|
-
if (def.authorize !== undefined && typeof def.authorize !== "function")
|
|
51
|
-
throw new Error(`[logic-sdk] authorize on ${where} must be a policy function, like \`authorize: member\`.`);
|
|
52
|
-
if (def.expose !== undefined && def.expose !== true)
|
|
53
|
-
throw new Error(`[logic-sdk] expose on ${where} must be \`true\` or left out.`);
|
|
54
|
-
if (def.expose && !def.authorize)
|
|
55
|
-
throw new Error(`[logic-sdk] ${where} has expose: true but no authorize. Say who may call it.`);
|
|
56
|
-
if (def.expose && !def.output)
|
|
57
|
-
throw new Error(`[logic-sdk] ${where} has expose: true but no output. Say what callers may see.`);
|
|
58
|
-
if (typeof def.handler !== "function")
|
|
59
|
-
throw new Error(`[logic-sdk] ${where} needs a handler(ctx, input).`);
|
|
60
|
-
return Object.freeze({ [BRAND]: kind, kind, ...def });
|
|
61
|
-
};
|
|
15
|
+
// One implementation behind the typed signature of `Constructor`: the types are the contract, the adapters check `authorize`.
|
|
16
|
+
const make = (kind) => (def) => Object.freeze({ [BRAND]: kind, kind, ...def });
|
|
62
17
|
return {
|
|
63
18
|
/** Create the registry once at startup: `createRegistry({ modules, database, services })`. */
|
|
64
|
-
createRegistry: (options) => build(options, {}), // meta in wrap is typed by
|
|
19
|
+
createRegistry: (options) => build(options, {}), // meta in wrap is typed by CallMetaOf<C>; the values come from typed defs
|
|
65
20
|
/** Reads data. Can run other queries. No writes, no events, no services. */
|
|
66
21
|
query: make("query"),
|
|
67
22
|
/** Changes data inside one transaction. Can run queries and mutations (same transaction) and emit events. */
|
|
@@ -70,20 +25,39 @@ export function init() {
|
|
|
70
25
|
action: make("action"),
|
|
71
26
|
/** Something that happened. Emitted by mutations, delivered after commit. */
|
|
72
27
|
event: (def) => Object.freeze({ [BRAND]: "event", kind: "event", ...def }),
|
|
73
|
-
/**
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
28
|
+
/**
|
|
29
|
+
* Run a function on a schedule, as `scope` (a cron has no caller). Export it from a module, like listeners, and call
|
|
30
|
+
* `registry.jobs.tick()` every minute (or from your platform's cron trigger):
|
|
31
|
+
* `cron({ schedule: "0 9 * * 1", run: () => reports.sendWeekly, scope: system })`.
|
|
32
|
+
*/
|
|
33
|
+
cron: (def) => {
|
|
34
|
+
const { id, schedule, timezone, run, input, scope, attempts } = def;
|
|
35
|
+
parseSchedule(schedule);
|
|
36
|
+
if (timezone !== undefined)
|
|
37
|
+
assertTimeZone(timezone);
|
|
38
|
+
checkAttempts("cron", attempts);
|
|
39
|
+
return Object.freeze({ [BRAND]: "cron", kind: "cron", id, schedule, timezone, run, input, scope, attempts });
|
|
40
|
+
},
|
|
41
|
+
/**
|
|
42
|
+
* React to an event after commit, like an action. Must be idempotent.
|
|
43
|
+
* `listener({ event: () => bookings.confirmed, async handler(ctx, payload) {…} })`
|
|
44
|
+
*/
|
|
45
|
+
listener: (def) => {
|
|
46
|
+
const { id, event, attempts, delay, when, meta, handler } = def;
|
|
47
|
+
checkAttempts("listener", attempts);
|
|
48
|
+
if (delay !== undefined && !(Number.isFinite(delay) && delay >= 0))
|
|
49
|
+
throw new Error(`[logic-sdk] listener delay must be seconds, 0 or more (got ${delay}).`);
|
|
50
|
+
// meta is checked against ListenerMetaOf<C> above and stored loose, like Fn.meta, for wrap and adapters
|
|
51
|
+
return Object.freeze({ [BRAND]: "listener", kind: "listener", id, event, attempts, delay, when, meta: meta, handler });
|
|
52
|
+
},
|
|
81
53
|
};
|
|
82
54
|
}
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
55
|
+
/** How deep `ctx.run` calls may nest. Past it, a function is running itself without end. */
|
|
56
|
+
const MAX_RUN_DEPTH = 64;
|
|
57
|
+
function checkAttempts(what, attempts) {
|
|
58
|
+
if (attempts !== undefined && !(Number.isInteger(attempts) && attempts >= 1))
|
|
59
|
+
throw new Error(`[logic-sdk] ${what} attempts must be a whole number of tries, 1 or more (got ${attempts}).`);
|
|
60
|
+
}
|
|
87
61
|
/** Create the registry once at startup. Prefer the `createRegistry` returned by `init()`: it's typed with your config. */
|
|
88
62
|
export function createRegistry(options) {
|
|
89
63
|
return build(options, {});
|
|
@@ -98,59 +72,112 @@ function mergeConfig(base, patch) {
|
|
|
98
72
|
const keys = new Set([...Object.keys(base), ...Object.keys(patch)]);
|
|
99
73
|
return Object.fromEntries([...keys].map((k) => [k, mergeConfig(base[k], patch[k])])); // fromEntries: `__proto__` stays a key
|
|
100
74
|
}
|
|
75
|
+
/** A frozen copy of plain data, so settings can't change under everyone else or hide behavior (a client, a class). */
|
|
76
|
+
function freezeConfig(value) {
|
|
77
|
+
assertPlain(value, "config", "config holds plain data: pass a Date as an ISO string, and put clients in services");
|
|
78
|
+
const freeze = (v) => {
|
|
79
|
+
if (v && typeof v === "object") {
|
|
80
|
+
for (const item of Object.values(v))
|
|
81
|
+
freeze(item);
|
|
82
|
+
Object.freeze(v);
|
|
83
|
+
}
|
|
84
|
+
return v;
|
|
85
|
+
};
|
|
86
|
+
return freeze(structuredClone(value));
|
|
87
|
+
}
|
|
101
88
|
/**
|
|
102
|
-
*
|
|
103
|
-
* a
|
|
89
|
+
* Plain data, what survives JSON: plain objects, arrays, strings, finite numbers, booleans, null (undefined is dropped).
|
|
90
|
+
* Anything else (a Date, a Map, a class instance, a function, a cycle) is rejected with its path.
|
|
104
91
|
*/
|
|
105
|
-
function
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
92
|
+
function assertPlain(value, what, hint) {
|
|
93
|
+
const seen = new Set();
|
|
94
|
+
const check = (v, path) => {
|
|
95
|
+
const fail = (found) => {
|
|
96
|
+
throw new Error(`[logic-sdk] ${what} isn't plain data${path ? ` at ${path}` : ""}: ${found}. ${hint}.`);
|
|
97
|
+
};
|
|
98
|
+
if (v === null || v === undefined || typeof v === "string" || typeof v === "boolean")
|
|
99
|
+
return;
|
|
100
|
+
if (typeof v === "number") {
|
|
101
|
+
if (!Number.isFinite(v))
|
|
102
|
+
fail(String(v));
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
if (typeof v !== "object")
|
|
106
|
+
return fail(`a ${typeof v}`);
|
|
107
|
+
if (seen.has(v))
|
|
108
|
+
fail("a circular reference");
|
|
109
|
+
seen.add(v);
|
|
110
|
+
if (Array.isArray(v))
|
|
111
|
+
v.forEach((item, i) => check(item, `${path}[${i}]`));
|
|
112
|
+
else {
|
|
113
|
+
if (!isPlain(v))
|
|
114
|
+
fail(`a ${v.constructor?.name ?? "class instance"}`);
|
|
115
|
+
for (const [k, item] of Object.entries(v))
|
|
116
|
+
check(item, path ? `${path}.${k}` : k);
|
|
117
|
+
}
|
|
118
|
+
seen.delete(v);
|
|
119
|
+
};
|
|
120
|
+
check(value, "");
|
|
115
121
|
}
|
|
116
|
-
const describeIssues = (issues) => issues.map((i) => ({ message: i.message, path: i.path?.map((p) => (typeof p === "object" ? p.key : p)) }));
|
|
117
122
|
const isBranded = (v) => !!v && typeof v === "object" && BRAND in v;
|
|
118
123
|
/**
|
|
119
|
-
* What `createRegistry` finds in your modules, without a database or services: every function, event and
|
|
120
|
-
*
|
|
124
|
+
* What `createRegistry` finds in your modules, without a database or services: every function, event, listener and
|
|
125
|
+
* cron with its id. For tools (the CLI, docs generators) that inspect an app without running it.
|
|
121
126
|
*/
|
|
122
127
|
export function describeModules(modules) {
|
|
123
128
|
const ids = new Map();
|
|
124
129
|
const functions = [];
|
|
125
130
|
const events = [];
|
|
126
131
|
const listeners = [];
|
|
132
|
+
const crons = [];
|
|
133
|
+
const taken = new Map();
|
|
127
134
|
for (const [module, ns] of Object.entries(modules)) {
|
|
128
135
|
for (const [name, value] of Object.entries(ns)) {
|
|
129
136
|
if (!isBranded(value) || ids.has(value))
|
|
130
137
|
continue;
|
|
131
|
-
const
|
|
138
|
+
const local = value.id ?? name;
|
|
139
|
+
if (value.id !== undefined && (typeof value.id !== "string" || !/^[A-Za-z0-9_-]+$/.test(value.id)))
|
|
140
|
+
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>.`);
|
|
141
|
+
const id = `${module}.${local}`;
|
|
142
|
+
const other = taken.get(id);
|
|
143
|
+
if (other)
|
|
144
|
+
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.`);
|
|
145
|
+
taken.set(id, name);
|
|
132
146
|
ids.set(value, id);
|
|
133
147
|
if (value.kind === "event")
|
|
134
148
|
events.push({ id, module, name, event: value });
|
|
135
149
|
else if (value.kind === "listener")
|
|
136
150
|
listeners.push({ id, module, name, listener: value, event: value.event() });
|
|
151
|
+
else if (value.kind === "cron")
|
|
152
|
+
crons.push({ id, module, name, cron: value, run: value.run() });
|
|
137
153
|
else
|
|
138
|
-
functions.push({ id, module, name, kind: value.kind, fn: value
|
|
154
|
+
functions.push({ id, module, name, kind: value.kind, fn: value });
|
|
139
155
|
}
|
|
140
156
|
}
|
|
141
|
-
return { ids, functions, events, listeners };
|
|
157
|
+
return { ids, functions, events, listeners, crons };
|
|
142
158
|
}
|
|
143
159
|
function build(options, o) {
|
|
144
|
-
const { ids, functions, events, listeners } = describeModules(options.modules);
|
|
160
|
+
const { ids, functions, events, listeners, crons } = describeModules(options.modules);
|
|
145
161
|
const database = o.database ?? options.database;
|
|
146
162
|
const services = o.services ?? options.services ?? {};
|
|
147
163
|
const config = freezeConfig(mergeConfig(options.config ?? {}, o.config));
|
|
148
|
-
const
|
|
164
|
+
const jobsAdapter = o.adapter ?? options.jobs?.adapter ?? inProcess();
|
|
165
|
+
const jobScope = options.jobs?.scope;
|
|
166
|
+
if (jobScope?.store && !jobScope.load)
|
|
167
|
+
throw new Error("[logic-sdk] jobs.scope has store but no load. Jobs run as a scope, so rebuild it from what store saved.");
|
|
168
|
+
// a job any adapter but inProcess() keeps runs as a scope saved earlier: rebuild it, or its roles are the ones from
|
|
169
|
+
// back then (AshOban's actor_persister). The app's adapter, so a test registry agrees with the app it wraps.
|
|
170
|
+
const appAdapter = options.jobs?.adapter;
|
|
171
|
+
if (appAdapter && !runsNow(appAdapter) && !jobScope?.load)
|
|
172
|
+
throw new Error("[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 " +
|
|
173
|
+
"roles (null discards the job). Add `store` to save only ids. To keep the scope as it was, `load: (saved) => saved`.");
|
|
149
174
|
const now = o.now ?? options.now ?? (() => new Date());
|
|
150
175
|
const wrap = options.wrap ?? ((_c, next) => next());
|
|
151
|
-
const maxEventDepth = options.maxEventDepth ?? 8;
|
|
152
|
-
|
|
153
|
-
const
|
|
176
|
+
const maxEventDepth = options.jobs?.maxEventDepth ?? 8;
|
|
177
|
+
checkAttempts("database transaction", options.database?.transactionAttempts);
|
|
178
|
+
const transactionAttempts = options.database?.transactionAttempts ?? 3; // the app's, so a test's nested adapter keeps it
|
|
179
|
+
const waitUntil = "waitUntil" in o ? o.waitUntil : options.waitUntil; // tests turn it off: listeners finish inside the test
|
|
180
|
+
const reportRaw = o.onError ?? options.onError ?? ((e, info) => console.error(`[logic-sdk] ${info.source} failed`, e));
|
|
154
181
|
const report = (e, info) => {
|
|
155
182
|
try {
|
|
156
183
|
reportRaw(e, info);
|
|
@@ -159,12 +186,13 @@ function build(options, o) {
|
|
|
159
186
|
console.error("[logic-sdk] onError threw", inner, "while reporting", e);
|
|
160
187
|
}
|
|
161
188
|
};
|
|
162
|
-
if (functions.some((f) => f.kind === "mutation")
|
|
163
|
-
throw new Error("[logic-sdk] Mutations need a database
|
|
164
|
-
"
|
|
189
|
+
if (!database && functions.some((f) => f.kind === "mutation"))
|
|
190
|
+
throw new Error("[logic-sdk] Mutations need a database: createRegistry({ database: drizzleAdapter(db) }). It needs interactive " +
|
|
191
|
+
"transactions, so Cloudflare D1 and HTTP drivers can't run mutations.");
|
|
165
192
|
for (const l of listeners)
|
|
166
|
-
if (!
|
|
193
|
+
if (!ids.has(l.event))
|
|
167
194
|
throw new Error(`[logic-sdk] Listener ${l.id} listens to an event that isn't registered in any module.`);
|
|
195
|
+
jobsAdapter.check?.({ listeners, database });
|
|
168
196
|
const idOf = (x) => {
|
|
169
197
|
const id = ids.get(x);
|
|
170
198
|
if (!id)
|
|
@@ -188,47 +216,21 @@ function build(options, o) {
|
|
|
188
216
|
throw new Error(`[logic-sdk] ${what} is invalid: ${JSON.stringify(describeIssues(r.issues))}`);
|
|
189
217
|
return r.value;
|
|
190
218
|
}
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
219
|
+
/** What our own code passed a mutation's ctx, checked by the time it commits: a bad value fails the commit. */
|
|
220
|
+
function checkAtCommit(tx, schema, value, what, keep) {
|
|
221
|
+
const check = parseOwn(schema, value, what).then((parsed) => keep?.(parsed));
|
|
222
|
+
check.catch(() => { }); // surfaced at commit; never an unhandled rejection
|
|
223
|
+
tx.pending.push(check);
|
|
196
224
|
}
|
|
197
|
-
const
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
const event = eventByName.get(envelope.name);
|
|
202
|
-
for (const l of byEvent.get(envelope.name) ?? []) {
|
|
203
|
-
const frame = { scope: envelope.scope, depth: 0, eventDepth };
|
|
204
|
-
try {
|
|
205
|
-
await wrap({ id: l.id, kind: "listener", meta: undefined, input: envelope.payload, scope: envelope.scope, depth: 0 }, async () => {
|
|
206
|
-
const payload = event ? await parseOwn(event.payload, envelope.payload, `${envelope.name} payload`) : envelope.payload;
|
|
207
|
-
return l.listener.handler({ ...actionCtx(frame, l.id), event: { ...envelope, payload } }, payload); // SAFETY: as in invoke
|
|
208
|
-
});
|
|
209
|
-
}
|
|
210
|
-
catch (error) {
|
|
211
|
-
failures.push({ listener: l.id, error });
|
|
212
|
-
}
|
|
213
|
-
}
|
|
214
|
-
return failures;
|
|
215
|
-
}
|
|
216
|
-
/** In-process delivery: failures go to onError. */
|
|
217
|
-
const deliverOne = (eventDepth) => async (envelope) => {
|
|
218
|
-
for (const f of await runListeners(envelope, eventDepth))
|
|
219
|
-
report(f.error, { listener: f.listener, envelope });
|
|
220
|
-
};
|
|
221
|
-
/** Public: for durable dispatchers. Throws an AggregateError if any listener failed, so the consumer can retry. */
|
|
222
|
-
async function dispatch(envelope) {
|
|
223
|
-
const failures = await runListeners(envelope, 1);
|
|
224
|
-
if (failures.length)
|
|
225
|
-
throw new AggregateError(failures.map((f) => f.error), `[logic-sdk] ${failures.length} listener(s) failed for ${envelope.name}: ${failures.map((f) => f.listener).join(", ")}`);
|
|
225
|
+
for (const c of crons) {
|
|
226
|
+
if (!ids.has(c.run))
|
|
227
|
+
throw new Error(`[logic-sdk] Cron ${c.id} runs a function that isn't registered. Export it from its module's index.ts.`);
|
|
228
|
+
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");
|
|
226
229
|
}
|
|
227
230
|
// ── ctx ──────────────────────────────────────────────────────────────────
|
|
228
|
-
/** The frame a call
|
|
231
|
+
/** The frame for a call from here: its scope patch and signal. `invoke` adds the call to the trail. */
|
|
229
232
|
const enter = (frame, options) => ({
|
|
230
233
|
...frame,
|
|
231
|
-
depth: frame.depth + 1,
|
|
232
234
|
scope: options?.scope ? { ...frame.scope, ...options.scope } : frame.scope,
|
|
233
235
|
signal: options?.signal ?? frame.signal,
|
|
234
236
|
abortOn: options?.signal,
|
|
@@ -245,53 +247,115 @@ function build(options, o) {
|
|
|
245
247
|
...baseCtx(frame, id, ["query"]),
|
|
246
248
|
db: frame.tx ? frame.tx.db : database?.db,
|
|
247
249
|
});
|
|
248
|
-
function mutationCtx(frame, id) {
|
|
249
|
-
const tx = frame.tx;
|
|
250
|
+
function mutationCtx(frame, tx, id) {
|
|
250
251
|
return {
|
|
251
252
|
...baseCtx(frame, id, ["query", "mutation"]),
|
|
252
253
|
db: tx.db,
|
|
253
254
|
emit: (event, payload) => {
|
|
254
|
-
const name = idOf(event);
|
|
255
|
-
payload = structuredClone(payload); // what was emitted is what gets delivered, even if the caller mutates it after
|
|
256
255
|
// reserve the slot now so events keep emit order, even with async schemas
|
|
257
|
-
const envelope =
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
256
|
+
const envelope = envelopeOf(event, payload, frame.scope, frame.eventDepth + 1);
|
|
257
|
+
tx.events.push(envelope);
|
|
258
|
+
checkAtCommit(tx, event.payload, envelope.payload, `${envelope.name} payload`, (parsed) => tx.parsed.set(envelope, parsed));
|
|
259
|
+
},
|
|
260
|
+
schedule: (fn, input, { at, delay, attempts = 1, replace }) => {
|
|
261
|
+
const fnId = idOf(fn);
|
|
262
|
+
const seconds = at ? (at.getTime() - now().getTime()) / 1000 : (delay ?? NaN);
|
|
263
|
+
if (!Number.isFinite(seconds) || (!at && seconds < 0))
|
|
264
|
+
throw new Error(`[logic-sdk] ctx.schedule(${fnId}) needs an \`at\` date or a \`delay\` in seconds, 0 or more.`);
|
|
265
|
+
checkAttempts(`ctx.schedule(${fnId})`, attempts);
|
|
266
|
+
if (replace !== undefined) {
|
|
267
|
+
if (!replace)
|
|
268
|
+
throw new Error(`[logic-sdk] ctx.schedule(${fnId}) replace must be a non-empty key.`);
|
|
269
|
+
if (!jobsAdapter.replaces)
|
|
270
|
+
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.`);
|
|
271
|
+
}
|
|
272
|
+
// due now (no delay, or an `at` already past): runs after commit like a listener, no holding needed
|
|
273
|
+
const waits = seconds > 0;
|
|
274
|
+
if (waits)
|
|
275
|
+
checkHold(`ctx.schedule(${fnId})`, seconds);
|
|
276
|
+
assertPlain(input, `${fnId} input`, "Scheduled calls wait as JSON: send an ISO string and let the schema turn it into a Date");
|
|
277
|
+
const job = {
|
|
278
|
+
kind: "call",
|
|
279
|
+
id: `${fnId}@${crypto.randomUUID()}`,
|
|
280
|
+
fn: fnId,
|
|
281
|
+
input: structuredClone(input),
|
|
282
|
+
scope: storedScope(frame.scope, `the scope scheduling ${fnId}`),
|
|
283
|
+
attempts,
|
|
284
|
+
depth: waits ? 0 : frame.eventDepth + 1, // due now, it's the next hop of this chain; a real wait starts a new one
|
|
263
285
|
};
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
286
|
+
if (waits)
|
|
287
|
+
job.runAt = new Date(now().getTime() + seconds * 1000).toISOString();
|
|
288
|
+
if (replace !== undefined) {
|
|
289
|
+
job.replace = replace;
|
|
290
|
+
// scheduled twice in this transaction: the later one wins here too (the dropped one's input is still checked:
|
|
291
|
+
// a bad input is a bug wherever it is)
|
|
292
|
+
const earlier = tx.calls.findIndex((c) => replaceKeyOf(c) === replaceKeyOf(job));
|
|
293
|
+
if (earlier >= 0)
|
|
294
|
+
tx.calls.splice(earlier, 1);
|
|
295
|
+
}
|
|
296
|
+
tx.calls.push(job);
|
|
297
|
+
// our own code passed it: a bad input is a bug, surfaced at commit like an event's payload
|
|
298
|
+
if (fn.input)
|
|
299
|
+
checkAtCommit(tx, fn.input, job.input, `${fnId} input`);
|
|
300
|
+
return job.id;
|
|
268
301
|
},
|
|
269
302
|
};
|
|
270
303
|
}
|
|
304
|
+
/** An emitted event as jobs carry it: plain JSON, and copied, so what was emitted is what gets delivered. */
|
|
305
|
+
function envelopeOf(event, payload, scope, depth) {
|
|
306
|
+
const name = idOf(event);
|
|
307
|
+
// a queue carries JSON: a Date or a class instance would work in-process and break only in production
|
|
308
|
+
assertPlain(payload, `${name} payload`, "Events travel through queues as JSON: send an ISO string and let the schema turn it into a Date");
|
|
309
|
+
return { id: crypto.randomUUID(), name, payload: structuredClone(payload), scope: storedScope(scope, `the scope emitting ${name}`), occurredAt: now().toISOString(), depth };
|
|
310
|
+
}
|
|
311
|
+
/** What a job keeps of the scope it runs as: `jobs.scope.store`'s pick, as a JSON copy. */
|
|
312
|
+
function storedScope(scope, what) {
|
|
313
|
+
const stored = jobScope?.store ? jobScope.store(scope) : scope;
|
|
314
|
+
assertPlain(stored, what, "Jobs carry the scope through queues as JSON: keep it to ids (jobs.scope.store picks what's saved)");
|
|
315
|
+
return structuredClone(stored);
|
|
316
|
+
}
|
|
271
317
|
const actionCtx = (frame, id) => ({
|
|
272
318
|
...baseCtx(frame, id, ["query", "mutation", "action"]),
|
|
273
319
|
signal: frame.signal,
|
|
274
320
|
services,
|
|
275
321
|
});
|
|
322
|
+
const { toJobs, deliver, jobs, due, checkHold } = makeJobs({
|
|
323
|
+
listeners,
|
|
324
|
+
crons,
|
|
325
|
+
functions,
|
|
326
|
+
idOf,
|
|
327
|
+
jobsAdapter,
|
|
328
|
+
database,
|
|
329
|
+
jobScope,
|
|
330
|
+
maxEventDepth,
|
|
331
|
+
now,
|
|
332
|
+
wrap,
|
|
333
|
+
report,
|
|
334
|
+
runAs: (fn, input, scope, eventDepth, queued) => invoke(fn, input, enter({ scope, trail: [], eventDepth, queued }, undefined), ["query", "mutation", "action"]),
|
|
335
|
+
listenerCtx: (scope, eventDepth, id, queued) => actionCtx({ scope, trail: [id], eventDepth, queued }, id),
|
|
336
|
+
});
|
|
276
337
|
// ── invoke ───────────────────────────────────────────────────────────────
|
|
277
|
-
async function invoke(fn, rawInput,
|
|
338
|
+
async function invoke(fn, rawInput, outer, allowed) {
|
|
278
339
|
const id = idOf(fn);
|
|
279
340
|
if (!allowed.includes(fn.kind))
|
|
280
341
|
throw new Error(`[logic-sdk] ${id} is a ${fn.kind}; it can't be run from here (allowed: ${allowed.join(", ")}).`);
|
|
281
|
-
const
|
|
342
|
+
const depth = outer.trail.length;
|
|
343
|
+
// a function that runs itself, through other modules or not, never returns: stop it with the path, not run out of memory
|
|
344
|
+
if (depth > MAX_RUN_DEPTH)
|
|
345
|
+
throw new Error(`[logic-sdk] ctx.run nested past ${MAX_RUN_DEPTH} calls: … → ${[...outer.trail.slice(-6), id].join(" → ")}. ` +
|
|
346
|
+
"Recurse in a plain helper that takes ctx, or make each step separate work (an event, or ctx.schedule).");
|
|
347
|
+
const frame = { ...outer, trail: [...outer.trail, id] };
|
|
348
|
+
const call = { id, kind: fn.kind, meta: fn.meta, input: rawInput, scope: frame.scope, depth };
|
|
282
349
|
/** Authorize, then validate, before any transaction opens: denied or bad calls never touch the database. */
|
|
283
350
|
const prepare = async () => {
|
|
284
351
|
frame.abortOn?.throwIfAborted();
|
|
285
352
|
if (fn.authorize) {
|
|
286
353
|
// SAFETY: the registry erases each policy's scope type; the caller's scope is the app's Scope by construction
|
|
287
|
-
|
|
288
|
-
if (verdict instanceof Promise)
|
|
289
|
-
throw new Error(`[logic-sdk] The policy on ${id} returned a Promise. Policies are sync and read only the scope.`);
|
|
290
|
-
if (verdict !== true)
|
|
354
|
+
if (fn.authorize(frame.scope) !== true)
|
|
291
355
|
throw new DomainError("forbidden", `${id}.forbidden`);
|
|
292
356
|
}
|
|
293
357
|
// no `input`: the function takes nothing, whatever an adapter sends (AI tools send `{}`)
|
|
294
|
-
return fn.input ? parseInput(fn.input, rawInput, id,
|
|
358
|
+
return fn.input ? parseInput(fn.input, rawInput, id, depth > 0) : undefined;
|
|
295
359
|
};
|
|
296
360
|
const execute = async (input, ctx) => {
|
|
297
361
|
// SAFETY: the handler's types were erased when it was registered. `ctx` was built for its kind,
|
|
@@ -309,7 +373,7 @@ function build(options, o) {
|
|
|
309
373
|
if (frame.tx) {
|
|
310
374
|
const tx = frame.tx;
|
|
311
375
|
try {
|
|
312
|
-
return await execute(await prepare(), mutationCtx(frame, id));
|
|
376
|
+
return await execute(await prepare(), mutationCtx(frame, tx, id));
|
|
313
377
|
}
|
|
314
378
|
catch (e) {
|
|
315
379
|
if (!tx.doomed) {
|
|
@@ -324,84 +388,74 @@ function build(options, o) {
|
|
|
324
388
|
const input = await prepare();
|
|
325
389
|
let committed;
|
|
326
390
|
for (let attempt = 1;; attempt++) {
|
|
327
|
-
let state;
|
|
328
391
|
try {
|
|
392
|
+
// SAFETY: createRegistry refuses mutations without a database that has interactive transactions
|
|
329
393
|
committed = await database.transaction(async (txDb) => {
|
|
330
394
|
// fresh per attempt, so a retry never reuses events from a failed attempt
|
|
331
|
-
const tx =
|
|
332
|
-
const out = await execute(input, mutationCtx({ ...frame, tx }, id));
|
|
395
|
+
const tx = { db: txDb, doomed: false, reason: undefined, events: [], parsed: new Map(), calls: [], pending: [] };
|
|
396
|
+
const out = await execute(input, mutationCtx({ ...frame, tx }, tx, id));
|
|
333
397
|
await Promise.all(tx.pending);
|
|
334
398
|
if (tx.doomed)
|
|
335
399
|
throw tx.reason;
|
|
336
|
-
|
|
337
|
-
|
|
400
|
+
const jobs = toJobs(tx.events, tx.calls, tx.parsed);
|
|
401
|
+
if (jobs.length)
|
|
402
|
+
await jobsAdapter.enqueue?.(txDb, jobs);
|
|
403
|
+
return { out, events: tx.events, jobs };
|
|
338
404
|
});
|
|
339
405
|
break;
|
|
340
406
|
}
|
|
341
407
|
catch (e) {
|
|
342
|
-
if (attempt <
|
|
408
|
+
if (attempt < transactionAttempts && database.retryable?.(e)) { // SAFETY: as above
|
|
343
409
|
// a random pause, so transactions that just deadlocked don't retry in lockstep and collide again
|
|
344
410
|
await new Promise((r) => setTimeout(r, Math.random() * 20 * attempt));
|
|
345
411
|
continue;
|
|
346
412
|
}
|
|
347
413
|
throw e;
|
|
348
414
|
}
|
|
349
|
-
finally {
|
|
350
|
-
if (state)
|
|
351
|
-
await Promise.allSettled(state.pending);
|
|
352
|
-
}
|
|
353
415
|
}
|
|
354
416
|
// committed. Nothing below may fail the caller.
|
|
355
|
-
|
|
356
|
-
await afterCommit(committed.outbox, frame);
|
|
417
|
+
await afterCommit(committed.events, committed.jobs, frame.queued);
|
|
357
418
|
return committed.out;
|
|
358
419
|
});
|
|
359
420
|
}
|
|
360
|
-
async function afterCommit(
|
|
421
|
+
async function afterCommit(emitted, jobs, queued) {
|
|
361
422
|
try {
|
|
362
|
-
for (const e of
|
|
423
|
+
for (const e of emitted)
|
|
363
424
|
o.record?.(e);
|
|
364
|
-
|
|
365
|
-
if (eventDepth > maxEventDepth) {
|
|
366
|
-
report(new Error(`[logic-sdk] event chain deeper than ${maxEventDepth}: stopped delivering (listener loop?)`), {
|
|
367
|
-
listener: "(dispatcher)",
|
|
368
|
-
envelope: outbox[0],
|
|
369
|
-
});
|
|
425
|
+
if (!jobs.length)
|
|
370
426
|
return;
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
427
|
+
if (queued)
|
|
428
|
+
return void queued.push(...jobs); // queued by a job: delivered once that job is settled
|
|
429
|
+
const delivery = deliver(jobs);
|
|
430
|
+
if (waitUntil) {
|
|
374
431
|
try {
|
|
375
|
-
|
|
432
|
+
waitUntil(delivery);
|
|
376
433
|
return;
|
|
377
434
|
}
|
|
378
435
|
catch (e) {
|
|
379
|
-
report(e, {
|
|
436
|
+
report(e, { source: "(waitUntil)" });
|
|
380
437
|
}
|
|
381
438
|
}
|
|
382
439
|
await delivery;
|
|
383
440
|
}
|
|
384
441
|
catch (e) {
|
|
385
|
-
report(e, {
|
|
442
|
+
report(e, { source: "(after commit)" });
|
|
386
443
|
}
|
|
387
444
|
}
|
|
388
445
|
return {
|
|
389
|
-
modules: options.modules,
|
|
390
446
|
as: (scope) => ({
|
|
391
447
|
scope,
|
|
392
|
-
run: (fn, input, options) => invoke(fn, input, enter({ scope,
|
|
448
|
+
run: (fn, input, options) => invoke(fn, input, enter({ scope, trail: [], eventDepth: 0 }, options), ["query", "mutation", "action"]),
|
|
393
449
|
}),
|
|
394
|
-
functions,
|
|
395
|
-
events,
|
|
396
|
-
listeners,
|
|
450
|
+
definitions: { functions, events, listeners, crons },
|
|
397
451
|
idOf,
|
|
398
|
-
|
|
452
|
+
jobs,
|
|
399
453
|
[INTERNAL]: {
|
|
400
454
|
options,
|
|
401
455
|
config,
|
|
402
456
|
derive: (more) => build(options, { ...o, ...more, config: mergeConfig(o.config, more.config) }),
|
|
457
|
+
envelope: (event, payload, scope) => envelopeOf(event, payload, scope, 1),
|
|
458
|
+
due,
|
|
403
459
|
},
|
|
404
460
|
};
|
|
405
461
|
}
|
|
406
|
-
/** @internal */
|
|
407
|
-
export const internal = (registry) => registry[INTERNAL];
|