@supacloud/commands 0.12.0 → 0.13.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 +91 -0
- package/dist/http-action.d.ts +82 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +313 -0
- package/dist/outbox.d.ts +48 -0
- package/package.json +5 -5
package/README.md
CHANGED
|
@@ -94,6 +94,97 @@ and still enforce authorization and operation identity. A `rejected` receipt is
|
|
|
94
94
|
distinct from a preflight `COMMAND_REJECTED` exception: it is durable evidence for
|
|
95
95
|
that operation, not permission to generate a new key and blindly retry.
|
|
96
96
|
|
|
97
|
+
### Outbound HTTP
|
|
98
|
+
|
|
99
|
+
`createHttpAction` is the transport adapter for an external REST endpoint. Product surfaces should call this **Outbound HTTP** or a connector, not "Actions"; it is an internal delivery primitive, not a GraphQL resolver. It does
|
|
100
|
+
not create a GraphQL resolver and it does not retry writes; compose it with
|
|
101
|
+
`createExternalCommand` so the durable receipt, authorization, audit and
|
|
102
|
+
reconciliation rules stay in one place.
|
|
103
|
+
|
|
104
|
+
```ts
|
|
105
|
+
import { createExternalCommand, createHttpAction, plaintextCommandInput } from "@supacloud/commands";
|
|
106
|
+
|
|
107
|
+
const refundApi = createHttpAction<{ orderId: string }>({
|
|
108
|
+
url: "https://payments.example.com/v1/refunds",
|
|
109
|
+
allowedHosts: ["payments.example.com"],
|
|
110
|
+
headers: () => ({ authorization: `Bearer ${process.env.PAYMENTS_TOKEN}` }),
|
|
111
|
+
body: (input) => JSON.stringify({ orderId: input.orderId }),
|
|
112
|
+
lookup: { url: (input) => `https://payments.example.com/v1/refunds/${input.orderId}` },
|
|
113
|
+
timeoutMs: 10_000,
|
|
114
|
+
maxResponseBytes: 64 * 1024,
|
|
115
|
+
// Use the Management API's safeOutboundFetch when the destination is not a
|
|
116
|
+
// fixed, pre-validated host. This package has no Node-only DNS dependency.
|
|
117
|
+
fetch,
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
const refund = createExternalCommand({
|
|
121
|
+
store,
|
|
122
|
+
name: "payment.refund",
|
|
123
|
+
input,
|
|
124
|
+
result,
|
|
125
|
+
inputCodec: plaintextCommandInput,
|
|
126
|
+
authorize: () => "allow",
|
|
127
|
+
send: refundApi.send,
|
|
128
|
+
lookup: refundApi.lookup,
|
|
129
|
+
matches: (request, result) => request.orderId === result.orderId,
|
|
130
|
+
audit: { event: "payment.refunded", details: () => ({}) },
|
|
131
|
+
rejection: {
|
|
132
|
+
isDefinitiveWriteFailure: refundApi.isDefinitiveWriteFailure,
|
|
133
|
+
audit: { event: "payment.refund.rejected", details: () => ({}) },
|
|
134
|
+
},
|
|
135
|
+
});
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
The adapter:
|
|
139
|
+
|
|
140
|
+
- sends the durable `dispatchKey` as `idempotency-key` by default;
|
|
141
|
+
- requires HTTPS except explicit loopback development;
|
|
142
|
+
- supports exact host allowlisting and rejects embedded URL credentials;
|
|
143
|
+
- bounds timeout and response bytes;
|
|
144
|
+
- disables automatic redirect following;
|
|
145
|
+
- maps non-2xx responses to `HttpActionError` with status and retryability;
|
|
146
|
+
- optionally performs a read-only `lookup` for reconciliation, treating 404 as
|
|
147
|
+
"no remote record";
|
|
148
|
+
- returns `isDefinitiveWriteFailure=false` unless the provider contract
|
|
149
|
+
explicitly permits classifying specific statuses as pre-effect rejections.
|
|
150
|
+
|
|
151
|
+
`send` is called once per durable dispatch. Network failures, timeouts and
|
|
152
|
+
ambiguous HTTP errors remain unknown and are reconciled through `lookup`; never
|
|
153
|
+
add an automatic POST retry loop around the adapter. Large or secret payloads
|
|
154
|
+
belong in Storage/domain tables, not in retryable queue messages.
|
|
155
|
+
|
|
156
|
+
### Transactional Outbox
|
|
157
|
+
|
|
158
|
+
`createOutboxDispatcher` is a storage-independent dispatcher for an
|
|
159
|
+
application-owned outbox. SQL owns the table and the `FOR UPDATE SKIP LOCKED`
|
|
160
|
+
claim; this package owns bounded retries, dead-lettering and topic routing.
|
|
161
|
+
|
|
162
|
+
```ts
|
|
163
|
+
import { createOutboxDispatcher, type OutboxStore } from "@supacloud/commands";
|
|
164
|
+
|
|
165
|
+
const dispatcher = createOutboxDispatcher({
|
|
166
|
+
store, // claim/complete/retry/deadLetter
|
|
167
|
+
workerId: "app-worker-1",
|
|
168
|
+
maxRuns: 10,
|
|
169
|
+
handlers: {
|
|
170
|
+
"order.paid": async (message) => {
|
|
171
|
+
// Resolve the current entity by ID; do not trust stale payload state.
|
|
172
|
+
await deliverOrderPaid(message.idempotencyKey, message.payload);
|
|
173
|
+
},
|
|
174
|
+
},
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
while (!stopping) {
|
|
178
|
+
if (await dispatcher.runOnce() === 0) await sleep(1_000);
|
|
179
|
+
}
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
The outbox row must be inserted in the same transaction as the business
|
|
183
|
+
mutation. Delivery is at-least-once: consumers must deduplicate by
|
|
184
|
+
`idempotencyKey`. Unknown topics are dead-lettered instead of retried forever.
|
|
185
|
+
The SQL/table/worker template lives in
|
|
186
|
+
[`docs/examples/outbox`](../../docs/examples/outbox/README.md).
|
|
187
|
+
|
|
97
188
|
## Recovery
|
|
98
189
|
|
|
99
190
|
Interactive methods reauthorize the original actor. Worker `recover` requires
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import type { ExternalDispatch } from "./external";
|
|
2
|
+
/**
|
|
3
|
+
* Typed HTTP adapter for an external action.
|
|
4
|
+
*
|
|
5
|
+
* This is intentionally not a GraphQL resolver. It provides the transport
|
|
6
|
+
* contract that a Command/Function can compose with `createExternalCommand`:
|
|
7
|
+
* stable request shape, idempotency key propagation, bounded timeout/body,
|
|
8
|
+
* protocol/host allowlisting and response parsing.
|
|
9
|
+
*
|
|
10
|
+
* DNS resolution and redirect re-validation are not implemented here because
|
|
11
|
+
* this package has no Node-only dependency. Inject a hardened fetch (for
|
|
12
|
+
* example the Management API's safeOutboundFetch) when the target is not a
|
|
13
|
+
* fixed, pre-validated host. The adapter disables automatic redirect following.
|
|
14
|
+
*/
|
|
15
|
+
export type HttpActionMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
|
|
16
|
+
export type HttpActionUrl<Input> = string | ((input: Input, dispatch: ExternalDispatch) => string);
|
|
17
|
+
export type HttpActionHeaders<Input> = Record<string, string> | ((input: Input, dispatch: ExternalDispatch) => Record<string, string> | undefined);
|
|
18
|
+
export type HttpActionBody<Input> = (input: Input, dispatch: ExternalDispatch) => string | Uint8Array | undefined;
|
|
19
|
+
export interface HttpActionLookup<Input> {
|
|
20
|
+
/** URL used for read-only reconciliation. */
|
|
21
|
+
url: HttpActionUrl<Input>;
|
|
22
|
+
/** Defaults to GET. */
|
|
23
|
+
method?: HttpActionMethod;
|
|
24
|
+
headers?: HttpActionHeaders<Input>;
|
|
25
|
+
/** Statuses that mean "no remote record yet". Defaults to [404]. */
|
|
26
|
+
notFoundStatuses?: readonly number[];
|
|
27
|
+
}
|
|
28
|
+
export interface HttpActionOptions<Input> {
|
|
29
|
+
/** Fixed URL or a function of the validated input. */
|
|
30
|
+
url: HttpActionUrl<Input>;
|
|
31
|
+
/** Defaults to POST. */
|
|
32
|
+
method?: HttpActionMethod;
|
|
33
|
+
headers?: HttpActionHeaders<Input>;
|
|
34
|
+
/** Returned value must already be encoded (for example JSON.stringify). */
|
|
35
|
+
body?: HttpActionBody<Input>;
|
|
36
|
+
/** Total request deadline. Defaults to 30 seconds. */
|
|
37
|
+
timeoutMs?: number;
|
|
38
|
+
/** Buffered response cap. Defaults to 1 MiB. */
|
|
39
|
+
maxResponseBytes?: number;
|
|
40
|
+
/** Optional exact host/host:port allowlist. */
|
|
41
|
+
allowedHosts?: readonly string[];
|
|
42
|
+
/** Permit HTTP only for loopback hosts. HTTPS is always required otherwise. */
|
|
43
|
+
allowInsecureHttp?: boolean;
|
|
44
|
+
/** Header used for the durable dispatch key. Defaults to idempotency-key; null disables it. */
|
|
45
|
+
idempotencyHeader?: string | null;
|
|
46
|
+
/** Injected transport. Use a hardened fetch for untrusted destinations. */
|
|
47
|
+
fetch?: typeof fetch;
|
|
48
|
+
/** Response parser. Defaults to JSON.parse for non-empty bodies. */
|
|
49
|
+
parse?: (body: string, response: Response) => unknown;
|
|
50
|
+
/** Optional read-only reconciliation request. Without it lookup returns null. */
|
|
51
|
+
lookup?: HttpActionLookup<Input>;
|
|
52
|
+
/**
|
|
53
|
+
* HTTP statuses that prove the remote rejected the write before any effect.
|
|
54
|
+
* Leave empty unless the provider contract is explicit; a 401/403/409 can
|
|
55
|
+
* still be returned after a write was applied.
|
|
56
|
+
*/
|
|
57
|
+
definitiveRejectionStatuses?: readonly number[];
|
|
58
|
+
}
|
|
59
|
+
export type HttpActionErrorCode = "HTTP_ACTION_URL_INVALID" | "HTTP_ACTION_URL_NOT_ALLOWED" | "HTTP_ACTION_REQUEST_INVALID" | "HTTP_ACTION_TIMEOUT" | "HTTP_ACTION_ABORTED" | "HTTP_ACTION_NETWORK" | "HTTP_ACTION_STATUS" | "HTTP_ACTION_RESPONSE_TOO_LARGE" | "HTTP_ACTION_INVALID_RESPONSE";
|
|
60
|
+
export declare class HttpActionError extends Error {
|
|
61
|
+
readonly code: HttpActionErrorCode;
|
|
62
|
+
readonly status: number | undefined;
|
|
63
|
+
readonly retryable: boolean;
|
|
64
|
+
constructor(code: HttpActionErrorCode, message: string, options?: {
|
|
65
|
+
status?: number;
|
|
66
|
+
retryable?: boolean;
|
|
67
|
+
cause?: unknown;
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
export interface HttpActionAdapter<Input> {
|
|
71
|
+
/** Dispatch once. Never retried by this adapter; the durable command owns ambiguity. */
|
|
72
|
+
send(input: Input, dispatch: ExternalDispatch): Promise<unknown>;
|
|
73
|
+
/** Read-only reconciliation. Returns null when no lookup is configured or the remote has no record. */
|
|
74
|
+
lookup(input: Input, dispatch: ExternalDispatch): Promise<unknown | null>;
|
|
75
|
+
/**
|
|
76
|
+
* Explicit provider-rejection classifier. Defaults to false for every error;
|
|
77
|
+
* configure `definitiveRejectionStatuses` only when the provider contract
|
|
78
|
+
* guarantees no effect was applied.
|
|
79
|
+
*/
|
|
80
|
+
isDefinitiveWriteFailure(error: unknown): boolean;
|
|
81
|
+
}
|
|
82
|
+
export declare function createHttpAction<Input>(options: HttpActionOptions<Input>): HttpActionAdapter<Input>;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
export { createTransactionalCommand } from "./transactional";
|
|
2
2
|
export { createExecutionPolicy, ExecutionPolicyError, type ExecutionPolicyOptions, type ExecutionPolicyEvent } from "./execution-policy";
|
|
3
3
|
export { createExternalCommand, type ExternalDispatch } from "./external";
|
|
4
|
+
export { createHttpAction, HttpActionError, type HttpActionAdapter, type HttpActionBody, type HttpActionErrorCode, type HttpActionHeaders, type HttpActionLookup, type HttpActionMethod, type HttpActionOptions, type HttpActionUrl, } from "./http-action";
|
|
4
5
|
export { plaintextCommandInput, type CommandInputCodec, type PersistentCommandDefinition, type RecoveryPrincipal } from "./context";
|
|
5
6
|
export { createCommandRecoveryHandler, type RecoverableCommand, type CommandWorkflowPort, type CommandWorkflowAttempt, type CommandRecoveryEvent } from "./recovery";
|
|
7
|
+
export { createOutboxDispatcher, boundedOutboxError, nextOutboxAttempt, type OutboxDispatcher, type OutboxDispatcherOptions, type OutboxHandler, type OutboxMessage, type OutboxStore, } from "./outbox";
|
|
6
8
|
export type { CommandObserver } from "./observation";
|
|
7
9
|
export type { CommandStore, CommandStoreSession, StoredCommand, OperationReference, CommandRetentionStore, RecoveryScope, } from "./store";
|
package/dist/index.js
CHANGED
|
@@ -502,6 +502,244 @@ function createExternalCommand(definition) {
|
|
|
502
502
|
}
|
|
503
503
|
};
|
|
504
504
|
}
|
|
505
|
+
// src/http-action.ts
|
|
506
|
+
class HttpActionError extends Error {
|
|
507
|
+
code;
|
|
508
|
+
status;
|
|
509
|
+
retryable;
|
|
510
|
+
constructor(code, message, options = {}) {
|
|
511
|
+
super(message, options.cause === undefined ? undefined : { cause: options.cause });
|
|
512
|
+
this.name = "HttpActionError";
|
|
513
|
+
this.code = code;
|
|
514
|
+
this.status = options.status;
|
|
515
|
+
this.retryable = options.retryable ?? false;
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
var DEFAULT_TIMEOUT_MS = 30000;
|
|
519
|
+
var DEFAULT_MAX_RESPONSE_BYTES = 1048576;
|
|
520
|
+
function createHttpAction(options) {
|
|
521
|
+
const timeoutMs = positiveInteger(options.timeoutMs ?? DEFAULT_TIMEOUT_MS, "timeoutMs");
|
|
522
|
+
const maxResponseBytes = positiveInteger(options.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES, "maxResponseBytes");
|
|
523
|
+
const allowedHosts = (options.allowedHosts ?? []).map((host) => host.trim().toLowerCase()).filter(Boolean);
|
|
524
|
+
const idempotencyHeader = options.idempotencyHeader === undefined ? "idempotency-key" : options.idempotencyHeader;
|
|
525
|
+
const fetchImpl = options.fetch ?? fetch;
|
|
526
|
+
const parse = options.parse ?? parseJson;
|
|
527
|
+
const definitiveStatuses = new Set(options.definitiveRejectionStatuses ?? []);
|
|
528
|
+
const lookup = options.lookup;
|
|
529
|
+
const request = async (input, dispatch, method, rawUrl, headers, body) => {
|
|
530
|
+
if (dispatch.signal?.aborted) {
|
|
531
|
+
throw new HttpActionError("HTTP_ACTION_ABORTED", "HTTP action was aborted", { retryable: true });
|
|
532
|
+
}
|
|
533
|
+
const url = assertSafeUrl(rawUrl, allowedHosts, options.allowInsecureHttp === true);
|
|
534
|
+
const scope = abortScope(dispatch.signal, timeoutMs);
|
|
535
|
+
try {
|
|
536
|
+
const response = await fetchImpl(url.toString(), {
|
|
537
|
+
method,
|
|
538
|
+
...headers === undefined ? {} : { headers },
|
|
539
|
+
...body === undefined ? {} : { body },
|
|
540
|
+
signal: scope.controller.signal,
|
|
541
|
+
redirect: "error"
|
|
542
|
+
});
|
|
543
|
+
const text = await readCapped(response, maxResponseBytes);
|
|
544
|
+
return { response, text };
|
|
545
|
+
} catch (error) {
|
|
546
|
+
if (scope.timedOut()) {
|
|
547
|
+
throw new HttpActionError("HTTP_ACTION_TIMEOUT", "HTTP action timed out", {
|
|
548
|
+
retryable: true,
|
|
549
|
+
cause: error
|
|
550
|
+
});
|
|
551
|
+
}
|
|
552
|
+
if (dispatch.signal?.aborted) {
|
|
553
|
+
throw new HttpActionError("HTTP_ACTION_ABORTED", "HTTP action was aborted", {
|
|
554
|
+
retryable: true,
|
|
555
|
+
cause: error
|
|
556
|
+
});
|
|
557
|
+
}
|
|
558
|
+
if (error instanceof HttpActionError)
|
|
559
|
+
throw error;
|
|
560
|
+
throw new HttpActionError("HTTP_ACTION_NETWORK", "HTTP action request failed", {
|
|
561
|
+
retryable: true,
|
|
562
|
+
cause: error
|
|
563
|
+
});
|
|
564
|
+
} finally {
|
|
565
|
+
scope.cleanup();
|
|
566
|
+
}
|
|
567
|
+
};
|
|
568
|
+
return {
|
|
569
|
+
async send(input, dispatch) {
|
|
570
|
+
const url = resolveUrl(options.url, input, dispatch);
|
|
571
|
+
const headers = resolveHeaders(options.headers, input, dispatch);
|
|
572
|
+
if (idempotencyHeader !== null && !headers.has(idempotencyHeader)) {
|
|
573
|
+
headers.set(idempotencyHeader, dispatch.idempotencyKey);
|
|
574
|
+
}
|
|
575
|
+
let encoded;
|
|
576
|
+
try {
|
|
577
|
+
encoded = options.body?.(input, dispatch);
|
|
578
|
+
} catch (error) {
|
|
579
|
+
throw new HttpActionError("HTTP_ACTION_REQUEST_INVALID", "HTTP action body resolver failed", { cause: error });
|
|
580
|
+
}
|
|
581
|
+
const body = encoded instanceof Uint8Array ? new Uint8Array(encoded).buffer : encoded;
|
|
582
|
+
if (body !== undefined && !headers.has("content-type")) {
|
|
583
|
+
headers.set("content-type", "application/json");
|
|
584
|
+
}
|
|
585
|
+
const method = options.method ?? "POST";
|
|
586
|
+
const { response, text } = await request(input, dispatch, method, url, headers, body);
|
|
587
|
+
if (!response.ok) {
|
|
588
|
+
throw new HttpActionError("HTTP_ACTION_STATUS", `HTTP action failed with status ${response.status}`, {
|
|
589
|
+
status: response.status,
|
|
590
|
+
retryable: response.status >= 500 || response.status === 429
|
|
591
|
+
});
|
|
592
|
+
}
|
|
593
|
+
return parseResponse(parse, text, response);
|
|
594
|
+
},
|
|
595
|
+
async lookup(input, dispatch) {
|
|
596
|
+
if (lookup === undefined)
|
|
597
|
+
return null;
|
|
598
|
+
const url = resolveUrl(lookup.url, input, dispatch);
|
|
599
|
+
const headers = resolveHeaders(lookup.headers, input, dispatch);
|
|
600
|
+
const method = lookup.method ?? "GET";
|
|
601
|
+
const { response, text } = await request(input, dispatch, method, url, headers, undefined);
|
|
602
|
+
if ((lookup.notFoundStatuses ?? [404]).includes(response.status))
|
|
603
|
+
return null;
|
|
604
|
+
if (!response.ok) {
|
|
605
|
+
throw new HttpActionError("HTTP_ACTION_STATUS", `HTTP lookup failed with status ${response.status}`, {
|
|
606
|
+
status: response.status,
|
|
607
|
+
retryable: response.status >= 500 || response.status === 429
|
|
608
|
+
});
|
|
609
|
+
}
|
|
610
|
+
return parseResponse(parse, text, response);
|
|
611
|
+
},
|
|
612
|
+
isDefinitiveWriteFailure(error) {
|
|
613
|
+
return error instanceof HttpActionError && error.code === "HTTP_ACTION_STATUS" && error.status !== undefined && definitiveStatuses.has(error.status);
|
|
614
|
+
}
|
|
615
|
+
};
|
|
616
|
+
}
|
|
617
|
+
function resolveUrl(value, input, dispatch) {
|
|
618
|
+
try {
|
|
619
|
+
return typeof value === "string" ? value : value(input, dispatch);
|
|
620
|
+
} catch (error) {
|
|
621
|
+
throw new HttpActionError("HTTP_ACTION_URL_INVALID", "HTTP action URL resolver failed", { cause: error });
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
function resolveHeaders(value, input, dispatch) {
|
|
625
|
+
try {
|
|
626
|
+
const source = typeof value === "function" ? value(input, dispatch) : value;
|
|
627
|
+
return new Headers(source ?? {});
|
|
628
|
+
} catch (error) {
|
|
629
|
+
throw new HttpActionError("HTTP_ACTION_REQUEST_INVALID", "HTTP action headers are invalid", { cause: error });
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
function assertSafeUrl(raw, allowedHosts, allowInsecureHttp) {
|
|
633
|
+
let url;
|
|
634
|
+
try {
|
|
635
|
+
url = new URL(raw);
|
|
636
|
+
} catch (error) {
|
|
637
|
+
throw new HttpActionError("HTTP_ACTION_URL_INVALID", "HTTP action URL is invalid", { cause: error });
|
|
638
|
+
}
|
|
639
|
+
if (url.username || url.password) {
|
|
640
|
+
throw new HttpActionError("HTTP_ACTION_URL_NOT_ALLOWED", "HTTP action URL must not embed credentials");
|
|
641
|
+
}
|
|
642
|
+
const loopback = isLoopbackHost(url.hostname);
|
|
643
|
+
if (url.protocol !== "https:") {
|
|
644
|
+
if (url.protocol !== "http:" || !allowInsecureHttp || !loopback) {
|
|
645
|
+
throw new HttpActionError("HTTP_ACTION_URL_NOT_ALLOWED", "HTTP action requires HTTPS; HTTP is only allowed for explicit loopback development");
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
if (allowedHosts.length > 0) {
|
|
649
|
+
const hostname = url.hostname.toLowerCase();
|
|
650
|
+
const host = url.host.toLowerCase();
|
|
651
|
+
if (!allowedHosts.includes(hostname) && !allowedHosts.includes(host)) {
|
|
652
|
+
throw new HttpActionError("HTTP_ACTION_URL_NOT_ALLOWED", `HTTP action host is not allowed: ${hostname}`);
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
return url;
|
|
656
|
+
}
|
|
657
|
+
function isLoopbackHost(hostname) {
|
|
658
|
+
const host = hostname.toLowerCase().replace(/^\[|\]$/g, "");
|
|
659
|
+
return host === "localhost" || host === "127.0.0.1" || host === "::1";
|
|
660
|
+
}
|
|
661
|
+
function abortScope(signal, timeoutMs) {
|
|
662
|
+
const controller = new AbortController;
|
|
663
|
+
let timedOut = false;
|
|
664
|
+
if (signal?.aborted)
|
|
665
|
+
controller.abort(signal.reason);
|
|
666
|
+
const onAbort = () => controller.abort(signal?.reason);
|
|
667
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
668
|
+
const timer = setTimeout(() => {
|
|
669
|
+
timedOut = true;
|
|
670
|
+
controller.abort(new Error("HTTP action timeout"));
|
|
671
|
+
}, timeoutMs);
|
|
672
|
+
return {
|
|
673
|
+
controller,
|
|
674
|
+
timedOut: () => timedOut,
|
|
675
|
+
cleanup: () => {
|
|
676
|
+
clearTimeout(timer);
|
|
677
|
+
signal?.removeEventListener("abort", onAbort);
|
|
678
|
+
}
|
|
679
|
+
};
|
|
680
|
+
}
|
|
681
|
+
async function readCapped(response, maxBytes) {
|
|
682
|
+
const declared = Number(response.headers.get("content-length"));
|
|
683
|
+
if (Number.isFinite(declared) && declared > maxBytes) {
|
|
684
|
+
await response.body?.cancel().catch(() => {});
|
|
685
|
+
throw new HttpActionError("HTTP_ACTION_RESPONSE_TOO_LARGE", `HTTP action response exceeds ${maxBytes} bytes`);
|
|
686
|
+
}
|
|
687
|
+
if (response.body === null)
|
|
688
|
+
return "";
|
|
689
|
+
const reader = response.body.getReader();
|
|
690
|
+
const chunks = [];
|
|
691
|
+
let size = 0;
|
|
692
|
+
try {
|
|
693
|
+
while (true) {
|
|
694
|
+
const chunk = await reader.read();
|
|
695
|
+
if (chunk.done)
|
|
696
|
+
break;
|
|
697
|
+
size += chunk.value.byteLength;
|
|
698
|
+
if (size > maxBytes) {
|
|
699
|
+
await reader.cancel().catch(() => {});
|
|
700
|
+
throw new HttpActionError("HTTP_ACTION_RESPONSE_TOO_LARGE", `HTTP action response exceeds ${maxBytes} bytes`);
|
|
701
|
+
}
|
|
702
|
+
chunks.push(chunk.value);
|
|
703
|
+
}
|
|
704
|
+
} finally {
|
|
705
|
+
reader.releaseLock();
|
|
706
|
+
}
|
|
707
|
+
const merged = new Uint8Array(size);
|
|
708
|
+
let offset = 0;
|
|
709
|
+
for (const chunk of chunks) {
|
|
710
|
+
merged.set(chunk, offset);
|
|
711
|
+
offset += chunk.byteLength;
|
|
712
|
+
}
|
|
713
|
+
return new TextDecoder().decode(merged);
|
|
714
|
+
}
|
|
715
|
+
function parseResponse(parse, body, response) {
|
|
716
|
+
try {
|
|
717
|
+
return parse(body, response);
|
|
718
|
+
} catch (error) {
|
|
719
|
+
if (error instanceof HttpActionError)
|
|
720
|
+
throw error;
|
|
721
|
+
throw new HttpActionError("HTTP_ACTION_INVALID_RESPONSE", "HTTP action response parser failed", {
|
|
722
|
+
cause: error
|
|
723
|
+
});
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
function parseJson(body) {
|
|
727
|
+
if (body.trim() === "")
|
|
728
|
+
return null;
|
|
729
|
+
try {
|
|
730
|
+
return JSON.parse(body);
|
|
731
|
+
} catch (error) {
|
|
732
|
+
throw new HttpActionError("HTTP_ACTION_INVALID_RESPONSE", "HTTP action response is not valid JSON", {
|
|
733
|
+
cause: error
|
|
734
|
+
});
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
function positiveInteger(value, field) {
|
|
738
|
+
if (!Number.isSafeInteger(value) || value <= 0) {
|
|
739
|
+
throw new TypeError(`${field} must be a positive integer`);
|
|
740
|
+
}
|
|
741
|
+
return value;
|
|
742
|
+
}
|
|
505
743
|
// src/recovery.ts
|
|
506
744
|
import { CommandError as CommandError4, commandIdentifier as commandIdentifier3, decodeCommandJson, decodeDurableCommandReceipt as decodeDurableCommandReceipt3 } from "@supacloud/contracts";
|
|
507
745
|
function decodeClaim(value) {
|
|
@@ -611,11 +849,86 @@ function createCommandRecoveryHandler(options) {
|
|
|
611
849
|
}
|
|
612
850
|
};
|
|
613
851
|
}
|
|
852
|
+
// src/outbox.ts
|
|
853
|
+
var DEFAULT_RETRY_DELAYS_SECONDS = [60, 300, 1800];
|
|
854
|
+
var MAX_ERROR_BYTES = 2048;
|
|
855
|
+
function createOutboxDispatcher(options) {
|
|
856
|
+
const maxRuns = positive(options.maxRuns ?? 10, "maxRuns");
|
|
857
|
+
const retryDelays = (options.retryDelaysSeconds ?? DEFAULT_RETRY_DELAYS_SECONDS).filter((value) => Number.isFinite(value) && value > 0);
|
|
858
|
+
if (retryDelays.length === 0)
|
|
859
|
+
throw new TypeError("retryDelaysSeconds must contain a positive value");
|
|
860
|
+
const now = options.now ?? (() => new Date);
|
|
861
|
+
return {
|
|
862
|
+
async runOnce(limit = maxRuns) {
|
|
863
|
+
const bounded = positive(limit, "limit");
|
|
864
|
+
const messages = await options.store.claim(bounded, options.workerId);
|
|
865
|
+
for (const message of messages) {
|
|
866
|
+
await dispatchOne(message, options, retryDelays, now);
|
|
867
|
+
}
|
|
868
|
+
return messages.length;
|
|
869
|
+
}
|
|
870
|
+
};
|
|
871
|
+
}
|
|
872
|
+
async function dispatchOne(message, options, retryDelays, now) {
|
|
873
|
+
const handler = options.handlers[message.topic] ?? options.handlers["*"];
|
|
874
|
+
if (handler === undefined) {
|
|
875
|
+
const error = `OUTBOX_HANDLER_MISSING:${message.topic}`;
|
|
876
|
+
await options.store.deadLetter(message, error);
|
|
877
|
+
report(options, { message, error, terminal: true });
|
|
878
|
+
return;
|
|
879
|
+
}
|
|
880
|
+
try {
|
|
881
|
+
await handler(message);
|
|
882
|
+
await options.store.complete(message);
|
|
883
|
+
} catch (cause) {
|
|
884
|
+
const error = boundedError(cause);
|
|
885
|
+
const terminal = message.attempt >= message.maxAttempts;
|
|
886
|
+
if (terminal) {
|
|
887
|
+
await options.store.deadLetter(message, error);
|
|
888
|
+
} else {
|
|
889
|
+
const delay = retryDelays[Math.min(message.attempt - 1, retryDelays.length - 1)];
|
|
890
|
+
await options.store.retry(message, error, new Date(now().getTime() + delay * 1000));
|
|
891
|
+
}
|
|
892
|
+
report(options, { message, error, terminal });
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
function report(options, event) {
|
|
896
|
+
try {
|
|
897
|
+
options.onError?.(event);
|
|
898
|
+
} catch {}
|
|
899
|
+
}
|
|
900
|
+
function boundedOutboxError(error) {
|
|
901
|
+
return boundedError(error);
|
|
902
|
+
}
|
|
903
|
+
function nextOutboxAttempt(attempt, retryDelaysSeconds = DEFAULT_RETRY_DELAYS_SECONDS) {
|
|
904
|
+
const delays = retryDelaysSeconds.filter((value) => Number.isFinite(value) && value > 0);
|
|
905
|
+
const selected = delays[Math.min(Math.max(0, attempt - 1), delays.length - 1)];
|
|
906
|
+
if (selected === undefined)
|
|
907
|
+
throw new TypeError("retryDelaysSeconds must contain a positive value");
|
|
908
|
+
return new Date(Date.now() + selected * 1000);
|
|
909
|
+
}
|
|
910
|
+
function boundedError(error) {
|
|
911
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
912
|
+
const bytes = new TextEncoder().encode(message);
|
|
913
|
+
if (bytes.byteLength <= MAX_ERROR_BYTES)
|
|
914
|
+
return message;
|
|
915
|
+
return new TextDecoder().decode(bytes.slice(0, MAX_ERROR_BYTES));
|
|
916
|
+
}
|
|
917
|
+
function positive(value, field) {
|
|
918
|
+
if (!Number.isSafeInteger(value) || value <= 0)
|
|
919
|
+
throw new TypeError(`${field} must be a positive integer`);
|
|
920
|
+
return value;
|
|
921
|
+
}
|
|
614
922
|
export {
|
|
615
923
|
ExecutionPolicyError,
|
|
924
|
+
HttpActionError,
|
|
925
|
+
boundedOutboxError,
|
|
616
926
|
createCommandRecoveryHandler,
|
|
617
927
|
createExecutionPolicy,
|
|
618
928
|
createExternalCommand,
|
|
929
|
+
createHttpAction,
|
|
930
|
+
createOutboxDispatcher,
|
|
619
931
|
createTransactionalCommand,
|
|
932
|
+
nextOutboxAttempt,
|
|
620
933
|
plaintextCommandInput
|
|
621
934
|
};
|
package/dist/outbox.d.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Storage-independent transactional outbox dispatcher.
|
|
3
|
+
*
|
|
4
|
+
* The application writes the outbox row in the same transaction as the business
|
|
5
|
+
* mutation. This module only claims and dispatches rows; it deliberately does
|
|
6
|
+
* not own an HTTP server, a database driver, or a second command ledger.
|
|
7
|
+
*/
|
|
8
|
+
export interface OutboxMessage {
|
|
9
|
+
id: string;
|
|
10
|
+
topic: string;
|
|
11
|
+
payload: unknown;
|
|
12
|
+
idempotencyKey: string;
|
|
13
|
+
/** 1-based attempt number after the store's claim operation. */
|
|
14
|
+
attempt: number;
|
|
15
|
+
maxAttempts: number;
|
|
16
|
+
}
|
|
17
|
+
export interface OutboxStore {
|
|
18
|
+
/** Atomically claim up to `limit` due rows (for example FOR UPDATE SKIP LOCKED). */
|
|
19
|
+
claim(limit: number, workerId: string): Promise<readonly OutboxMessage[]>;
|
|
20
|
+
complete(message: OutboxMessage): Promise<void>;
|
|
21
|
+
retry(message: OutboxMessage, error: string, nextAttemptAt: Date): Promise<void>;
|
|
22
|
+
deadLetter(message: OutboxMessage, error: string): Promise<void>;
|
|
23
|
+
}
|
|
24
|
+
export type OutboxHandler = (message: OutboxMessage) => Promise<void> | void;
|
|
25
|
+
export interface OutboxDispatcherOptions {
|
|
26
|
+
store: OutboxStore;
|
|
27
|
+
/** Exact topic handlers; "*" is the fallback. */
|
|
28
|
+
handlers: Readonly<Record<string, OutboxHandler>>;
|
|
29
|
+
workerId: string;
|
|
30
|
+
/** Per-run claim bound. Defaults to 10. */
|
|
31
|
+
maxRuns?: number;
|
|
32
|
+
now?: () => Date;
|
|
33
|
+
/** Bounded retry schedule in seconds; the last entry is reused. */
|
|
34
|
+
retryDelaysSeconds?: readonly number[];
|
|
35
|
+
/** Best-effort observability; never changes dispatch outcome. */
|
|
36
|
+
onError?: (event: {
|
|
37
|
+
message: OutboxMessage;
|
|
38
|
+
error: string;
|
|
39
|
+
terminal: boolean;
|
|
40
|
+
}) => void;
|
|
41
|
+
}
|
|
42
|
+
export interface OutboxDispatcher {
|
|
43
|
+
/** Drain one bounded batch; returns the number of claimed messages. */
|
|
44
|
+
runOnce(limit?: number): Promise<number>;
|
|
45
|
+
}
|
|
46
|
+
export declare function createOutboxDispatcher(options: OutboxDispatcherOptions): OutboxDispatcher;
|
|
47
|
+
export declare function boundedOutboxError(error: unknown): string;
|
|
48
|
+
export declare function nextOutboxAttempt(attempt: number, retryDelaysSeconds?: readonly number[]): Date;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@supacloud/commands",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.13.0",
|
|
4
4
|
"description": "Storage-independent durable command execution and recovery",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -25,17 +25,17 @@
|
|
|
25
25
|
"build": "bun run build:js && bun run build:types",
|
|
26
26
|
"build:js": "bun build src/index.ts src/typebox.ts --outdir dist --target node --external @supacloud/contracts --external typebox",
|
|
27
27
|
"build:types": "tsc -p tsconfig.json --emitDeclarationOnly",
|
|
28
|
-
"typecheck": "
|
|
29
|
-
"typecheck:test": "
|
|
28
|
+
"typecheck": "bun check --no-script -p tsconfig.json",
|
|
29
|
+
"typecheck:test": "bun check --no-script -p tsconfig.test.json",
|
|
30
30
|
"test": "bun test",
|
|
31
31
|
"prepublishOnly": "bun run build"
|
|
32
32
|
},
|
|
33
33
|
"dependencies": {
|
|
34
|
-
"@supacloud/contracts": "0.
|
|
34
|
+
"@supacloud/contracts": "0.17.0"
|
|
35
35
|
},
|
|
36
36
|
"devDependencies": {
|
|
37
37
|
"typebox": "1.4.3",
|
|
38
|
-
"@types/bun": "1.4.
|
|
38
|
+
"@types/bun": "1.4.5",
|
|
39
39
|
"typescript": "7.1.0-beta"
|
|
40
40
|
},
|
|
41
41
|
"peerDependencies": {
|