@supacloud/commands 0.5.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/context.d.ts +2 -2
- package/dist/execution-policy.d.ts +9 -0
- package/dist/index.d.ts +3 -2
- package/dist/index.js +88 -20
- package/dist/observation.d.ts +3 -0
- package/dist/recovery.d.ts +12 -0
- package/dist/store.d.ts +1 -1
- package/dist/transactional.d.ts +2 -2
- package/dist/typebox.js +43 -8
- package/package.json +2 -2
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
|
|
package/dist/context.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type CommandAuthorization, type CommandIdentity, type ContractDecoder, type DurableCommandReceipt } from "@supacloud/contracts";
|
|
2
|
-
import type { CommandStore, CommandStoreSession, OperationReference, StoredCommand } from "./store";
|
|
2
|
+
import type { CommandStore, CommandStoreSession, OperationReference, StoredCommand, ValidatedOperationReference } from "./store";
|
|
3
3
|
export interface CommandInputCodec {
|
|
4
4
|
encode(canonicalInput: string): string | Promise<string>;
|
|
5
5
|
decode(payload: string): string | Promise<string>;
|
|
@@ -25,7 +25,7 @@ export interface PersistentCommandDefinition<Input, Result, Transaction> {
|
|
|
25
25
|
};
|
|
26
26
|
}
|
|
27
27
|
interface Prepared<Input> {
|
|
28
|
-
reference:
|
|
28
|
+
reference: ValidatedOperationReference;
|
|
29
29
|
input: Input;
|
|
30
30
|
fingerprint: string;
|
|
31
31
|
payload: string;
|
|
@@ -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
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
// src/transactional.ts
|
|
2
|
-
import {
|
|
2
|
+
import {
|
|
3
|
+
CommandError as CommandError2,
|
|
4
|
+
canonicalCommandJson as canonicalCommandJson2
|
|
5
|
+
} from "@supacloud/contracts";
|
|
3
6
|
|
|
4
7
|
// src/context.ts
|
|
5
8
|
import {
|
|
6
9
|
CommandError,
|
|
7
10
|
canonicalCommandJson,
|
|
8
11
|
commandIdentifier,
|
|
9
|
-
|
|
12
|
+
decodeValidatedCommandReference,
|
|
10
13
|
decodeDurableCommandReceipt
|
|
11
14
|
} from "@supacloud/contracts";
|
|
12
15
|
var plaintextCommandInput = {
|
|
@@ -33,7 +36,14 @@ function commandContext(definition) {
|
|
|
33
36
|
const name = commandIdentifier(definition.name), event = commandIdentifier(definition.audit.event);
|
|
34
37
|
const reference = (identity, key) => {
|
|
35
38
|
try {
|
|
36
|
-
return {
|
|
39
|
+
return {
|
|
40
|
+
...decodeValidatedCommandReference({
|
|
41
|
+
...identity,
|
|
42
|
+
command: name,
|
|
43
|
+
operationId: key,
|
|
44
|
+
dispatchKey: key
|
|
45
|
+
})
|
|
46
|
+
};
|
|
37
47
|
} catch {
|
|
38
48
|
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
39
49
|
}
|
|
@@ -141,6 +151,15 @@ function commandContext(definition) {
|
|
|
141
151
|
return { prepare, lock, find, restore, transaction, audit, insert };
|
|
142
152
|
}
|
|
143
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
|
+
|
|
144
163
|
// src/execution-policy.ts
|
|
145
164
|
class ExecutionPolicyError extends Error {
|
|
146
165
|
code;
|
|
@@ -153,7 +172,8 @@ class ExecutionPolicyError extends Error {
|
|
|
153
172
|
function createExecutionPolicy(options) {
|
|
154
173
|
const retry = options.retry ? { ...options.retry } : undefined;
|
|
155
174
|
const circuit = options.circuit ? { ...options.circuit } : undefined;
|
|
156
|
-
const { kind, timeoutMs } = options;
|
|
175
|
+
const { kind, timeoutMs, observer } = options;
|
|
176
|
+
const emit = (event) => emitCommandObservation(observer, { kind, ...event });
|
|
157
177
|
for (const value of [timeoutMs, retry?.maxAttempts, retry?.delayMs, circuit?.failureThreshold, circuit?.resetAfterMs]) {
|
|
158
178
|
if (value !== undefined && (!Number.isSafeInteger(value) || value < 1 || value > 2147483647)) {
|
|
159
179
|
throw new TypeError("Execution policy values must be positive bounded integers");
|
|
@@ -165,11 +185,15 @@ function createExecutionPolicy(options) {
|
|
|
165
185
|
let generation = 0;
|
|
166
186
|
return Object.freeze({
|
|
167
187
|
async execute(run, parent) {
|
|
168
|
-
if (parent?.aborted)
|
|
188
|
+
if (parent?.aborted) {
|
|
189
|
+
emit({ attempt: 0, phase: "rejected", reason: "EXECUTION_ABORTED" });
|
|
169
190
|
throw new ExecutionPolicyError("EXECUTION_ABORTED");
|
|
191
|
+
}
|
|
170
192
|
const halfOpen = openUntil !== 0;
|
|
171
|
-
if (halfOpen && (Date.now() < openUntil || probe))
|
|
193
|
+
if (halfOpen && (Date.now() < openUntil || probe)) {
|
|
194
|
+
emit({ attempt: 0, phase: "rejected", reason: "CIRCUIT_OPEN" });
|
|
172
195
|
throw new ExecutionPolicyError("CIRCUIT_OPEN");
|
|
196
|
+
}
|
|
173
197
|
if (halfOpen)
|
|
174
198
|
probe = true;
|
|
175
199
|
const currentGeneration = generation;
|
|
@@ -184,9 +208,12 @@ function createExecutionPolicy(options) {
|
|
|
184
208
|
const cancelled = () => new ExecutionPolicyError(kind === "command" ? "COMMAND_OUTCOME_UNKNOWN" : expired ? "EXECUTION_TIMEOUT" : "EXECUTION_ABORTED");
|
|
185
209
|
try {
|
|
186
210
|
for (let attempt = 1;; attempt++) {
|
|
187
|
-
if (controller.signal.aborted)
|
|
211
|
+
if (controller.signal.aborted) {
|
|
212
|
+
emit({ attempt, phase: "rejected", reason: cancelled().code });
|
|
188
213
|
throw cancelled();
|
|
214
|
+
}
|
|
189
215
|
try {
|
|
216
|
+
emit({ attempt, phase: "started" });
|
|
190
217
|
const result = await run(controller.signal);
|
|
191
218
|
if (controller.signal.aborted)
|
|
192
219
|
throw cancelled();
|
|
@@ -197,17 +224,25 @@ function createExecutionPolicy(options) {
|
|
|
197
224
|
generation++;
|
|
198
225
|
}
|
|
199
226
|
}
|
|
227
|
+
emit({ attempt, phase: "succeeded" });
|
|
200
228
|
return result;
|
|
201
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
|
+
});
|
|
202
236
|
if (controller.signal.aborted)
|
|
203
237
|
throw cancelled();
|
|
204
|
-
if (
|
|
238
|
+
if (unknownOutcome)
|
|
205
239
|
throw error;
|
|
206
240
|
if (!retry || halfOpen || attempt >= retry.maxAttempts)
|
|
207
241
|
throw error;
|
|
208
242
|
const decision = retry.classify(error);
|
|
209
243
|
if (decision !== "rolled-back" && !(kind === "read" && decision === "retry"))
|
|
210
244
|
throw error;
|
|
245
|
+
emit({ attempt, phase: "retry", reason: decision });
|
|
211
246
|
await new Promise((resolve) => {
|
|
212
247
|
const done = () => {
|
|
213
248
|
clearTimeout(wait);
|
|
@@ -456,6 +491,7 @@ function createCommandRecoveryHandler(options) {
|
|
|
456
491
|
const tenantId = commandIdentifier2(options.tenantId);
|
|
457
492
|
const principal = { subject: commandIdentifier2(options.principal.subject) };
|
|
458
493
|
const commands = { ...options.commands }, { workflows, authorize } = options;
|
|
494
|
+
const observer = options.observer;
|
|
459
495
|
const delaySeconds = options.retryDelaySeconds;
|
|
460
496
|
if (!Number.isSafeInteger(delaySeconds) || delaySeconds < 0 || delaySeconds > 86400)
|
|
461
497
|
throw new TypeError("Invalid recovery delay");
|
|
@@ -468,32 +504,64 @@ function createCommandRecoveryHandler(options) {
|
|
|
468
504
|
const command = commands[reference.command];
|
|
469
505
|
if (!command)
|
|
470
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
|
+
};
|
|
471
527
|
let receipt;
|
|
472
528
|
try {
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
if (
|
|
477
|
-
|
|
478
|
-
for (const key of ["tenantId", "actorId", "command", "operationId"]) {
|
|
479
|
-
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)
|
|
480
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
|
+
}
|
|
481
539
|
}
|
|
482
|
-
|
|
540
|
+
return decoded;
|
|
541
|
+
});
|
|
483
542
|
} catch (error) {
|
|
484
543
|
if (error instanceof CommandError4 && (error.code === "COMMAND_INPUT_EXPIRED" || error.code === "COMMAND_RECEIPT_INVALID")) {
|
|
485
|
-
|
|
544
|
+
const reason = error.code;
|
|
545
|
+
await observe("fail", () => workflows.fail({ ...attempt, errorMessage: reason }), reason);
|
|
486
546
|
return "failed";
|
|
487
547
|
}
|
|
488
|
-
await
|
|
548
|
+
await observe("retry", () => workflows.retry({
|
|
549
|
+
...attempt,
|
|
550
|
+
errorMessage: "COMMAND_RECOVERY_FAILED",
|
|
551
|
+
delaySeconds
|
|
552
|
+
}), "COMMAND_RECOVERY_FAILED");
|
|
489
553
|
return "retry";
|
|
490
554
|
}
|
|
491
555
|
if (receipt?.status === "confirmed" && receipt.audit === "complete") {
|
|
492
556
|
const output = { commandId, status: "confirmed", audit: "complete" };
|
|
493
|
-
await workflows.complete({ ...attempt, stepOutput: output, runOutput: output });
|
|
557
|
+
await observe("complete", () => workflows.complete({ ...attempt, stepOutput: output, runOutput: output }));
|
|
494
558
|
return "completed";
|
|
495
559
|
}
|
|
496
|
-
await
|
|
560
|
+
await observe("retry", () => workflows.retry({
|
|
561
|
+
...attempt,
|
|
562
|
+
errorMessage: "COMMAND_RECOVERY_REQUIRED",
|
|
563
|
+
delaySeconds
|
|
564
|
+
}), "COMMAND_RECOVERY_REQUIRED");
|
|
497
565
|
return "retry";
|
|
498
566
|
}
|
|
499
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/store.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export type { OperationReference, StoredCommand, CommandStoreSession, CommandStore, RecoveryScope, CommandRetentionStore, } from "@supacloud/contracts";
|
|
1
|
+
export type { OperationReference, ValidatedOperationReference, StoredCommand, CommandStoreSession, CommandStore, RecoveryScope, RecoveryClaim, CommandRecoveryStore, CommandRetentionStore, } from "@supacloud/contracts";
|
package/dist/transactional.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type CommandIdentity, type DurableCommandReceipt } from "@supacloud/contracts";
|
|
1
|
+
import { type CommandIdentity, type DurableCommandReceipt, type ValidatedOperationReference } from "@supacloud/contracts";
|
|
2
2
|
import { type PersistentCommandDefinition } from "./context";
|
|
3
3
|
import type { CommandStore } from "./store";
|
|
4
4
|
import { type ExecutionPolicyOptions } from "./execution-policy";
|
|
@@ -6,7 +6,7 @@ type TransactionOf<Store extends CommandStore<unknown>> = Store extends CommandS
|
|
|
6
6
|
type TransactionalCommandDefinition<Input, Result, Store extends CommandStore<unknown>> = Omit<PersistentCommandDefinition<Input, Result, TransactionOf<Store>>, "store"> & {
|
|
7
7
|
executionPolicy?: Omit<ExecutionPolicyOptions, "kind">;
|
|
8
8
|
store: Store;
|
|
9
|
-
execute(transaction: TransactionOf<Store>, input: Input, identity:
|
|
9
|
+
execute(transaction: TransactionOf<Store>, input: Input, identity: ValidatedOperationReference, signal: AbortSignal): Promise<unknown>;
|
|
10
10
|
};
|
|
11
11
|
export declare function createTransactionalCommand<Input, Result, Store extends CommandStore<unknown>>(definition: TransactionalCommandDefinition<Input, Result, Store>): {
|
|
12
12
|
kind: "transactional";
|
package/dist/typebox.js
CHANGED
|
@@ -3,14 +3,17 @@ import { TypeCompiler } from "@sinclair/typebox/compiler";
|
|
|
3
3
|
import { Value } from "@sinclair/typebox/value";
|
|
4
4
|
|
|
5
5
|
// src/transactional.ts
|
|
6
|
-
import {
|
|
6
|
+
import {
|
|
7
|
+
CommandError as CommandError2,
|
|
8
|
+
canonicalCommandJson as canonicalCommandJson2
|
|
9
|
+
} from "@supacloud/contracts";
|
|
7
10
|
|
|
8
11
|
// src/context.ts
|
|
9
12
|
import {
|
|
10
13
|
CommandError,
|
|
11
14
|
canonicalCommandJson,
|
|
12
15
|
commandIdentifier,
|
|
13
|
-
|
|
16
|
+
decodeValidatedCommandReference,
|
|
14
17
|
decodeDurableCommandReceipt
|
|
15
18
|
} from "@supacloud/contracts";
|
|
16
19
|
var plaintextCommandInput = {
|
|
@@ -37,7 +40,14 @@ function commandContext(definition) {
|
|
|
37
40
|
const name = commandIdentifier(definition.name), event = commandIdentifier(definition.audit.event);
|
|
38
41
|
const reference = (identity, key) => {
|
|
39
42
|
try {
|
|
40
|
-
return {
|
|
43
|
+
return {
|
|
44
|
+
...decodeValidatedCommandReference({
|
|
45
|
+
...identity,
|
|
46
|
+
command: name,
|
|
47
|
+
operationId: key,
|
|
48
|
+
dispatchKey: key
|
|
49
|
+
})
|
|
50
|
+
};
|
|
41
51
|
} catch {
|
|
42
52
|
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
43
53
|
}
|
|
@@ -145,6 +155,15 @@ function commandContext(definition) {
|
|
|
145
155
|
return { prepare, lock, find, restore, transaction, audit, insert };
|
|
146
156
|
}
|
|
147
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
|
+
|
|
148
167
|
// src/execution-policy.ts
|
|
149
168
|
class ExecutionPolicyError extends Error {
|
|
150
169
|
code;
|
|
@@ -157,7 +176,8 @@ class ExecutionPolicyError extends Error {
|
|
|
157
176
|
function createExecutionPolicy(options) {
|
|
158
177
|
const retry = options.retry ? { ...options.retry } : undefined;
|
|
159
178
|
const circuit = options.circuit ? { ...options.circuit } : undefined;
|
|
160
|
-
const { kind, timeoutMs } = options;
|
|
179
|
+
const { kind, timeoutMs, observer } = options;
|
|
180
|
+
const emit = (event) => emitCommandObservation(observer, { kind, ...event });
|
|
161
181
|
for (const value of [timeoutMs, retry?.maxAttempts, retry?.delayMs, circuit?.failureThreshold, circuit?.resetAfterMs]) {
|
|
162
182
|
if (value !== undefined && (!Number.isSafeInteger(value) || value < 1 || value > 2147483647)) {
|
|
163
183
|
throw new TypeError("Execution policy values must be positive bounded integers");
|
|
@@ -169,11 +189,15 @@ function createExecutionPolicy(options) {
|
|
|
169
189
|
let generation = 0;
|
|
170
190
|
return Object.freeze({
|
|
171
191
|
async execute(run, parent) {
|
|
172
|
-
if (parent?.aborted)
|
|
192
|
+
if (parent?.aborted) {
|
|
193
|
+
emit({ attempt: 0, phase: "rejected", reason: "EXECUTION_ABORTED" });
|
|
173
194
|
throw new ExecutionPolicyError("EXECUTION_ABORTED");
|
|
195
|
+
}
|
|
174
196
|
const halfOpen = openUntil !== 0;
|
|
175
|
-
if (halfOpen && (Date.now() < openUntil || probe))
|
|
197
|
+
if (halfOpen && (Date.now() < openUntil || probe)) {
|
|
198
|
+
emit({ attempt: 0, phase: "rejected", reason: "CIRCUIT_OPEN" });
|
|
176
199
|
throw new ExecutionPolicyError("CIRCUIT_OPEN");
|
|
200
|
+
}
|
|
177
201
|
if (halfOpen)
|
|
178
202
|
probe = true;
|
|
179
203
|
const currentGeneration = generation;
|
|
@@ -188,9 +212,12 @@ function createExecutionPolicy(options) {
|
|
|
188
212
|
const cancelled = () => new ExecutionPolicyError(kind === "command" ? "COMMAND_OUTCOME_UNKNOWN" : expired ? "EXECUTION_TIMEOUT" : "EXECUTION_ABORTED");
|
|
189
213
|
try {
|
|
190
214
|
for (let attempt = 1;; attempt++) {
|
|
191
|
-
if (controller.signal.aborted)
|
|
215
|
+
if (controller.signal.aborted) {
|
|
216
|
+
emit({ attempt, phase: "rejected", reason: cancelled().code });
|
|
192
217
|
throw cancelled();
|
|
218
|
+
}
|
|
193
219
|
try {
|
|
220
|
+
emit({ attempt, phase: "started" });
|
|
194
221
|
const result = await run(controller.signal);
|
|
195
222
|
if (controller.signal.aborted)
|
|
196
223
|
throw cancelled();
|
|
@@ -201,17 +228,25 @@ function createExecutionPolicy(options) {
|
|
|
201
228
|
generation++;
|
|
202
229
|
}
|
|
203
230
|
}
|
|
231
|
+
emit({ attempt, phase: "succeeded" });
|
|
204
232
|
return result;
|
|
205
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
|
+
});
|
|
206
240
|
if (controller.signal.aborted)
|
|
207
241
|
throw cancelled();
|
|
208
|
-
if (
|
|
242
|
+
if (unknownOutcome)
|
|
209
243
|
throw error;
|
|
210
244
|
if (!retry || halfOpen || attempt >= retry.maxAttempts)
|
|
211
245
|
throw error;
|
|
212
246
|
const decision = retry.classify(error);
|
|
213
247
|
if (decision !== "rolled-back" && !(kind === "read" && decision === "retry"))
|
|
214
248
|
throw error;
|
|
249
|
+
emit({ attempt, phase: "retry", reason: decision });
|
|
215
250
|
await new Promise((resolve) => {
|
|
216
251
|
const done = () => {
|
|
217
252
|
clearTimeout(wait);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@supacloud/commands",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"description": "Storage-independent durable command execution and recovery",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -29,7 +29,7 @@
|
|
|
29
29
|
"prepublishOnly": "bun run build"
|
|
30
30
|
},
|
|
31
31
|
"dependencies": {
|
|
32
|
-
"@supacloud/contracts": "0.
|
|
32
|
+
"@supacloud/contracts": "0.5.0"
|
|
33
33
|
},
|
|
34
34
|
"devDependencies": {
|
|
35
35
|
"@sinclair/typebox": "0.34.52",
|