logic-sdk 0.6.3 → 0.7.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/dist/errors.d.ts +10 -1
- package/dist/errors.js +11 -2
- package/dist/index.js +31 -6
- package/dist/jobs.js +4 -2
- package/dist/types.d.ts +4 -3
- package/package.json +2 -2
- package/skills/logic-sdk/SKILL.md +2 -2
- package/src/errors.ts +11 -2
- package/src/index.ts +38 -6
- package/src/jobs.ts +4 -2
- package/src/types.ts +4 -3
package/dist/errors.d.ts
CHANGED
|
@@ -30,10 +30,19 @@ export declare const describeIssues: (issues: readonly StandardSchemaV1.Issue[])
|
|
|
30
30
|
/** A payload that stopped matching its event's schema (a deploy changed it while it waited): delivering again won't help. */
|
|
31
31
|
export declare class StalePayload extends Error {
|
|
32
32
|
}
|
|
33
|
+
/**
|
|
34
|
+
* A mutation's commit after a nested mutation failed and was caught: the transaction they share is doomed. Its
|
|
35
|
+
* `cause` is that failure, and retries (a transaction's, a job's) treat it as the cause would be treated.
|
|
36
|
+
*/
|
|
37
|
+
export declare class CaughtNestedFailure extends Error {
|
|
38
|
+
}
|
|
33
39
|
/**
|
|
34
40
|
* Throw where there's no valid session, outside your functions (a route, a middleware): `toResponse` makes it a 401.
|
|
35
41
|
* Inside a function, a policy answers instead (a scope with no actor, then `forbidden`).
|
|
36
42
|
*/
|
|
37
43
|
export declare const unauthenticated: (code?: string, details?: unknown) => DomainError;
|
|
38
|
-
/**
|
|
44
|
+
/**
|
|
45
|
+
* An error and the ones it wraps (`cause`), six deep at most: a driver's error usually arrives wrapped by the ORM,
|
|
46
|
+
* and a caught nested failure wraps that once more.
|
|
47
|
+
*/
|
|
39
48
|
export declare function causes(error: unknown): Generator<object>;
|
package/dist/errors.js
CHANGED
|
@@ -39,13 +39,22 @@ export const describeIssues = (issues) => issues.map((i) => ({ message: i.messag
|
|
|
39
39
|
/** A payload that stopped matching its event's schema (a deploy changed it while it waited): delivering again won't help. */
|
|
40
40
|
export class StalePayload extends Error {
|
|
41
41
|
}
|
|
42
|
+
/**
|
|
43
|
+
* A mutation's commit after a nested mutation failed and was caught: the transaction they share is doomed. Its
|
|
44
|
+
* `cause` is that failure, and retries (a transaction's, a job's) treat it as the cause would be treated.
|
|
45
|
+
*/
|
|
46
|
+
export class CaughtNestedFailure extends Error {
|
|
47
|
+
}
|
|
42
48
|
/**
|
|
43
49
|
* Throw where there's no valid session, outside your functions (a route, a middleware): `toResponse` makes it a 401.
|
|
44
50
|
* Inside a function, a policy answers instead (a scope with no actor, then `forbidden`).
|
|
45
51
|
*/
|
|
46
52
|
export const unauthenticated = (code = "unauthenticated", details) => new DomainError("unauthenticated", code, details);
|
|
47
|
-
/**
|
|
53
|
+
/**
|
|
54
|
+
* An error and the ones it wraps (`cause`), six deep at most: a driver's error usually arrives wrapped by the ORM,
|
|
55
|
+
* and a caught nested failure wraps that once more.
|
|
56
|
+
*/
|
|
48
57
|
export function* causes(error) {
|
|
49
|
-
for (let e = error, i = 0; typeof e === "object" && e !== null && i <
|
|
58
|
+
for (let e = error, i = 0; typeof e === "object" && e !== null && i < 6; e = "cause" in e ? e.cause : undefined, i++)
|
|
50
59
|
yield e;
|
|
51
60
|
}
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { describeIssues, DomainError, errorsFor, forbiddenOf, moduleOf, PRIVATE } from "./errors.js";
|
|
1
|
+
import { CaughtNestedFailure, describeIssues, DomainError, errorsFor, forbiddenOf, moduleOf, PRIVATE } from "./errors.js";
|
|
2
2
|
import { inProcess, makeJobs, replaceKeyOf, runsNow } from "./jobs.js";
|
|
3
3
|
import { assertTimeZone, parseSchedule } from "./schedule.js";
|
|
4
4
|
import { BRAND, INTERNAL } from "./types.js";
|
|
@@ -58,6 +58,19 @@ function checkAttempts(what, attempts) {
|
|
|
58
58
|
if (attempts !== undefined && !(Number.isInteger(attempts) && attempts >= 1))
|
|
59
59
|
throw new Error(`[logic-sdk] ${what} attempts must be a whole number of tries, 1 or more (got ${attempts}).`);
|
|
60
60
|
}
|
|
61
|
+
/** What a mutation throws at commit when a nested mutation failed and was caught: the transaction they share is doomed. */
|
|
62
|
+
function caughtNestedFailure(id, tx) {
|
|
63
|
+
let why;
|
|
64
|
+
try {
|
|
65
|
+
why = tx.reason instanceof Error ? tx.reason.message : String(tx.reason);
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
why = Object.prototype.toString.call(tx.reason); // an object String() can't print
|
|
69
|
+
}
|
|
70
|
+
return new CaughtNestedFailure(`[logic-sdk] ${tx.doomedBy?.at(-1)} failed inside ${id}'s transaction (${tx.doomedBy?.join(" → ")}) and was ` +
|
|
71
|
+
`caught, so ${id} can't commit: a mutation shares its transaction with the mutations it runs. To let each one ` +
|
|
72
|
+
`commit or fail on its own, run them from an action. The failure (this error's cause): ${why}`, { cause: tx.reason });
|
|
73
|
+
}
|
|
61
74
|
/** Create the registry once at startup. Prefer the `createRegistry` returned by `init()`: it's typed with your config. */
|
|
62
75
|
export function createRegistry(options) {
|
|
63
76
|
return build(options, {});
|
|
@@ -230,10 +243,10 @@ function build(options, o) {
|
|
|
230
243
|
assertPlain(c.cron.input, `${c.id} input`, "Cron runs travel through queues as JSON: send an ISO string and let the schema turn it into a Date");
|
|
231
244
|
}
|
|
232
245
|
// ── ctx ──────────────────────────────────────────────────────────────────
|
|
233
|
-
/** The frame for a call from here: its scope
|
|
246
|
+
/** The frame for a call from here: its scope and signal. `invoke` adds the call to the trail. */
|
|
234
247
|
const enter = (frame, options) => ({
|
|
235
248
|
...frame,
|
|
236
|
-
scope: options?.scope
|
|
249
|
+
scope: options?.scope ?? frame.scope,
|
|
237
250
|
signal: options?.signal ?? frame.signal,
|
|
238
251
|
abortOn: options?.signal,
|
|
239
252
|
});
|
|
@@ -386,6 +399,7 @@ function build(options, o) {
|
|
|
386
399
|
if (!tx.doomed) {
|
|
387
400
|
tx.doomed = true;
|
|
388
401
|
tx.reason = e;
|
|
402
|
+
tx.doomedBy = frame.trail.slice(tx.from);
|
|
389
403
|
}
|
|
390
404
|
throw e;
|
|
391
405
|
}
|
|
@@ -398,14 +412,21 @@ function build(options, o) {
|
|
|
398
412
|
const input = await prepare();
|
|
399
413
|
let committed;
|
|
400
414
|
for (let attempt = 1;; attempt++) {
|
|
415
|
+
const attemptTx = {};
|
|
401
416
|
try {
|
|
402
417
|
committed = await database.transaction(async (txDb) => {
|
|
403
418
|
// fresh per attempt, so a retry never reuses events from a failed attempt
|
|
404
|
-
const tx = {
|
|
419
|
+
const tx = {
|
|
420
|
+
db: txDb, doomed: false, reason: undefined, from: frame.trail.length - 1, doomedBy: undefined,
|
|
421
|
+
events: [], parsed: new Map(), calls: [], pending: [],
|
|
422
|
+
};
|
|
423
|
+
attemptTx.current = tx;
|
|
405
424
|
const out = await execute(input, mutationCtx({ ...frame, tx }, tx, id));
|
|
406
425
|
await Promise.all(tx.pending);
|
|
426
|
+
// a nested failure was caught: a bug, so its own error, with the failure as its cause (Ecto's aborted
|
|
427
|
+
// transaction). Retries still see a deadlock: `retryable` walks causes
|
|
407
428
|
if (tx.doomed)
|
|
408
|
-
throw tx
|
|
429
|
+
throw caughtNestedFailure(id, tx);
|
|
409
430
|
const jobs = toJobs(tx.events, tx.calls, tx.parsed);
|
|
410
431
|
if (jobs.length)
|
|
411
432
|
await jobsAdapter.enqueue?.(txDb, jobs);
|
|
@@ -414,7 +435,11 @@ function build(options, o) {
|
|
|
414
435
|
break;
|
|
415
436
|
}
|
|
416
437
|
catch (e) {
|
|
417
|
-
|
|
438
|
+
// a lost race dooms the transaction even when a caller caught it and went on: Postgres then fails the next
|
|
439
|
+
// statement with 25P02, or the caller throws its own error, and the race is still what to retry
|
|
440
|
+
const doomed = attemptTx.current?.doomed ? attemptTx.current.reason : undefined;
|
|
441
|
+
const lostRace = database.retryable?.(e) || (doomed !== undefined && database.retryable?.(doomed));
|
|
442
|
+
if (attempt < transactionAttempts && lostRace) {
|
|
418
443
|
// a random pause, so transactions that just deadlocked don't retry in lockstep and collide again
|
|
419
444
|
await new Promise((r) => setTimeout(r, Math.random() * 20 * attempt));
|
|
420
445
|
continue;
|
package/dist/jobs.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { describeIssues, isDomainError, StalePayload } from "./errors.js";
|
|
1
|
+
import { CaughtNestedFailure, describeIssues, isDomainError, StalePayload } from "./errors.js";
|
|
2
2
|
import { isDue, parseSchedule } from "./schedule.js";
|
|
3
3
|
import { RUNS_NOW } from "./types.js";
|
|
4
4
|
const IN_PROCESS = {
|
|
@@ -137,7 +137,9 @@ export function makeJobs(deps) {
|
|
|
137
137
|
return await work();
|
|
138
138
|
}
|
|
139
139
|
catch (error) {
|
|
140
|
-
|
|
140
|
+
// a caught nested failure is retried as its cause would be: a swallowed `reject` still fails at once
|
|
141
|
+
const decisive = error instanceof CaughtNestedFailure ? error.cause : error;
|
|
142
|
+
const retrying = attempt < attempts && !(decisive instanceof StalePayload) && !(isDomainError(decisive) && decisive.kind !== "conflict");
|
|
141
143
|
if (!retrying)
|
|
142
144
|
return failed(error);
|
|
143
145
|
report(error, { ...info, outcome: "retry" });
|
package/dist/types.d.ts
CHANGED
|
@@ -266,10 +266,11 @@ export interface Listener<O = unknown, C extends Config = any> extends FromInit<
|
|
|
266
266
|
/** What a single call may change: who it runs as (part of the scope) and when to give up. Nothing else. */
|
|
267
267
|
export interface RunOptions<S = object> {
|
|
268
268
|
/**
|
|
269
|
-
*
|
|
270
|
-
*
|
|
269
|
+
* The whole scope for this call and everything it runs, never merged: `{ scope: { ...ctx.scope, locale: "es" } }`
|
|
270
|
+
* to render in another language, `{ scope: asSystem("reports.weekly") }` to act as someone else on purpose. The
|
|
271
|
+
* callee's policy sees it. Whole, so it's one of your scope's variants: a patch could build one that isn't.
|
|
271
272
|
*/
|
|
272
|
-
scope?:
|
|
273
|
+
scope?: S;
|
|
273
274
|
/**
|
|
274
275
|
* Checked before this call starts. Inside, actions get it as `ctx.signal` to pass on (`fetch(url, { signal })`).
|
|
275
276
|
* Never checked between your steps, so a caller who gives up can't leave a workflow half done.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "logic-sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"description": "Queries, mutations, actions and events for TypeScript apps. Transactions, after-commit events and scopes, on any runtime.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"actions",
|
|
@@ -113,7 +113,7 @@
|
|
|
113
113
|
"drizzle-orm": ">=1.0.0-rc.6 <2",
|
|
114
114
|
"pg-boss": ">=12.39.0 <13",
|
|
115
115
|
"ai": ">=7 <8",
|
|
116
|
-
"@logic-sdk/cli": ">=0.6.
|
|
116
|
+
"@logic-sdk/cli": ">=0.6.4 <0.7.0"
|
|
117
117
|
},
|
|
118
118
|
"peerDependenciesMeta": {
|
|
119
119
|
"@orpc/server": {
|
|
@@ -68,10 +68,10 @@ export const cancel = mutation({
|
|
|
68
68
|
5. **Always filter by `ctx.scope.accountId`** in `data.ts` helpers, writes included. Loading helpers throw `ctx.errors.notFound()`. Scope is who and where (actor, account, locale); input is what.
|
|
69
69
|
6. **Authorize every function a user, client or AI tool may call.** `authorize: member` (a policy from `policies.ts`) says who may call it: sync, reads only scope, runs on every call including nested ones. Publish a function by listing it in `src/rpc.ts` (`toORPCProcedure(fn)`) or an agent's tools (`toAITool(caller, fn)`); both refuse one without `authorize`. A hand-written route or Server Action can `caller.run` anything, nothing stops it: only call functions that have `authorize` from them. Give published functions an `output` so nothing unintended leaves.
|
|
70
70
|
7. **Record rules are `can*` predicates.** Load through a scoped helper, then `if (!canX(ctx.scope.actor, record)) throw ctx.errors.deny();`. `can*` is sync, its result is always used, and the same predicate feeds UI flags in list queries: `can: { cancel: canCancel(actor, b) }`. A rule that must hold at commit goes in the write's `WHERE` or a `FOR UPDATE` re-select.
|
|
71
|
-
8. **Errors:** `throw ctx.errors.reject("snake_reason", details?)` when a rule says no, `ctx.errors.conflict(...)` when someone got there first, `ctx.errors.notFound()`, `ctx.errors.deny()`. Codes are namespaced to your module for you. Never return error objects; never throw plain `Error` for expected cases. Catch only in actions; in a mutation, catch only to rethrow your own error.
|
|
71
|
+
8. **Errors:** `throw ctx.errors.reject("snake_reason", details?)` when a rule says no, `ctx.errors.conflict(...)` when someone got there first, `ctx.errors.notFound()`, `ctx.errors.deny()`. Codes are namespaced to your module for you. Never return error objects; never throw plain `Error` for expected cases. Catch only in actions; in a mutation, catch only to rethrow your own error: nested mutations share the caller's transaction, so a caught failure fails the commit with an error naming both. Work over many rows where each must commit or fail alone (a cron over every account) is an `action` that `ctx.run`s the mutation per row inside `try`/`catch`.
|
|
72
72
|
9. **Need the result? `run` it. Just a consequence? `emit`** and let the owning module react in its `listeners.ts`.
|
|
73
73
|
10. **A listener that wants only some events says so with `when: (payload) => boolean`** (sync, from the payload only), instead of returning early in its handler: the others get no job. The emitter never filters for its listeners.
|
|
74
|
-
11. **Listeners must be idempotent** (record `ctx.event.id` per listener, since listeners of one event share it, and skip it if seen, when a repeat would charge or email twice). They run with the emitter's scope (or the one `jobs.scope.load` rebuilds, when the app sets it), so they run internal functions. To act as someone else on purpose,
|
|
74
|
+
11. **Listeners must be idempotent** (record `ctx.event.id` per listener, since listeners of one event share it, and skip it if seen, when a repeat would charge or email twice). They run with the emitter's scope (or the one `jobs.scope.load` rebuilds, when the app sets it), so they run internal functions. To act as someone else on purpose, pass the whole scope for that call: `ctx.run(fn, input, { scope: { ...ctx.scope, actor: system } })`. It's never merged, so it's always one of your scope's variants.
|
|
75
75
|
12. **Time** comes from `ctx.now()`, never `new Date()`, so tests can freeze it.
|
|
76
76
|
13. **Use separate `export const`s**, not functions nested in an object. Name them by verb within the module (`bookings.confirm`, not `bookings.confirmBooking`). Names are unique per module. Renaming a listener, event or function that queued jobs may still reference? Keep its id: `listener({ id: "oldName", ... })`. Put one sentence of JSDoc above each (`/** Cancel a booking and free its dates */`): editors show it on hover, and `logic-sdk list` prints it.
|
|
77
77
|
14. **`ctx` comes first, everywhere:** `handler(ctx, input)` in functions, `handler(ctx, payload)` in listeners, helpers `findBooking(ctx, id)`. A function that takes nothing leaves out `input`: `handler(ctx)`, called as `run(fn)`. A form's schema comes from the function it submits to (`properties.update.input.pick({ name: true })`), not from a schema the module exports.
|
package/src/errors.ts
CHANGED
|
@@ -56,13 +56,22 @@ export const describeIssues = (issues: readonly StandardSchemaV1.Issue[]) =>
|
|
|
56
56
|
/** A payload that stopped matching its event's schema (a deploy changed it while it waited): delivering again won't help. */
|
|
57
57
|
export class StalePayload extends Error {}
|
|
58
58
|
|
|
59
|
+
/**
|
|
60
|
+
* A mutation's commit after a nested mutation failed and was caught: the transaction they share is doomed. Its
|
|
61
|
+
* `cause` is that failure, and retries (a transaction's, a job's) treat it as the cause would be treated.
|
|
62
|
+
*/
|
|
63
|
+
export class CaughtNestedFailure extends Error {}
|
|
64
|
+
|
|
59
65
|
/**
|
|
60
66
|
* Throw where there's no valid session, outside your functions (a route, a middleware): `toResponse` makes it a 401.
|
|
61
67
|
* Inside a function, a policy answers instead (a scope with no actor, then `forbidden`).
|
|
62
68
|
*/
|
|
63
69
|
export const unauthenticated = (code = "unauthenticated", details?: unknown) => new DomainError("unauthenticated", code, details);
|
|
64
70
|
|
|
65
|
-
/**
|
|
71
|
+
/**
|
|
72
|
+
* An error and the ones it wraps (`cause`), six deep at most: a driver's error usually arrives wrapped by the ORM,
|
|
73
|
+
* and a caught nested failure wraps that once more.
|
|
74
|
+
*/
|
|
66
75
|
export function* causes(error: unknown): Generator<object> {
|
|
67
|
-
for (let e = error, i = 0; typeof e === "object" && e !== null && i <
|
|
76
|
+
for (let e = error, i = 0; typeof e === "object" && e !== null && i < 6; e = "cause" in e ? e.cause : undefined, i++) yield e;
|
|
68
77
|
}
|
package/src/index.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { describeIssues, DomainError, errorsFor, forbiddenOf, moduleOf, PRIVATE } from "./errors.ts";
|
|
1
|
+
import { CaughtNestedFailure, describeIssues, DomainError, errorsFor, forbiddenOf, moduleOf, PRIVATE } from "./errors.ts";
|
|
2
2
|
import { inProcess, makeJobs, replaceKeyOf, runsNow } from "./jobs.ts";
|
|
3
3
|
import { assertTimeZone, parseSchedule } from "./schedule.ts";
|
|
4
4
|
import { BRAND, INTERNAL } from "./types.ts";
|
|
@@ -242,6 +242,10 @@ interface TxState {
|
|
|
242
242
|
db: unknown;
|
|
243
243
|
doomed: boolean;
|
|
244
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;
|
|
245
249
|
events: Envelope[];
|
|
246
250
|
/** Each event's payload as its schema parsed it, for listeners' `when`: the value their handler gets. */
|
|
247
251
|
parsed: Map<Envelope, unknown>;
|
|
@@ -264,6 +268,22 @@ interface Frame {
|
|
|
264
268
|
tx?: TxState;
|
|
265
269
|
}
|
|
266
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
|
+
|
|
267
287
|
/** Create the registry once at startup. Prefer the `createRegistry` returned by `init()`: it's typed with your config. */
|
|
268
288
|
export function createRegistry<S extends object = object, const Mods extends Record<string, object> = Record<string, object>>(
|
|
269
289
|
options: RegistryOptions<Mods>,
|
|
@@ -441,10 +461,10 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
|
|
|
441
461
|
}
|
|
442
462
|
|
|
443
463
|
// ── ctx ──────────────────────────────────────────────────────────────────
|
|
444
|
-
/** The frame for a call from here: its scope
|
|
464
|
+
/** The frame for a call from here: its scope and signal. `invoke` adds the call to the trail. */
|
|
445
465
|
const enter = (frame: Frame, options: RunOptions | undefined): Frame => ({
|
|
446
466
|
...frame,
|
|
447
|
-
scope: options?.scope
|
|
467
|
+
scope: options?.scope ?? frame.scope,
|
|
448
468
|
signal: options?.signal ?? frame.signal,
|
|
449
469
|
abortOn: options?.signal,
|
|
450
470
|
});
|
|
@@ -600,6 +620,7 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
|
|
|
600
620
|
if (!tx.doomed) {
|
|
601
621
|
tx.doomed = true;
|
|
602
622
|
tx.reason = e;
|
|
623
|
+
tx.doomedBy = frame.trail.slice(tx.from);
|
|
603
624
|
}
|
|
604
625
|
throw e;
|
|
605
626
|
}
|
|
@@ -612,20 +633,31 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
|
|
|
612
633
|
const input = await prepare();
|
|
613
634
|
let committed: { out: unknown; events: Envelope[]; jobs: Job[] };
|
|
614
635
|
for (let attempt = 1; ; attempt++) {
|
|
636
|
+
const attemptTx: { current?: TxState } = {};
|
|
615
637
|
try {
|
|
616
638
|
committed = await database.transaction(async (txDb) => {
|
|
617
639
|
// fresh per attempt, so a retry never reuses events from a failed attempt
|
|
618
|
-
const tx: TxState = {
|
|
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;
|
|
619
645
|
const out = await execute(input, mutationCtx({ ...frame, tx }, tx, id));
|
|
620
646
|
await Promise.all(tx.pending);
|
|
621
|
-
|
|
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);
|
|
622
650
|
const jobs = toJobs(tx.events, tx.calls, tx.parsed);
|
|
623
651
|
if (jobs.length) await jobsAdapter.enqueue?.(txDb, jobs);
|
|
624
652
|
return { out, events: tx.events, jobs };
|
|
625
653
|
});
|
|
626
654
|
break;
|
|
627
655
|
} catch (e) {
|
|
628
|
-
|
|
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) {
|
|
629
661
|
// a random pause, so transactions that just deadlocked don't retry in lockstep and collide again
|
|
630
662
|
await new Promise((r) => setTimeout(r, Math.random() * 20 * attempt));
|
|
631
663
|
continue;
|
package/src/jobs.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { describeIssues, isDomainError, StalePayload } from "./errors.ts";
|
|
1
|
+
import { CaughtNestedFailure, describeIssues, isDomainError, StalePayload } from "./errors.ts";
|
|
2
2
|
import { isDue, parseSchedule } from "./schedule.ts";
|
|
3
3
|
import type {
|
|
4
4
|
ActionCtx,
|
|
@@ -185,7 +185,9 @@ export function makeJobs(deps: JobsDeps) {
|
|
|
185
185
|
try {
|
|
186
186
|
return await work();
|
|
187
187
|
} catch (error) {
|
|
188
|
-
|
|
188
|
+
// a caught nested failure is retried as its cause would be: a swallowed `reject` still fails at once
|
|
189
|
+
const decisive = error instanceof CaughtNestedFailure ? error.cause : error;
|
|
190
|
+
const retrying = attempt < attempts && !(decisive instanceof StalePayload) && !(isDomainError(decisive) && decisive.kind !== "conflict");
|
|
189
191
|
if (!retrying) return failed(error);
|
|
190
192
|
report(error, { ...info, outcome: "retry" });
|
|
191
193
|
throw error;
|
package/src/types.ts
CHANGED
|
@@ -267,10 +267,11 @@ export interface Listener<O = unknown, C extends Config = any> extends FromInit<
|
|
|
267
267
|
/** What a single call may change: who it runs as (part of the scope) and when to give up. Nothing else. */
|
|
268
268
|
export interface RunOptions<S = object> {
|
|
269
269
|
/**
|
|
270
|
-
*
|
|
271
|
-
*
|
|
270
|
+
* The whole scope for this call and everything it runs, never merged: `{ scope: { ...ctx.scope, locale: "es" } }`
|
|
271
|
+
* to render in another language, `{ scope: asSystem("reports.weekly") }` to act as someone else on purpose. The
|
|
272
|
+
* callee's policy sees it. Whole, so it's one of your scope's variants: a patch could build one that isn't.
|
|
272
273
|
*/
|
|
273
|
-
scope?:
|
|
274
|
+
scope?: S;
|
|
274
275
|
/**
|
|
275
276
|
* Checked before this call starts. Inside, actions get it as `ctx.signal` to pass on (`fetch(url, { signal })`).
|
|
276
277
|
* Never checked between your steps, so a caller who gives up can't leave a workflow half done.
|