better-ship 0.16.0 → 0.18.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/dist/{application-Cf9SER-i.js → application-CNdzHIXk.js} +5 -7
- package/dist/{application-Cf9SER-i.js.map → application-CNdzHIXk.js.map} +1 -1
- package/dist/application.d.ts +2 -2
- package/dist/application.js +1 -1
- package/dist/better-auth/apple-client-secret.d.ts +1 -1
- package/dist/better-auth/apple-client-secret.js +2 -2
- package/dist/better-auth/apple-client-secret.js.map +1 -1
- package/dist/better-auth/auth-client.js +1 -1
- package/dist/better-auth/rate-limit.d.ts +1 -1
- package/dist/better-auth/rate-limit.js +4 -6
- package/dist/better-auth/rate-limit.js.map +1 -1
- package/dist/better-auth.js +1 -1
- package/dist/billing/client.d.ts +86 -0
- package/dist/billing/client.d.ts.map +1 -0
- package/dist/billing/client.js +77 -0
- package/dist/billing/client.js.map +1 -0
- package/dist/cloudflare/auth-secondary-storage.d.ts +1 -1
- package/dist/cloudflare/auth-secondary-storage.js +1 -1
- package/dist/cloudflare/durable-object-client.js +1 -1
- package/dist/cloudflare/durable-object-errors.d.ts +1 -1
- package/dist/cloudflare/durable-object-errors.js +1 -1
- package/dist/cloudflare/kv-client.d.ts +31 -0
- package/dist/cloudflare/kv-client.d.ts.map +1 -0
- package/dist/cloudflare/kv-client.js +62 -0
- package/dist/cloudflare/kv-client.js.map +1 -0
- package/dist/cloudflare/kv-errors.d.ts +52 -0
- package/dist/cloudflare/kv-errors.d.ts.map +1 -0
- package/dist/cloudflare/kv-errors.js +144 -0
- package/dist/cloudflare/kv-errors.js.map +1 -0
- package/dist/cloudflare/queue.d.ts +2 -2
- package/dist/cloudflare/queue.d.ts.map +1 -1
- package/dist/cloudflare/queue.js +10 -12
- package/dist/cloudflare/queue.js.map +1 -1
- package/dist/cloudflare/r2-client.d.ts +70 -0
- package/dist/cloudflare/r2-client.d.ts.map +1 -0
- package/dist/cloudflare/r2-client.js +153 -0
- package/dist/cloudflare/r2-client.js.map +1 -0
- package/dist/cloudflare/r2-errors.d.ts +34 -0
- package/dist/cloudflare/r2-errors.d.ts.map +1 -0
- package/dist/cloudflare/r2-errors.js +90 -0
- package/dist/cloudflare/r2-errors.js.map +1 -0
- package/dist/cloudflare/scheduled.d.ts +1 -1
- package/dist/cloudflare/scheduled.js +2 -2
- package/dist/cloudflare/scheduled.js.map +1 -1
- package/dist/cloudflare.d.ts +10 -5
- package/dist/cloudflare.d.ts.map +1 -1
- package/dist/cloudflare.js +21 -10
- package/dist/cloudflare.js.map +1 -1
- package/dist/{core-ClSP5-V9.js → core-UUW2unJd.js} +106 -195
- package/dist/core-UUW2unJd.js.map +1 -0
- package/dist/core.d.ts +2 -2
- package/dist/core.js +2 -2
- package/dist/http.d.ts +2 -2
- package/dist/http.js +3 -3
- package/dist/http.js.map +1 -1
- package/dist/{index-Cchdg2aQ.d.ts → index-CYHXOH08.d.ts} +2 -2
- package/dist/{index-Cchdg2aQ.d.ts.map → index-CYHXOH08.d.ts.map} +1 -1
- package/dist/{index-DvJUcSW1.d.ts → index-DUFS0SJ_.d.ts} +41 -102
- package/dist/index-DUFS0SJ_.d.ts.map +1 -0
- package/dist/{outbox-repository-options-ICOF8g2h.js → outbox-repository-options-CgdqU20T.js} +2 -2
- package/dist/{outbox-repository-options-ICOF8g2h.js.map → outbox-repository-options-CgdqU20T.js.map} +1 -1
- package/dist/{outbox-repository-options-AkihEaik.d.ts → outbox-repository-options-DjBgFhMi.d.ts} +3 -3
- package/dist/{outbox-repository-options-AkihEaik.d.ts.map → outbox-repository-options-DjBgFhMi.d.ts.map} +1 -1
- package/dist/postgres.d.ts +10 -5
- package/dist/postgres.d.ts.map +1 -1
- package/dist/postgres.js +21 -10
- package/dist/postgres.js.map +1 -1
- package/dist/posthog/metrics.d.ts +1 -1
- package/dist/posthog/server.d.ts +2 -2
- package/dist/posthog/server.js +1 -1
- package/dist/resend.d.ts +3 -3
- package/dist/resend.js +2 -2
- package/dist/sentry/client.d.ts +1 -1
- package/dist/sentry/client.d.ts.map +1 -1
- package/dist/sentry/client.js +10 -4
- package/dist/sentry/client.js.map +1 -1
- package/dist/sentry/server.d.ts +2 -2
- package/dist/sentry/server.js +5 -5
- package/dist/sentry/server.js.map +1 -1
- package/dist/stripe/payment-service.d.ts +52 -0
- package/dist/stripe/payment-service.d.ts.map +1 -0
- package/dist/stripe/payment-service.error.d.ts +13 -0
- package/dist/stripe/payment-service.error.d.ts.map +1 -0
- package/dist/stripe/payment-service.error.js +30 -0
- package/dist/stripe/payment-service.error.js.map +1 -0
- package/dist/stripe/payment-service.js +72 -0
- package/dist/stripe/payment-service.js.map +1 -0
- package/dist/stripe/payment-webhook.d.ts +18 -0
- package/dist/stripe/payment-webhook.d.ts.map +1 -0
- package/dist/stripe/payment-webhook.js +47 -0
- package/dist/stripe/payment-webhook.js.map +1 -0
- package/dist/tanstack.d.ts +1 -1
- package/dist/tanstack.js +4 -4
- package/dist/tanstack.js.map +1 -1
- package/dist/testing/outbox-repository.d.ts +2 -2
- package/dist/testing/payment-service.d.ts +10 -0
- package/dist/testing/payment-service.d.ts.map +1 -0
- package/dist/testing/payment-service.js +76 -0
- package/dist/testing/payment-service.js.map +1 -0
- package/dist/{webhook-verification-D6aGQfNi.js → webhook-verification-BBmjkHgI.js} +2 -2
- package/dist/{webhook-verification-D6aGQfNi.js.map → webhook-verification-BBmjkHgI.js.map} +1 -1
- package/dist/{webhook-verification-BcQQG-vY.d.ts → webhook-verification-BuxPzdr4.d.ts} +2 -2
- package/dist/{webhook-verification-BcQQG-vY.d.ts.map → webhook-verification-BuxPzdr4.d.ts.map} +1 -1
- package/package.json +15 -6
- package/src/application/outbox-relay.ts +3 -1
- package/src/core/console-log-sink.ts +65 -0
- package/src/core/index.ts +1 -4
- package/src/core/logger.ts +80 -281
- package/src/infrastructure/better-auth/apple-client-secret.ts +1 -1
- package/src/infrastructure/better-auth/rate-limit.ts +3 -1
- package/src/infrastructure/billing/client.ts +173 -0
- package/src/infrastructure/cloudflare/d1-database-execution.ts +27 -6
- package/src/infrastructure/cloudflare/kv-client.ts +79 -0
- package/src/infrastructure/cloudflare/kv-errors.ts +157 -0
- package/src/infrastructure/cloudflare/queue/queue-consumer.ts +8 -9
- package/src/infrastructure/cloudflare/r2-client.ts +162 -0
- package/src/infrastructure/cloudflare/r2-errors.ts +111 -0
- package/src/infrastructure/cloudflare/scheduled/scheduled-handler.ts +1 -1
- package/src/infrastructure/http/webhook-handler.ts +1 -1
- package/src/infrastructure/postgres/postgres-database-execution.ts +27 -6
- package/src/infrastructure/sentry/client.ts +6 -3
- package/src/infrastructure/sentry/server.ts +4 -4
- package/src/infrastructure/stripe/payment-service.error.ts +42 -0
- package/src/infrastructure/stripe/payment-service.ts +129 -0
- package/src/infrastructure/stripe/payment-webhook.ts +49 -0
- package/src/infrastructure/tanstack/resolve-failure.ts +3 -2
- package/src/infrastructure/testing/payment-service-contract.ts +91 -0
- package/dist/core-ClSP5-V9.js.map +0 -1
- package/dist/index-DvJUcSW1.d.ts.map +0 -1
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { l as spreadJitterMs, s as exponentialDelayCapMs } from "../core-UUW2unJd.js";
|
|
2
|
+
import { KVError, decideKVRetry, isKVPutRateLimitError } from "./kv-errors.js";
|
|
3
|
+
import { Result } from "better-result";
|
|
4
|
+
|
|
5
|
+
//#region src/infrastructure/cloudflare/kv-client.ts
|
|
6
|
+
/** KV access with Typist's automatic transient retries and final KVError conversion. */
|
|
7
|
+
var KVClient = class {
|
|
8
|
+
kv;
|
|
9
|
+
constructor(kv) {
|
|
10
|
+
this.kv = kv;
|
|
11
|
+
}
|
|
12
|
+
/** Read text, or return null when the key does not exist. */
|
|
13
|
+
async get(key) {
|
|
14
|
+
return await this.run("get", key, async () => this.kv.get(key));
|
|
15
|
+
}
|
|
16
|
+
/** Read JSON without schema validation; the caller supplies its stored type. */
|
|
17
|
+
async getJson(key) {
|
|
18
|
+
return await this.run("get", key, async () => this.kv.get(key, "json"));
|
|
19
|
+
}
|
|
20
|
+
/** Write text; positive TTL values pass to KV in seconds, and other TTL values omit expiration. */
|
|
21
|
+
async put(key, value, options) {
|
|
22
|
+
const kvOptions = {};
|
|
23
|
+
if (options?.ttl !== void 0 && options.ttl > 0) kvOptions.expirationTtl = options.ttl;
|
|
24
|
+
await this.run("put", key, async () => this.kv.put(key, value, kvOptions));
|
|
25
|
+
}
|
|
26
|
+
/** Serialize once before writing; serialization failures retain their original error. */
|
|
27
|
+
async putJson(key, value, options) {
|
|
28
|
+
await this.put(key, JSON.stringify(value), options);
|
|
29
|
+
}
|
|
30
|
+
/** Delete a key; a missing key succeeds, and transient failures retry automatically. */
|
|
31
|
+
async delete(key) {
|
|
32
|
+
await this.run("delete", key, async () => this.kv.delete(key));
|
|
33
|
+
}
|
|
34
|
+
/** Expose Typist's three-method secondary storage bridge without changing KV semantics. */
|
|
35
|
+
asSecondaryStorage() {
|
|
36
|
+
return {
|
|
37
|
+
get: (key) => this.get(key),
|
|
38
|
+
set: (key, value, ttl) => this.put(key, value, { ttl }),
|
|
39
|
+
delete: (key) => this.delete(key)
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
async run(operation, key, work) {
|
|
43
|
+
const result = await Result.tryPromise({
|
|
44
|
+
try: work,
|
|
45
|
+
catch: (cause) => cause
|
|
46
|
+
}, { retry: {
|
|
47
|
+
times: 2,
|
|
48
|
+
shouldRetry: (cause) => decideKVRetry(cause).retry,
|
|
49
|
+
delayMs: (cause, { attempt }) => (isKVPutRateLimitError(cause) ? 1e3 : 0) + spreadJitterMs(exponentialDelayCapMs(25, 3e3, attempt))
|
|
50
|
+
} });
|
|
51
|
+
if (result.isOk()) return result.value;
|
|
52
|
+
throw new KVError({
|
|
53
|
+
operation,
|
|
54
|
+
key,
|
|
55
|
+
cause: result.error
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
//#endregion
|
|
61
|
+
export { KVClient };
|
|
62
|
+
//# sourceMappingURL=kv-client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"kv-client.js","names":[],"sources":["../../src/infrastructure/cloudflare/kv-client.ts"],"sourcesContent":["import { Result } from 'better-result'\n\nimport { exponentialDelayCapMs, spreadJitterMs } from '@/core'\n\nimport { decideKVRetry, isKVPutRateLimitError, KVError } from './kv-errors.ts'\n\n/** Text storage bridge with the same TTL behavior as KVClient. */\nexport type KVSecondaryStorage = {\n get: (key: string) => Promise<string | null>\n set: (key: string, value: string, ttl?: number) => Promise<void>\n delete: (key: string) => Promise<void>\n}\n\ntype KVOperation = 'get' | 'put' | 'delete'\n\n/** KV access with Typist's automatic transient retries and final KVError conversion. */\nexport class KVClient {\n constructor(private readonly kv: KVNamespace) {}\n\n /** Read text, or return null when the key does not exist. */\n async get(key: string): Promise<string | null> {\n return await this.run('get', key, async () => this.kv.get(key))\n }\n\n /** Read JSON without schema validation; the caller supplies its stored type. */\n async getJson<T>(key: string): Promise<T | null> {\n return await this.run('get', key, async () => this.kv.get<T>(key, 'json'))\n }\n\n /** Write text; positive TTL values pass to KV in seconds, and other TTL values omit expiration. */\n async put(key: string, value: string, options?: { ttl?: number | undefined }): Promise<void> {\n const kvOptions: KVNamespacePutOptions = {}\n if (options?.ttl !== undefined && options.ttl > 0) {\n kvOptions.expirationTtl = options.ttl\n }\n await this.run('put', key, async () => this.kv.put(key, value, kvOptions))\n }\n\n /** Serialize once before writing; serialization failures retain their original error. */\n async putJson(\n key: string,\n // oxlint-disable-next-line anti-slop/no-unknown-parameters -- Preserve the approved JSON serialization boundary and Typist's public signature.\n value: unknown,\n options?: { ttl?: number | undefined },\n ): Promise<void> {\n await this.put(key, JSON.stringify(value), options)\n }\n\n /** Delete a key; a missing key succeeds, and transient failures retry automatically. */\n async delete(key: string): Promise<void> {\n await this.run('delete', key, async () => this.kv.delete(key))\n }\n\n /** Expose Typist's three-method secondary storage bridge without changing KV semantics. */\n asSecondaryStorage(): KVSecondaryStorage {\n return {\n get: (key) => this.get(key),\n set: (key, value, ttl) => this.put(key, value, { ttl }),\n delete: (key) => this.delete(key),\n }\n }\n\n private async run<T>(operation: KVOperation, key: string, work: () => Promise<T>): Promise<T> {\n const result = await Result.tryPromise(\n { try: work, catch: (cause) => cause },\n {\n retry: {\n times: 2,\n shouldRetry: (cause) => decideKVRetry(cause).retry,\n delayMs: (cause, { attempt }) =>\n (isKVPutRateLimitError(cause) ? 1_000 : 0) +\n spreadJitterMs(exponentialDelayCapMs(25, 3_000, attempt)),\n },\n },\n )\n if (result.isOk()) return result.value\n throw new KVError({ operation, key, cause: result.error })\n }\n}\n"],"mappings":";;;;;;AAgBA,IAAa,WAAb,MAAsB;CACS;CAA7B,YAAY,AAAiB,IAAiB;EAAjB;CAAkB;;CAG/C,MAAM,IAAI,KAAqC;EAC7C,OAAO,MAAM,KAAK,IAAI,OAAO,KAAK,YAAY,KAAK,GAAG,IAAI,GAAG,CAAC;CAChE;;CAGA,MAAM,QAAW,KAAgC;EAC/C,OAAO,MAAM,KAAK,IAAI,OAAO,KAAK,YAAY,KAAK,GAAG,IAAO,KAAK,MAAM,CAAC;CAC3E;;CAGA,MAAM,IAAI,KAAa,OAAe,SAAuD;EAC3F,MAAM,YAAmC,CAAC;EAC1C,IAAI,SAAS,QAAQ,UAAa,QAAQ,MAAM,GAC9C,UAAU,gBAAgB,QAAQ;EAEpC,MAAM,KAAK,IAAI,OAAO,KAAK,YAAY,KAAK,GAAG,IAAI,KAAK,OAAO,SAAS,CAAC;CAC3E;;CAGA,MAAM,QACJ,KAEA,OACA,SACe;EACf,MAAM,KAAK,IAAI,KAAK,KAAK,UAAU,KAAK,GAAG,OAAO;CACpD;;CAGA,MAAM,OAAO,KAA4B;EACvC,MAAM,KAAK,IAAI,UAAU,KAAK,YAAY,KAAK,GAAG,OAAO,GAAG,CAAC;CAC/D;;CAGA,qBAAyC;EACvC,OAAO;GACL,MAAM,QAAQ,KAAK,IAAI,GAAG;GAC1B,MAAM,KAAK,OAAO,QAAQ,KAAK,IAAI,KAAK,OAAO,EAAE,IAAI,CAAC;GACtD,SAAS,QAAQ,KAAK,OAAO,GAAG;EAClC;CACF;CAEA,MAAc,IAAO,WAAwB,KAAa,MAAoC;EAC5F,MAAM,SAAS,MAAM,OAAO,WAC1B;GAAE,KAAK;GAAM,QAAQ,UAAU;EAAM,GACrC,EACE,OAAO;GACL,OAAO;GACP,cAAc,UAAU,cAAc,KAAK,CAAC,CAAC;GAC7C,UAAU,OAAO,EAAE,eAChB,sBAAsB,KAAK,IAAI,MAAQ,KACxC,eAAe,sBAAsB,IAAI,KAAO,OAAO,CAAC;EAC5D,EACF,CACF;EACA,IAAI,OAAO,KAAK,GAAG,OAAO,OAAO;EACjC,MAAM,IAAI,QAAQ;GAAE;GAAW;GAAK,OAAO,OAAO;EAAM,CAAC;CAC3D;AACF"}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { Xt as AppError, Zt as FailureClassification } from "../index-DUFS0SJ_.js";
|
|
2
|
+
//#region src/infrastructure/cloudflare/kv-errors.d.ts
|
|
3
|
+
/** KV operations recognized in binding error messages. */
|
|
4
|
+
export type KVOperation = 'get' | 'put' | 'delete' | 'list';
|
|
5
|
+
/** KV failure kinds retained from Typist's binding tests. */
|
|
6
|
+
export type KVErrorKind = 'invalid_key' | 'key_too_large' | 'invalid_expiration_ttl' | 'invalid_expiration' | 'invalid_cache_ttl' | 'invalid_list_limit' | 'value_too_large' | 'client_error' | 'rate_limited' | 'server_error';
|
|
7
|
+
/** Evidence extracted from a KV error and its causes. */
|
|
8
|
+
export interface KVErrorMeta {
|
|
9
|
+
kind: KVErrorKind;
|
|
10
|
+
message: string;
|
|
11
|
+
status?: number | undefined;
|
|
12
|
+
operation?: Uppercase<KVOperation> | undefined;
|
|
13
|
+
}
|
|
14
|
+
/** Extract Typist's verified KV message formats, including nested causes. */
|
|
15
|
+
export declare function extractKVMeta(cause: unknown): KVErrorMeta | undefined;
|
|
16
|
+
/** Identify recognized KV failures that another attempt cannot resolve. */
|
|
17
|
+
export declare function isTerminalKVError(cause: unknown): boolean;
|
|
18
|
+
/** Identify a PUT rate limit that requires at least one second before retrying. */
|
|
19
|
+
export declare function isKVPutRateLimitError(cause: unknown): boolean;
|
|
20
|
+
/** Identify PUT rate limits, server failures, and request timeouts. */
|
|
21
|
+
export declare function isTransientKVError(cause: unknown): boolean;
|
|
22
|
+
/** Apply Typist's KV, overload, platform, and transport checks in their original order. */
|
|
23
|
+
export declare function isRetryableKVError(cause: unknown): boolean;
|
|
24
|
+
/** Return the existing retry decision and minimum delay in milliseconds. */
|
|
25
|
+
export declare function decideKVRetry(cause: unknown): {
|
|
26
|
+
retry: false;
|
|
27
|
+
} | {
|
|
28
|
+
retry: true;
|
|
29
|
+
retryAfterMs: number;
|
|
30
|
+
};
|
|
31
|
+
/** A final KV failure with Typist's diagnostics and Better Ship's error classification. */
|
|
32
|
+
export declare class KVError extends AppError {
|
|
33
|
+
readonly _tag = "KVError";
|
|
34
|
+
readonly classification: FailureClassification;
|
|
35
|
+
retryable: boolean;
|
|
36
|
+
readonly operation: KVOperation;
|
|
37
|
+
readonly key?: string | undefined;
|
|
38
|
+
readonly cause: unknown;
|
|
39
|
+
readonly kv?: KVErrorMeta | undefined;
|
|
40
|
+
readonly context: {
|
|
41
|
+
operation: KVOperation;
|
|
42
|
+
key?: string | undefined;
|
|
43
|
+
kv?: KVErrorMeta | undefined;
|
|
44
|
+
};
|
|
45
|
+
constructor(args: {
|
|
46
|
+
operation: KVOperation;
|
|
47
|
+
key?: string | undefined;
|
|
48
|
+
cause: unknown;
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
//#endregion
|
|
52
|
+
//# sourceMappingURL=kv-errors.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"kv-errors.d.ts","names":[],"sources":["../../src/infrastructure/cloudflare/kv-errors.ts"],"mappings":";;;YASY;;YAGA;;iBAaK;EACf,MAAM;EACN;EACA;EACA,YAAY,UAAU;;;wBAIR,cAAc,iBAAiB;;wBAwC/B,kBAAkB;;wBASlB,sBAAsB;;wBAMtB,mBAAmB;;wBAOnB,mBAAmB;;wBAQnB,cACd;EACG;;EAAmB;EAAa;;;qBAMxB,gBAAgB;WAClB;WACA,gBAAgB;EACzB;WACS,WAAW;WACX;WACS;WACT,KAAK;WACL;IACP,WAAW;IACX;IACA,KAAK;;EAGP,YAAY;IAAQ,WAAW;IAAa;IAA0B"}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { g as isCloudflareRetryableError, h as isCloudflareOverloadedError, nt as AppError, y as isTransientTransportError } from "../core-UUW2unJd.js";
|
|
2
|
+
|
|
3
|
+
//#region src/infrastructure/cloudflare/kv-errors.ts
|
|
4
|
+
/** Extract Typist's verified KV message formats, including nested causes. */
|
|
5
|
+
function extractKVMeta(cause) {
|
|
6
|
+
const message = getDeepErrorMessage(cause);
|
|
7
|
+
if (!message) return void 0;
|
|
8
|
+
const statusMatch = message.match(/\bKV\s+(GET|PUT|DELETE|LIST)\s+failed:\s+(\d{3})\b/);
|
|
9
|
+
const operation = statusMatch?.[1];
|
|
10
|
+
const status = statusMatch ? Number(statusMatch[2]) : void 0;
|
|
11
|
+
if (/Key name cannot be empty/i.test(message)) return {
|
|
12
|
+
kind: "invalid_key",
|
|
13
|
+
message,
|
|
14
|
+
status,
|
|
15
|
+
operation
|
|
16
|
+
};
|
|
17
|
+
if (/exceeds key length limit/i.test(message)) return {
|
|
18
|
+
kind: "key_too_large",
|
|
19
|
+
message,
|
|
20
|
+
status,
|
|
21
|
+
operation
|
|
22
|
+
};
|
|
23
|
+
if (/Invalid expiration_ttl/i.test(message)) return {
|
|
24
|
+
kind: "invalid_expiration_ttl",
|
|
25
|
+
message,
|
|
26
|
+
status,
|
|
27
|
+
operation
|
|
28
|
+
};
|
|
29
|
+
if (/Invalid expiration of/i.test(message)) return {
|
|
30
|
+
kind: "invalid_expiration",
|
|
31
|
+
message,
|
|
32
|
+
status,
|
|
33
|
+
operation
|
|
34
|
+
};
|
|
35
|
+
if (/Invalid cache_ttl/i.test(message)) return {
|
|
36
|
+
kind: "invalid_cache_ttl",
|
|
37
|
+
message,
|
|
38
|
+
status,
|
|
39
|
+
operation
|
|
40
|
+
};
|
|
41
|
+
if (/Invalid key_count_limit/i.test(message)) return {
|
|
42
|
+
kind: "invalid_list_limit",
|
|
43
|
+
message,
|
|
44
|
+
status,
|
|
45
|
+
operation
|
|
46
|
+
};
|
|
47
|
+
if (/value.*(too large|exceeds)|exceeds.*value/i.test(message)) return {
|
|
48
|
+
kind: "value_too_large",
|
|
49
|
+
message,
|
|
50
|
+
status,
|
|
51
|
+
operation
|
|
52
|
+
};
|
|
53
|
+
if (status === 429) return {
|
|
54
|
+
kind: "rate_limited",
|
|
55
|
+
message,
|
|
56
|
+
status,
|
|
57
|
+
operation
|
|
58
|
+
};
|
|
59
|
+
if (status !== void 0 && status >= 500) return {
|
|
60
|
+
kind: "server_error",
|
|
61
|
+
message,
|
|
62
|
+
status,
|
|
63
|
+
operation
|
|
64
|
+
};
|
|
65
|
+
if (status !== void 0 && status >= 400) return {
|
|
66
|
+
kind: "client_error",
|
|
67
|
+
message,
|
|
68
|
+
status,
|
|
69
|
+
operation
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
/** Identify recognized KV failures that another attempt cannot resolve. */
|
|
73
|
+
function isTerminalKVError(cause) {
|
|
74
|
+
const meta = extractKVMeta(cause);
|
|
75
|
+
if (!meta) return false;
|
|
76
|
+
if (meta.kind === "rate_limited" || meta.kind === "server_error") return false;
|
|
77
|
+
if (meta.status === 408) return false;
|
|
78
|
+
return true;
|
|
79
|
+
}
|
|
80
|
+
/** Identify a PUT rate limit that requires at least one second before retrying. */
|
|
81
|
+
function isKVPutRateLimitError(cause) {
|
|
82
|
+
const meta = extractKVMeta(cause);
|
|
83
|
+
return meta?.operation === "PUT" && meta.kind === "rate_limited";
|
|
84
|
+
}
|
|
85
|
+
/** Identify PUT rate limits, server failures, and request timeouts. */
|
|
86
|
+
function isTransientKVError(cause) {
|
|
87
|
+
const meta = extractKVMeta(cause);
|
|
88
|
+
if (!meta) return false;
|
|
89
|
+
return isKVPutRateLimitError(cause) || meta.kind === "server_error" || meta.status === 408;
|
|
90
|
+
}
|
|
91
|
+
/** Apply Typist's KV, overload, platform, and transport checks in their original order. */
|
|
92
|
+
function isRetryableKVError(cause) {
|
|
93
|
+
if (isTerminalKVError(cause)) return false;
|
|
94
|
+
if (isTransientKVError(cause)) return true;
|
|
95
|
+
if (isCloudflareOverloadedError(cause)) return false;
|
|
96
|
+
return isCloudflareRetryableError(cause) || isTransientTransportError(cause);
|
|
97
|
+
}
|
|
98
|
+
/** Return the existing retry decision and minimum delay in milliseconds. */
|
|
99
|
+
function decideKVRetry(cause) {
|
|
100
|
+
if (!isRetryableKVError(cause)) return { retry: false };
|
|
101
|
+
return {
|
|
102
|
+
retry: true,
|
|
103
|
+
retryAfterMs: isKVPutRateLimitError(cause) ? 1e3 : 0
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
/** A final KV failure with Typist's diagnostics and Better Ship's error classification. */
|
|
107
|
+
var KVError = class extends AppError {
|
|
108
|
+
_tag = "KVError";
|
|
109
|
+
classification;
|
|
110
|
+
retryable;
|
|
111
|
+
operation;
|
|
112
|
+
key;
|
|
113
|
+
cause;
|
|
114
|
+
kv;
|
|
115
|
+
context;
|
|
116
|
+
constructor(args) {
|
|
117
|
+
const kv = extractKVMeta(args.cause);
|
|
118
|
+
const causeMessage = getDeepErrorMessage(args.cause) || String(args.cause);
|
|
119
|
+
const keyContext = args.key === void 0 ? "" : ` for key "${args.key}"`;
|
|
120
|
+
super(`KV ${args.operation} failed${keyContext}: ${causeMessage}`, { cause: args.cause });
|
|
121
|
+
this.operation = args.operation;
|
|
122
|
+
this.key = args.key;
|
|
123
|
+
this.cause = args.cause;
|
|
124
|
+
this.kv = kv;
|
|
125
|
+
this.context = {
|
|
126
|
+
operation: args.operation,
|
|
127
|
+
key: args.key,
|
|
128
|
+
kv
|
|
129
|
+
};
|
|
130
|
+
this.retryable = isRetryableKVError(args.cause);
|
|
131
|
+
this.classification = isTerminalKVError(args.cause) ? "terminal" : this.retryable ? "transient" : "unknown";
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
function getDeepErrorMessage(cause) {
|
|
135
|
+
if (typeof cause === "string") return cause;
|
|
136
|
+
if (cause === null || cause === void 0) return "";
|
|
137
|
+
if (typeof cause === "number" || typeof cause === "boolean" || typeof cause === "bigint") return String(cause);
|
|
138
|
+
if (typeof cause !== "object") return "";
|
|
139
|
+
return `${"message" in cause && typeof cause.message === "string" ? cause.message : ""} ${"cause" in cause ? getDeepErrorMessage(cause.cause) : ""}`.trim();
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
//#endregion
|
|
143
|
+
export { KVError, decideKVRetry, extractKVMeta, isKVPutRateLimitError, isRetryableKVError, isTerminalKVError, isTransientKVError };
|
|
144
|
+
//# sourceMappingURL=kv-errors.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"kv-errors.js","names":[],"sources":["../../src/infrastructure/cloudflare/kv-errors.ts"],"sourcesContent":["import {\n AppError,\n isCloudflareOverloadedError,\n isCloudflareRetryableError,\n isTransientTransportError,\n type FailureClassification,\n} from '@/core'\n\n/** KV operations recognized in binding error messages. */\nexport type KVOperation = 'get' | 'put' | 'delete' | 'list'\n\n/** KV failure kinds retained from Typist's binding tests. */\nexport type KVErrorKind =\n | 'invalid_key'\n | 'key_too_large'\n | 'invalid_expiration_ttl'\n | 'invalid_expiration'\n | 'invalid_cache_ttl'\n | 'invalid_list_limit'\n | 'value_too_large'\n | 'client_error'\n | 'rate_limited'\n | 'server_error'\n\n/** Evidence extracted from a KV error and its causes. */\nexport interface KVErrorMeta {\n kind: KVErrorKind\n message: string\n status?: number | undefined\n operation?: Uppercase<KVOperation> | undefined\n}\n\n/** Extract Typist's verified KV message formats, including nested causes. */\nexport function extractKVMeta(cause: unknown): KVErrorMeta | undefined {\n const message = getDeepErrorMessage(cause)\n if (!message) return undefined\n const statusMatch = message.match(/\\bKV\\s+(GET|PUT|DELETE|LIST)\\s+failed:\\s+(\\d{3})\\b/)\n // SAFETY: The regular expression permits only uppercase KV operation names in this capture.\n const operation = statusMatch?.[1] as Uppercase<KVOperation> | undefined\n const status = statusMatch ? Number(statusMatch[2]) : undefined\n\n if (/Key name cannot be empty/i.test(message)) {\n return { kind: 'invalid_key', message, status, operation }\n }\n if (/exceeds key length limit/i.test(message)) {\n return { kind: 'key_too_large', message, status, operation }\n }\n if (/Invalid expiration_ttl/i.test(message)) {\n return { kind: 'invalid_expiration_ttl', message, status, operation }\n }\n if (/Invalid expiration of/i.test(message)) {\n return { kind: 'invalid_expiration', message, status, operation }\n }\n if (/Invalid cache_ttl/i.test(message)) {\n return { kind: 'invalid_cache_ttl', message, status, operation }\n }\n if (/Invalid key_count_limit/i.test(message)) {\n return { kind: 'invalid_list_limit', message, status, operation }\n }\n if (/value.*(too large|exceeds)|exceeds.*value/i.test(message)) {\n return { kind: 'value_too_large', message, status, operation }\n }\n if (status === 429) return { kind: 'rate_limited', message, status, operation }\n if (status !== undefined && status >= 500) {\n return { kind: 'server_error', message, status, operation }\n }\n if (status !== undefined && status >= 400) {\n return { kind: 'client_error', message, status, operation }\n }\n return undefined\n}\n\n/** Identify recognized KV failures that another attempt cannot resolve. */\nexport function isTerminalKVError(cause: unknown): boolean {\n const meta = extractKVMeta(cause)\n if (!meta) return false\n if (meta.kind === 'rate_limited' || meta.kind === 'server_error') return false\n if (meta.status === 408) return false\n return true\n}\n\n/** Identify a PUT rate limit that requires at least one second before retrying. */\nexport function isKVPutRateLimitError(cause: unknown): boolean {\n const meta = extractKVMeta(cause)\n return meta?.operation === 'PUT' && meta.kind === 'rate_limited'\n}\n\n/** Identify PUT rate limits, server failures, and request timeouts. */\nexport function isTransientKVError(cause: unknown): boolean {\n const meta = extractKVMeta(cause)\n if (!meta) return false\n return isKVPutRateLimitError(cause) || meta.kind === 'server_error' || meta.status === 408\n}\n\n/** Apply Typist's KV, overload, platform, and transport checks in their original order. */\nexport function isRetryableKVError(cause: unknown): boolean {\n if (isTerminalKVError(cause)) return false\n if (isTransientKVError(cause)) return true\n if (isCloudflareOverloadedError(cause)) return false\n return isCloudflareRetryableError(cause) || isTransientTransportError(cause)\n}\n\n/** Return the existing retry decision and minimum delay in milliseconds. */\nexport function decideKVRetry(\n cause: unknown,\n): { retry: false } | { retry: true; retryAfterMs: number } {\n if (!isRetryableKVError(cause)) return { retry: false }\n return { retry: true, retryAfterMs: isKVPutRateLimitError(cause) ? 1_000 : 0 }\n}\n\n/** A final KV failure with Typist's diagnostics and Better Ship's error classification. */\nexport class KVError extends AppError {\n readonly _tag = 'KVError'\n readonly classification: FailureClassification\n retryable: boolean\n readonly operation: KVOperation\n readonly key?: string | undefined\n override readonly cause: unknown\n readonly kv?: KVErrorMeta | undefined\n readonly context: {\n operation: KVOperation\n key?: string | undefined\n kv?: KVErrorMeta | undefined\n }\n\n constructor(args: { operation: KVOperation; key?: string | undefined; cause: unknown }) {\n const kv = extractKVMeta(args.cause)\n const causeMessage = getDeepErrorMessage(args.cause) || String(args.cause)\n const keyContext = args.key === undefined ? '' : ` for key \"${args.key}\"`\n super(`KV ${args.operation} failed${keyContext}: ${causeMessage}`, { cause: args.cause })\n this.operation = args.operation\n this.key = args.key\n this.cause = args.cause\n this.kv = kv\n this.context = { operation: args.operation, key: args.key, kv }\n this.retryable = isRetryableKVError(args.cause)\n this.classification = isTerminalKVError(args.cause)\n ? 'terminal'\n : this.retryable\n ? 'transient'\n : 'unknown'\n }\n}\n\n// oxlint-disable anti-slop/no-runtime-typeof -- Preserve Typist's primitive messages and nested causes at the raw binding boundary.\nfunction getDeepErrorMessage(cause: unknown): string {\n if (typeof cause === 'string') return cause\n if (cause === null || cause === undefined) return ''\n if (typeof cause === 'number' || typeof cause === 'boolean' || typeof cause === 'bigint') {\n return String(cause)\n }\n if (typeof cause !== 'object') return ''\n const message = 'message' in cause && typeof cause.message === 'string' ? cause.message : ''\n const causeMessage = 'cause' in cause ? getDeepErrorMessage(cause.cause) : ''\n return `${message} ${causeMessage}`.trim()\n}\n// oxlint-enable anti-slop/no-runtime-typeof\n"],"mappings":";;;;AAiCA,SAAgB,cAAc,OAAyC;CACrE,MAAM,UAAU,oBAAoB,KAAK;CACzC,IAAI,CAAC,SAAS,OAAO;CACrB,MAAM,cAAc,QAAQ,MAAM,oDAAoD;CAEtF,MAAM,YAAY,cAAc;CAChC,MAAM,SAAS,cAAc,OAAO,YAAY,EAAE,IAAI;CAEtD,IAAI,4BAA4B,KAAK,OAAO,GAC1C,OAAO;EAAE,MAAM;EAAe;EAAS;EAAQ;CAAU;CAE3D,IAAI,4BAA4B,KAAK,OAAO,GAC1C,OAAO;EAAE,MAAM;EAAiB;EAAS;EAAQ;CAAU;CAE7D,IAAI,0BAA0B,KAAK,OAAO,GACxC,OAAO;EAAE,MAAM;EAA0B;EAAS;EAAQ;CAAU;CAEtE,IAAI,yBAAyB,KAAK,OAAO,GACvC,OAAO;EAAE,MAAM;EAAsB;EAAS;EAAQ;CAAU;CAElE,IAAI,qBAAqB,KAAK,OAAO,GACnC,OAAO;EAAE,MAAM;EAAqB;EAAS;EAAQ;CAAU;CAEjE,IAAI,2BAA2B,KAAK,OAAO,GACzC,OAAO;EAAE,MAAM;EAAsB;EAAS;EAAQ;CAAU;CAElE,IAAI,6CAA6C,KAAK,OAAO,GAC3D,OAAO;EAAE,MAAM;EAAmB;EAAS;EAAQ;CAAU;CAE/D,IAAI,WAAW,KAAK,OAAO;EAAE,MAAM;EAAgB;EAAS;EAAQ;CAAU;CAC9E,IAAI,WAAW,UAAa,UAAU,KACpC,OAAO;EAAE,MAAM;EAAgB;EAAS;EAAQ;CAAU;CAE5D,IAAI,WAAW,UAAa,UAAU,KACpC,OAAO;EAAE,MAAM;EAAgB;EAAS;EAAQ;CAAU;AAG9D;;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EACxF,KAAK,YAAY,KAAK;EACtB,KAAK,MAAM,KAAK;EAChB,KAAK,QAAQ,KAAK;EAClB,KAAK,KAAK;EACV,KAAK,UAAU;GAAE,WAAW,KAAK;GAAW,KAAK,KAAK;GAAK;EAAG;EAC9D,KAAK,YAAY,mBAAmB,KAAK,KAAK;EAC9C,KAAK,iBAAiB,kBAAkB,KAAK,KAAK,IAC9C,aACA,KAAK,YACH,cACA;CACR;AACF;AAGA,SAAS,oBAAoB,OAAwB;CACnD,IAAI,OAAO,UAAU,UAAU,OAAO;CACtC,IAAI,UAAU,QAAQ,UAAU,QAAW,OAAO;CAClD,IAAI,OAAO,UAAU,YAAY,OAAO,UAAU,aAAa,OAAO,UAAU,UAC9E,OAAO,OAAO,KAAK;CAErB,IAAI,OAAO,UAAU,UAAU,OAAO;CAGtC,OAAO,GAFS,aAAa,SAAS,OAAO,MAAM,YAAY,WAAW,MAAM,UAAU,GAExE,GADG,WAAW,QAAQ,oBAAoB,MAAM,KAAK,IAAI,KACvC,KAAK;AAC3C"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { D as OutboxRelay, E as IOutboxRelay } from "../index-
|
|
1
|
+
import { U as DomainCommand, W as DomainEvent, Xt as AppError, Zt as FailureClassification } from "../index-DUFS0SJ_.js";
|
|
2
|
+
import { D as OutboxRelay, E as IOutboxRelay } from "../index-CYHXOH08.js";
|
|
3
3
|
import { z } from "zod";
|
|
4
4
|
//#region src/infrastructure/cloudflare/queue/queue-message.d.ts
|
|
5
5
|
/** A message a queue carries: a command from outside the request, or an event from the outbox. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"queue.d.ts","names":[],"sources":["../../src/infrastructure/cloudflare/queue/queue-message.ts","../../src/infrastructure/cloudflare/queue/queue-client.ts","../../src/infrastructure/cloudflare/queue/queue-consumer.ts","../../src/infrastructure/cloudflare/queue/queue-limits.ts","../../src/infrastructure/cloudflare/queue/queue.errors.ts","../../src/infrastructure/cloudflare/queue/redelivery-policy.ts","../../src/infrastructure/cloudflare/queue/wait-until-wake.ts"],"mappings":";;;;;KAGY,eAAe,gBAAgB;;;;KCa/B;WAA8B;;;KAG9B,aAAa,QAAQ,KAAK,MAAM;;;;;KAMhC,mBAAmB,iBAAiB,cAAc;WACnD,QAAQ,SAAS,OAAO,MAAM,aAAa;;WAE3C,YAAY,KAAK;WACjB,SAAS,SAAS,aAAa;;;UAIzB,aAAa,iBAAiB;EAC7C,KAAK,SAAS,UAAU,UAAU,mBAAmB;EACrD,UAAU,UAAU,cAAc,YAAY;;EAE9C,iBAAiB,aAAa,UAC5B,UAAU,cAAc,QACvB,QAAQ,cAAc;;EAEzB,UAAU,SAAS,UAAU;;;;;;qBA8BlB,YACX,iBAAiB,cACjB,gCACW,aAAa;mBACK;EAA7B,YAA6B,SAAS,mBAAmB,UAAU;;EAG7D,KAAK,SAAS,UAAU,UAAU,mBAAmB;;EA4BrD,UAAU,UAAU,cAAc,YAAY;EAO9C,iBAAiB,aAAa,UAClC,UAAU,cAAc,QACvB,QAAQ,cAAc;EAMnB,UAAU,SAAS,UAAU;;UAQrB;UA4BN;UAIM;;;;;KCpJJ,gBAAgB,iBAAiB,iBAC3C,SAAS,UACT,iBACA,WAAW,kBACR;;KAGO,YAAY,iBAAiB;EAEvC,OAAO,SAAS,WAAW;;;;;;;qBAQhB,cAAc,iBAAiB;mBAQvB;mBACA;mBACA;mBACA;;;;;;;EAJnB,YACmB,KAAK,YAAY,WACjB,aAAa,KAAK,aAAa,yBAC/B,QAAQ,EAAE,QAAQ,WAClB,eAAc,gBAAgB;;EAI3C,aAAa,OAAO,eAAe;UAc3B;;
|
|
1
|
+
{"version":3,"file":"queue.d.ts","names":[],"sources":["../../src/infrastructure/cloudflare/queue/queue-message.ts","../../src/infrastructure/cloudflare/queue/queue-client.ts","../../src/infrastructure/cloudflare/queue/queue-consumer.ts","../../src/infrastructure/cloudflare/queue/queue-limits.ts","../../src/infrastructure/cloudflare/queue/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Y,OAAO,aAAa;;wBAKhC,cAAc,UAC5B,OAAO,cAAc,aAAa,aACjC;;;;KCjCS;;wBA4CI,mBAAmB,iBAAiB;;qBASvC,uBAAuB;WACzB;WACA,gBAAgB;WAChB,WAAW;EAEpB,YAAY;aAAiB,WAAW;aAAyB;;;;;;;qBAWtD,8BAA8B;WAChC;WACA;WACA;WACA;WACA;EAET,YAAY;aACD;aACA;aACA;;;;;;;qBAeA,mCAAmC;WACrC;WACA;EAET,YAAY;;;;;KCrFF;WACG;WAAwB;;WAExB;WACA,gBAAgB,QAAQ;WACxB;;;;;;;;wBASC,iBAAiB,gBAAgB,kBAAkB;;;;wBCxBnD,cACd,SAAS,KAAK,gCACd,OAAO,KAAK,wBACX"}
|
package/dist/cloudflare/queue.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { o as MessageAlreadyProcessedError } from "../application-
|
|
1
|
+
import { b as shouldRetryFailure, c as exponentialEqualJitterMs, d as classifyFailure, f as retryAfterSecondsOf, l as spreadJitterMs, nt as AppError, r as createLogger, u as classifyBoundaryError } from "../core-UUW2unJd.js";
|
|
2
|
+
import { o as MessageAlreadyProcessedError } from "../application-CNdzHIXk.js";
|
|
3
3
|
import { Result } from "better-result";
|
|
4
4
|
|
|
5
5
|
//#region src/infrastructure/cloudflare/queue/queue-limits.ts
|
|
@@ -338,10 +338,10 @@ var QueueConsumer = class {
|
|
|
338
338
|
try {
|
|
339
339
|
const body = await this.parseMessage(message);
|
|
340
340
|
if (body === null) {
|
|
341
|
-
logger$1.error("invalid_message_format", {
|
|
341
|
+
logger$1.error("invalid_message_format", {
|
|
342
342
|
attempt: message.attempts,
|
|
343
343
|
queueMessageId: message.id
|
|
344
|
-
}
|
|
344
|
+
});
|
|
345
345
|
await this.parkPoison(message);
|
|
346
346
|
return;
|
|
347
347
|
}
|
|
@@ -350,7 +350,7 @@ var QueueConsumer = class {
|
|
|
350
350
|
await this.bus.handle(body);
|
|
351
351
|
});
|
|
352
352
|
message.ack();
|
|
353
|
-
logger$1.debug(
|
|
353
|
+
logger$1.debug("queue_message_processed", { name: body.name });
|
|
354
354
|
} catch (cause) {
|
|
355
355
|
this.handleFailure(message, parsed, cause);
|
|
356
356
|
}
|
|
@@ -387,12 +387,10 @@ var QueueConsumer = class {
|
|
|
387
387
|
if (decision.action === "ack") {
|
|
388
388
|
logger$1.error("message_discarded", {
|
|
389
389
|
error: cause,
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
attempt: message.attempts
|
|
395
|
-
}
|
|
390
|
+
name: parsed?.name,
|
|
391
|
+
messageId: parsed?.id,
|
|
392
|
+
queueMessageId: message.id,
|
|
393
|
+
attempt: message.attempts
|
|
396
394
|
});
|
|
397
395
|
message.ack();
|
|
398
396
|
return;
|
|
@@ -407,7 +405,7 @@ var QueueConsumer = class {
|
|
|
407
405
|
};
|
|
408
406
|
if (decision.classification === "unknown" && message.attempts === 1) logger$1.error("queue_unknown_failure", {
|
|
409
407
|
error: cause,
|
|
410
|
-
|
|
408
|
+
...context
|
|
411
409
|
});
|
|
412
410
|
else logger$1.debug("redelivery_requested", context);
|
|
413
411
|
message.retry({ delaySeconds: decision.delaySeconds });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"queue.js","names":["logger","logger"],"sources":["../../src/infrastructure/cloudflare/queue/queue-limits.ts","../../src/infrastructure/cloudflare/queue/queue.errors.ts","../../src/infrastructure/cloudflare/queue/queue-client.ts","../../src/infrastructure/cloudflare/queue/redelivery-policy.ts","../../src/infrastructure/cloudflare/queue/queue-consumer.ts","../../src/infrastructure/cloudflare/queue/wait-until-wake.ts"],"sourcesContent":["import type { QueueMessage } from './queue-message.ts'\n\n/**\n * The Cloudflare Queues producer limits with metadata headroom, checked before each send so a\n * violation never reaches the binding. The dead letter has the same per-message limit.\n * https://developers.cloudflare.com/queues/platform/limits/\n */\nexport const QUEUE_LIMITS = {\n messageBytes: 127_000,\n batchBytes: 250_000,\n batchCount: 100,\n} as const\n\n/** The size the binding measures: the JSON encoding of the body, in UTF-8 bytes. */\nexport function messageByteLength(message: QueueMessage): number {\n return new TextEncoder().encode(JSON.stringify(message)).length\n}\n\n/** A message with its measured size. */\nexport type SizedMessage<TMessage> = { readonly message: TMessage; readonly bytes: number }\n\n/** Measure every message once. */\nexport function sizeMessages<TMessage extends QueueMessage>(\n messages: ReadonlyArray<TMessage>,\n): SizedMessage<TMessage>[] {\n return messages.map((message) => ({ message, bytes: messageByteLength(message) }))\n}\n\n/** Whether one message is over the per-message limit. */\nexport function isOversized(sized: SizedMessage<QueueMessage>): boolean {\n return sized.bytes > QUEUE_LIMITS.messageBytes\n}\n\n/** Split a batch at the message-count and byte limits, keeping the order. */\nexport function chunkByLimits<TMessage>(\n sized: ReadonlyArray<SizedMessage<TMessage>>,\n): TMessage[][] {\n const chunks: TMessage[][] = []\n let current: TMessage[] = []\n let bytes = 0\n for (const item of sized) {\n const full =\n current.length >= QUEUE_LIMITS.batchCount || bytes + item.bytes > QUEUE_LIMITS.batchBytes\n if (current.length > 0 && full) {\n chunks.push(current)\n current = []\n bytes = 0\n }\n current.push(item.message)\n bytes += item.bytes\n }\n if (current.length > 0) chunks.push(current)\n return chunks\n}\n","import { AppError, classifyBoundaryError, type FailureClassification } from '@/core'\n\n/** The Queue binding calls the client makes. Each is safe to repeat. */\nexport type QueueOperation = 'send' | 'send_batch' | 'send_dlq'\n\nconst QUEUE_OPERATION_MESSAGES = {\n send: 'Failed to send queue message',\n send_batch: 'Failed to send queue batch',\n send_dlq: 'Failed to send DLQ message',\n} satisfies Readonly<Record<QueueOperation, string>>\n\n/**\n * Cloudflare Queues error codes, by whether a repeat could change the answer. The reference\n * marks only 10201 and 10250 for retry; 10251 waits for processing, 15000 is nobody's call.\n * https://developers.cloudflare.com/queues/reference/error-codes/\n */\nconst QUEUE_ERROR_CLASSIFICATIONS = new Map<number, FailureClassification>([\n [10104, 'terminal'], // QueueNotFound\n [10106, 'terminal'], // Unauthorized\n [10107, 'terminal'], // QueueIDMalformed\n [10201, 'transient'], // ClientDisconnected\n [10202, 'terminal'], // BatchDelayInvalid\n [10203, 'terminal'], // MessageMetadataInvalid\n [10204, 'terminal'], // MessageSizeOutOfBounds\n [10205, 'terminal'], // BatchSizeOutOfBounds\n [10206, 'terminal'], // BatchCountOutOfBounds\n [10207, 'terminal'], // JSONRequestBodyInvalid\n [10208, 'terminal'], // JSONRequestBodyMalformed\n [10250, 'transient'], // QueueOverloaded\n [10251, 'transient'], // QueueStorageLimitExceeded\n [10252, 'terminal'], // QueueDisabled\n [10253, 'terminal'], // FreeTierLimitExceeded\n [15000, 'unknown'], // UnknownInternalError\n])\n\nfunction extractQueueErrorCode(cause: unknown): number | undefined {\n if (!(cause instanceof Error)) return undefined\n const match = /(\\d{5})\\)?\\s*$/.exec(cause.message)\n return match?.[1] === undefined ? undefined : Number(match[1])\n}\n\nfunction classifyQueueBoundaryError(cause: unknown): FailureClassification | undefined {\n const code = extractQueueErrorCode(cause)\n return code === undefined ? undefined : QUEUE_ERROR_CLASSIFICATIONS.get(code)\n}\n\n/** Classify a raw Queue binding failure: the code table first, then Cloudflare's signals, then transport. */\nexport function classifyQueueError(cause: unknown): FailureClassification {\n return classifyBoundaryError({\n cause,\n classifyBoundary: classifyQueueBoundaryError,\n includeCloudflare: true,\n })\n}\n\n/** A send through a Queue binding failed. The classification says whether an immediate retry may help. */\nexport class QueueSendError extends AppError {\n readonly _tag = 'QueueSendError'\n readonly classification: FailureClassification\n readonly operation: QueueOperation\n\n constructor(args: { readonly operation: QueueOperation; readonly cause: unknown }) {\n super(QUEUE_OPERATION_MESSAGES[args.operation], { cause: args.cause })\n this.classification = classifyQueueError(args.cause)\n this.operation = args.operation\n }\n}\n\n/**\n * A message over the per-message cap can never be sent on any queue; the dead letter has the\n * same cap. The client detects it before the send, so it never comes from a platform error.\n */\nexport class OversizedMessageError extends AppError {\n readonly _tag = 'OversizedMessageError'\n readonly classification = 'terminal'\n readonly messageName: string\n readonly bytes: number\n readonly limit: number\n\n constructor(args: {\n readonly messageName: string\n readonly bytes: number\n readonly limit: number\n }) {\n super(\n `Queue message \"${args.messageName}\" is ${String(args.bytes)} bytes, over the ${String(args.limit)} limit`,\n )\n this.messageName = args.messageName\n this.bytes = args.bytes\n this.limit = args.limit\n }\n}\n\n/**\n * The dead letter did not accept an unparseable message. Always transient, whatever the send\n * failure was, so the source delivery retries instead of acknowledging and losing the body.\n */\nexport class DeadLetterUnavailableError extends AppError {\n readonly _tag = 'DeadLetterUnavailableError'\n readonly classification = 'transient'\n\n constructor(cause: unknown) {\n super('The dead letter did not accept the message', { cause })\n }\n}\n","import { Result } from 'better-result'\n\nimport { createLogger, shouldRetryFailure } from '@/core'\n\nimport {\n chunkByLimits,\n isOversized,\n messageByteLength,\n QUEUE_LIMITS,\n sizeMessages,\n type SizedMessage,\n} from './queue-limits.ts'\nimport type { QueueMessage } from './queue-message.ts'\nimport { OversizedMessageError, QueueSendError, type QueueOperation } from './queue.errors.ts'\n\n/** Cloudflare's delivery delay, in seconds. */\nexport type QueueSendOptions = { readonly delaySeconds: number }\n\n/** The two calls the client makes on a queue binding. */\nexport type QueueBinding<Body> = Pick<Queue<Body>, 'send' | 'sendBatch'>\n\n/**\n * The lanes and the dead letter of one application. A lane is a queue with its own consumer\n * settings; `laneOf` is the product's routing rule, written once at the composition root.\n */\nexport type QueueClientOptions<TMessage extends QueueMessage, Lane extends string> = {\n readonly queues: Readonly<Record<Lane, QueueBinding<TMessage>>>\n /** Where the consumer parks poison bodies. Cloudflare also routes exhausted retries here. */\n readonly deadLetter: Pick<Queue, 'send'>\n readonly laneOf: (message: TMessage) => Lane\n}\n\n/** The port an entrypoint, a relay, or a consumer sends through. */\nexport interface IQueueClient<TMessage extends QueueMessage> {\n send(message: TMessage, options?: QueueSendOptions): Promise<void>\n sendBatch(messages: ReadonlyArray<TMessage>): Promise<void>\n /** Sends every message within the limits and returns the oversized ones. */\n sendBatchPartial<Sent extends TMessage>(\n messages: ReadonlyArray<Sent>,\n ): Promise<ReadonlyArray<Sent>>\n /** Parks a delivered message's body as it arrived. */\n sendToDlq(message: Message): Promise<void>\n}\n\nconst logger = createLogger('queue-client')\n\n/** Immediate retries of one binding call: three attempts, 250 ms then 500 ms, with jitter. */\nconst RETRY_TIMES = 2\nconst RETRY_BASE_DELAY_MS = 250\n\n/** Every send is safe to repeat, so a transient failure gets an immediate retry; terminal and unknown stop. */\nfunction shouldRetrySend(error: QueueSendError): boolean {\n return shouldRetryFailure({\n classification: error.classification,\n repeatSafe: true,\n owner: 'immediate',\n })\n}\n\nfunction oversizedError(sized: SizedMessage<QueueMessage>): OversizedMessageError {\n return new OversizedMessageError({\n messageName: sized.message.name,\n bytes: sized.bytes,\n limit: QUEUE_LIMITS.messageBytes,\n })\n}\n\n/**\n * Sends messages to the application's queues. Checks the size limits before a send, retries a\n * transient binding failure a bounded number of times, and converts the final failure to `QueueSendError`.\n */\nexport class QueueClient<\n TMessage extends QueueMessage,\n Lane extends string,\n> implements IQueueClient<TMessage> {\n constructor(private readonly options: QueueClientOptions<TMessage, Lane>) {}\n\n /** @throws OversizedMessageError before the send. @throws QueueSendError after the retries. */\n async send(message: TMessage, options?: QueueSendOptions): Promise<void> {\n const sized = { message, bytes: messageByteLength(message) }\n if (isOversized(sized)) {\n logger.warn('queue_message_oversized', {\n name: message.name,\n type: message.type,\n bytes: sized.bytes,\n })\n throw oversizedError(sized)\n }\n\n const queue = this.queueFor(message)\n logger.debug('sending_message', {\n name: message.name,\n type: message.type,\n delaySeconds: options?.delaySeconds,\n })\n\n await this.callQueue('send', async () => {\n if (options) {\n await queue.send(message, options)\n } else {\n await queue.send(message)\n }\n })\n }\n\n /** Rejects the whole batch before any send when one message is oversized. */\n async sendBatch(messages: ReadonlyArray<TMessage>): Promise<void> {\n const sized = sizeMessages(messages)\n const oversized = sized.find(isOversized)\n if (oversized) throw oversizedError(oversized)\n await this.sendSizedBatch(sized)\n }\n\n async sendBatchPartial<Sent extends TMessage>(\n messages: ReadonlyArray<Sent>,\n ): Promise<ReadonlyArray<Sent>> {\n const sized = sizeMessages(messages)\n await this.sendSizedBatch(sized.filter((item) => !isOversized(item)))\n return sized.filter(isOversized).map((item) => item.message)\n }\n\n async sendToDlq(message: Message): Promise<void> {\n logger.debug('sending_to_dlq', { queueMessageId: message.id })\n await this.callQueue('send_dlq', async () => {\n await this.options.deadLetter.send(message.body)\n })\n }\n\n /** Each lane's chunks retry on their own, so one failed chunk does not resend the others. */\n private async sendSizedBatch(sized: ReadonlyArray<SizedMessage<TMessage>>): Promise<void> {\n const byLane = new Map<Lane, SizedMessage<TMessage>[]>()\n for (const item of sized) {\n const lane = this.options.laneOf(item.message)\n const items = byLane.get(lane) ?? []\n items.push(item)\n byLane.set(lane, items)\n }\n\n logger.debug('sending_batch', {\n count: sized.length,\n lanes: [...byLane].map(([lane, items]) => ({ lane, count: items.length })),\n })\n\n const sends: Promise<void>[] = []\n for (const [lane, items] of byLane) {\n const queue = this.options.queues[lane]\n for (const group of chunkByLimits(items)) {\n sends.push(\n this.callQueue('send_batch', async () => {\n await queue.sendBatch(group.map((body) => ({ body })))\n }),\n )\n }\n }\n await Promise.all(sends)\n }\n\n private queueFor(message: TMessage): QueueBinding<TMessage> {\n return this.options.queues[this.options.laneOf(message)]\n }\n\n private async callQueue<T>(operation: QueueOperation, call: () => Promise<T>): Promise<T> {\n const result = await Result.tryPromise(\n {\n try: call,\n catch: (cause) => new QueueSendError({ operation, cause }),\n },\n {\n retry: {\n times: RETRY_TIMES,\n delayMs: RETRY_BASE_DELAY_MS,\n backoff: 'exponential',\n jitter: true,\n shouldRetry: shouldRetrySend,\n },\n },\n )\n if (result.isErr()) throw result.error\n return result.value\n }\n}\n","import {\n classifyFailure,\n exponentialEqualJitterMs,\n retryAfterSecondsOf,\n shouldRetryFailure,\n spreadJitterMs,\n type FailureClassification,\n} from '@/core'\n\nconst BASE_RETRY_DELAY_MS = 5_000\nconst MAX_RETRY_DELAY_MS = 120_000\nconst RETRY_AFTER_SPREAD_MS = 5_000\n/** Cloudflare Queues accept a redelivery delay of at most one day. */\nconst MAX_QUEUE_DELAY_SECONDS = 24 * 60 * 60\n\n/** How the consumer settles one failed message: acknowledge it, or have Cloudflare redeliver it after a delay. */\nexport type RedeliveryDecision =\n | { readonly action: 'ack'; readonly classification: 'terminal' }\n | {\n readonly action: 'retry'\n readonly classification: Exclude<FailureClassification, 'terminal'>\n readonly delaySeconds: number\n }\n\n/**\n * Decide whether the consumer acknowledges a failed message or asks Cloudflare to redeliver it.\n * A terminal failure acknowledges. Transient and unknown failures redeliver: after the advertised\n * wait plus a spread when the error carries one, else with exponential equal-jitter backoff.\n * An `AggregateError` from event delivery redelivers when any member does, after the longest wait.\n */\nexport function decideRedelivery(cause: unknown, attempt: number): RedeliveryDecision {\n if (cause instanceof AggregateError && cause.errors.length > 0) {\n const decisions = cause.errors.map((member) => decideRedelivery(member, attempt))\n const retries = decisions.filter((decision) => decision.action === 'retry')\n if (retries.length === 0) return { action: 'ack', classification: 'terminal' }\n\n // Redelivery must respect every failed subscriber's required wait.\n return {\n action: 'retry',\n classification: retries.some((decision) => decision.classification === 'unknown')\n ? 'unknown'\n : 'transient',\n delaySeconds: Math.max(...retries.map((decision) => decision.delaySeconds)),\n }\n }\n\n const classification = classifyFailure(cause)\n if (classification === 'terminal') return { action: 'ack', classification }\n\n const canRetry = shouldRetryFailure({ classification, repeatSafe: true, owner: 'durable' })\n if (!canRetry) return { action: 'ack', classification: 'terminal' }\n\n const retryAfterSeconds = retryAfterSecondsOf(cause)\n const delayMs =\n retryAfterSeconds === null\n ? exponentialEqualJitterMs(BASE_RETRY_DELAY_MS, MAX_RETRY_DELAY_MS, attempt)\n : retryAfterSeconds * 1_000 + spreadJitterMs(RETRY_AFTER_SPREAD_MS)\n\n return {\n action: 'retry',\n classification,\n delaySeconds: Math.min(MAX_QUEUE_DELAY_SECONDS, Math.max(1, Math.ceil(delayMs / 1_000))),\n }\n}\n","import type { z } from 'zod'\n\nimport { MessageAlreadyProcessedError } from '@/application'\nimport { createLogger } from '@/core'\n\nimport type { IQueueClient } from './queue-client.ts'\nimport type { QueueMessage } from './queue-message.ts'\nimport { DeadLetterUnavailableError } from './queue.errors.ts'\nimport { decideRedelivery } from './redelivery-policy.ts'\n\nconst logger = createLogger('queue-consumer')\n\n/** Wraps one dispatch: an error-tracking scope, an analytics context. The default runs it as is. */\nexport type DispatchWrapper<TMessage extends QueueMessage> = (\n message: TMessage,\n attempt: number,\n run: () => Promise<void>,\n) => Promise<void>\n\n/** The one call the consumer makes on the bus. */\nexport type DispatchBus<TMessage extends QueueMessage> = {\n // oxlint-disable-next-line anti-slop/no-unknown-returns -- the bus resolves to each handler's own value; the consumer discards it.\n handle(message: TMessage): Promise<unknown>\n}\n\n/**\n * Parses and dispatches each queue message, then selects acknowledgement or retry.\n * Cloudflare owns the retry limit and sends exhausted messages to the configured dead letter.\n * The consumer logs each failure once; handlers do not.\n */\nexport class QueueConsumer<TMessage extends QueueMessage> {\n /**\n * @param bus - Where a parsed message goes.\n * @param queueClient - Parks an unparseable body in the dead letter.\n * @param schema - What a body may be: the application's `messages.queueSchema`.\n * @param wrapDispatch - Wraps one dispatch in the application's context. Default: run it as is.\n */\n constructor(\n private readonly bus: DispatchBus<TMessage>,\n private readonly queueClient: Pick<IQueueClient<TMessage>, 'sendToDlq'>,\n private readonly schema: z.ZodType<TMessage>,\n private readonly wrapDispatch: DispatchWrapper<TMessage> = (_message, _attempt, run) => run(),\n ) {}\n\n /** Every message settles on its own. A settlement that throws rejects the batch after its siblings settle. */\n async processBatch(batch: MessageBatch): Promise<void> {\n logger.debug('queue_batch_received', { count: batch.messages.length })\n const results = await Promise.allSettled(\n batch.messages.map((message) => this.processMessage(message)),\n )\n const rejected = results\n .filter((result) => result.status === 'rejected')\n .map((result) => result.reason)\n\n if (rejected.length > 0) {\n throw new AggregateError(rejected, 'Queue message settlement failed')\n }\n }\n\n private async processMessage(message: Message): Promise<void> {\n let parsed: TMessage | null = null\n\n try {\n const body = await this.parseMessage(message)\n if (body === null) {\n // An unparseable body cannot succeed on retry, so park it for inspection.\n logger.error('invalid_message_format', {\n details: { attempt: message.attempts, queueMessageId: message.id },\n })\n await this.parkPoison(message)\n return\n }\n parsed = body\n\n await this.wrapDispatch(body, message.attempts, async () => {\n await this.bus.handle(body)\n })\n message.ack()\n logger.debug(`queue_message_processed:${body.name}`, { name: body.name })\n } catch (cause) {\n this.handleFailure(message, parsed, cause)\n }\n }\n\n /** Returns null on failure; the caller owns the single log point. */\n private async parseMessage(message: Message): Promise<TMessage | null> {\n const result = await this.schema.safeParseAsync(message.body)\n return result.success ? result.data : null\n }\n\n /** Park an unparseable message in the dead letter, then acknowledge its source delivery. */\n private async parkPoison(message: Message): Promise<void> {\n try {\n await this.queueClient.sendToDlq(message)\n message.ack()\n } catch (cause) {\n throw new DeadLetterUnavailableError(cause)\n }\n }\n\n /**\n * Retry declared transient and unknown failures so Cloudflare can enforce the attempt ceiling.\n * Acknowledge only declared terminal failures.\n */\n private handleFailure(message: Message, parsed: TMessage | null, cause: unknown): void {\n if (cause instanceof MessageAlreadyProcessedError) {\n logger.debug('duplicate_skipped', {\n name: parsed?.name,\n messageId: cause.messageId,\n attempt: message.attempts,\n })\n message.ack()\n return\n }\n\n const decision = decideRedelivery(cause, message.attempts)\n if (decision.action === 'ack') {\n logger.error('message_discarded', {\n error: cause,\n details: {\n name: parsed?.name,\n messageId: parsed?.id,\n queueMessageId: message.id,\n attempt: message.attempts,\n },\n })\n message.ack()\n return\n }\n\n const context = {\n name: parsed?.name,\n messageId: parsed?.id,\n queueMessageId: message.id,\n attempt: message.attempts,\n classification: decision.classification,\n delaySeconds: decision.delaySeconds,\n }\n if (decision.classification === 'unknown' && message.attempts === 1) {\n logger.error('queue_unknown_failure', { error: cause, details: context })\n } else {\n logger.debug('redelivery_requested', context)\n }\n message.retry({ delaySeconds: decision.delaySeconds })\n }\n}\n","import type { IOutboxRelay, OutboxRelay } from '@/application'\nimport { createLogger } from '@/core'\n\nconst logger = createLogger('outbox-wake')\n\n/** Register delivery after commit; log a failed drain once and leave recovery to the scheduled sweep. */\nexport function waitUntilWake(\n context: Pick<ExecutionContext, 'waitUntil'>,\n relay: Pick<OutboxRelay, 'drain'>,\n): IOutboxRelay {\n return {\n wake: () =>\n context.waitUntil(\n relay.drain().catch((cause: unknown) => {\n logger.error('outbox_wake_failed', { error: cause })\n }),\n ),\n }\n}\n"],"mappings":";;;;;;;;;;AAOA,MAAa,eAAe;CAC1B,cAAc;CACd,YAAY;CACZ,YAAY;AACd;;AAGA,SAAgB,kBAAkB,SAA+B;CAC/D,OAAO,IAAI,YAAY,CAAC,CAAC,OAAO,KAAK,UAAU,OAAO,CAAC,CAAC,CAAC;AAC3D;;AAMA,SAAgB,aACd,UAC0B;CAC1B,OAAO,SAAS,KAAK,aAAa;EAAE;EAAS,OAAO,kBAAkB,OAAO;CAAE,EAAE;AACnF;;AAGA,SAAgB,YAAY,OAA4C;CACtE,OAAO,MAAM,QAAQ,aAAa;AACpC;;AAGA,SAAgB,cACd,OACc;CACd,MAAM,SAAuB,CAAC;CAC9B,IAAI,UAAsB,CAAC;CAC3B,IAAI,QAAQ;CACZ,KAAK,MAAM,QAAQ,OAAO;EACxB,MAAM,OACJ,QAAQ,UAAU,aAAa,cAAc,QAAQ,KAAK,QAAQ,aAAa;EACjF,IAAI,QAAQ,SAAS,KAAK,MAAM;GAC9B,OAAO,KAAK,OAAO;GACnB,UAAU,CAAC;GACX,QAAQ;EACV;EACA,QAAQ,KAAK,KAAK,OAAO;EACzB,SAAS,KAAK;CAChB;CACA,IAAI,QAAQ,SAAS,GAAG,OAAO,KAAK,OAAO;CAC3C,OAAO;AACT;;;;AChDA,MAAM,2BAA2B;CAC/B,MAAM;CACN,YAAY;CACZ,UAAU;AACZ;;;;;;AAOA,MAAM,8CAA8B,IAAI,IAAmC;CACzE,CAAC,OAAO,UAAU;CAClB,CAAC,OAAO,UAAU;CAClB,CA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F"}
|
|
1
|
+
{"version":3,"file":"queue.js","names":["logger","logger"],"sources":["../../src/infrastructure/cloudflare/queue/queue-limits.ts","../../src/infrastructure/cloudflare/queue/queue.errors.ts","../../src/infrastructure/cloudflare/queue/queue-client.ts","../../src/infrastructure/cloudflare/queue/redelivery-policy.ts","../../src/infrastructure/cloudflare/queue/queue-consumer.ts","../../src/infrastructure/cloudflare/queue/wait-until-wake.ts"],"sourcesContent":["import type { QueueMessage } from './queue-message.ts'\n\n/**\n * The Cloudflare Queues producer limits with metadata headroom, checked before each send so a\n * violation never reaches the binding. The dead letter has the same per-message limit.\n * https://developers.cloudflare.com/queues/platform/limits/\n */\nexport const QUEUE_LIMITS = {\n messageBytes: 127_000,\n batchBytes: 250_000,\n batchCount: 100,\n} as const\n\n/** The size the binding measures: the JSON encoding of the body, in UTF-8 bytes. */\nexport function messageByteLength(message: QueueMessage): number {\n return new TextEncoder().encode(JSON.stringify(message)).length\n}\n\n/** A message with its measured size. */\nexport type SizedMessage<TMessage> = { readonly message: TMessage; readonly bytes: number }\n\n/** Measure every message once. */\nexport function sizeMessages<TMessage extends QueueMessage>(\n messages: ReadonlyArray<TMessage>,\n): SizedMessage<TMessage>[] {\n return messages.map((message) => ({ message, bytes: messageByteLength(message) }))\n}\n\n/** Whether one message is over the per-message limit. */\nexport function isOversized(sized: SizedMessage<QueueMessage>): boolean {\n return sized.bytes > QUEUE_LIMITS.messageBytes\n}\n\n/** Split a batch at the message-count and byte limits, keeping the order. */\nexport function chunkByLimits<TMessage>(\n sized: ReadonlyArray<SizedMessage<TMessage>>,\n): TMessage[][] {\n const chunks: TMessage[][] = []\n let current: TMessage[] = []\n let bytes = 0\n for (const item of sized) {\n const full =\n current.length >= QUEUE_LIMITS.batchCount || bytes + item.bytes > QUEUE_LIMITS.batchBytes\n if (current.length > 0 && full) {\n chunks.push(current)\n current = []\n bytes = 0\n }\n current.push(item.message)\n bytes += item.bytes\n }\n if (current.length > 0) chunks.push(current)\n return chunks\n}\n","import { AppError, classifyBoundaryError, type FailureClassification } from '@/core'\n\n/** The Queue binding calls the client makes. Each is safe to repeat. */\nexport type QueueOperation = 'send' | 'send_batch' | 'send_dlq'\n\nconst QUEUE_OPERATION_MESSAGES = {\n send: 'Failed to send queue message',\n send_batch: 'Failed to send queue batch',\n send_dlq: 'Failed to send DLQ message',\n} satisfies Readonly<Record<QueueOperation, string>>\n\n/**\n * Cloudflare Queues error codes, by whether a repeat could change the answer. The reference\n * marks only 10201 and 10250 for retry; 10251 waits for processing, 15000 is nobody's call.\n * https://developers.cloudflare.com/queues/reference/error-codes/\n */\nconst QUEUE_ERROR_CLASSIFICATIONS = new Map<number, FailureClassification>([\n [10104, 'terminal'], // QueueNotFound\n [10106, 'terminal'], // Unauthorized\n [10107, 'terminal'], // QueueIDMalformed\n [10201, 'transient'], // ClientDisconnected\n [10202, 'terminal'], // BatchDelayInvalid\n [10203, 'terminal'], // MessageMetadataInvalid\n [10204, 'terminal'], // MessageSizeOutOfBounds\n [10205, 'terminal'], // BatchSizeOutOfBounds\n [10206, 'terminal'], // BatchCountOutOfBounds\n [10207, 'terminal'], // JSONRequestBodyInvalid\n [10208, 'terminal'], // JSONRequestBodyMalformed\n [10250, 'transient'], // QueueOverloaded\n [10251, 'transient'], // QueueStorageLimitExceeded\n [10252, 'terminal'], // QueueDisabled\n [10253, 'terminal'], // FreeTierLimitExceeded\n [15000, 'unknown'], // UnknownInternalError\n])\n\nfunction extractQueueErrorCode(cause: unknown): number | undefined {\n if (!(cause instanceof Error)) return undefined\n const match = /(\\d{5})\\)?\\s*$/.exec(cause.message)\n return match?.[1] === undefined ? undefined : Number(match[1])\n}\n\nfunction classifyQueueBoundaryError(cause: unknown): FailureClassification | undefined {\n const code = extractQueueErrorCode(cause)\n return code === undefined ? undefined : QUEUE_ERROR_CLASSIFICATIONS.get(code)\n}\n\n/** Classify a raw Queue binding failure: the code table first, then Cloudflare's signals, then transport. */\nexport function classifyQueueError(cause: unknown): FailureClassification {\n return classifyBoundaryError({\n cause,\n classifyBoundary: classifyQueueBoundaryError,\n includeCloudflare: true,\n })\n}\n\n/** A send through a Queue binding failed. The classification says whether an immediate retry may help. */\nexport class QueueSendError extends AppError {\n readonly _tag = 'QueueSendError'\n readonly classification: FailureClassification\n readonly operation: QueueOperation\n\n constructor(args: { readonly operation: QueueOperation; readonly cause: unknown }) {\n super(QUEUE_OPERATION_MESSAGES[args.operation], { cause: args.cause })\n this.classification = classifyQueueError(args.cause)\n this.operation = args.operation\n }\n}\n\n/**\n * A message over the per-message cap can never be sent on any queue; the dead letter has the\n * same cap. The client detects it before the send, so it never comes from a platform error.\n */\nexport class OversizedMessageError extends AppError {\n readonly _tag = 'OversizedMessageError'\n readonly classification = 'terminal'\n readonly messageName: string\n readonly bytes: number\n readonly limit: number\n\n constructor(args: {\n readonly messageName: string\n readonly bytes: number\n readonly limit: number\n }) {\n super(\n `Queue message \"${args.messageName}\" is ${String(args.bytes)} bytes, over the ${String(args.limit)} limit`,\n )\n this.messageName = args.messageName\n this.bytes = args.bytes\n this.limit = args.limit\n }\n}\n\n/**\n * The dead letter did not accept an unparseable message. Always transient, whatever the send\n * failure was, so the source delivery retries instead of acknowledging and losing the body.\n */\nexport class DeadLetterUnavailableError extends AppError {\n readonly _tag = 'DeadLetterUnavailableError'\n readonly classification = 'transient'\n\n constructor(cause: unknown) {\n super('The dead letter did not accept the message', { cause })\n }\n}\n","import { Result } from 'better-result'\n\nimport { createLogger, shouldRetryFailure } from '@/core'\n\nimport {\n chunkByLimits,\n isOversized,\n messageByteLength,\n QUEUE_LIMITS,\n sizeMessages,\n type SizedMessage,\n} from './queue-limits.ts'\nimport type { QueueMessage } from './queue-message.ts'\nimport { OversizedMessageError, QueueSendError, type QueueOperation } from './queue.errors.ts'\n\n/** Cloudflare's delivery delay, in seconds. */\nexport type QueueSendOptions = { readonly delaySeconds: number }\n\n/** The two calls the client makes on a queue binding. */\nexport type QueueBinding<Body> = Pick<Queue<Body>, 'send' | 'sendBatch'>\n\n/**\n * The lanes and the dead letter of one application. A lane is a queue with its own consumer\n * settings; `laneOf` is the product's routing rule, written once at the composition root.\n */\nexport type QueueClientOptions<TMessage extends QueueMessage, Lane extends string> = {\n readonly queues: Readonly<Record<Lane, QueueBinding<TMessage>>>\n /** Where the consumer parks poison bodies. Cloudflare also routes exhausted retries here. */\n readonly deadLetter: Pick<Queue, 'send'>\n readonly laneOf: (message: TMessage) => Lane\n}\n\n/** The port an entrypoint, a relay, or a consumer sends through. */\nexport interface IQueueClient<TMessage extends QueueMessage> {\n send(message: TMessage, options?: QueueSendOptions): Promise<void>\n sendBatch(messages: ReadonlyArray<TMessage>): Promise<void>\n /** Sends every message within the limits and returns the oversized ones. */\n sendBatchPartial<Sent extends TMessage>(\n messages: ReadonlyArray<Sent>,\n ): Promise<ReadonlyArray<Sent>>\n /** Parks a delivered message's body as it arrived. */\n sendToDlq(message: Message): Promise<void>\n}\n\nconst logger = createLogger('queue-client')\n\n/** Immediate retries of one binding call: three attempts, 250 ms then 500 ms, with jitter. */\nconst RETRY_TIMES = 2\nconst RETRY_BASE_DELAY_MS = 250\n\n/** Every send is safe to repeat, so a transient failure gets an immediate retry; terminal and unknown stop. */\nfunction shouldRetrySend(error: QueueSendError): boolean {\n return shouldRetryFailure({\n classification: error.classification,\n repeatSafe: true,\n owner: 'immediate',\n })\n}\n\nfunction oversizedError(sized: SizedMessage<QueueMessage>): OversizedMessageError {\n return new OversizedMessageError({\n messageName: sized.message.name,\n bytes: sized.bytes,\n limit: QUEUE_LIMITS.messageBytes,\n })\n}\n\n/**\n * Sends messages to the application's queues. Checks the size limits before a send, retries a\n * transient binding failure a bounded number of times, and converts the final failure to `QueueSendError`.\n */\nexport class QueueClient<\n TMessage extends QueueMessage,\n Lane extends string,\n> implements IQueueClient<TMessage> {\n constructor(private readonly options: QueueClientOptions<TMessage, Lane>) {}\n\n /** @throws OversizedMessageError before the send. @throws QueueSendError after the retries. */\n async send(message: TMessage, options?: QueueSendOptions): Promise<void> {\n const sized = { message, bytes: messageByteLength(message) }\n if (isOversized(sized)) {\n logger.warn('queue_message_oversized', {\n name: message.name,\n type: message.type,\n bytes: sized.bytes,\n })\n throw oversizedError(sized)\n }\n\n const queue = this.queueFor(message)\n logger.debug('sending_message', {\n name: message.name,\n type: message.type,\n delaySeconds: options?.delaySeconds,\n })\n\n await this.callQueue('send', async () => {\n if (options) {\n await queue.send(message, options)\n } else {\n await queue.send(message)\n }\n })\n }\n\n /** Rejects the whole batch before any send when one message is oversized. */\n async sendBatch(messages: ReadonlyArray<TMessage>): Promise<void> {\n const sized = sizeMessages(messages)\n const oversized = sized.find(isOversized)\n if (oversized) throw oversizedError(oversized)\n await this.sendSizedBatch(sized)\n }\n\n async sendBatchPartial<Sent extends TMessage>(\n messages: ReadonlyArray<Sent>,\n ): Promise<ReadonlyArray<Sent>> {\n const sized = sizeMessages(messages)\n await this.sendSizedBatch(sized.filter((item) => !isOversized(item)))\n return sized.filter(isOversized).map((item) => item.message)\n }\n\n async sendToDlq(message: Message): Promise<void> {\n logger.debug('sending_to_dlq', { queueMessageId: message.id })\n await this.callQueue('send_dlq', async () => {\n await this.options.deadLetter.send(message.body)\n })\n }\n\n /** Each lane's chunks retry on their own, so one failed chunk does not resend the others. */\n private async sendSizedBatch(sized: ReadonlyArray<SizedMessage<TMessage>>): Promise<void> {\n const byLane = new Map<Lane, SizedMessage<TMessage>[]>()\n for (const item of sized) {\n const lane = this.options.laneOf(item.message)\n const items = byLane.get(lane) ?? []\n items.push(item)\n byLane.set(lane, items)\n }\n\n logger.debug('sending_batch', {\n count: sized.length,\n lanes: [...byLane].map(([lane, items]) => ({ lane, count: items.length })),\n })\n\n const sends: Promise<void>[] = []\n for (const [lane, items] of byLane) {\n const queue = this.options.queues[lane]\n for (const group of chunkByLimits(items)) {\n sends.push(\n this.callQueue('send_batch', async () => {\n await queue.sendBatch(group.map((body) => ({ body })))\n }),\n )\n }\n }\n await Promise.all(sends)\n }\n\n private queueFor(message: TMessage): QueueBinding<TMessage> {\n return this.options.queues[this.options.laneOf(message)]\n }\n\n private async callQueue<T>(operation: QueueOperation, call: () => Promise<T>): Promise<T> {\n const result = await Result.tryPromise(\n {\n try: call,\n catch: (cause) => new QueueSendError({ operation, cause }),\n },\n {\n retry: {\n times: RETRY_TIMES,\n delayMs: RETRY_BASE_DELAY_MS,\n backoff: 'exponential',\n jitter: true,\n shouldRetry: shouldRetrySend,\n },\n },\n )\n if (result.isErr()) throw result.error\n return result.value\n }\n}\n","import {\n classifyFailure,\n exponentialEqualJitterMs,\n retryAfterSecondsOf,\n shouldRetryFailure,\n spreadJitterMs,\n type FailureClassification,\n} from '@/core'\n\nconst BASE_RETRY_DELAY_MS = 5_000\nconst MAX_RETRY_DELAY_MS = 120_000\nconst RETRY_AFTER_SPREAD_MS = 5_000\n/** Cloudflare Queues accept a redelivery delay of at most one day. */\nconst MAX_QUEUE_DELAY_SECONDS = 24 * 60 * 60\n\n/** How the consumer settles one failed message: acknowledge it, or have Cloudflare redeliver it after a delay. */\nexport type RedeliveryDecision =\n | { readonly action: 'ack'; readonly classification: 'terminal' }\n | {\n readonly action: 'retry'\n readonly classification: Exclude<FailureClassification, 'terminal'>\n readonly delaySeconds: number\n }\n\n/**\n * Decide whether the consumer acknowledges a failed message or asks Cloudflare to redeliver it.\n * A terminal failure acknowledges. Transient and unknown failures redeliver: after the advertised\n * wait plus a spread when the error carries one, else with exponential equal-jitter backoff.\n * An `AggregateError` from event delivery redelivers when any member does, after the longest wait.\n */\nexport function decideRedelivery(cause: unknown, attempt: number): RedeliveryDecision {\n if (cause instanceof AggregateError && cause.errors.length > 0) {\n const decisions = cause.errors.map((member) => decideRedelivery(member, attempt))\n const retries = decisions.filter((decision) => decision.action === 'retry')\n if (retries.length === 0) return { action: 'ack', classification: 'terminal' }\n\n // Redelivery must respect every failed subscriber's required wait.\n return {\n action: 'retry',\n classification: retries.some((decision) => decision.classification === 'unknown')\n ? 'unknown'\n : 'transient',\n delaySeconds: Math.max(...retries.map((decision) => decision.delaySeconds)),\n }\n }\n\n const classification = classifyFailure(cause)\n if (classification === 'terminal') return { action: 'ack', classification }\n\n const canRetry = shouldRetryFailure({ classification, repeatSafe: true, owner: 'durable' })\n if (!canRetry) return { action: 'ack', classification: 'terminal' }\n\n const retryAfterSeconds = retryAfterSecondsOf(cause)\n const delayMs =\n retryAfterSeconds === null\n ? exponentialEqualJitterMs(BASE_RETRY_DELAY_MS, MAX_RETRY_DELAY_MS, attempt)\n : retryAfterSeconds * 1_000 + spreadJitterMs(RETRY_AFTER_SPREAD_MS)\n\n return {\n action: 'retry',\n classification,\n delaySeconds: Math.min(MAX_QUEUE_DELAY_SECONDS, Math.max(1, Math.ceil(delayMs / 1_000))),\n }\n}\n","import type { z } from 'zod'\n\nimport { MessageAlreadyProcessedError } from '@/application'\nimport { createLogger } from '@/core'\n\nimport type { IQueueClient } from './queue-client.ts'\nimport type { QueueMessage } from './queue-message.ts'\nimport { DeadLetterUnavailableError } from './queue.errors.ts'\nimport { decideRedelivery } from './redelivery-policy.ts'\n\nconst logger = createLogger('queue-consumer')\n\n/** Wraps one dispatch: an error-tracking scope, an analytics context. The default runs it as is. */\nexport type DispatchWrapper<TMessage extends QueueMessage> = (\n message: TMessage,\n attempt: number,\n run: () => Promise<void>,\n) => Promise<void>\n\n/** The one call the consumer makes on the bus. */\nexport type DispatchBus<TMessage extends QueueMessage> = {\n // oxlint-disable-next-line anti-slop/no-unknown-returns -- the bus resolves to each handler's own value; the consumer discards it.\n handle(message: TMessage): Promise<unknown>\n}\n\n/**\n * Parses and dispatches each queue message, then selects acknowledgement or retry.\n * Cloudflare owns the retry limit and sends exhausted messages to the configured dead letter.\n * The consumer logs each failure once; handlers do not.\n */\nexport class QueueConsumer<TMessage extends QueueMessage> {\n /**\n * @param bus - Where a parsed message goes.\n * @param queueClient - Parks an unparseable body in the dead letter.\n * @param schema - What a body may be: the application's `messages.queueSchema`.\n * @param wrapDispatch - Wraps one dispatch in the application's context. Default: run it as is.\n */\n constructor(\n private readonly bus: DispatchBus<TMessage>,\n private readonly queueClient: Pick<IQueueClient<TMessage>, 'sendToDlq'>,\n private readonly schema: z.ZodType<TMessage>,\n private readonly wrapDispatch: DispatchWrapper<TMessage> = (_message, _attempt, run) => run(),\n ) {}\n\n /** Every message settles on its own. A settlement that throws rejects the batch after its siblings settle. */\n async processBatch(batch: MessageBatch): Promise<void> {\n logger.debug('queue_batch_received', { count: batch.messages.length })\n const results = await Promise.allSettled(\n batch.messages.map((message) => this.processMessage(message)),\n )\n const rejected = results\n .filter((result) => result.status === 'rejected')\n .map((result) => result.reason)\n\n if (rejected.length > 0) {\n throw new AggregateError(rejected, 'Queue message settlement failed')\n }\n }\n\n private async processMessage(message: Message): Promise<void> {\n let parsed: TMessage | null = null\n\n try {\n const body = await this.parseMessage(message)\n if (body === null) {\n // An unparseable body cannot succeed on retry, so park it for inspection.\n logger.error('invalid_message_format', {\n attempt: message.attempts,\n queueMessageId: message.id,\n })\n await this.parkPoison(message)\n return\n }\n parsed = body\n\n await this.wrapDispatch(body, message.attempts, async () => {\n await this.bus.handle(body)\n })\n message.ack()\n logger.debug('queue_message_processed', { name: body.name })\n } catch (cause) {\n this.handleFailure(message, parsed, cause)\n }\n }\n\n /** Returns null on failure; the caller owns the single log point. */\n private async parseMessage(message: Message): Promise<TMessage | null> {\n const result = await this.schema.safeParseAsync(message.body)\n return result.success ? result.data : null\n }\n\n /** Park an unparseable message in the dead letter, then acknowledge its source delivery. */\n private async parkPoison(message: Message): Promise<void> {\n try {\n await this.queueClient.sendToDlq(message)\n message.ack()\n } catch (cause) {\n throw new DeadLetterUnavailableError(cause)\n }\n }\n\n /**\n * Retry declared transient and unknown failures so Cloudflare can enforce the attempt ceiling.\n * Acknowledge only declared terminal failures.\n */\n private handleFailure(message: Message, parsed: TMessage | null, cause: unknown): void {\n if (cause instanceof MessageAlreadyProcessedError) {\n logger.debug('duplicate_skipped', {\n name: parsed?.name,\n messageId: cause.messageId,\n attempt: message.attempts,\n })\n message.ack()\n return\n }\n\n const decision = decideRedelivery(cause, message.attempts)\n if (decision.action === 'ack') {\n logger.error('message_discarded', {\n error: cause,\n name: parsed?.name,\n messageId: parsed?.id,\n queueMessageId: message.id,\n attempt: message.attempts,\n })\n message.ack()\n return\n }\n\n const context = {\n name: parsed?.name,\n messageId: parsed?.id,\n queueMessageId: message.id,\n attempt: message.attempts,\n classification: decision.classification,\n delaySeconds: decision.delaySeconds,\n }\n if (decision.classification === 'unknown' && message.attempts === 1) {\n logger.error('queue_unknown_failure', { error: cause, ...context })\n } else {\n logger.debug('redelivery_requested', context)\n }\n message.retry({ delaySeconds: decision.delaySeconds })\n }\n}\n","import type { IOutboxRelay, OutboxRelay } from '@/application'\nimport { createLogger } from '@/core'\n\nconst logger = createLogger('outbox-wake')\n\n/** Register delivery after commit; log a failed drain once and leave recovery to the scheduled sweep. */\nexport function waitUntilWake(\n context: Pick<ExecutionContext, 'waitUntil'>,\n relay: Pick<OutboxRelay, 'drain'>,\n): IOutboxRelay {\n return {\n wake: () =>\n context.waitUntil(\n relay.drain().catch((cause: unknown) => {\n logger.error('outbox_wake_failed', { error: cause })\n }),\n ),\n }\n}\n"],"mappings":";;;;;;;;;;AAOA,MAAa,eAAe;CAC1B,cAAc;CACd,YAAY;CACZ,YAAY;AACd;;AAGA,SAAgB,kBAAkB,SAA+B;CAC/D,OAAO,IAAI,YAAY,CAAC,CAAC,OAAO,KAAK,UAAU,OAAO,CAAC,CAAC,CAAC;AAC3D;;AAMA,SAAgB,aACd,UAC0B;CAC1B,OAAO,SAAS,KAAK,aAAa;EAAE;EAAS,OAAO,kBAAkB,OAAO;CAAE,EAAE;AACnF;;AAGA,SAAgB,YAAY,OAA4C;CACtE,OAAO,MAAM,QAAQ,aAAa;AACpC;;AAGA,SAAgB,cACd,OACc;CACd,MAAM,SAAuB,CAAC;CAC9B,IAAI,UAAsB,CAAC;CAC3B,IAAI,QAAQ;CACZ,KAAK,MAAM,QAAQ,OAAO;EACxB,MAAM,OACJ,QA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a,QAAQ,aAAa,GAChE,SAAO,MAAM,yBAAyB;GAAE,OAAO;GAAO,GAAG;EAAQ,CAAC;OAElE,SAAO,MAAM,wBAAwB,OAAO;EAE9C,QAAQ,MAAM,EAAE,cAAc,SAAS,aAAa,CAAC;CACvD;AACF;;;;AC7IA,MAAM,SAAS,aAAa,aAAa;;AAGzC,SAAgB,cACd,SACA,OACc;CACd,OAAO,EACL,YACE,QAAQ,UACN,MAAM,MAAM,CAAC,CAAC,OAAO,UAAmB;EACtC,OAAO,MAAM,sBAAsB,EAAE,OAAO,MAAM,CAAC;CACrD,CAAC,CACH,EACJ;AACF"}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
//#region src/infrastructure/cloudflare/r2-client.d.ts
|
|
2
|
+
/** Values accepted by the R2 binding. */
|
|
3
|
+
export type R2Value = Parameters<R2Bucket['put']>[1];
|
|
4
|
+
/** Missing objects, failed conditions, and returned bodies are distinct outcomes. */
|
|
5
|
+
export type R2GetResult = {
|
|
6
|
+
status: 'missing';
|
|
7
|
+
} | {
|
|
8
|
+
status: 'precondition-failed';
|
|
9
|
+
object: R2Object;
|
|
10
|
+
} | {
|
|
11
|
+
status: 'found';
|
|
12
|
+
object: R2ObjectBody;
|
|
13
|
+
};
|
|
14
|
+
/** A failed condition does not establish whether an earlier attempt committed. */
|
|
15
|
+
export type R2PutResult = {
|
|
16
|
+
status: 'precondition-failed';
|
|
17
|
+
} | {
|
|
18
|
+
status: 'stored';
|
|
19
|
+
object: R2Object;
|
|
20
|
+
};
|
|
21
|
+
/** Untrusted JSON data, with absence separate from a stored null. The application supplies its schema. */
|
|
22
|
+
export type R2JsonResult = {
|
|
23
|
+
status: 'missing';
|
|
24
|
+
} | {
|
|
25
|
+
status: 'found';
|
|
26
|
+
value: unknown;
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* R2 access with one attempt per operation and typed failures. Inject the bucket at the composition root.
|
|
30
|
+
* Callers own retries, stream replay, and recovery. The client does not log or buffer streamed uploads.
|
|
31
|
+
*/
|
|
32
|
+
export declare class R2Client {
|
|
33
|
+
private readonly bucket;
|
|
34
|
+
constructor(bucket: R2Bucket);
|
|
35
|
+
/** Read native metadata, or return null when the object does not exist. */
|
|
36
|
+
head(key: string): Promise<R2Object | null>;
|
|
37
|
+
/** Return a native body without consuming it. The consumer owns later body-read failures. */
|
|
38
|
+
get(key: string, options?: R2GetOptions): Promise<R2GetResult>;
|
|
39
|
+
/** Buffer one stored JSON body. Read failures throw R2Error; invalid JSON throws R2JsonError. */
|
|
40
|
+
getJson(key: string): Promise<R2JsonResult>;
|
|
41
|
+
/** Write once, including conditional writes. Pass streams directly to the binding. */
|
|
42
|
+
put(key: string, body: R2Value, options?: R2PutOptions): Promise<R2PutResult>;
|
|
43
|
+
/** Serialize once and default the content type to application/json without changing caller options. */
|
|
44
|
+
putJson(key: string, value: unknown, options?: R2PutOptions): Promise<R2PutResult>;
|
|
45
|
+
/** Delete keys in one binding call. Missing keys succeed; R2 enforces its batch limit. */
|
|
46
|
+
delete(keys: string | string[]): Promise<void>;
|
|
47
|
+
/** Return one native page with the requested metadata, cursor, and delimiter results. */
|
|
48
|
+
list(options?: R2ListOptions): Promise<R2Objects>;
|
|
49
|
+
/** Create once. A failed response can leave an upload whose ID the caller never received. */
|
|
50
|
+
createMultipartUpload(key: string, options?: R2MultipartOptions): Promise<R2MultipartClient>;
|
|
51
|
+
/** Construct a handle without I/O. Each subsequent operation checks whether the upload exists. */
|
|
52
|
+
resumeMultipartUpload(key: string, uploadId: string): R2MultipartClient;
|
|
53
|
+
}
|
|
54
|
+
/** An upload handle that binds its key and ID once. Every operation makes one attempt. */
|
|
55
|
+
export declare class R2MultipartClient {
|
|
56
|
+
private readonly upload;
|
|
57
|
+
constructor(upload: R2MultipartUpload);
|
|
58
|
+
/** The destination object key. */
|
|
59
|
+
get key(): string;
|
|
60
|
+
/** The provider ID to persist when the application needs to resume this upload. */
|
|
61
|
+
get uploadId(): string;
|
|
62
|
+
/** Upload one part without buffering or replaying its body. */
|
|
63
|
+
uploadPart(partNumber: number, body: Exclude<R2Value, null>, options?: R2UploadPartOptions): Promise<R2UploadedPart>;
|
|
64
|
+
/** Sort a copy of the parts and return native metadata after completion. Callers own uncertain outcomes. */
|
|
65
|
+
complete(parts: ReadonlyArray<R2UploadedPart>): Promise<R2Object>;
|
|
66
|
+
/** Ensure no active upload remains. NoSuchUpload succeeds; a completed object remains intact. */
|
|
67
|
+
abort(): Promise<void>;
|
|
68
|
+
}
|
|
69
|
+
//#endregion
|
|
70
|
+
//# sourceMappingURL=r2-client.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"r2-client.d.ts","names":[],"sources":["../../src/infrastructure/cloudflare/r2-client.ts"],"mappings":";;YAKY,UAAU,WAAW;;YAGrB;EACN;;EACA;EAA+B,QAAQ;;EACvC;EAAiB,QAAQ;;;YAGnB;EAAgB;;EAAoC;EAAkB,QAAQ;;;YAG9E;EAAiB;;EAAwB;EAAiB;;;;;;qBAMzD;mBACkB;EAA7B,YAA6B,QAAQ;;EAGrC,KAAK,cAAc,QAAQ;;EAKrB,IAAI,aAAa,UAAU,eAAe,QAAQ;;EAQlD,QAAQ,cAAc,QAAQ;;EAc9B,IAAI,aAAa,MAAM,SAAS,UAAU,eAAe,QAAQ;;EAMjE,QACJ,aAEA,gBACA,UAAU,eACT,QAAQ;;EAYX,OAAO,0BAA0B;;EAKjC,KAAK,UAAU,gBAAgB,QAAQ;;EAKjC,sBACJ,aACA,UAAU,qBACT,QAAQ;;EAQX,sBAAsB,aAAa,mBAAmB;;;qBAM3C;mBACkB;EAA7B,YAA6B,QAAQ;;MAGjC;;MAKA;;EAKJ,WACE,oBACA,MAAM,QAAQ,gBACd,UAAU,sBACT,QAAQ;;EAKX,SAAS,OAAO,cAAc,kBAAkB,QAAQ;;EAOlD,SAAS"}
|