@supacloud/commands 0.4.0 → 0.5.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 +22 -0
- package/dist/execution-policy.d.ts +27 -0
- package/dist/external.d.ts +2 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +127 -5
- package/dist/transactional.d.ts +4 -2
- package/dist/typebox.d.ts +40 -0
- package/dist/typebox.js +334 -0
- package/package.json +15 -2
package/README.md
CHANGED
|
@@ -1,5 +1,27 @@
|
|
|
1
1
|
# @supacloud/commands
|
|
2
2
|
|
|
3
|
+
## Schema and Execution Policies
|
|
4
|
+
|
|
5
|
+
`@supacloud/commands/typebox` exports `createTypeBoxTransactionalCommand`.
|
|
6
|
+
Pass `schemas: { input, result }` to derive both handler types and runtime
|
|
7
|
+
validation from TypeBox. The concrete store transaction type is retained,
|
|
8
|
+
including Drizzle `transaction.db`. Typed callers use `execute` / `lookup`;
|
|
9
|
+
transport adapters use `executeUnknown` / `lookupUnknown`. Both validate at
|
|
10
|
+
runtime without coercion, defaults or transforms.
|
|
11
|
+
|
|
12
|
+
`createExecutionPolicy` provides explicit cooperative timeouts, classified retries
|
|
13
|
+
and a circuit breaker per host-owned operation. Transactional commands accept
|
|
14
|
+
`executionPolicy` and forward an `AbortSignal` to the handler; pass it to drivers.
|
|
15
|
+
Read retries require classification as `retry` or `rolled-back`; command retries
|
|
16
|
+
require a driver-confirmed `rolled-back` failure. Unknown write outcomes and
|
|
17
|
+
external dispatches are never automatically retried. Recover via durable receipts.
|
|
18
|
+
|
|
19
|
+
Timeout requests cancellation but retains ownership until the driver settles.
|
|
20
|
+
An uncooperative driver can exceed the timeout. Transactional cancellation is
|
|
21
|
+
conservatively reported as `COMMAND_OUTCOME_UNKNOWN`, not proof of rollback.
|
|
22
|
+
Circuit `isFailure` should exclude authorization, schema and domain rejection.
|
|
23
|
+
Circuit state is local to the policy instance, not distributed.
|
|
24
|
+
|
|
3
25
|
Storage-independent durable execution. Depends only on `@supacloud/contracts`;
|
|
4
26
|
no SQL driver, HTTP server, Svelte lifecycle or scheduler is bundled.
|
|
5
27
|
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export declare class ExecutionPolicyError extends Error {
|
|
2
|
+
readonly code: "CIRCUIT_OPEN" | "EXECUTION_ABORTED" | "EXECUTION_TIMEOUT" | "COMMAND_OUTCOME_UNKNOWN";
|
|
3
|
+
constructor(code: "CIRCUIT_OPEN" | "EXECUTION_ABORTED" | "EXECUTION_TIMEOUT" | "COMMAND_OUTCOME_UNKNOWN");
|
|
4
|
+
}
|
|
5
|
+
type RetryDecision = "retry" | "rolled-back" | "stop";
|
|
6
|
+
export interface ExecutionPolicyOptions {
|
|
7
|
+
kind: "read" | "command";
|
|
8
|
+
/** Cooperative cancellation. The operation must forward the signal to its driver. */
|
|
9
|
+
timeoutMs?: number;
|
|
10
|
+
retry?: {
|
|
11
|
+
maxAttempts: number;
|
|
12
|
+
delayMs: number;
|
|
13
|
+
/** Commands may retry only a driver-confirmed rollback, never an unknown outcome. */
|
|
14
|
+
classify(error: unknown): RetryDecision;
|
|
15
|
+
};
|
|
16
|
+
circuit?: {
|
|
17
|
+
failureThreshold: number;
|
|
18
|
+
resetAfterMs: number;
|
|
19
|
+
/** Exclude authorization, validation and business-rule rejection. */
|
|
20
|
+
isFailure(error: unknown): boolean;
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
/** One instance per named operation/authority boundary, explicitly constructed by the host. */
|
|
24
|
+
export declare function createExecutionPolicy(options: ExecutionPolicyOptions): Readonly<{
|
|
25
|
+
execute<Result>(run: (signal: AbortSignal) => Promise<Result>, parent?: AbortSignal): Promise<Result>;
|
|
26
|
+
}>;
|
|
27
|
+
export {};
|
package/dist/external.d.ts
CHANGED
|
@@ -3,6 +3,7 @@ import { type PersistentCommandDefinition, type RecoveryPrincipal } from "./cont
|
|
|
3
3
|
import type { CommandStore, OperationReference } from "./store";
|
|
4
4
|
export interface ExternalDispatch {
|
|
5
5
|
idempotencyKey: string;
|
|
6
|
+
signal?: AbortSignal;
|
|
6
7
|
}
|
|
7
8
|
type TransactionOf<Store extends CommandStore<unknown>> = Store extends CommandStore<infer Transaction> ? Transaction : never;
|
|
8
9
|
type ExternalCommandDefinition<Input, Result, Store extends CommandStore<unknown>> = Omit<PersistentCommandDefinition<Input, Result, TransactionOf<Store>>, "store"> & {
|
|
@@ -13,7 +14,7 @@ type ExternalCommandDefinition<Input, Result, Store extends CommandStore<unknown
|
|
|
13
14
|
};
|
|
14
15
|
export declare function createExternalCommand<Input, Result, Store extends CommandStore<unknown>>(definition: ExternalCommandDefinition<Input, Result, Store>): {
|
|
15
16
|
kind: "external";
|
|
16
|
-
execute(identity: CommandIdentity, key: string, value: unknown): Promise<import("@supacloud/contracts").DurableCommandReceipt<Result>>;
|
|
17
|
+
execute(identity: CommandIdentity, key: string, value: unknown, signal?: AbortSignal): Promise<import("@supacloud/contracts").DurableCommandReceipt<Result>>;
|
|
17
18
|
lookup: (identity: CommandIdentity, key: string, value: unknown, principal?: RecoveryPrincipal) => Promise<import("@supacloud/contracts").DurableCommandReceipt<Result> | null>;
|
|
18
19
|
reconcile: (identity: CommandIdentity, key: string, value: unknown, principal?: RecoveryPrincipal) => Promise<import("@supacloud/contracts").DurableCommandReceipt<Result> | null>;
|
|
19
20
|
flushAudit: (identity: CommandIdentity, key: string, value: unknown, principal?: RecoveryPrincipal) => Promise<import("@supacloud/contracts").DurableCommandReceipt<Result> | null>;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
export { createTransactionalCommand } from "./transactional";
|
|
2
|
+
export { createExecutionPolicy, ExecutionPolicyError, type ExecutionPolicyOptions } from "./execution-policy";
|
|
2
3
|
export { createExternalCommand, type ExternalDispatch } from "./external";
|
|
3
4
|
export { plaintextCommandInput, type CommandInputCodec, type PersistentCommandDefinition, type RecoveryPrincipal } from "./context";
|
|
4
5
|
export { createCommandRecoveryHandler, type RecoverableCommand, type CommandWorkflowPort, type CommandWorkflowAttempt } from "./recovery";
|
package/dist/index.js
CHANGED
|
@@ -141,26 +141,141 @@ function commandContext(definition) {
|
|
|
141
141
|
return { prepare, lock, find, restore, transaction, audit, insert };
|
|
142
142
|
}
|
|
143
143
|
|
|
144
|
+
// src/execution-policy.ts
|
|
145
|
+
class ExecutionPolicyError extends Error {
|
|
146
|
+
code;
|
|
147
|
+
constructor(code) {
|
|
148
|
+
super(code);
|
|
149
|
+
this.code = code;
|
|
150
|
+
this.name = "ExecutionPolicyError";
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
function createExecutionPolicy(options) {
|
|
154
|
+
const retry = options.retry ? { ...options.retry } : undefined;
|
|
155
|
+
const circuit = options.circuit ? { ...options.circuit } : undefined;
|
|
156
|
+
const { kind, timeoutMs } = options;
|
|
157
|
+
for (const value of [timeoutMs, retry?.maxAttempts, retry?.delayMs, circuit?.failureThreshold, circuit?.resetAfterMs]) {
|
|
158
|
+
if (value !== undefined && (!Number.isSafeInteger(value) || value < 1 || value > 2147483647)) {
|
|
159
|
+
throw new TypeError("Execution policy values must be positive bounded integers");
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
let failures = 0;
|
|
163
|
+
let openUntil = 0;
|
|
164
|
+
let probe = false;
|
|
165
|
+
let generation = 0;
|
|
166
|
+
return Object.freeze({
|
|
167
|
+
async execute(run, parent) {
|
|
168
|
+
if (parent?.aborted)
|
|
169
|
+
throw new ExecutionPolicyError("EXECUTION_ABORTED");
|
|
170
|
+
const halfOpen = openUntil !== 0;
|
|
171
|
+
if (halfOpen && (Date.now() < openUntil || probe))
|
|
172
|
+
throw new ExecutionPolicyError("CIRCUIT_OPEN");
|
|
173
|
+
if (halfOpen)
|
|
174
|
+
probe = true;
|
|
175
|
+
const currentGeneration = generation;
|
|
176
|
+
const controller = new AbortController;
|
|
177
|
+
let expired = false;
|
|
178
|
+
const abort = () => controller.abort();
|
|
179
|
+
parent?.addEventListener("abort", abort, { once: true });
|
|
180
|
+
const timer = timeoutMs === undefined ? undefined : setTimeout(() => {
|
|
181
|
+
expired = true;
|
|
182
|
+
controller.abort();
|
|
183
|
+
}, timeoutMs);
|
|
184
|
+
const cancelled = () => new ExecutionPolicyError(kind === "command" ? "COMMAND_OUTCOME_UNKNOWN" : expired ? "EXECUTION_TIMEOUT" : "EXECUTION_ABORTED");
|
|
185
|
+
try {
|
|
186
|
+
for (let attempt = 1;; attempt++) {
|
|
187
|
+
if (controller.signal.aborted)
|
|
188
|
+
throw cancelled();
|
|
189
|
+
try {
|
|
190
|
+
const result = await run(controller.signal);
|
|
191
|
+
if (controller.signal.aborted)
|
|
192
|
+
throw cancelled();
|
|
193
|
+
if (currentGeneration === generation) {
|
|
194
|
+
failures = 0;
|
|
195
|
+
if (halfOpen) {
|
|
196
|
+
openUntil = 0;
|
|
197
|
+
generation++;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
return result;
|
|
201
|
+
} catch (error) {
|
|
202
|
+
if (controller.signal.aborted)
|
|
203
|
+
throw cancelled();
|
|
204
|
+
if (kind === "command" && error !== null && typeof error === "object" && "code" in error && error.code === "COMMAND_OUTCOME_UNKNOWN")
|
|
205
|
+
throw error;
|
|
206
|
+
if (!retry || halfOpen || attempt >= retry.maxAttempts)
|
|
207
|
+
throw error;
|
|
208
|
+
const decision = retry.classify(error);
|
|
209
|
+
if (decision !== "rolled-back" && !(kind === "read" && decision === "retry"))
|
|
210
|
+
throw error;
|
|
211
|
+
await new Promise((resolve) => {
|
|
212
|
+
const done = () => {
|
|
213
|
+
clearTimeout(wait);
|
|
214
|
+
controller.signal.removeEventListener("abort", done);
|
|
215
|
+
resolve();
|
|
216
|
+
};
|
|
217
|
+
const wait = setTimeout(done, retry.delayMs);
|
|
218
|
+
controller.signal.addEventListener("abort", done, { once: true });
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
} catch (error) {
|
|
223
|
+
if (circuit && currentGeneration === generation) {
|
|
224
|
+
if (circuit.isFailure(error)) {
|
|
225
|
+
failures++;
|
|
226
|
+
if (halfOpen || failures >= circuit.failureThreshold) {
|
|
227
|
+
openUntil = Date.now() + circuit.resetAfterMs;
|
|
228
|
+
generation++;
|
|
229
|
+
}
|
|
230
|
+
} else if (halfOpen) {
|
|
231
|
+
openUntil = 0;
|
|
232
|
+
failures = 0;
|
|
233
|
+
generation++;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
throw error;
|
|
237
|
+
} finally {
|
|
238
|
+
clearTimeout(timer);
|
|
239
|
+
parent?.removeEventListener("abort", abort);
|
|
240
|
+
if (halfOpen)
|
|
241
|
+
probe = false;
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
|
|
144
247
|
// src/transactional.ts
|
|
145
248
|
function createTransactionalCommand(definition) {
|
|
146
249
|
const context = commandContext(definition);
|
|
250
|
+
const policy = createExecutionPolicy({ ...definition.executionPolicy, kind: "command" });
|
|
147
251
|
return {
|
|
148
252
|
kind: "transactional",
|
|
149
|
-
async execute(identity, key, value) {
|
|
253
|
+
async execute(identity, key, value, signal) {
|
|
150
254
|
const request = await context.prepare(identity, key, value);
|
|
151
|
-
return context.transaction(async (session) => {
|
|
255
|
+
return policy.execute((signal) => context.transaction(async (session) => {
|
|
256
|
+
if (signal.aborted)
|
|
257
|
+
throw new CommandError2("COMMAND_OUTCOME_UNKNOWN");
|
|
152
258
|
await context.lock(session, request);
|
|
153
259
|
const existing = await context.find(session, request, "transactional");
|
|
154
260
|
if (existing !== null)
|
|
155
261
|
return existing;
|
|
156
|
-
const raw = JSON.parse(canonicalCommandJson2(await definition.execute(session.transaction, request.input, request.reference)));
|
|
262
|
+
const raw = JSON.parse(canonicalCommandJson2(await definition.execute(session.transaction, request.input, request.reference, signal)));
|
|
157
263
|
const result = definition.result(raw);
|
|
264
|
+
if (signal.aborted)
|
|
265
|
+
throw new CommandError2("COMMAND_OUTCOME_UNKNOWN");
|
|
158
266
|
await context.insert(session, request, "transactional", { result: raw });
|
|
159
267
|
await context.audit(session, request, result);
|
|
268
|
+
if (signal.aborted)
|
|
269
|
+
throw new CommandError2("COMMAND_OUTCOME_UNKNOWN");
|
|
160
270
|
const receipt = await context.find(session, request, "transactional");
|
|
161
271
|
if (receipt === null)
|
|
162
272
|
throw new CommandError2("COMMAND_RECEIPT_INVALID");
|
|
163
273
|
return receipt;
|
|
274
|
+
}), signal).catch((error) => {
|
|
275
|
+
if (error instanceof ExecutionPolicyError) {
|
|
276
|
+
throw new CommandError2(error.code === "COMMAND_OUTCOME_UNKNOWN" ? error.code : "COMMAND_UNAVAILABLE");
|
|
277
|
+
}
|
|
278
|
+
throw error;
|
|
164
279
|
});
|
|
165
280
|
},
|
|
166
281
|
async lookup(identity, key, value) {
|
|
@@ -237,7 +352,9 @@ function createExternalCommand(definition) {
|
|
|
237
352
|
};
|
|
238
353
|
return {
|
|
239
354
|
kind: "external",
|
|
240
|
-
async execute(identity, key, value) {
|
|
355
|
+
async execute(identity, key, value, signal) {
|
|
356
|
+
if (signal?.aborted)
|
|
357
|
+
throw new CommandError3("COMMAND_UNAVAILABLE");
|
|
241
358
|
const request = await context.prepare(identity, key, value);
|
|
242
359
|
const acquired = await context.transaction(async (session) => {
|
|
243
360
|
await context.lock(session, request);
|
|
@@ -253,7 +370,10 @@ function createExternalCommand(definition) {
|
|
|
253
370
|
if (!acquired.fresh)
|
|
254
371
|
return acquired.receipt;
|
|
255
372
|
try {
|
|
256
|
-
await definition.send(request.input, {
|
|
373
|
+
await definition.send(request.input, {
|
|
374
|
+
idempotencyKey: acquired.receipt.dispatchKey,
|
|
375
|
+
...signal === undefined ? {} : { signal }
|
|
376
|
+
});
|
|
257
377
|
} catch {}
|
|
258
378
|
try {
|
|
259
379
|
const receipt = await reconcile(identity, key, request.input);
|
|
@@ -379,7 +499,9 @@ function createCommandRecoveryHandler(options) {
|
|
|
379
499
|
};
|
|
380
500
|
}
|
|
381
501
|
export {
|
|
502
|
+
ExecutionPolicyError,
|
|
382
503
|
createCommandRecoveryHandler,
|
|
504
|
+
createExecutionPolicy,
|
|
383
505
|
createExternalCommand,
|
|
384
506
|
createTransactionalCommand,
|
|
385
507
|
plaintextCommandInput
|
package/dist/transactional.d.ts
CHANGED
|
@@ -1,14 +1,16 @@
|
|
|
1
1
|
import { type CommandIdentity, type DurableCommandReceipt } from "@supacloud/contracts";
|
|
2
2
|
import { type PersistentCommandDefinition } from "./context";
|
|
3
3
|
import type { CommandStore } from "./store";
|
|
4
|
+
import { type ExecutionPolicyOptions } from "./execution-policy";
|
|
4
5
|
type TransactionOf<Store extends CommandStore<unknown>> = Store extends CommandStore<infer Transaction> ? Transaction : never;
|
|
5
6
|
type TransactionalCommandDefinition<Input, Result, Store extends CommandStore<unknown>> = Omit<PersistentCommandDefinition<Input, Result, TransactionOf<Store>>, "store"> & {
|
|
7
|
+
executionPolicy?: Omit<ExecutionPolicyOptions, "kind">;
|
|
6
8
|
store: Store;
|
|
7
|
-
execute(transaction: TransactionOf<Store>, input: Input, identity: CommandIdentity): Promise<unknown>;
|
|
9
|
+
execute(transaction: TransactionOf<Store>, input: Input, identity: CommandIdentity, signal: AbortSignal): Promise<unknown>;
|
|
8
10
|
};
|
|
9
11
|
export declare function createTransactionalCommand<Input, Result, Store extends CommandStore<unknown>>(definition: TransactionalCommandDefinition<Input, Result, Store>): {
|
|
10
12
|
kind: "transactional";
|
|
11
|
-
execute(identity: CommandIdentity, key: string, value: unknown): Promise<DurableCommandReceipt<Result>>;
|
|
13
|
+
execute(identity: CommandIdentity, key: string, value: unknown, signal?: AbortSignal): Promise<DurableCommandReceipt<Result>>;
|
|
12
14
|
lookup(identity: CommandIdentity, key: string, value: unknown): Promise<DurableCommandReceipt<Result> | null>;
|
|
13
15
|
lookupByReference(identity: CommandIdentity, key: string): Promise<DurableCommandReceipt<Result> | null>;
|
|
14
16
|
};
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { Static, TSchema } from "@sinclair/typebox";
|
|
2
|
+
import type { CommandIdentity } from "@supacloud/contracts";
|
|
3
|
+
import type { CommandStore } from "./store";
|
|
4
|
+
import type { PersistentCommandDefinition } from "./context";
|
|
5
|
+
import type { ExecutionPolicyOptions } from "./execution-policy";
|
|
6
|
+
type TransactionOf<Store extends CommandStore<unknown>> = Store extends CommandStore<infer Transaction> ? Transaction : never;
|
|
7
|
+
export interface TypeBoxCommandSchemas<InputSchema extends TSchema, ResultSchema extends TSchema> {
|
|
8
|
+
readonly input: InputSchema;
|
|
9
|
+
readonly result: ResultSchema;
|
|
10
|
+
}
|
|
11
|
+
export type TypeBoxCommandDefinition<InputSchema extends TSchema, ResultSchema extends TSchema, Store extends CommandStore<unknown>> = Omit<PersistentCommandDefinition<NoInfer<Static<InputSchema>>, NoInfer<Static<ResultSchema>>, NoInfer<TransactionOf<Store>>>, "store" | "input" | "result"> & {
|
|
12
|
+
readonly store: Store;
|
|
13
|
+
readonly executionPolicy?: Omit<ExecutionPolicyOptions, "kind">;
|
|
14
|
+
readonly schemas: TypeBoxCommandSchemas<InputSchema, ResultSchema>;
|
|
15
|
+
execute(transaction: NoInfer<TransactionOf<Store>>, input: NoInfer<Static<InputSchema>>, identity: CommandIdentity, signal: AbortSignal): Promise<NoInfer<Static<ResultSchema>>>;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* Schema-first, JSON-preserving use case. Validation does not coerce, apply
|
|
19
|
+
* defaults or run TypeBox transforms; types describe the encoded JSON shape.
|
|
20
|
+
* Storage, authorization, receipts and audit stay with the existing executor.
|
|
21
|
+
*/
|
|
22
|
+
export declare function createTypeBoxTransactionalCommand<const InputSchema extends TSchema, const ResultSchema extends TSchema, Store extends CommandStore<unknown>>(definition: TypeBoxCommandDefinition<InputSchema, ResultSchema, Store>): Readonly<{
|
|
23
|
+
kind: "transactional";
|
|
24
|
+
execute(identity: CommandIdentity, key: string, value: Static<InputSchema>, signal?: AbortSignal): Promise<import("@supacloud/contracts").DurableCommandReceipt<NoInfer<(ResultSchema & {
|
|
25
|
+
params: [];
|
|
26
|
+
})["static"]>>>;
|
|
27
|
+
lookup(identity: CommandIdentity, key: string, value: Static<InputSchema>): Promise<import("@supacloud/contracts").DurableCommandReceipt<NoInfer<(ResultSchema & {
|
|
28
|
+
params: [];
|
|
29
|
+
})["static"]>> | null>;
|
|
30
|
+
executeUnknown: (identity: CommandIdentity, key: string, value: unknown, signal?: AbortSignal) => Promise<import("@supacloud/contracts").DurableCommandReceipt<NoInfer<(ResultSchema & {
|
|
31
|
+
params: [];
|
|
32
|
+
})["static"]>>>;
|
|
33
|
+
lookupUnknown: (identity: CommandIdentity, key: string, value: unknown) => Promise<import("@supacloud/contracts").DurableCommandReceipt<NoInfer<(ResultSchema & {
|
|
34
|
+
params: [];
|
|
35
|
+
})["static"]>> | null>;
|
|
36
|
+
lookupByReference: (identity: CommandIdentity, key: string) => Promise<import("@supacloud/contracts").DurableCommandReceipt<NoInfer<(ResultSchema & {
|
|
37
|
+
params: [];
|
|
38
|
+
})["static"]>> | null>;
|
|
39
|
+
}>;
|
|
40
|
+
export {};
|
package/dist/typebox.js
ADDED
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
// src/typebox.ts
|
|
2
|
+
import { TypeCompiler } from "@sinclair/typebox/compiler";
|
|
3
|
+
import { Value } from "@sinclair/typebox/value";
|
|
4
|
+
|
|
5
|
+
// src/transactional.ts
|
|
6
|
+
import { CommandError as CommandError2, canonicalCommandJson as canonicalCommandJson2 } from "@supacloud/contracts";
|
|
7
|
+
|
|
8
|
+
// src/context.ts
|
|
9
|
+
import {
|
|
10
|
+
CommandError,
|
|
11
|
+
canonicalCommandJson,
|
|
12
|
+
commandIdentifier,
|
|
13
|
+
decodeCommandIdentity,
|
|
14
|
+
decodeDurableCommandReceipt
|
|
15
|
+
} from "@supacloud/contracts";
|
|
16
|
+
var plaintextCommandInput = {
|
|
17
|
+
encode: (value) => value,
|
|
18
|
+
decode: (value) => value
|
|
19
|
+
};
|
|
20
|
+
async function fingerprint(value) {
|
|
21
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value));
|
|
22
|
+
return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
23
|
+
}
|
|
24
|
+
async function checkAuthorization(run) {
|
|
25
|
+
let decision;
|
|
26
|
+
try {
|
|
27
|
+
decision = await run();
|
|
28
|
+
} catch {
|
|
29
|
+
throw new CommandError("COMMAND_UNAVAILABLE");
|
|
30
|
+
}
|
|
31
|
+
if (decision === "deny")
|
|
32
|
+
throw new CommandError("COMMAND_REJECTED");
|
|
33
|
+
if (decision !== "allow")
|
|
34
|
+
throw new CommandError("COMMAND_UNAVAILABLE");
|
|
35
|
+
}
|
|
36
|
+
function commandContext(definition) {
|
|
37
|
+
const name = commandIdentifier(definition.name), event = commandIdentifier(definition.audit.event);
|
|
38
|
+
const reference = (identity, key) => {
|
|
39
|
+
try {
|
|
40
|
+
return { ...decodeCommandIdentity(identity), command: name, operationId: commandIdentifier(key) };
|
|
41
|
+
} catch {
|
|
42
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
const prepare = async (identity, key, value) => {
|
|
46
|
+
const ref = reference(identity, key);
|
|
47
|
+
let input, canonical;
|
|
48
|
+
try {
|
|
49
|
+
canonical = canonicalCommandJson(definition.input(value));
|
|
50
|
+
const json = JSON.parse(canonical);
|
|
51
|
+
input = definition.input(json);
|
|
52
|
+
if (canonicalCommandJson(input) !== canonical)
|
|
53
|
+
throw new Error("Unstable input codec");
|
|
54
|
+
} catch {
|
|
55
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
56
|
+
}
|
|
57
|
+
let payload;
|
|
58
|
+
try {
|
|
59
|
+
payload = await definition.inputCodec.encode(canonical);
|
|
60
|
+
} catch {
|
|
61
|
+
throw new CommandError("COMMAND_UNAVAILABLE");
|
|
62
|
+
}
|
|
63
|
+
if (typeof payload !== "string")
|
|
64
|
+
throw new CommandError("COMMAND_UNAVAILABLE");
|
|
65
|
+
return { reference: ref, input, fingerprint: await fingerprint(canonical), payload };
|
|
66
|
+
};
|
|
67
|
+
const authorize = async (session, request, principal) => {
|
|
68
|
+
if (principal !== undefined) {
|
|
69
|
+
commandIdentifier(principal.subject);
|
|
70
|
+
const authorizeRecovery = definition.authorizeRecovery;
|
|
71
|
+
if (!authorizeRecovery)
|
|
72
|
+
throw new CommandError("COMMAND_REJECTED");
|
|
73
|
+
await checkAuthorization(() => authorizeRecovery(principal, request.reference, session.transaction));
|
|
74
|
+
} else {
|
|
75
|
+
await checkAuthorization(() => definition.authorize(request.reference, request.input, session.transaction));
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
const lock = async (session, request, principal) => {
|
|
79
|
+
await session.lock(request.reference);
|
|
80
|
+
await authorize(session, request, principal);
|
|
81
|
+
};
|
|
82
|
+
const find = async (session, request, kind) => {
|
|
83
|
+
const stored = await session.read(request.reference);
|
|
84
|
+
if (stored === null)
|
|
85
|
+
return null;
|
|
86
|
+
if (stored.inputFingerprint !== request.fingerprint || stored.kind !== kind)
|
|
87
|
+
throw new CommandError("COMMAND_IDEMPOTENCY_CONFLICT");
|
|
88
|
+
try {
|
|
89
|
+
const receipt = decodeDurableCommandReceipt(stored.receipt, definition.result);
|
|
90
|
+
for (const key of ["tenantId", "actorId", "command", "operationId"]) {
|
|
91
|
+
if (receipt[key] !== request.reference[key])
|
|
92
|
+
throw new Error("Mismatched receipt");
|
|
93
|
+
}
|
|
94
|
+
if (kind === "transactional" && (receipt.status !== "confirmed" || receipt.audit !== "complete"))
|
|
95
|
+
throw new Error("Invalid receipt state");
|
|
96
|
+
return receipt;
|
|
97
|
+
} catch {
|
|
98
|
+
throw new CommandError("COMMAND_RECEIPT_INVALID");
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
const transaction = async (run) => {
|
|
102
|
+
try {
|
|
103
|
+
return await definition.store.transaction(run);
|
|
104
|
+
} catch (error) {
|
|
105
|
+
if (error instanceof CommandError)
|
|
106
|
+
throw error;
|
|
107
|
+
throw new CommandError("COMMAND_OUTCOME_UNKNOWN");
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
const restore = async (identity, key, principal) => {
|
|
111
|
+
const ref = reference(identity, key);
|
|
112
|
+
return transaction(async (session) => {
|
|
113
|
+
await session.lock(ref);
|
|
114
|
+
const stored = await session.read(ref);
|
|
115
|
+
if (stored === null)
|
|
116
|
+
return null;
|
|
117
|
+
if (stored.inputPayload === null)
|
|
118
|
+
throw new CommandError("COMMAND_INPUT_EXPIRED");
|
|
119
|
+
let json;
|
|
120
|
+
try {
|
|
121
|
+
const decoded = await definition.inputCodec.decode(stored.inputPayload);
|
|
122
|
+
if (typeof decoded !== "string")
|
|
123
|
+
throw new Error("Invalid payload");
|
|
124
|
+
json = JSON.parse(decoded);
|
|
125
|
+
} catch {
|
|
126
|
+
throw new CommandError("COMMAND_UNAVAILABLE");
|
|
127
|
+
}
|
|
128
|
+
const request = await prepare(identity, key, json);
|
|
129
|
+
if (request.fingerprint !== stored.inputFingerprint)
|
|
130
|
+
throw new CommandError("COMMAND_RECEIPT_INVALID");
|
|
131
|
+
await authorize(session, request, principal);
|
|
132
|
+
return request;
|
|
133
|
+
});
|
|
134
|
+
};
|
|
135
|
+
const audit = async (session, request, result) => {
|
|
136
|
+
const details = JSON.parse(canonicalCommandJson(definition.audit.details(request.input, result)));
|
|
137
|
+
await definition.audit.write?.(session.transaction, request.input, result);
|
|
138
|
+
await session.audit(request.reference, event, details);
|
|
139
|
+
};
|
|
140
|
+
const insert = async (session, request, kind, raw) => {
|
|
141
|
+
const reference = { ...request.reference, dispatchKey: crypto.randomUUID() };
|
|
142
|
+
const receipt = raw === undefined ? { ...reference, status: "pending", audit: "pending" } : { ...reference, status: "confirmed", audit: "complete", result: raw.result };
|
|
143
|
+
await session.insert({ receipt, kind, inputFingerprint: request.fingerprint, inputPayload: request.payload });
|
|
144
|
+
};
|
|
145
|
+
return { prepare, lock, find, restore, transaction, audit, insert };
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// src/execution-policy.ts
|
|
149
|
+
class ExecutionPolicyError extends Error {
|
|
150
|
+
code;
|
|
151
|
+
constructor(code) {
|
|
152
|
+
super(code);
|
|
153
|
+
this.code = code;
|
|
154
|
+
this.name = "ExecutionPolicyError";
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
function createExecutionPolicy(options) {
|
|
158
|
+
const retry = options.retry ? { ...options.retry } : undefined;
|
|
159
|
+
const circuit = options.circuit ? { ...options.circuit } : undefined;
|
|
160
|
+
const { kind, timeoutMs } = options;
|
|
161
|
+
for (const value of [timeoutMs, retry?.maxAttempts, retry?.delayMs, circuit?.failureThreshold, circuit?.resetAfterMs]) {
|
|
162
|
+
if (value !== undefined && (!Number.isSafeInteger(value) || value < 1 || value > 2147483647)) {
|
|
163
|
+
throw new TypeError("Execution policy values must be positive bounded integers");
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
let failures = 0;
|
|
167
|
+
let openUntil = 0;
|
|
168
|
+
let probe = false;
|
|
169
|
+
let generation = 0;
|
|
170
|
+
return Object.freeze({
|
|
171
|
+
async execute(run, parent) {
|
|
172
|
+
if (parent?.aborted)
|
|
173
|
+
throw new ExecutionPolicyError("EXECUTION_ABORTED");
|
|
174
|
+
const halfOpen = openUntil !== 0;
|
|
175
|
+
if (halfOpen && (Date.now() < openUntil || probe))
|
|
176
|
+
throw new ExecutionPolicyError("CIRCUIT_OPEN");
|
|
177
|
+
if (halfOpen)
|
|
178
|
+
probe = true;
|
|
179
|
+
const currentGeneration = generation;
|
|
180
|
+
const controller = new AbortController;
|
|
181
|
+
let expired = false;
|
|
182
|
+
const abort = () => controller.abort();
|
|
183
|
+
parent?.addEventListener("abort", abort, { once: true });
|
|
184
|
+
const timer = timeoutMs === undefined ? undefined : setTimeout(() => {
|
|
185
|
+
expired = true;
|
|
186
|
+
controller.abort();
|
|
187
|
+
}, timeoutMs);
|
|
188
|
+
const cancelled = () => new ExecutionPolicyError(kind === "command" ? "COMMAND_OUTCOME_UNKNOWN" : expired ? "EXECUTION_TIMEOUT" : "EXECUTION_ABORTED");
|
|
189
|
+
try {
|
|
190
|
+
for (let attempt = 1;; attempt++) {
|
|
191
|
+
if (controller.signal.aborted)
|
|
192
|
+
throw cancelled();
|
|
193
|
+
try {
|
|
194
|
+
const result = await run(controller.signal);
|
|
195
|
+
if (controller.signal.aborted)
|
|
196
|
+
throw cancelled();
|
|
197
|
+
if (currentGeneration === generation) {
|
|
198
|
+
failures = 0;
|
|
199
|
+
if (halfOpen) {
|
|
200
|
+
openUntil = 0;
|
|
201
|
+
generation++;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
return result;
|
|
205
|
+
} catch (error) {
|
|
206
|
+
if (controller.signal.aborted)
|
|
207
|
+
throw cancelled();
|
|
208
|
+
if (kind === "command" && error !== null && typeof error === "object" && "code" in error && error.code === "COMMAND_OUTCOME_UNKNOWN")
|
|
209
|
+
throw error;
|
|
210
|
+
if (!retry || halfOpen || attempt >= retry.maxAttempts)
|
|
211
|
+
throw error;
|
|
212
|
+
const decision = retry.classify(error);
|
|
213
|
+
if (decision !== "rolled-back" && !(kind === "read" && decision === "retry"))
|
|
214
|
+
throw error;
|
|
215
|
+
await new Promise((resolve) => {
|
|
216
|
+
const done = () => {
|
|
217
|
+
clearTimeout(wait);
|
|
218
|
+
controller.signal.removeEventListener("abort", done);
|
|
219
|
+
resolve();
|
|
220
|
+
};
|
|
221
|
+
const wait = setTimeout(done, retry.delayMs);
|
|
222
|
+
controller.signal.addEventListener("abort", done, { once: true });
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
} catch (error) {
|
|
227
|
+
if (circuit && currentGeneration === generation) {
|
|
228
|
+
if (circuit.isFailure(error)) {
|
|
229
|
+
failures++;
|
|
230
|
+
if (halfOpen || failures >= circuit.failureThreshold) {
|
|
231
|
+
openUntil = Date.now() + circuit.resetAfterMs;
|
|
232
|
+
generation++;
|
|
233
|
+
}
|
|
234
|
+
} else if (halfOpen) {
|
|
235
|
+
openUntil = 0;
|
|
236
|
+
failures = 0;
|
|
237
|
+
generation++;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
throw error;
|
|
241
|
+
} finally {
|
|
242
|
+
clearTimeout(timer);
|
|
243
|
+
parent?.removeEventListener("abort", abort);
|
|
244
|
+
if (halfOpen)
|
|
245
|
+
probe = false;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// src/transactional.ts
|
|
252
|
+
function createTransactionalCommand(definition) {
|
|
253
|
+
const context = commandContext(definition);
|
|
254
|
+
const policy = createExecutionPolicy({ ...definition.executionPolicy, kind: "command" });
|
|
255
|
+
return {
|
|
256
|
+
kind: "transactional",
|
|
257
|
+
async execute(identity, key, value, signal) {
|
|
258
|
+
const request = await context.prepare(identity, key, value);
|
|
259
|
+
return policy.execute((signal) => context.transaction(async (session) => {
|
|
260
|
+
if (signal.aborted)
|
|
261
|
+
throw new CommandError2("COMMAND_OUTCOME_UNKNOWN");
|
|
262
|
+
await context.lock(session, request);
|
|
263
|
+
const existing = await context.find(session, request, "transactional");
|
|
264
|
+
if (existing !== null)
|
|
265
|
+
return existing;
|
|
266
|
+
const raw = JSON.parse(canonicalCommandJson2(await definition.execute(session.transaction, request.input, request.reference, signal)));
|
|
267
|
+
const result = definition.result(raw);
|
|
268
|
+
if (signal.aborted)
|
|
269
|
+
throw new CommandError2("COMMAND_OUTCOME_UNKNOWN");
|
|
270
|
+
await context.insert(session, request, "transactional", { result: raw });
|
|
271
|
+
await context.audit(session, request, result);
|
|
272
|
+
if (signal.aborted)
|
|
273
|
+
throw new CommandError2("COMMAND_OUTCOME_UNKNOWN");
|
|
274
|
+
const receipt = await context.find(session, request, "transactional");
|
|
275
|
+
if (receipt === null)
|
|
276
|
+
throw new CommandError2("COMMAND_RECEIPT_INVALID");
|
|
277
|
+
return receipt;
|
|
278
|
+
}), signal).catch((error) => {
|
|
279
|
+
if (error instanceof ExecutionPolicyError) {
|
|
280
|
+
throw new CommandError2(error.code === "COMMAND_OUTCOME_UNKNOWN" ? error.code : "COMMAND_UNAVAILABLE");
|
|
281
|
+
}
|
|
282
|
+
throw error;
|
|
283
|
+
});
|
|
284
|
+
},
|
|
285
|
+
async lookup(identity, key, value) {
|
|
286
|
+
const request = await context.prepare(identity, key, value);
|
|
287
|
+
return context.transaction(async (session) => {
|
|
288
|
+
await context.lock(session, request);
|
|
289
|
+
return context.find(session, request, "transactional");
|
|
290
|
+
});
|
|
291
|
+
},
|
|
292
|
+
async lookupByReference(identity, key) {
|
|
293
|
+
const request = await context.restore(identity, key);
|
|
294
|
+
if (request === null)
|
|
295
|
+
return null;
|
|
296
|
+
return context.transaction(async (session) => {
|
|
297
|
+
await context.lock(session, request);
|
|
298
|
+
return context.find(session, request, "transactional");
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// src/typebox.ts
|
|
305
|
+
function decoder(schema) {
|
|
306
|
+
const validator = TypeCompiler.Compile(Value.Clone(schema));
|
|
307
|
+
return (value) => {
|
|
308
|
+
if (!validator.Check(value))
|
|
309
|
+
throw new TypeError("Invalid command schema value");
|
|
310
|
+
return value;
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
function createTypeBoxTransactionalCommand(definition) {
|
|
314
|
+
const command = createTransactionalCommand({
|
|
315
|
+
...definition,
|
|
316
|
+
input: decoder(definition.schemas.input),
|
|
317
|
+
result: decoder(definition.schemas.result)
|
|
318
|
+
});
|
|
319
|
+
return Object.freeze({
|
|
320
|
+
kind: command.kind,
|
|
321
|
+
execute(identity, key, value, signal) {
|
|
322
|
+
return command.execute(identity, key, value, signal);
|
|
323
|
+
},
|
|
324
|
+
lookup(identity, key, value) {
|
|
325
|
+
return command.lookup(identity, key, value);
|
|
326
|
+
},
|
|
327
|
+
executeUnknown: command.execute,
|
|
328
|
+
lookupUnknown: command.lookup,
|
|
329
|
+
lookupByReference: command.lookupByReference
|
|
330
|
+
});
|
|
331
|
+
}
|
|
332
|
+
export {
|
|
333
|
+
createTypeBoxTransactionalCommand
|
|
334
|
+
};
|
package/package.json
CHANGED
|
@@ -1,11 +1,15 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@supacloud/commands",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "Storage-independent durable command execution and recovery",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
7
7
|
"types": "./dist/index.d.ts",
|
|
8
8
|
"exports": {
|
|
9
|
+
"./typebox": {
|
|
10
|
+
"types": "./dist/typebox.d.ts",
|
|
11
|
+
"import": "./dist/typebox.js"
|
|
12
|
+
},
|
|
9
13
|
".": {
|
|
10
14
|
"types": "./dist/index.d.ts",
|
|
11
15
|
"import": "./dist/index.js"
|
|
@@ -17,7 +21,7 @@
|
|
|
17
21
|
],
|
|
18
22
|
"scripts": {
|
|
19
23
|
"build": "bun run build:js && bun run build:types",
|
|
20
|
-
"build:js": "bun build src/index.ts --outdir dist --target node --external @supacloud/contracts",
|
|
24
|
+
"build:js": "bun build src/index.ts src/typebox.ts --outdir dist --target node --external @supacloud/contracts --external @sinclair/typebox",
|
|
21
25
|
"build:types": "tsc -p tsconfig.json --emitDeclarationOnly",
|
|
22
26
|
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
23
27
|
"typecheck:test": "tsc -p tsconfig.test.json --noEmit",
|
|
@@ -28,9 +32,18 @@
|
|
|
28
32
|
"@supacloud/contracts": "0.4.0"
|
|
29
33
|
},
|
|
30
34
|
"devDependencies": {
|
|
35
|
+
"@sinclair/typebox": "0.34.52",
|
|
31
36
|
"@types/bun": "1.4.2",
|
|
32
37
|
"typescript": "7.0.2"
|
|
33
38
|
},
|
|
39
|
+
"peerDependencies": {
|
|
40
|
+
"@sinclair/typebox": "0.34.52"
|
|
41
|
+
},
|
|
42
|
+
"peerDependenciesMeta": {
|
|
43
|
+
"@sinclair/typebox": {
|
|
44
|
+
"optional": true
|
|
45
|
+
}
|
|
46
|
+
},
|
|
34
47
|
"license": "MIT",
|
|
35
48
|
"repository": {
|
|
36
49
|
"type": "git",
|