@supacloud/commands 0.6.0 → 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/README.md +8 -0
- package/dist/execution-policy.d.ts +9 -0
- package/dist/index.d.ts +3 -2
- package/dist/index.js +75 -17
- package/dist/observation.d.ts +3 -0
- package/dist/recovery.d.ts +12 -0
- package/dist/typebox.js +30 -5
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -22,6 +22,14 @@ conservatively reported as `COMMAND_OUTCOME_UNKNOWN`, not proof of rollback.
|
|
|
22
22
|
Circuit `isFailure` should exclude authorization, schema and domain rejection.
|
|
23
23
|
Circuit state is local to the policy instance, not distributed.
|
|
24
24
|
|
|
25
|
+
Both `createExecutionPolicy` and `createCommandRecoveryHandler` accept an optional
|
|
26
|
+
`observer`. Exported `ExecutionPolicyEvent` and `CommandRecoveryEvent` report
|
|
27
|
+
attempts, fixed decisions and recovery/settlement stages, never input, output or
|
|
28
|
+
raw exception data. Observers are best-effort, not awaited, and cannot turn their
|
|
29
|
+
own failures into command retries. A successful recovery lookup is not a
|
|
30
|
+
successful acknowledgement; check the separate `complete` stage.
|
|
31
|
+
See [composition and recovery](../../docs/framework-composition.md).
|
|
32
|
+
|
|
25
33
|
Storage-independent durable execution. Depends only on `@supacloud/contracts`;
|
|
26
34
|
no SQL driver, HTTP server, Svelte lifecycle or scheduler is bundled.
|
|
27
35
|
|
|
@@ -1,10 +1,19 @@
|
|
|
1
|
+
import { type CommandObserver } from "./observation";
|
|
1
2
|
export declare class ExecutionPolicyError extends Error {
|
|
2
3
|
readonly code: "CIRCUIT_OPEN" | "EXECUTION_ABORTED" | "EXECUTION_TIMEOUT" | "COMMAND_OUTCOME_UNKNOWN";
|
|
3
4
|
constructor(code: "CIRCUIT_OPEN" | "EXECUTION_ABORTED" | "EXECUTION_TIMEOUT" | "COMMAND_OUTCOME_UNKNOWN");
|
|
4
5
|
}
|
|
5
6
|
type RetryDecision = "retry" | "rolled-back" | "stop";
|
|
7
|
+
export interface ExecutionPolicyEvent {
|
|
8
|
+
kind: "read" | "command";
|
|
9
|
+
attempt: number;
|
|
10
|
+
phase: "started" | "succeeded" | "failed" | "retry" | "rejected";
|
|
11
|
+
reason?: RetryDecision | ExecutionPolicyError["code"];
|
|
12
|
+
}
|
|
6
13
|
export interface ExecutionPolicyOptions {
|
|
7
14
|
kind: "read" | "command";
|
|
15
|
+
/** Metadata only. Attach operation/trace labels in the host's observer closure. */
|
|
16
|
+
observer?: CommandObserver<ExecutionPolicyEvent>;
|
|
8
17
|
/** Cooperative cancellation. The operation must forward the signal to its driver. */
|
|
9
18
|
timeoutMs?: number;
|
|
10
19
|
retry?: {
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export { createTransactionalCommand } from "./transactional";
|
|
2
|
-
export { createExecutionPolicy, ExecutionPolicyError, type ExecutionPolicyOptions } from "./execution-policy";
|
|
2
|
+
export { createExecutionPolicy, ExecutionPolicyError, type ExecutionPolicyOptions, type ExecutionPolicyEvent } from "./execution-policy";
|
|
3
3
|
export { createExternalCommand, type ExternalDispatch } from "./external";
|
|
4
4
|
export { plaintextCommandInput, type CommandInputCodec, type PersistentCommandDefinition, type RecoveryPrincipal } from "./context";
|
|
5
|
-
export { createCommandRecoveryHandler, type RecoverableCommand, type CommandWorkflowPort, type CommandWorkflowAttempt } from "./recovery";
|
|
5
|
+
export { createCommandRecoveryHandler, type RecoverableCommand, type CommandWorkflowPort, type CommandWorkflowAttempt, type CommandRecoveryEvent } from "./recovery";
|
|
6
|
+
export type { CommandObserver } from "./observation";
|
|
6
7
|
export type { CommandStore, CommandStoreSession, StoredCommand, OperationReference, CommandRetentionStore, RecoveryScope, } from "./store";
|
package/dist/index.js
CHANGED
|
@@ -151,6 +151,15 @@ function commandContext(definition) {
|
|
|
151
151
|
return { prepare, lock, find, restore, transaction, audit, insert };
|
|
152
152
|
}
|
|
153
153
|
|
|
154
|
+
// src/observation.ts
|
|
155
|
+
function emitCommandObservation(observer, event) {
|
|
156
|
+
if (!observer)
|
|
157
|
+
return;
|
|
158
|
+
try {
|
|
159
|
+
Promise.resolve(observer(Object.freeze(event))).catch(() => {});
|
|
160
|
+
} catch {}
|
|
161
|
+
}
|
|
162
|
+
|
|
154
163
|
// src/execution-policy.ts
|
|
155
164
|
class ExecutionPolicyError extends Error {
|
|
156
165
|
code;
|
|
@@ -163,7 +172,8 @@ class ExecutionPolicyError extends Error {
|
|
|
163
172
|
function createExecutionPolicy(options) {
|
|
164
173
|
const retry = options.retry ? { ...options.retry } : undefined;
|
|
165
174
|
const circuit = options.circuit ? { ...options.circuit } : undefined;
|
|
166
|
-
const { kind, timeoutMs } = options;
|
|
175
|
+
const { kind, timeoutMs, observer } = options;
|
|
176
|
+
const emit = (event) => emitCommandObservation(observer, { kind, ...event });
|
|
167
177
|
for (const value of [timeoutMs, retry?.maxAttempts, retry?.delayMs, circuit?.failureThreshold, circuit?.resetAfterMs]) {
|
|
168
178
|
if (value !== undefined && (!Number.isSafeInteger(value) || value < 1 || value > 2147483647)) {
|
|
169
179
|
throw new TypeError("Execution policy values must be positive bounded integers");
|
|
@@ -175,11 +185,15 @@ function createExecutionPolicy(options) {
|
|
|
175
185
|
let generation = 0;
|
|
176
186
|
return Object.freeze({
|
|
177
187
|
async execute(run, parent) {
|
|
178
|
-
if (parent?.aborted)
|
|
188
|
+
if (parent?.aborted) {
|
|
189
|
+
emit({ attempt: 0, phase: "rejected", reason: "EXECUTION_ABORTED" });
|
|
179
190
|
throw new ExecutionPolicyError("EXECUTION_ABORTED");
|
|
191
|
+
}
|
|
180
192
|
const halfOpen = openUntil !== 0;
|
|
181
|
-
if (halfOpen && (Date.now() < openUntil || probe))
|
|
193
|
+
if (halfOpen && (Date.now() < openUntil || probe)) {
|
|
194
|
+
emit({ attempt: 0, phase: "rejected", reason: "CIRCUIT_OPEN" });
|
|
182
195
|
throw new ExecutionPolicyError("CIRCUIT_OPEN");
|
|
196
|
+
}
|
|
183
197
|
if (halfOpen)
|
|
184
198
|
probe = true;
|
|
185
199
|
const currentGeneration = generation;
|
|
@@ -194,9 +208,12 @@ function createExecutionPolicy(options) {
|
|
|
194
208
|
const cancelled = () => new ExecutionPolicyError(kind === "command" ? "COMMAND_OUTCOME_UNKNOWN" : expired ? "EXECUTION_TIMEOUT" : "EXECUTION_ABORTED");
|
|
195
209
|
try {
|
|
196
210
|
for (let attempt = 1;; attempt++) {
|
|
197
|
-
if (controller.signal.aborted)
|
|
211
|
+
if (controller.signal.aborted) {
|
|
212
|
+
emit({ attempt, phase: "rejected", reason: cancelled().code });
|
|
198
213
|
throw cancelled();
|
|
214
|
+
}
|
|
199
215
|
try {
|
|
216
|
+
emit({ attempt, phase: "started" });
|
|
200
217
|
const result = await run(controller.signal);
|
|
201
218
|
if (controller.signal.aborted)
|
|
202
219
|
throw cancelled();
|
|
@@ -207,17 +224,25 @@ function createExecutionPolicy(options) {
|
|
|
207
224
|
generation++;
|
|
208
225
|
}
|
|
209
226
|
}
|
|
227
|
+
emit({ attempt, phase: "succeeded" });
|
|
210
228
|
return result;
|
|
211
229
|
} catch (error) {
|
|
230
|
+
const unknownOutcome = kind === "command" && error !== null && typeof error === "object" && "code" in error && error.code === "COMMAND_OUTCOME_UNKNOWN";
|
|
231
|
+
emit({
|
|
232
|
+
attempt,
|
|
233
|
+
phase: "failed",
|
|
234
|
+
...controller.signal.aborted ? { reason: cancelled().code } : unknownOutcome ? { reason: "COMMAND_OUTCOME_UNKNOWN" } : {}
|
|
235
|
+
});
|
|
212
236
|
if (controller.signal.aborted)
|
|
213
237
|
throw cancelled();
|
|
214
|
-
if (
|
|
238
|
+
if (unknownOutcome)
|
|
215
239
|
throw error;
|
|
216
240
|
if (!retry || halfOpen || attempt >= retry.maxAttempts)
|
|
217
241
|
throw error;
|
|
218
242
|
const decision = retry.classify(error);
|
|
219
243
|
if (decision !== "rolled-back" && !(kind === "read" && decision === "retry"))
|
|
220
244
|
throw error;
|
|
245
|
+
emit({ attempt, phase: "retry", reason: decision });
|
|
221
246
|
await new Promise((resolve) => {
|
|
222
247
|
const done = () => {
|
|
223
248
|
clearTimeout(wait);
|
|
@@ -466,6 +491,7 @@ function createCommandRecoveryHandler(options) {
|
|
|
466
491
|
const tenantId = commandIdentifier2(options.tenantId);
|
|
467
492
|
const principal = { subject: commandIdentifier2(options.principal.subject) };
|
|
468
493
|
const commands = { ...options.commands }, { workflows, authorize } = options;
|
|
494
|
+
const observer = options.observer;
|
|
469
495
|
const delaySeconds = options.retryDelaySeconds;
|
|
470
496
|
if (!Number.isSafeInteger(delaySeconds) || delaySeconds < 0 || delaySeconds > 86400)
|
|
471
497
|
throw new TypeError("Invalid recovery delay");
|
|
@@ -478,32 +504,64 @@ function createCommandRecoveryHandler(options) {
|
|
|
478
504
|
const command = commands[reference.command];
|
|
479
505
|
if (!command)
|
|
480
506
|
throw new CommandError4("COMMAND_REJECTED");
|
|
507
|
+
const observe = async (stage, run, reason) => {
|
|
508
|
+
const emit = (phase) => emitCommandObservation(observer, {
|
|
509
|
+
command: reference.command,
|
|
510
|
+
commandId,
|
|
511
|
+
stepId: attempt.stepId,
|
|
512
|
+
attempt: attempt.attempt,
|
|
513
|
+
stage,
|
|
514
|
+
phase,
|
|
515
|
+
...reason === undefined ? {} : { reason }
|
|
516
|
+
});
|
|
517
|
+
emit("started");
|
|
518
|
+
try {
|
|
519
|
+
const result = await run();
|
|
520
|
+
emit("succeeded");
|
|
521
|
+
return result;
|
|
522
|
+
} catch (error) {
|
|
523
|
+
emit("failed");
|
|
524
|
+
throw error;
|
|
525
|
+
}
|
|
526
|
+
};
|
|
481
527
|
let receipt;
|
|
482
528
|
try {
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
if (
|
|
487
|
-
|
|
488
|
-
for (const key of ["tenantId", "actorId", "command", "operationId"]) {
|
|
489
|
-
if (receipt[key] !== reference[key])
|
|
529
|
+
receipt = await observe("recover", async () => {
|
|
530
|
+
const raw = await command.recover({ ...principal }, { ...reference });
|
|
531
|
+
const decoded = raw === null ? null : decodeDurableCommandReceipt3(raw, decodeCommandJson);
|
|
532
|
+
if (decoded !== null) {
|
|
533
|
+
if (decoded.dispatchKey !== commandId)
|
|
490
534
|
throw new CommandError4("COMMAND_RECEIPT_INVALID");
|
|
535
|
+
for (const key of ["tenantId", "actorId", "command", "operationId"]) {
|
|
536
|
+
if (decoded[key] !== reference[key])
|
|
537
|
+
throw new CommandError4("COMMAND_RECEIPT_INVALID");
|
|
538
|
+
}
|
|
491
539
|
}
|
|
492
|
-
|
|
540
|
+
return decoded;
|
|
541
|
+
});
|
|
493
542
|
} catch (error) {
|
|
494
543
|
if (error instanceof CommandError4 && (error.code === "COMMAND_INPUT_EXPIRED" || error.code === "COMMAND_RECEIPT_INVALID")) {
|
|
495
|
-
|
|
544
|
+
const reason = error.code;
|
|
545
|
+
await observe("fail", () => workflows.fail({ ...attempt, errorMessage: reason }), reason);
|
|
496
546
|
return "failed";
|
|
497
547
|
}
|
|
498
|
-
await
|
|
548
|
+
await observe("retry", () => workflows.retry({
|
|
549
|
+
...attempt,
|
|
550
|
+
errorMessage: "COMMAND_RECOVERY_FAILED",
|
|
551
|
+
delaySeconds
|
|
552
|
+
}), "COMMAND_RECOVERY_FAILED");
|
|
499
553
|
return "retry";
|
|
500
554
|
}
|
|
501
555
|
if (receipt?.status === "confirmed" && receipt.audit === "complete") {
|
|
502
556
|
const output = { commandId, status: "confirmed", audit: "complete" };
|
|
503
|
-
await workflows.complete({ ...attempt, stepOutput: output, runOutput: output });
|
|
557
|
+
await observe("complete", () => workflows.complete({ ...attempt, stepOutput: output, runOutput: output }));
|
|
504
558
|
return "completed";
|
|
505
559
|
}
|
|
506
|
-
await
|
|
560
|
+
await observe("retry", () => workflows.retry({
|
|
561
|
+
...attempt,
|
|
562
|
+
errorMessage: "COMMAND_RECOVERY_REQUIRED",
|
|
563
|
+
delaySeconds
|
|
564
|
+
}), "COMMAND_RECOVERY_REQUIRED");
|
|
507
565
|
return "retry";
|
|
508
566
|
}
|
|
509
567
|
};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
/** Best-effort metadata only; never an audit receipt or a settlement mechanism. */
|
|
2
|
+
export type CommandObserver<Event> = (event: Readonly<Event>) => void | Promise<void>;
|
|
3
|
+
export declare function emitCommandObservation<Event extends object>(observer: CommandObserver<Event> | undefined, event: Event): void;
|
package/dist/recovery.d.ts
CHANGED
|
@@ -1,6 +1,17 @@
|
|
|
1
1
|
import { type CommandAuthorization, type DurableCommandReceipt } from "@supacloud/contracts";
|
|
2
2
|
import { type RecoveryPrincipal } from "./context";
|
|
3
3
|
import type { OperationReference } from "./store";
|
|
4
|
+
import { type CommandObserver } from "./observation";
|
|
5
|
+
export interface CommandRecoveryEvent {
|
|
6
|
+
command: string;
|
|
7
|
+
commandId: string;
|
|
8
|
+
stepId: string;
|
|
9
|
+
attempt: number;
|
|
10
|
+
stage: "recover" | "complete" | "retry" | "fail";
|
|
11
|
+
phase: "started" | "succeeded" | "failed";
|
|
12
|
+
/** Fixed reason codes, never raw lookup or transport errors. */
|
|
13
|
+
reason?: "COMMAND_INPUT_EXPIRED" | "COMMAND_RECEIPT_INVALID" | "COMMAND_RECOVERY_FAILED" | "COMMAND_RECOVERY_REQUIRED";
|
|
14
|
+
}
|
|
4
15
|
export interface RecoverableCommand {
|
|
5
16
|
recover(principal: RecoveryPrincipal, reference: OperationReference): Promise<DurableCommandReceipt<unknown> | null>;
|
|
6
17
|
}
|
|
@@ -32,6 +43,7 @@ export declare function createCommandRecoveryHandler(options: {
|
|
|
32
43
|
commands: Readonly<Record<string, RecoverableCommand>>;
|
|
33
44
|
authorize(): CommandAuthorization | Promise<CommandAuthorization>;
|
|
34
45
|
retryDelaySeconds: number;
|
|
46
|
+
observer?: CommandObserver<CommandRecoveryEvent>;
|
|
35
47
|
}): {
|
|
36
48
|
run(value: unknown): Promise<"completed" | "retry" | "failed">;
|
|
37
49
|
};
|
package/dist/typebox.js
CHANGED
|
@@ -155,6 +155,15 @@ function commandContext(definition) {
|
|
|
155
155
|
return { prepare, lock, find, restore, transaction, audit, insert };
|
|
156
156
|
}
|
|
157
157
|
|
|
158
|
+
// src/observation.ts
|
|
159
|
+
function emitCommandObservation(observer, event) {
|
|
160
|
+
if (!observer)
|
|
161
|
+
return;
|
|
162
|
+
try {
|
|
163
|
+
Promise.resolve(observer(Object.freeze(event))).catch(() => {});
|
|
164
|
+
} catch {}
|
|
165
|
+
}
|
|
166
|
+
|
|
158
167
|
// src/execution-policy.ts
|
|
159
168
|
class ExecutionPolicyError extends Error {
|
|
160
169
|
code;
|
|
@@ -167,7 +176,8 @@ class ExecutionPolicyError extends Error {
|
|
|
167
176
|
function createExecutionPolicy(options) {
|
|
168
177
|
const retry = options.retry ? { ...options.retry } : undefined;
|
|
169
178
|
const circuit = options.circuit ? { ...options.circuit } : undefined;
|
|
170
|
-
const { kind, timeoutMs } = options;
|
|
179
|
+
const { kind, timeoutMs, observer } = options;
|
|
180
|
+
const emit = (event) => emitCommandObservation(observer, { kind, ...event });
|
|
171
181
|
for (const value of [timeoutMs, retry?.maxAttempts, retry?.delayMs, circuit?.failureThreshold, circuit?.resetAfterMs]) {
|
|
172
182
|
if (value !== undefined && (!Number.isSafeInteger(value) || value < 1 || value > 2147483647)) {
|
|
173
183
|
throw new TypeError("Execution policy values must be positive bounded integers");
|
|
@@ -179,11 +189,15 @@ function createExecutionPolicy(options) {
|
|
|
179
189
|
let generation = 0;
|
|
180
190
|
return Object.freeze({
|
|
181
191
|
async execute(run, parent) {
|
|
182
|
-
if (parent?.aborted)
|
|
192
|
+
if (parent?.aborted) {
|
|
193
|
+
emit({ attempt: 0, phase: "rejected", reason: "EXECUTION_ABORTED" });
|
|
183
194
|
throw new ExecutionPolicyError("EXECUTION_ABORTED");
|
|
195
|
+
}
|
|
184
196
|
const halfOpen = openUntil !== 0;
|
|
185
|
-
if (halfOpen && (Date.now() < openUntil || probe))
|
|
197
|
+
if (halfOpen && (Date.now() < openUntil || probe)) {
|
|
198
|
+
emit({ attempt: 0, phase: "rejected", reason: "CIRCUIT_OPEN" });
|
|
186
199
|
throw new ExecutionPolicyError("CIRCUIT_OPEN");
|
|
200
|
+
}
|
|
187
201
|
if (halfOpen)
|
|
188
202
|
probe = true;
|
|
189
203
|
const currentGeneration = generation;
|
|
@@ -198,9 +212,12 @@ function createExecutionPolicy(options) {
|
|
|
198
212
|
const cancelled = () => new ExecutionPolicyError(kind === "command" ? "COMMAND_OUTCOME_UNKNOWN" : expired ? "EXECUTION_TIMEOUT" : "EXECUTION_ABORTED");
|
|
199
213
|
try {
|
|
200
214
|
for (let attempt = 1;; attempt++) {
|
|
201
|
-
if (controller.signal.aborted)
|
|
215
|
+
if (controller.signal.aborted) {
|
|
216
|
+
emit({ attempt, phase: "rejected", reason: cancelled().code });
|
|
202
217
|
throw cancelled();
|
|
218
|
+
}
|
|
203
219
|
try {
|
|
220
|
+
emit({ attempt, phase: "started" });
|
|
204
221
|
const result = await run(controller.signal);
|
|
205
222
|
if (controller.signal.aborted)
|
|
206
223
|
throw cancelled();
|
|
@@ -211,17 +228,25 @@ function createExecutionPolicy(options) {
|
|
|
211
228
|
generation++;
|
|
212
229
|
}
|
|
213
230
|
}
|
|
231
|
+
emit({ attempt, phase: "succeeded" });
|
|
214
232
|
return result;
|
|
215
233
|
} catch (error) {
|
|
234
|
+
const unknownOutcome = kind === "command" && error !== null && typeof error === "object" && "code" in error && error.code === "COMMAND_OUTCOME_UNKNOWN";
|
|
235
|
+
emit({
|
|
236
|
+
attempt,
|
|
237
|
+
phase: "failed",
|
|
238
|
+
...controller.signal.aborted ? { reason: cancelled().code } : unknownOutcome ? { reason: "COMMAND_OUTCOME_UNKNOWN" } : {}
|
|
239
|
+
});
|
|
216
240
|
if (controller.signal.aborted)
|
|
217
241
|
throw cancelled();
|
|
218
|
-
if (
|
|
242
|
+
if (unknownOutcome)
|
|
219
243
|
throw error;
|
|
220
244
|
if (!retry || halfOpen || attempt >= retry.maxAttempts)
|
|
221
245
|
throw error;
|
|
222
246
|
const decision = retry.classify(error);
|
|
223
247
|
if (decision !== "rolled-back" && !(kind === "read" && decision === "retry"))
|
|
224
248
|
throw error;
|
|
249
|
+
emit({ attempt, phase: "retry", reason: decision });
|
|
225
250
|
await new Promise((resolve) => {
|
|
226
251
|
const done = () => {
|
|
227
252
|
clearTimeout(wait);
|