@supacloud/commands 0.3.1
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 +49 -0
- package/dist/context.d.ts +45 -0
- package/dist/external.d.ts +21 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +386 -0
- package/dist/recovery.d.ts +37 -0
- package/dist/store.d.ts +1 -0
- package/dist/transactional.d.ts +10 -0
- package/package.json +40 -0
package/README.md
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# @supacloud/commands
|
|
2
|
+
|
|
3
|
+
Storage-independent durable execution. Depends only on `@supacloud/contracts`;
|
|
4
|
+
no SQL driver, HTTP server, Svelte lifecycle or scheduler is bundled.
|
|
5
|
+
|
|
6
|
+
## Execution
|
|
7
|
+
|
|
8
|
+
- `createTransactionalCommand`: one store transaction contains authorization,
|
|
9
|
+
business mutation, validated receipt and audit. Use the provided transaction
|
|
10
|
+
for every local business/audit write.
|
|
11
|
+
- `createExternalCommand`: commits intent before one send. Duplicate execution,
|
|
12
|
+
reconciliation, audit recovery and background recovery never resend.
|
|
13
|
+
- `createCommandRecoveryHandler`: handles one already-claimed Workflow recovery
|
|
14
|
+
step. Explicit tenant, named handlers and worker authorization; no claim loop,
|
|
15
|
+
independent leases, retention scheduler or business redispatch.
|
|
16
|
+
|
|
17
|
+
All factories require a `store`, domain input/result decoders, an `inputCodec`,
|
|
18
|
+
an explicit `"allow"` / `"deny"` policy and domain audit metadata. A thrown or
|
|
19
|
+
invalid authorization decision means `COMMAND_UNAVAILABLE`, never denial.
|
|
20
|
+
Choose `plaintextCommandInput` only for non-secret inputs; use a host-owned
|
|
21
|
+
authenticated encryption codec and key lifecycle otherwise. Fingerprints are
|
|
22
|
+
not encryption; receipts/results and audit details need their own data policy.
|
|
23
|
+
|
|
24
|
+
PostgreSQL integration uses `createPostgresCommandStore` from `@supacloud/db`.
|
|
25
|
+
The storage interfaces are owned by contracts and re-exported here as types.
|
|
26
|
+
Other stores must provide equivalent transaction and receipt guarantees; merely
|
|
27
|
+
implementing the TypeScript interface does not prove persistence correctness.
|
|
28
|
+
|
|
29
|
+
## Recovery
|
|
30
|
+
|
|
31
|
+
Interactive methods reauthorize the original actor. Worker `recover` requires
|
|
32
|
+
independent `authorizeRecovery(principal, reference, transaction)` and keeps
|
|
33
|
+
the original receipt identity. No recovery policy means denial. Neither method
|
|
34
|
+
assumes that a cancelled or failed request rolled back.
|
|
35
|
+
|
|
36
|
+
Pass `supacloud.workflows` as the handler's `workflows` port. The existing dispatcher
|
|
37
|
+
routes reconcile steps to `run(claim)` and other steps to their registered handlers.
|
|
38
|
+
PGMQ/Workflow owns delivery, visibility, attempts and dead-letter state. Completion
|
|
39
|
+
requires confirmed business output and complete audit, not merely a successful
|
|
40
|
+
lookup call. Bound lookup duration and monitor failed/unknown operations.
|
|
41
|
+
|
|
42
|
+
Redaction keeps fingerprints and receipts: same-input explicit replay deduplicates;
|
|
43
|
+
different input conflicts; reference-only lookup returns `COMMAND_INPUT_EXPIRED`.
|
|
44
|
+
Never issue a new operation just because the old input expired.
|
|
45
|
+
Already confirmed/audited receipts can still acknowledge a delayed recovery step
|
|
46
|
+
after input redaction. Retention is a separate maintenance operation.
|
|
47
|
+
|
|
48
|
+
See [breaking changes, schema upgrade, release and rollback](../../docs/command-migration.md).
|
|
49
|
+
Run `bun run typecheck`, `bun run typecheck:test`, `bun test` and `bun run build`.
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { type CommandAuthorization, type CommandIdentity, type ContractDecoder, type DurableCommandReceipt } from "@supacloud/contracts";
|
|
2
|
+
import type { CommandStore, CommandStoreSession, OperationReference, StoredCommand } from "./store";
|
|
3
|
+
export interface CommandInputCodec {
|
|
4
|
+
encode(canonicalInput: string): string | Promise<string>;
|
|
5
|
+
decode(payload: string): string | Promise<string>;
|
|
6
|
+
}
|
|
7
|
+
/** Explicit opt-in for non-secret inputs. Supply an authenticated encryption codec otherwise. */
|
|
8
|
+
export declare const plaintextCommandInput: CommandInputCodec;
|
|
9
|
+
export interface RecoveryPrincipal {
|
|
10
|
+
subject: string;
|
|
11
|
+
}
|
|
12
|
+
export interface PersistentCommandDefinition<Input, Result, Transaction> {
|
|
13
|
+
store: CommandStore<Transaction>;
|
|
14
|
+
name: string;
|
|
15
|
+
input: ContractDecoder<Input>;
|
|
16
|
+
result: ContractDecoder<Result>;
|
|
17
|
+
inputCodec: CommandInputCodec;
|
|
18
|
+
authorize(identity: CommandIdentity, input: Input, transaction: Transaction): CommandAuthorization | Promise<CommandAuthorization>;
|
|
19
|
+
/** Independent worker authorization; never impersonate a revoked interactive session. */
|
|
20
|
+
authorizeRecovery?(principal: RecoveryPrincipal, reference: OperationReference, transaction: Transaction): CommandAuthorization | Promise<CommandAuthorization>;
|
|
21
|
+
audit: {
|
|
22
|
+
event: string;
|
|
23
|
+
details(input: Input, result: Result): unknown;
|
|
24
|
+
write?(transaction: Transaction, input: Input, result: Result): Promise<void>;
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
interface Prepared<Input> {
|
|
28
|
+
reference: OperationReference;
|
|
29
|
+
input: Input;
|
|
30
|
+
fingerprint: string;
|
|
31
|
+
payload: string;
|
|
32
|
+
}
|
|
33
|
+
export declare function checkAuthorization(run: () => CommandAuthorization | Promise<CommandAuthorization>): Promise<void>;
|
|
34
|
+
export declare function commandContext<Input, Result, Transaction>(definition: PersistentCommandDefinition<Input, Result, Transaction>): {
|
|
35
|
+
prepare: (identity: CommandIdentity, key: string, value: unknown) => Promise<Prepared<Input>>;
|
|
36
|
+
lock: (session: CommandStoreSession<Transaction>, request: Prepared<Input>, principal?: RecoveryPrincipal) => Promise<void>;
|
|
37
|
+
find: (session: CommandStoreSession<Transaction>, request: Prepared<Input>, kind: StoredCommand["kind"]) => Promise<DurableCommandReceipt<Result> | null>;
|
|
38
|
+
restore: (identity: CommandIdentity, key: string, principal?: RecoveryPrincipal) => Promise<Prepared<Input> | null>;
|
|
39
|
+
transaction: <T>(run: (session: CommandStoreSession<Transaction>) => Promise<T>) => Promise<T>;
|
|
40
|
+
audit: (session: CommandStoreSession<Transaction>, request: Prepared<Input>, result: Result) => Promise<void>;
|
|
41
|
+
insert: (session: CommandStoreSession<Transaction>, request: Prepared<Input>, kind: StoredCommand["kind"], raw?: {
|
|
42
|
+
result: unknown;
|
|
43
|
+
}) => Promise<void>;
|
|
44
|
+
};
|
|
45
|
+
export {};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { type CommandIdentity } from "@supacloud/contracts";
|
|
2
|
+
import { type PersistentCommandDefinition, type RecoveryPrincipal } from "./context";
|
|
3
|
+
import type { OperationReference } from "./store";
|
|
4
|
+
export interface ExternalDispatch {
|
|
5
|
+
idempotencyKey: string;
|
|
6
|
+
}
|
|
7
|
+
export declare function createExternalCommand<Input, Result, Transaction>(definition: PersistentCommandDefinition<Input, Result, Transaction> & {
|
|
8
|
+
send(input: Input, dispatch: ExternalDispatch): Promise<unknown>;
|
|
9
|
+
lookup(input: Input, dispatch: ExternalDispatch): Promise<unknown>;
|
|
10
|
+
matches(input: Input, result: Result): boolean;
|
|
11
|
+
}): {
|
|
12
|
+
kind: "external";
|
|
13
|
+
execute(identity: CommandIdentity, key: string, value: unknown): Promise<import("@supacloud/contracts").DurableCommandReceipt<Result>>;
|
|
14
|
+
lookup: (identity: CommandIdentity, key: string, value: unknown, principal?: RecoveryPrincipal) => Promise<import("@supacloud/contracts").DurableCommandReceipt<Result> | null>;
|
|
15
|
+
reconcile: (identity: CommandIdentity, key: string, value: unknown, principal?: RecoveryPrincipal) => Promise<import("@supacloud/contracts").DurableCommandReceipt<Result> | null>;
|
|
16
|
+
flushAudit: (identity: CommandIdentity, key: string, value: unknown, principal?: RecoveryPrincipal) => Promise<import("@supacloud/contracts").DurableCommandReceipt<Result> | null>;
|
|
17
|
+
lookupByReference(identity: CommandIdentity, key: string): Promise<import("@supacloud/contracts").DurableCommandReceipt<Result> | null>;
|
|
18
|
+
reconcileByReference(identity: CommandIdentity, key: string): Promise<import("@supacloud/contracts").DurableCommandReceipt<Result> | null>;
|
|
19
|
+
flushAuditByReference(identity: CommandIdentity, key: string): Promise<import("@supacloud/contracts").DurableCommandReceipt<Result> | null>;
|
|
20
|
+
recover(principal: RecoveryPrincipal, reference: OperationReference): Promise<import("@supacloud/contracts").DurableCommandReceipt<Result> | null>;
|
|
21
|
+
};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { createTransactionalCommand } from "./transactional";
|
|
2
|
+
export { createExternalCommand, type ExternalDispatch } from "./external";
|
|
3
|
+
export { plaintextCommandInput, type CommandInputCodec, type PersistentCommandDefinition, type RecoveryPrincipal } from "./context";
|
|
4
|
+
export { createCommandRecoveryHandler, type RecoverableCommand, type CommandWorkflowPort, type CommandWorkflowAttempt } from "./recovery";
|
|
5
|
+
export type { CommandStore, CommandStoreSession, StoredCommand, OperationReference, CommandRetentionStore, RecoveryScope, } from "./store";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,386 @@
|
|
|
1
|
+
// src/transactional.ts
|
|
2
|
+
import { CommandError as CommandError2, canonicalCommandJson as canonicalCommandJson2 } from "@supacloud/contracts";
|
|
3
|
+
|
|
4
|
+
// src/context.ts
|
|
5
|
+
import {
|
|
6
|
+
CommandError,
|
|
7
|
+
canonicalCommandJson,
|
|
8
|
+
commandIdentifier,
|
|
9
|
+
decodeCommandIdentity,
|
|
10
|
+
decodeDurableCommandReceipt
|
|
11
|
+
} from "@supacloud/contracts";
|
|
12
|
+
var plaintextCommandInput = {
|
|
13
|
+
encode: (value) => value,
|
|
14
|
+
decode: (value) => value
|
|
15
|
+
};
|
|
16
|
+
async function fingerprint(value) {
|
|
17
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value));
|
|
18
|
+
return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
19
|
+
}
|
|
20
|
+
async function checkAuthorization(run) {
|
|
21
|
+
let decision;
|
|
22
|
+
try {
|
|
23
|
+
decision = await run();
|
|
24
|
+
} catch {
|
|
25
|
+
throw new CommandError("COMMAND_UNAVAILABLE");
|
|
26
|
+
}
|
|
27
|
+
if (decision === "deny")
|
|
28
|
+
throw new CommandError("COMMAND_REJECTED");
|
|
29
|
+
if (decision !== "allow")
|
|
30
|
+
throw new CommandError("COMMAND_UNAVAILABLE");
|
|
31
|
+
}
|
|
32
|
+
function commandContext(definition) {
|
|
33
|
+
const name = commandIdentifier(definition.name), event = commandIdentifier(definition.audit.event);
|
|
34
|
+
const reference = (identity, key) => {
|
|
35
|
+
try {
|
|
36
|
+
return { ...decodeCommandIdentity(identity), command: name, operationId: commandIdentifier(key) };
|
|
37
|
+
} catch {
|
|
38
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
const prepare = async (identity, key, value) => {
|
|
42
|
+
const ref = reference(identity, key);
|
|
43
|
+
let input, canonical;
|
|
44
|
+
try {
|
|
45
|
+
canonical = canonicalCommandJson(definition.input(value));
|
|
46
|
+
const json = JSON.parse(canonical);
|
|
47
|
+
input = definition.input(json);
|
|
48
|
+
if (canonicalCommandJson(input) !== canonical)
|
|
49
|
+
throw new Error("Unstable input codec");
|
|
50
|
+
} catch {
|
|
51
|
+
throw new CommandError("COMMAND_INPUT_INVALID");
|
|
52
|
+
}
|
|
53
|
+
let payload;
|
|
54
|
+
try {
|
|
55
|
+
payload = await definition.inputCodec.encode(canonical);
|
|
56
|
+
} catch {
|
|
57
|
+
throw new CommandError("COMMAND_UNAVAILABLE");
|
|
58
|
+
}
|
|
59
|
+
if (typeof payload !== "string")
|
|
60
|
+
throw new CommandError("COMMAND_UNAVAILABLE");
|
|
61
|
+
return { reference: ref, input, fingerprint: await fingerprint(canonical), payload };
|
|
62
|
+
};
|
|
63
|
+
const authorize = async (session, request, principal) => {
|
|
64
|
+
if (principal !== undefined) {
|
|
65
|
+
commandIdentifier(principal.subject);
|
|
66
|
+
const authorizeRecovery = definition.authorizeRecovery;
|
|
67
|
+
if (!authorizeRecovery)
|
|
68
|
+
throw new CommandError("COMMAND_REJECTED");
|
|
69
|
+
await checkAuthorization(() => authorizeRecovery(principal, request.reference, session.transaction));
|
|
70
|
+
} else {
|
|
71
|
+
await checkAuthorization(() => definition.authorize(request.reference, request.input, session.transaction));
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
const lock = async (session, request, principal) => {
|
|
75
|
+
await session.lock(request.reference);
|
|
76
|
+
await authorize(session, request, principal);
|
|
77
|
+
};
|
|
78
|
+
const find = async (session, request, kind) => {
|
|
79
|
+
const stored = await session.read(request.reference);
|
|
80
|
+
if (stored === null)
|
|
81
|
+
return null;
|
|
82
|
+
if (stored.inputFingerprint !== request.fingerprint || stored.kind !== kind)
|
|
83
|
+
throw new CommandError("COMMAND_IDEMPOTENCY_CONFLICT");
|
|
84
|
+
try {
|
|
85
|
+
const receipt = decodeDurableCommandReceipt(stored.receipt, definition.result);
|
|
86
|
+
for (const key of ["tenantId", "actorId", "command", "operationId"]) {
|
|
87
|
+
if (receipt[key] !== request.reference[key])
|
|
88
|
+
throw new Error("Mismatched receipt");
|
|
89
|
+
}
|
|
90
|
+
if (kind === "transactional" && (receipt.status !== "confirmed" || receipt.audit !== "complete"))
|
|
91
|
+
throw new Error("Invalid receipt state");
|
|
92
|
+
return receipt;
|
|
93
|
+
} catch {
|
|
94
|
+
throw new CommandError("COMMAND_RECEIPT_INVALID");
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
const transaction = async (run) => {
|
|
98
|
+
try {
|
|
99
|
+
return await definition.store.transaction(run);
|
|
100
|
+
} catch (error) {
|
|
101
|
+
if (error instanceof CommandError)
|
|
102
|
+
throw error;
|
|
103
|
+
throw new CommandError("COMMAND_OUTCOME_UNKNOWN");
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
const restore = async (identity, key, principal) => {
|
|
107
|
+
const ref = reference(identity, key);
|
|
108
|
+
return transaction(async (session) => {
|
|
109
|
+
await session.lock(ref);
|
|
110
|
+
const stored = await session.read(ref);
|
|
111
|
+
if (stored === null)
|
|
112
|
+
return null;
|
|
113
|
+
if (stored.inputPayload === null)
|
|
114
|
+
throw new CommandError("COMMAND_INPUT_EXPIRED");
|
|
115
|
+
let json;
|
|
116
|
+
try {
|
|
117
|
+
const decoded = await definition.inputCodec.decode(stored.inputPayload);
|
|
118
|
+
if (typeof decoded !== "string")
|
|
119
|
+
throw new Error("Invalid payload");
|
|
120
|
+
json = JSON.parse(decoded);
|
|
121
|
+
} catch {
|
|
122
|
+
throw new CommandError("COMMAND_UNAVAILABLE");
|
|
123
|
+
}
|
|
124
|
+
const request = await prepare(identity, key, json);
|
|
125
|
+
if (request.fingerprint !== stored.inputFingerprint)
|
|
126
|
+
throw new CommandError("COMMAND_RECEIPT_INVALID");
|
|
127
|
+
await authorize(session, request, principal);
|
|
128
|
+
return request;
|
|
129
|
+
});
|
|
130
|
+
};
|
|
131
|
+
const audit = async (session, request, result) => {
|
|
132
|
+
const details = JSON.parse(canonicalCommandJson(definition.audit.details(request.input, result)));
|
|
133
|
+
await definition.audit.write?.(session.transaction, request.input, result);
|
|
134
|
+
await session.audit(request.reference, event, details);
|
|
135
|
+
};
|
|
136
|
+
const insert = async (session, request, kind, raw) => {
|
|
137
|
+
const reference = { ...request.reference, dispatchKey: crypto.randomUUID() };
|
|
138
|
+
const receipt = raw === undefined ? { ...reference, status: "pending", audit: "pending" } : { ...reference, status: "confirmed", audit: "complete", result: raw.result };
|
|
139
|
+
await session.insert({ receipt, kind, inputFingerprint: request.fingerprint, inputPayload: request.payload });
|
|
140
|
+
};
|
|
141
|
+
return { prepare, lock, find, restore, transaction, audit, insert };
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// src/transactional.ts
|
|
145
|
+
function createTransactionalCommand(definition) {
|
|
146
|
+
const context = commandContext(definition);
|
|
147
|
+
return {
|
|
148
|
+
kind: "transactional",
|
|
149
|
+
async execute(identity, key, value) {
|
|
150
|
+
const request = await context.prepare(identity, key, value);
|
|
151
|
+
return context.transaction(async (session) => {
|
|
152
|
+
await context.lock(session, request);
|
|
153
|
+
const existing = await context.find(session, request, "transactional");
|
|
154
|
+
if (existing !== null)
|
|
155
|
+
return existing;
|
|
156
|
+
const raw = JSON.parse(canonicalCommandJson2(await definition.execute(session.transaction, request.input, request.reference)));
|
|
157
|
+
const result = definition.result(raw);
|
|
158
|
+
await context.insert(session, request, "transactional", { result: raw });
|
|
159
|
+
await context.audit(session, request, result);
|
|
160
|
+
const receipt = await context.find(session, request, "transactional");
|
|
161
|
+
if (receipt === null)
|
|
162
|
+
throw new CommandError2("COMMAND_RECEIPT_INVALID");
|
|
163
|
+
return receipt;
|
|
164
|
+
});
|
|
165
|
+
},
|
|
166
|
+
async lookup(identity, key, value) {
|
|
167
|
+
const request = await context.prepare(identity, key, value);
|
|
168
|
+
return context.transaction(async (session) => {
|
|
169
|
+
await context.lock(session, request);
|
|
170
|
+
return context.find(session, request, "transactional");
|
|
171
|
+
});
|
|
172
|
+
},
|
|
173
|
+
async lookupByReference(identity, key) {
|
|
174
|
+
const request = await context.restore(identity, key);
|
|
175
|
+
if (request === null)
|
|
176
|
+
return null;
|
|
177
|
+
return context.transaction(async (session) => {
|
|
178
|
+
await context.lock(session, request);
|
|
179
|
+
return context.find(session, request, "transactional");
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
// src/external.ts
|
|
185
|
+
import { CommandError as CommandError3, canonicalCommandJson as canonicalCommandJson3, decodeDurableCommandReceipt as decodeDurableCommandReceipt2 } from "@supacloud/contracts";
|
|
186
|
+
function createExternalCommand(definition) {
|
|
187
|
+
const context = commandContext(definition);
|
|
188
|
+
const read = async (identity, key, value, principal) => {
|
|
189
|
+
const request = await context.prepare(identity, key, value);
|
|
190
|
+
return context.transaction(async (session) => {
|
|
191
|
+
await context.lock(session, request, principal);
|
|
192
|
+
return context.find(session, request, "external");
|
|
193
|
+
});
|
|
194
|
+
};
|
|
195
|
+
const flushAudit = async (identity, key, value, principal) => {
|
|
196
|
+
const request = await context.prepare(identity, key, value);
|
|
197
|
+
return context.transaction(async (session) => {
|
|
198
|
+
await context.lock(session, request, principal);
|
|
199
|
+
const receipt = await context.find(session, request, "external");
|
|
200
|
+
if (receipt === null || receipt.status !== "confirmed" || receipt.audit === "complete")
|
|
201
|
+
return receipt;
|
|
202
|
+
await context.audit(session, request, receipt.result);
|
|
203
|
+
await session.completeAudit(request.reference);
|
|
204
|
+
return context.find(session, request, "external");
|
|
205
|
+
});
|
|
206
|
+
};
|
|
207
|
+
const reconcile = async (identity, key, value, principal) => {
|
|
208
|
+
const request = await context.prepare(identity, key, value);
|
|
209
|
+
const before = await read(identity, key, value, principal);
|
|
210
|
+
if (before === null)
|
|
211
|
+
return null;
|
|
212
|
+
let confirmation;
|
|
213
|
+
if (before.status !== "confirmed") {
|
|
214
|
+
try {
|
|
215
|
+
const raw = JSON.parse(canonicalCommandJson3(await definition.lookup(request.input, { idempotencyKey: before.dispatchKey })));
|
|
216
|
+
if (definition.matches(request.input, definition.result(raw)) === true)
|
|
217
|
+
confirmation = { raw };
|
|
218
|
+
} catch {}
|
|
219
|
+
}
|
|
220
|
+
const receipt = await context.transaction(async (session) => {
|
|
221
|
+
await context.lock(session, request, principal);
|
|
222
|
+
if (confirmation !== undefined)
|
|
223
|
+
await session.confirm(request.reference, confirmation.raw);
|
|
224
|
+
else if (before.status !== "confirmed")
|
|
225
|
+
await session.markUnknown(request.reference);
|
|
226
|
+
return context.find(session, request, "external");
|
|
227
|
+
});
|
|
228
|
+
if (receipt?.status !== "confirmed" || receipt.audit === "complete")
|
|
229
|
+
return receipt;
|
|
230
|
+
try {
|
|
231
|
+
return await flushAudit(identity, key, value, principal);
|
|
232
|
+
} catch (error) {
|
|
233
|
+
if (error instanceof CommandError3 && error.code === "COMMAND_REJECTED")
|
|
234
|
+
throw error;
|
|
235
|
+
return receipt;
|
|
236
|
+
}
|
|
237
|
+
};
|
|
238
|
+
return {
|
|
239
|
+
kind: "external",
|
|
240
|
+
async execute(identity, key, value) {
|
|
241
|
+
const request = await context.prepare(identity, key, value);
|
|
242
|
+
const acquired = await context.transaction(async (session) => {
|
|
243
|
+
await context.lock(session, request);
|
|
244
|
+
const existing = await context.find(session, request, "external");
|
|
245
|
+
if (existing !== null)
|
|
246
|
+
return { fresh: false, receipt: existing };
|
|
247
|
+
await context.insert(session, request, "external");
|
|
248
|
+
const receipt = await context.find(session, request, "external");
|
|
249
|
+
if (receipt === null)
|
|
250
|
+
throw new CommandError3("COMMAND_RECEIPT_INVALID");
|
|
251
|
+
return { fresh: true, receipt };
|
|
252
|
+
});
|
|
253
|
+
if (!acquired.fresh)
|
|
254
|
+
return acquired.receipt;
|
|
255
|
+
try {
|
|
256
|
+
await definition.send(request.input, { idempotencyKey: acquired.receipt.dispatchKey });
|
|
257
|
+
} catch {}
|
|
258
|
+
try {
|
|
259
|
+
const receipt = await reconcile(identity, key, request.input);
|
|
260
|
+
if (receipt === null)
|
|
261
|
+
throw new Error("Missing receipt");
|
|
262
|
+
return receipt;
|
|
263
|
+
} catch {
|
|
264
|
+
throw new CommandError3("COMMAND_OUTCOME_UNKNOWN");
|
|
265
|
+
}
|
|
266
|
+
},
|
|
267
|
+
lookup: read,
|
|
268
|
+
reconcile,
|
|
269
|
+
flushAudit,
|
|
270
|
+
async lookupByReference(identity, key) {
|
|
271
|
+
const request = await context.restore(identity, key);
|
|
272
|
+
return request === null ? null : read(identity, key, request.input);
|
|
273
|
+
},
|
|
274
|
+
async reconcileByReference(identity, key) {
|
|
275
|
+
const request = await context.restore(identity, key);
|
|
276
|
+
return request === null ? null : reconcile(identity, key, request.input);
|
|
277
|
+
},
|
|
278
|
+
async flushAuditByReference(identity, key) {
|
|
279
|
+
const request = await context.restore(identity, key);
|
|
280
|
+
return request === null ? null : flushAudit(identity, key, request.input);
|
|
281
|
+
},
|
|
282
|
+
async recover(principal, reference) {
|
|
283
|
+
if (reference.command !== definition.name)
|
|
284
|
+
throw new CommandError3("COMMAND_REJECTED");
|
|
285
|
+
const completed = await context.transaction(async (session) => {
|
|
286
|
+
await session.lock(reference);
|
|
287
|
+
const authorize = definition.authorizeRecovery;
|
|
288
|
+
if (!authorize)
|
|
289
|
+
throw new CommandError3("COMMAND_REJECTED");
|
|
290
|
+
await checkAuthorization(() => authorize(principal, reference, session.transaction));
|
|
291
|
+
const stored = await session.read(reference);
|
|
292
|
+
if (stored?.receipt.status !== "confirmed" || stored.receipt.audit !== "complete")
|
|
293
|
+
return null;
|
|
294
|
+
if (stored.kind !== "external")
|
|
295
|
+
throw new CommandError3("COMMAND_RECEIPT_INVALID");
|
|
296
|
+
return decodeDurableCommandReceipt2(stored.receipt, definition.result);
|
|
297
|
+
});
|
|
298
|
+
if (completed !== null)
|
|
299
|
+
return completed;
|
|
300
|
+
const request = await context.restore(reference, reference.operationId, principal);
|
|
301
|
+
return request === null ? null : reconcile(reference, reference.operationId, request.input, principal);
|
|
302
|
+
}
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
// src/recovery.ts
|
|
306
|
+
import { CommandError as CommandError4, commandIdentifier as commandIdentifier2, decodeCommandJson, decodeDurableCommandReceipt as decodeDurableCommandReceipt3 } from "@supacloud/contracts";
|
|
307
|
+
function decodeClaim(value) {
|
|
308
|
+
if (!value || typeof value !== "object" || !("status" in value) || value.status !== "claimed" || !("workflowName" in value) || !("workflowVersion" in value) || value.workflowVersion !== "1" || !("stepKey" in value) || value.stepKey !== "reconcile" || !("runId" in value) || !("input" in value) || !("stepId" in value) || !("messageId" in value) || !("attempt" in value) || !("workerId" in value) || typeof value.attempt !== "number" || !Number.isSafeInteger(value.attempt) || value.attempt < 1 || typeof value.messageId !== "string" || !/^[1-9][0-9]*$/.test(value.messageId)) {
|
|
309
|
+
throw new TypeError("Invalid command recovery claim");
|
|
310
|
+
}
|
|
311
|
+
const input = value.input;
|
|
312
|
+
if (!input || typeof input !== "object" || !("tenantId" in input) || !("actorId" in input) || !("command" in input) || !("operationId" in input) || !("commandId" in input)) {
|
|
313
|
+
throw new TypeError("Invalid command recovery reference");
|
|
314
|
+
}
|
|
315
|
+
const commandId = commandIdentifier2(input.commandId);
|
|
316
|
+
if (value.runId !== commandId)
|
|
317
|
+
throw new TypeError("Mismatched command workflow");
|
|
318
|
+
const reference = {
|
|
319
|
+
tenantId: commandIdentifier2(input.tenantId),
|
|
320
|
+
actorId: commandIdentifier2(input.actorId),
|
|
321
|
+
command: commandIdentifier2(input.command),
|
|
322
|
+
operationId: commandIdentifier2(input.operationId)
|
|
323
|
+
};
|
|
324
|
+
if (value.workflowName !== "supacloud.command.reconcile" && value.workflowName !== `command.${reference.command}`) {
|
|
325
|
+
throw new TypeError("Invalid recovery workflow");
|
|
326
|
+
}
|
|
327
|
+
const attempt = {
|
|
328
|
+
stepId: commandIdentifier2(value.stepId),
|
|
329
|
+
messageId: value.messageId,
|
|
330
|
+
attempt: value.attempt,
|
|
331
|
+
workerId: commandIdentifier2(value.workerId)
|
|
332
|
+
};
|
|
333
|
+
return { commandId, reference, attempt };
|
|
334
|
+
}
|
|
335
|
+
function createCommandRecoveryHandler(options) {
|
|
336
|
+
const tenantId = commandIdentifier2(options.tenantId);
|
|
337
|
+
const principal = { subject: commandIdentifier2(options.principal.subject) };
|
|
338
|
+
const commands = { ...options.commands }, { workflows, authorize } = options;
|
|
339
|
+
const delaySeconds = options.retryDelaySeconds;
|
|
340
|
+
if (!Number.isSafeInteger(delaySeconds) || delaySeconds < 0 || delaySeconds > 86400)
|
|
341
|
+
throw new TypeError("Invalid recovery delay");
|
|
342
|
+
return {
|
|
343
|
+
async run(value) {
|
|
344
|
+
const { commandId, reference, attempt } = decodeClaim(value);
|
|
345
|
+
if (reference.tenantId !== tenantId || attempt.workerId !== principal.subject || !Object.hasOwn(commands, reference.command))
|
|
346
|
+
throw new CommandError4("COMMAND_REJECTED");
|
|
347
|
+
await checkAuthorization(authorize);
|
|
348
|
+
const command = commands[reference.command];
|
|
349
|
+
if (!command)
|
|
350
|
+
throw new CommandError4("COMMAND_REJECTED");
|
|
351
|
+
let receipt;
|
|
352
|
+
try {
|
|
353
|
+
const raw = await command.recover({ ...principal }, { ...reference });
|
|
354
|
+
receipt = raw === null ? null : decodeDurableCommandReceipt3(raw, decodeCommandJson);
|
|
355
|
+
if (receipt !== null) {
|
|
356
|
+
if (receipt.dispatchKey !== commandId)
|
|
357
|
+
throw new CommandError4("COMMAND_RECEIPT_INVALID");
|
|
358
|
+
for (const key of ["tenantId", "actorId", "command", "operationId"]) {
|
|
359
|
+
if (receipt[key] !== reference[key])
|
|
360
|
+
throw new CommandError4("COMMAND_RECEIPT_INVALID");
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
} catch (error) {
|
|
364
|
+
if (error instanceof CommandError4 && (error.code === "COMMAND_INPUT_EXPIRED" || error.code === "COMMAND_RECEIPT_INVALID")) {
|
|
365
|
+
await workflows.fail({ ...attempt, errorMessage: error.code });
|
|
366
|
+
return "failed";
|
|
367
|
+
}
|
|
368
|
+
await workflows.retry({ ...attempt, errorMessage: "COMMAND_RECOVERY_FAILED", delaySeconds });
|
|
369
|
+
return "retry";
|
|
370
|
+
}
|
|
371
|
+
if (receipt?.status === "confirmed" && receipt.audit === "complete") {
|
|
372
|
+
const output = { commandId, status: "confirmed", audit: "complete" };
|
|
373
|
+
await workflows.complete({ ...attempt, stepOutput: output, runOutput: output });
|
|
374
|
+
return "completed";
|
|
375
|
+
}
|
|
376
|
+
await workflows.retry({ ...attempt, errorMessage: "COMMAND_RECOVERY_REQUIRED", delaySeconds });
|
|
377
|
+
return "retry";
|
|
378
|
+
}
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
export {
|
|
382
|
+
createCommandRecoveryHandler,
|
|
383
|
+
createExternalCommand,
|
|
384
|
+
createTransactionalCommand,
|
|
385
|
+
plaintextCommandInput
|
|
386
|
+
};
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { type CommandAuthorization, type DurableCommandReceipt } from "@supacloud/contracts";
|
|
2
|
+
import { type RecoveryPrincipal } from "./context";
|
|
3
|
+
import type { OperationReference } from "./store";
|
|
4
|
+
export interface RecoverableCommand {
|
|
5
|
+
recover(principal: RecoveryPrincipal, reference: OperationReference): Promise<DurableCommandReceipt<unknown> | null>;
|
|
6
|
+
}
|
|
7
|
+
export interface CommandWorkflowAttempt {
|
|
8
|
+
stepId: string;
|
|
9
|
+
messageId: string;
|
|
10
|
+
attempt: number;
|
|
11
|
+
workerId: string;
|
|
12
|
+
}
|
|
13
|
+
/** Structurally implemented by supacloud.workflows. Delivery remains host-owned. */
|
|
14
|
+
export interface CommandWorkflowPort {
|
|
15
|
+
complete(request: CommandWorkflowAttempt & {
|
|
16
|
+
stepOutput: Record<string, unknown>;
|
|
17
|
+
runOutput: Record<string, unknown>;
|
|
18
|
+
}): Promise<unknown>;
|
|
19
|
+
retry(request: CommandWorkflowAttempt & {
|
|
20
|
+
errorMessage: string;
|
|
21
|
+
delaySeconds: number;
|
|
22
|
+
}): Promise<unknown>;
|
|
23
|
+
fail(request: CommandWorkflowAttempt & {
|
|
24
|
+
errorMessage: string;
|
|
25
|
+
}): Promise<unknown>;
|
|
26
|
+
}
|
|
27
|
+
/** Handles one already-claimed recovery step. No polling, leases or business sends. */
|
|
28
|
+
export declare function createCommandRecoveryHandler(options: {
|
|
29
|
+
workflows: CommandWorkflowPort;
|
|
30
|
+
principal: RecoveryPrincipal;
|
|
31
|
+
tenantId: string;
|
|
32
|
+
commands: Readonly<Record<string, RecoverableCommand>>;
|
|
33
|
+
authorize(): CommandAuthorization | Promise<CommandAuthorization>;
|
|
34
|
+
retryDelaySeconds: number;
|
|
35
|
+
}): {
|
|
36
|
+
run(value: unknown): Promise<"completed" | "retry" | "failed">;
|
|
37
|
+
};
|
package/dist/store.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export type { OperationReference, StoredCommand, CommandStoreSession, CommandStore, RecoveryScope, CommandRetentionStore, } from "@supacloud/contracts";
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { type CommandIdentity, type DurableCommandReceipt } from "@supacloud/contracts";
|
|
2
|
+
import { type PersistentCommandDefinition } from "./context";
|
|
3
|
+
export declare function createTransactionalCommand<Input, Result, Transaction>(definition: PersistentCommandDefinition<Input, Result, Transaction> & {
|
|
4
|
+
execute(transaction: Transaction, input: Input, identity: CommandIdentity): Promise<unknown>;
|
|
5
|
+
}): {
|
|
6
|
+
kind: "transactional";
|
|
7
|
+
execute(identity: CommandIdentity, key: string, value: unknown): Promise<DurableCommandReceipt<Result>>;
|
|
8
|
+
lookup(identity: CommandIdentity, key: string, value: unknown): Promise<DurableCommandReceipt<Result> | null>;
|
|
9
|
+
lookupByReference(identity: CommandIdentity, key: string): Promise<DurableCommandReceipt<Result> | null>;
|
|
10
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@supacloud/commands",
|
|
3
|
+
"version": "0.3.1",
|
|
4
|
+
"description": "Storage-independent durable command execution and recovery",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"dist",
|
|
16
|
+
"README.md"
|
|
17
|
+
],
|
|
18
|
+
"scripts": {
|
|
19
|
+
"build": "bun run build:js && bun run build:types",
|
|
20
|
+
"build:js": "bun build src/index.ts --outdir dist --target node --external @supacloud/contracts",
|
|
21
|
+
"build:types": "tsc -p tsconfig.json --emitDeclarationOnly",
|
|
22
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
23
|
+
"typecheck:test": "tsc -p tsconfig.test.json --noEmit",
|
|
24
|
+
"test": "bun test",
|
|
25
|
+
"prepublishOnly": "bun run build"
|
|
26
|
+
},
|
|
27
|
+
"dependencies": {
|
|
28
|
+
"@supacloud/contracts": "0.3.1"
|
|
29
|
+
},
|
|
30
|
+
"devDependencies": {
|
|
31
|
+
"@types/bun": "1.4.2",
|
|
32
|
+
"typescript": "7.0.2"
|
|
33
|
+
},
|
|
34
|
+
"license": "MIT",
|
|
35
|
+
"repository": {
|
|
36
|
+
"type": "git",
|
|
37
|
+
"url": "https://github.com/vibeunion/supacloud.git",
|
|
38
|
+
"directory": "packages/commands"
|
|
39
|
+
}
|
|
40
|
+
}
|