better-ship 0.7.0 → 0.10.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-DjsQtpgw.js → application-DYfcAy-Q.js} +2 -2
- package/dist/{application-DjsQtpgw.js.map → application-DYfcAy-Q.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 +11 -4
- package/dist/better-auth/apple-client-secret.d.ts.map +1 -1
- package/dist/better-auth/apple-client-secret.js +39 -11
- 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 +21 -2
- package/dist/better-auth/rate-limit.d.ts.map +1 -1
- package/dist/better-auth/rate-limit.js +38 -2
- package/dist/better-auth/rate-limit.js.map +1 -1
- package/dist/better-auth.js +1 -1
- package/dist/cloudflare/auth-secondary-storage.d.ts +1 -1
- package/dist/cloudflare/auth-secondary-storage.js +1 -1
- package/dist/cloudflare/queue.d.ts +175 -0
- package/dist/cloudflare/queue.d.ts.map +1 -0
- package/dist/cloudflare/queue.js +419 -0
- package/dist/cloudflare/queue.js.map +1 -0
- package/dist/cloudflare/scheduled.d.ts +36 -0
- package/dist/cloudflare/scheduled.d.ts.map +1 -0
- package/dist/cloudflare/scheduled.js +37 -0
- package/dist/cloudflare/scheduled.js.map +1 -0
- package/dist/cloudflare.d.ts +3 -3
- package/dist/cloudflare.js +3 -3
- package/dist/{core-Cx5SeyKV.js → core-DC_4pOrI.js} +92 -2
- package/dist/core-DC_4pOrI.js.map +1 -0
- package/dist/core.d.ts +2 -2
- package/dist/core.js +2 -2
- package/dist/{index-BStnggQO.d.ts → index-6XMPJu7u.d.ts} +49 -2
- package/dist/index-6XMPJu7u.d.ts.map +1 -0
- package/dist/{index-DWIRrJMP.d.ts → index-_Cihfq1J.d.ts} +2 -2
- package/dist/{index-DWIRrJMP.d.ts.map → index-_Cihfq1J.d.ts.map} +1 -1
- package/dist/postgres.d.ts +3 -3
- package/dist/postgres.js +3 -3
- package/dist/tanstack.d.ts +18 -7
- package/dist/tanstack.d.ts.map +1 -1
- package/dist/tanstack.js +3 -3
- package/dist/tanstack.js.map +1 -1
- package/dist/{unit-of-work-context-DToDpAkv.js → unit-of-work-context-BFCmU92Z.js} +2 -2
- package/dist/{unit-of-work-context-DToDpAkv.js.map → unit-of-work-context-BFCmU92Z.js.map} +1 -1
- package/dist/{unit-of-work-context-CPz9rdSS.d.ts → unit-of-work-context-BWTJfYPW.d.ts} +3 -3
- package/dist/{unit-of-work-context-CPz9rdSS.d.ts.map → unit-of-work-context-BWTJfYPW.d.ts.map} +1 -1
- package/package.json +3 -6
- package/src/core/backoff.ts +29 -0
- package/src/core/classify-failure.ts +60 -0
- package/src/core/cloudflare-classification.ts +45 -0
- package/src/core/index.ts +14 -0
- package/src/infrastructure/better-auth/apple-client-secret.ts +41 -14
- package/src/infrastructure/better-auth/rate-limit.ts +44 -1
- package/src/infrastructure/cloudflare/queue/index.ts +25 -0
- package/src/infrastructure/cloudflare/queue/queue-client.ts +177 -0
- package/src/infrastructure/cloudflare/queue/queue-consumer.ts +146 -0
- package/src/infrastructure/cloudflare/queue/queue-limits.ts +54 -0
- package/src/infrastructure/cloudflare/queue/queue-message.ts +4 -0
- package/src/infrastructure/cloudflare/queue/queue.errors.ts +105 -0
- package/src/infrastructure/cloudflare/queue/redelivery-policy.ts +64 -0
- package/src/infrastructure/cloudflare/scheduled/index.ts +8 -0
- package/src/infrastructure/cloudflare/scheduled/scheduled-handler.ts +62 -0
- package/src/infrastructure/tanstack/auth.middleware.ts +5 -3
- package/src/infrastructure/tanstack/error.middleware.ts +6 -7
- package/src/infrastructure/tanstack/request-context.ts +11 -0
- package/dist/core-Cx5SeyKV.js.map +0 -1
- package/dist/index-BStnggQO.d.ts.map +0 -1
|
@@ -0,0 +1,419 @@
|
|
|
1
|
+
import { U as AppError, a as createLogger, b as shouldRetryFailure, c as exponentialEqualJitterMs, d as classifyFailure, f as retryAfterSecondsOf, l as spreadJitterMs, u as classifyBoundaryError } from "../core-DC_4pOrI.js";
|
|
2
|
+
import { i as MessageAlreadyProcessedError } from "../application-DYfcAy-Q.js";
|
|
3
|
+
import { Result } from "better-result";
|
|
4
|
+
|
|
5
|
+
//#region src/infrastructure/cloudflare/queue/queue-limits.ts
|
|
6
|
+
/**
|
|
7
|
+
* The Cloudflare Queues producer limits with metadata headroom, checked before each send so a
|
|
8
|
+
* violation never reaches the binding. The dead letter has the same per-message limit.
|
|
9
|
+
* https://developers.cloudflare.com/queues/platform/limits/
|
|
10
|
+
*/
|
|
11
|
+
const QUEUE_LIMITS = {
|
|
12
|
+
messageBytes: 127e3,
|
|
13
|
+
batchBytes: 25e4,
|
|
14
|
+
batchCount: 100
|
|
15
|
+
};
|
|
16
|
+
/** The size the binding measures: the JSON encoding of the body, in UTF-8 bytes. */
|
|
17
|
+
function messageByteLength(message) {
|
|
18
|
+
return new TextEncoder().encode(JSON.stringify(message)).length;
|
|
19
|
+
}
|
|
20
|
+
/** Measure every message once. */
|
|
21
|
+
function sizeMessages(messages) {
|
|
22
|
+
return messages.map((message) => ({
|
|
23
|
+
message,
|
|
24
|
+
bytes: messageByteLength(message)
|
|
25
|
+
}));
|
|
26
|
+
}
|
|
27
|
+
/** Whether one message is over the per-message limit. */
|
|
28
|
+
function isOversized(sized) {
|
|
29
|
+
return sized.bytes > QUEUE_LIMITS.messageBytes;
|
|
30
|
+
}
|
|
31
|
+
/** Split a batch at the message-count and byte limits, keeping the order. */
|
|
32
|
+
function chunkByLimits(sized) {
|
|
33
|
+
const chunks = [];
|
|
34
|
+
let current = [];
|
|
35
|
+
let bytes = 0;
|
|
36
|
+
for (const item of sized) {
|
|
37
|
+
const full = current.length >= QUEUE_LIMITS.batchCount || bytes + item.bytes > QUEUE_LIMITS.batchBytes;
|
|
38
|
+
if (current.length > 0 && full) {
|
|
39
|
+
chunks.push(current);
|
|
40
|
+
current = [];
|
|
41
|
+
bytes = 0;
|
|
42
|
+
}
|
|
43
|
+
current.push(item.message);
|
|
44
|
+
bytes += item.bytes;
|
|
45
|
+
}
|
|
46
|
+
if (current.length > 0) chunks.push(current);
|
|
47
|
+
return chunks;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
//#endregion
|
|
51
|
+
//#region src/infrastructure/cloudflare/queue/queue.errors.ts
|
|
52
|
+
const QUEUE_OPERATION_MESSAGES = {
|
|
53
|
+
send: "Failed to send queue message",
|
|
54
|
+
send_batch: "Failed to send queue batch",
|
|
55
|
+
send_dlq: "Failed to send DLQ message"
|
|
56
|
+
};
|
|
57
|
+
/**
|
|
58
|
+
* Cloudflare Queues error codes, by whether a repeat could change the answer. The reference
|
|
59
|
+
* marks only 10201 and 10250 for retry; 10251 waits for processing, 15000 is nobody's call.
|
|
60
|
+
* https://developers.cloudflare.com/queues/reference/error-codes/
|
|
61
|
+
*/
|
|
62
|
+
const QUEUE_ERROR_CLASSIFICATIONS = /* @__PURE__ */ new Map([
|
|
63
|
+
[10104, "terminal"],
|
|
64
|
+
[10106, "terminal"],
|
|
65
|
+
[10107, "terminal"],
|
|
66
|
+
[10201, "transient"],
|
|
67
|
+
[10202, "terminal"],
|
|
68
|
+
[10203, "terminal"],
|
|
69
|
+
[10204, "terminal"],
|
|
70
|
+
[10205, "terminal"],
|
|
71
|
+
[10206, "terminal"],
|
|
72
|
+
[10207, "terminal"],
|
|
73
|
+
[10208, "terminal"],
|
|
74
|
+
[10250, "transient"],
|
|
75
|
+
[10251, "transient"],
|
|
76
|
+
[10252, "terminal"],
|
|
77
|
+
[10253, "terminal"],
|
|
78
|
+
[15e3, "unknown"]
|
|
79
|
+
]);
|
|
80
|
+
function extractQueueErrorCode(cause) {
|
|
81
|
+
if (!(cause instanceof Error)) return void 0;
|
|
82
|
+
const match = /(\d{5})\)?\s*$/.exec(cause.message);
|
|
83
|
+
return match?.[1] === void 0 ? void 0 : Number(match[1]);
|
|
84
|
+
}
|
|
85
|
+
function classifyQueueBoundaryError(cause) {
|
|
86
|
+
const code = extractQueueErrorCode(cause);
|
|
87
|
+
return code === void 0 ? void 0 : QUEUE_ERROR_CLASSIFICATIONS.get(code);
|
|
88
|
+
}
|
|
89
|
+
/** Classify a raw Queue binding failure: the code table first, then Cloudflare's signals, then transport. */
|
|
90
|
+
function classifyQueueError(cause) {
|
|
91
|
+
return classifyBoundaryError({
|
|
92
|
+
cause,
|
|
93
|
+
classifyBoundary: classifyQueueBoundaryError,
|
|
94
|
+
includeCloudflare: true
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
/** A send through a Queue binding failed. The classification says whether an immediate retry may help. */
|
|
98
|
+
var QueueSendError = class extends AppError {
|
|
99
|
+
_tag = "QueueSendError";
|
|
100
|
+
classification;
|
|
101
|
+
operation;
|
|
102
|
+
constructor(args) {
|
|
103
|
+
super(QUEUE_OPERATION_MESSAGES[args.operation], { cause: args.cause });
|
|
104
|
+
this.classification = classifyQueueError(args.cause);
|
|
105
|
+
this.operation = args.operation;
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
/**
|
|
109
|
+
* A message over the per-message cap can never be sent on any queue; the dead letter has the
|
|
110
|
+
* same cap. The client detects it before the send, so it never comes from a platform error.
|
|
111
|
+
*/
|
|
112
|
+
var OversizedMessageError = class extends AppError {
|
|
113
|
+
_tag = "OversizedMessageError";
|
|
114
|
+
classification = "terminal";
|
|
115
|
+
messageName;
|
|
116
|
+
bytes;
|
|
117
|
+
limit;
|
|
118
|
+
constructor(args) {
|
|
119
|
+
super(`Queue message "${args.messageName}" is ${String(args.bytes)} bytes, over the ${String(args.limit)} limit`);
|
|
120
|
+
this.messageName = args.messageName;
|
|
121
|
+
this.bytes = args.bytes;
|
|
122
|
+
this.limit = args.limit;
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
/**
|
|
126
|
+
* The dead letter did not accept an unparseable message. Always transient, whatever the send
|
|
127
|
+
* failure was, so the source delivery retries instead of acknowledging and losing the body.
|
|
128
|
+
*/
|
|
129
|
+
var DeadLetterUnavailableError = class extends AppError {
|
|
130
|
+
_tag = "DeadLetterUnavailableError";
|
|
131
|
+
classification = "transient";
|
|
132
|
+
constructor(cause) {
|
|
133
|
+
super("The dead letter did not accept the message", { cause });
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
//#endregion
|
|
138
|
+
//#region src/infrastructure/cloudflare/queue/queue-client.ts
|
|
139
|
+
const logger$1 = createLogger("queue-client");
|
|
140
|
+
/** Immediate retries of one binding call: three attempts, 250 ms then 500 ms, with jitter. */
|
|
141
|
+
const RETRY_TIMES = 2;
|
|
142
|
+
const RETRY_BASE_DELAY_MS = 250;
|
|
143
|
+
/** Every send is safe to repeat, so a transient failure gets an immediate retry; terminal and unknown stop. */
|
|
144
|
+
function shouldRetrySend(error) {
|
|
145
|
+
return shouldRetryFailure({
|
|
146
|
+
classification: error.classification,
|
|
147
|
+
repeatSafe: true,
|
|
148
|
+
owner: "immediate"
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
function oversizedError(sized) {
|
|
152
|
+
return new OversizedMessageError({
|
|
153
|
+
messageName: sized.message.name,
|
|
154
|
+
bytes: sized.bytes,
|
|
155
|
+
limit: QUEUE_LIMITS.messageBytes
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Sends messages to the application's queues. Checks the size limits before a send, retries a
|
|
160
|
+
* transient binding failure a bounded number of times, and converts the final failure to `QueueSendError`.
|
|
161
|
+
*/
|
|
162
|
+
var QueueClient = class {
|
|
163
|
+
options;
|
|
164
|
+
constructor(options) {
|
|
165
|
+
this.options = options;
|
|
166
|
+
}
|
|
167
|
+
/** @throws OversizedMessageError before the send. @throws QueueSendError after the retries. */
|
|
168
|
+
async send(message, options) {
|
|
169
|
+
const sized = {
|
|
170
|
+
message,
|
|
171
|
+
bytes: messageByteLength(message)
|
|
172
|
+
};
|
|
173
|
+
if (isOversized(sized)) {
|
|
174
|
+
logger$1.warn("queue_message_oversized", {
|
|
175
|
+
name: message.name,
|
|
176
|
+
type: message.type,
|
|
177
|
+
bytes: sized.bytes
|
|
178
|
+
});
|
|
179
|
+
throw oversizedError(sized);
|
|
180
|
+
}
|
|
181
|
+
const queue = this.queueFor(message);
|
|
182
|
+
logger$1.debug("sending_message", {
|
|
183
|
+
name: message.name,
|
|
184
|
+
type: message.type,
|
|
185
|
+
delaySeconds: options?.delaySeconds
|
|
186
|
+
});
|
|
187
|
+
await this.callQueue("send", async () => {
|
|
188
|
+
if (options) await queue.send(message, options);
|
|
189
|
+
else await queue.send(message);
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
/** Rejects the whole batch before any send when one message is oversized. */
|
|
193
|
+
async sendBatch(messages) {
|
|
194
|
+
const sized = sizeMessages(messages);
|
|
195
|
+
const oversized = sized.find(isOversized);
|
|
196
|
+
if (oversized) throw oversizedError(oversized);
|
|
197
|
+
await this.sendSizedBatch(sized);
|
|
198
|
+
}
|
|
199
|
+
async sendBatchPartial(messages) {
|
|
200
|
+
const sized = sizeMessages(messages);
|
|
201
|
+
await this.sendSizedBatch(sized.filter((item) => !isOversized(item)));
|
|
202
|
+
return sized.filter(isOversized).map((item) => item.message);
|
|
203
|
+
}
|
|
204
|
+
async sendToDlq(message) {
|
|
205
|
+
logger$1.debug("sending_to_dlq", { queueMessageId: message.id });
|
|
206
|
+
await this.callQueue("send_dlq", async () => {
|
|
207
|
+
await this.options.deadLetter.send(message.body);
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
/** Each lane's chunks retry on their own, so one failed chunk does not resend the others. */
|
|
211
|
+
async sendSizedBatch(sized) {
|
|
212
|
+
const byLane = /* @__PURE__ */ new Map();
|
|
213
|
+
for (const item of sized) {
|
|
214
|
+
const lane = this.options.laneOf(item.message);
|
|
215
|
+
const items = byLane.get(lane) ?? [];
|
|
216
|
+
items.push(item);
|
|
217
|
+
byLane.set(lane, items);
|
|
218
|
+
}
|
|
219
|
+
logger$1.debug("sending_batch", {
|
|
220
|
+
count: sized.length,
|
|
221
|
+
lanes: [...byLane].map(([lane, items]) => ({
|
|
222
|
+
lane,
|
|
223
|
+
count: items.length
|
|
224
|
+
}))
|
|
225
|
+
});
|
|
226
|
+
const sends = [];
|
|
227
|
+
for (const [lane, items] of byLane) {
|
|
228
|
+
const queue = this.options.queues[lane];
|
|
229
|
+
for (const group of chunkByLimits(items)) sends.push(this.callQueue("send_batch", async () => {
|
|
230
|
+
await queue.sendBatch(group.map((body) => ({ body })));
|
|
231
|
+
}));
|
|
232
|
+
}
|
|
233
|
+
await Promise.all(sends);
|
|
234
|
+
}
|
|
235
|
+
queueFor(message) {
|
|
236
|
+
return this.options.queues[this.options.laneOf(message)];
|
|
237
|
+
}
|
|
238
|
+
async callQueue(operation, call) {
|
|
239
|
+
const result = await Result.tryPromise({
|
|
240
|
+
try: call,
|
|
241
|
+
catch: (cause) => new QueueSendError({
|
|
242
|
+
operation,
|
|
243
|
+
cause
|
|
244
|
+
})
|
|
245
|
+
}, { retry: {
|
|
246
|
+
times: RETRY_TIMES,
|
|
247
|
+
delayMs: RETRY_BASE_DELAY_MS,
|
|
248
|
+
backoff: "exponential",
|
|
249
|
+
jitter: true,
|
|
250
|
+
shouldRetry: shouldRetrySend
|
|
251
|
+
} });
|
|
252
|
+
if (result.isErr()) throw result.error;
|
|
253
|
+
return result.value;
|
|
254
|
+
}
|
|
255
|
+
};
|
|
256
|
+
|
|
257
|
+
//#endregion
|
|
258
|
+
//#region src/infrastructure/cloudflare/queue/redelivery-policy.ts
|
|
259
|
+
const BASE_RETRY_DELAY_MS = 5e3;
|
|
260
|
+
const MAX_RETRY_DELAY_MS = 12e4;
|
|
261
|
+
const RETRY_AFTER_SPREAD_MS = 5e3;
|
|
262
|
+
/** Cloudflare Queues accept a redelivery delay of at most one day. */
|
|
263
|
+
const MAX_QUEUE_DELAY_SECONDS = 86400;
|
|
264
|
+
/**
|
|
265
|
+
* Decide whether the consumer acknowledges a failed message or asks Cloudflare to redeliver it.
|
|
266
|
+
* A terminal failure acknowledges. Transient and unknown failures redeliver: after the advertised
|
|
267
|
+
* wait plus a spread when the error carries one, else with exponential equal-jitter backoff.
|
|
268
|
+
* An `AggregateError` from event delivery redelivers when any member does, after the longest wait.
|
|
269
|
+
*/
|
|
270
|
+
function decideRedelivery(cause, attempt) {
|
|
271
|
+
if (cause instanceof AggregateError && cause.errors.length > 0) {
|
|
272
|
+
const retries = cause.errors.map((member) => decideRedelivery(member, attempt)).filter((decision) => decision.action === "retry");
|
|
273
|
+
if (retries.length === 0) return {
|
|
274
|
+
action: "ack",
|
|
275
|
+
classification: "terminal"
|
|
276
|
+
};
|
|
277
|
+
return {
|
|
278
|
+
action: "retry",
|
|
279
|
+
classification: retries.some((decision) => decision.classification === "unknown") ? "unknown" : "transient",
|
|
280
|
+
delaySeconds: Math.max(...retries.map((decision) => decision.delaySeconds))
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
const classification = classifyFailure(cause);
|
|
284
|
+
if (classification === "terminal") return {
|
|
285
|
+
action: "ack",
|
|
286
|
+
classification
|
|
287
|
+
};
|
|
288
|
+
if (!shouldRetryFailure({
|
|
289
|
+
classification,
|
|
290
|
+
repeatSafe: true,
|
|
291
|
+
owner: "durable"
|
|
292
|
+
})) return {
|
|
293
|
+
action: "ack",
|
|
294
|
+
classification: "terminal"
|
|
295
|
+
};
|
|
296
|
+
const retryAfterSeconds = retryAfterSecondsOf(cause);
|
|
297
|
+
const delayMs = retryAfterSeconds === null ? exponentialEqualJitterMs(BASE_RETRY_DELAY_MS, MAX_RETRY_DELAY_MS, attempt) : retryAfterSeconds * 1e3 + spreadJitterMs(RETRY_AFTER_SPREAD_MS);
|
|
298
|
+
return {
|
|
299
|
+
action: "retry",
|
|
300
|
+
classification,
|
|
301
|
+
delaySeconds: Math.min(MAX_QUEUE_DELAY_SECONDS, Math.max(1, Math.ceil(delayMs / 1e3)))
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
//#endregion
|
|
306
|
+
//#region src/infrastructure/cloudflare/queue/queue-consumer.ts
|
|
307
|
+
const logger = createLogger("queue-consumer");
|
|
308
|
+
/**
|
|
309
|
+
* Parses and dispatches each queue message, then selects acknowledgement or retry.
|
|
310
|
+
* Cloudflare owns the retry limit and sends exhausted messages to the configured dead letter.
|
|
311
|
+
* The consumer logs each failure once; handlers do not.
|
|
312
|
+
*/
|
|
313
|
+
var QueueConsumer = class {
|
|
314
|
+
bus;
|
|
315
|
+
queueClient;
|
|
316
|
+
schema;
|
|
317
|
+
wrapDispatch;
|
|
318
|
+
/**
|
|
319
|
+
* @param bus - Where a parsed message goes.
|
|
320
|
+
* @param queueClient - Parks an unparseable body in the dead letter.
|
|
321
|
+
* @param schema - What a body may be: the application's `messages.queueSchema`.
|
|
322
|
+
* @param wrapDispatch - Wraps one dispatch in the application's context. Default: run it as is.
|
|
323
|
+
*/
|
|
324
|
+
constructor(bus, queueClient, schema, wrapDispatch = (_message, _attempt, run) => run()) {
|
|
325
|
+
this.bus = bus;
|
|
326
|
+
this.queueClient = queueClient;
|
|
327
|
+
this.schema = schema;
|
|
328
|
+
this.wrapDispatch = wrapDispatch;
|
|
329
|
+
}
|
|
330
|
+
/** Every message settles on its own. A settlement that throws rejects the batch after its siblings settle. */
|
|
331
|
+
async processBatch(batch) {
|
|
332
|
+
logger.debug("queue_batch_received", { count: batch.messages.length });
|
|
333
|
+
const rejected = (await Promise.allSettled(batch.messages.map((message) => this.processMessage(message)))).filter((result) => result.status === "rejected").map((result) => result.reason);
|
|
334
|
+
if (rejected.length > 0) throw new AggregateError(rejected, "Queue message settlement failed");
|
|
335
|
+
}
|
|
336
|
+
async processMessage(message) {
|
|
337
|
+
let parsed = null;
|
|
338
|
+
try {
|
|
339
|
+
const body = await this.parseMessage(message);
|
|
340
|
+
if (body === null) {
|
|
341
|
+
logger.error("invalid_message_format", { details: {
|
|
342
|
+
attempt: message.attempts,
|
|
343
|
+
queueMessageId: message.id
|
|
344
|
+
} });
|
|
345
|
+
await this.parkPoison(message);
|
|
346
|
+
return;
|
|
347
|
+
}
|
|
348
|
+
parsed = body;
|
|
349
|
+
await this.wrapDispatch(body, message.attempts, async () => {
|
|
350
|
+
await this.bus.handle(body);
|
|
351
|
+
});
|
|
352
|
+
message.ack();
|
|
353
|
+
logger.debug(`queue_message_processed:${body.name}`, { name: body.name });
|
|
354
|
+
} catch (cause) {
|
|
355
|
+
this.handleFailure(message, parsed, cause);
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
/** Returns null on failure; the caller owns the single log point. */
|
|
359
|
+
async parseMessage(message) {
|
|
360
|
+
const result = await this.schema.safeParseAsync(message.body);
|
|
361
|
+
return result.success ? result.data : null;
|
|
362
|
+
}
|
|
363
|
+
/** Park an unparseable message in the dead letter, then acknowledge its source delivery. */
|
|
364
|
+
async parkPoison(message) {
|
|
365
|
+
try {
|
|
366
|
+
await this.queueClient.sendToDlq(message);
|
|
367
|
+
message.ack();
|
|
368
|
+
} catch (cause) {
|
|
369
|
+
throw new DeadLetterUnavailableError(cause);
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
/**
|
|
373
|
+
* Retry declared transient and unknown failures so Cloudflare can enforce the attempt ceiling.
|
|
374
|
+
* Acknowledge only declared terminal failures.
|
|
375
|
+
*/
|
|
376
|
+
handleFailure(message, parsed, cause) {
|
|
377
|
+
if (cause instanceof MessageAlreadyProcessedError) {
|
|
378
|
+
logger.debug("duplicate_skipped", {
|
|
379
|
+
name: parsed?.name,
|
|
380
|
+
messageId: cause.messageId,
|
|
381
|
+
attempt: message.attempts
|
|
382
|
+
});
|
|
383
|
+
message.ack();
|
|
384
|
+
return;
|
|
385
|
+
}
|
|
386
|
+
const decision = decideRedelivery(cause, message.attempts);
|
|
387
|
+
if (decision.action === "ack") {
|
|
388
|
+
logger.error("message_discarded", {
|
|
389
|
+
error: cause,
|
|
390
|
+
details: {
|
|
391
|
+
name: parsed?.name,
|
|
392
|
+
messageId: parsed?.id,
|
|
393
|
+
queueMessageId: message.id,
|
|
394
|
+
attempt: message.attempts
|
|
395
|
+
}
|
|
396
|
+
});
|
|
397
|
+
message.ack();
|
|
398
|
+
return;
|
|
399
|
+
}
|
|
400
|
+
const context = {
|
|
401
|
+
name: parsed?.name,
|
|
402
|
+
messageId: parsed?.id,
|
|
403
|
+
queueMessageId: message.id,
|
|
404
|
+
attempt: message.attempts,
|
|
405
|
+
classification: decision.classification,
|
|
406
|
+
delaySeconds: decision.delaySeconds
|
|
407
|
+
};
|
|
408
|
+
if (decision.classification === "unknown" && message.attempts === 1) logger.error("queue_unknown_failure", {
|
|
409
|
+
error: cause,
|
|
410
|
+
details: context
|
|
411
|
+
});
|
|
412
|
+
else logger.debug("redelivery_requested", context);
|
|
413
|
+
message.retry({ delaySeconds: decision.delaySeconds });
|
|
414
|
+
}
|
|
415
|
+
};
|
|
416
|
+
|
|
417
|
+
//#endregion
|
|
418
|
+
export { DeadLetterUnavailableError, OversizedMessageError, QUEUE_LIMITS, QueueClient, QueueConsumer, QueueSendError, chunkByLimits, classifyQueueError, decideRedelivery, isOversized, messageByteLength, sizeMessages };
|
|
419
|
+
//# sourceMappingURL=queue.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"queue.js","names":["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"],"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(messages: ReadonlyArray<TMessage>): Promise<ReadonlyArray<TMessage>>\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(messages: ReadonlyArray<TMessage>): Promise<ReadonlyArray<TMessage>> {\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"],"mappings":";;;;;;;;;;AAOA,MAAa,eAAe;CAC1B,cAAc;CACd,YAAY;CACZ,YAAY;AACd;;AAGA,SAAgB,kBAAk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;GACnB,CAAC;GACD,QAAQ,IAAI;GACZ;EACF;EAEA,MAAM,WAAW,iBAAiB,OAAO,QAAQ,QAAQ;EACzD,IAAI,SAAS,WAAW,OAAO;GAC7B,OAAO,MAAM,qBAAqB;IAChC,OAAO;IACP,SAAS;KACP,MAAM,QAAQ;KACd,WAAW,QAAQ;KACnB,gBAAgB,QAAQ;KACxB,SAAS,QAAQ;IACnB;GACF,CAAC;GACD,QAAQ,IAAI;GACZ;EACF;EAEA,MAAM,UAAU;GACd,MAAM,QAAQ;GACd,WAAW,QAAQ;GACnB,gBAAgB,QAAQ;GACxB,SAAS,QAAQ;GACjB,gBAAgB,SAAS;GACzB,cAAc,SAAS;EACzB;EACA,IAAI,SAAS,mBAAmB,aAAa,QAAQ,aAAa,GAChE,OAAO,MAAM,yBAAyB;GAAE,OAAO;GAAO,SAAS;EAAQ,CAAC;OAExE,OAAO,MAAM,wBAAwB,OAAO;EAE9C,QAAQ,MAAM,EAAE,cAAc,SAAS,aAAa,CAAC;CACvD;AACF"}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { q as MessageId } from "../index-6XMPJu7u.js";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
//#region src/infrastructure/cloudflare/scheduled/scheduled-handler.d.ts
|
|
4
|
+
/** The work one schedule runs. Nothing returns to the platform, so each run reports its own outcome. */
|
|
5
|
+
type ScheduledRun<Deps> = (deps: Deps, at: Date) => Promise<void>;
|
|
6
|
+
/** The cron expressions of a schedule map, as literal types. */
|
|
7
|
+
type ScheduleExpression<Schedules extends Readonly<Record<string, string>>> = Schedules[keyof Schedules];
|
|
8
|
+
/** The Cloudflare `scheduled` export, with the application's dependencies as its second argument. */
|
|
9
|
+
type ScheduledHandler<Deps> = (controller: ScheduledController, deps: Deps) => Promise<void>;
|
|
10
|
+
/** What `defineSchedules` returns: the map, its parser, and the handler factory. */
|
|
11
|
+
type AppSchedules<Schedules extends Readonly<Record<string, string>>> = {
|
|
12
|
+
readonly schedules: Schedules;
|
|
13
|
+
/** Parses `controller.cron`, a bare string from the platform, into a known expression. */
|
|
14
|
+
readonly schema: z.ZodType<ScheduleExpression<Schedules>>;
|
|
15
|
+
/**
|
|
16
|
+
* Route each schedule to its work. One run per expression, so a schedule added without
|
|
17
|
+
* work fails to compile. An expression Wrangler fires that the map does not know is logged
|
|
18
|
+
* once and ignored. A run that throws rejects, so Cloudflare marks the invocation failed.
|
|
19
|
+
*/
|
|
20
|
+
handler<Deps>(runs: Readonly<Record<ScheduleExpression<Schedules>, ScheduledRun<Deps>>>): ScheduledHandler<Deps>;
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* Define the application's schedules once: `EVERY_MINUTE: '* * * * *'`. Keys name the time,
|
|
24
|
+
* not the work, because one schedule may drive several commands. Wrangler's `triggers.crons`
|
|
25
|
+
* must hold exactly these expressions. Cron does not retry: a run that sweeps many items
|
|
26
|
+
* catches each item's failure itself.
|
|
27
|
+
*/
|
|
28
|
+
export declare function defineSchedules<const Schedules extends Readonly<Record<string, string>>>(schedules: Schedules): AppSchedules<Schedules>;
|
|
29
|
+
/**
|
|
30
|
+
* The id of a command a schedule issues: `cron:<Name>:<scheduledTime>`. A doubled trigger for
|
|
31
|
+
* the same time is then a duplicate by construction, and the unit of work skips it.
|
|
32
|
+
*/
|
|
33
|
+
export declare function scheduledMessageId(name: string, at: Date): MessageId;
|
|
34
|
+
//#endregion
|
|
35
|
+
export type { AppSchedules, ScheduleExpression, ScheduledHandler, ScheduledRun };
|
|
36
|
+
//# sourceMappingURL=scheduled.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scheduled.d.ts","names":[],"sources":["../../src/infrastructure/cloudflare/scheduled/scheduled-handler.ts"],"mappings":";;;;KAOY,aAAa,SAAS,MAAM,MAAM,IAAI,SAAS;;KAG/C,mBAAmB,kBAAkB,SAAS,2BACxD,gBAAgB;;KAGN,iBAAiB,SAAS,YAAY,qBAAqB,MAAM,SAAS;;KAG1E,aAAa,kBAAkB,SAAS;WACzC,WAAW;;WAEX,QAAQ,EAAE,QAAQ,mBAAmB;;;;;;EAM9C,QAAQ,MACN,MAAM,SAAS,OAAO,mBAAmB,YAAY,aAAa,UACjE,iBAAiB;;;;;;;;wBASN,sBAAsB,kBAAkB,SAAS,yBAC/D,WAAW,YACV,aAAa;;;;;wBAoBA,mBAAmB,cAAc,IAAI,OAAO"}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { a as createLogger } from "../core-DC_4pOrI.js";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
|
|
4
|
+
//#region src/infrastructure/cloudflare/scheduled/scheduled-handler.ts
|
|
5
|
+
const logger = createLogger("scheduled");
|
|
6
|
+
/**
|
|
7
|
+
* Define the application's schedules once: `EVERY_MINUTE: '* * * * *'`. Keys name the time,
|
|
8
|
+
* not the work, because one schedule may drive several commands. Wrangler's `triggers.crons`
|
|
9
|
+
* must hold exactly these expressions. Cron does not retry: a run that sweeps many items
|
|
10
|
+
* catches each item's failure itself.
|
|
11
|
+
*/
|
|
12
|
+
function defineSchedules(schedules) {
|
|
13
|
+
const schema = z.enum(schedules);
|
|
14
|
+
return {
|
|
15
|
+
schedules,
|
|
16
|
+
schema,
|
|
17
|
+
handler: (runs) => async (controller, deps) => {
|
|
18
|
+
const { cron } = controller;
|
|
19
|
+
if (!schema.validate(cron)) {
|
|
20
|
+
logger.error("scheduled_unknown_cron", { details: { cron } });
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
await runs[cron](deps, new Date(controller.scheduledTime));
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* The id of a command a schedule issues: `cron:<Name>:<scheduledTime>`. A doubled trigger for
|
|
29
|
+
* the same time is then a duplicate by construction, and the unit of work skips it.
|
|
30
|
+
*/
|
|
31
|
+
function scheduledMessageId(name, at) {
|
|
32
|
+
return `cron:${name}:${String(at.getTime())}`;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
//#endregion
|
|
36
|
+
export { defineSchedules, scheduledMessageId };
|
|
37
|
+
//# sourceMappingURL=scheduled.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scheduled.js","names":[],"sources":["../../src/infrastructure/cloudflare/scheduled/scheduled-handler.ts"],"sourcesContent":["import { z } from 'zod'\n\nimport { createLogger, type MessageId } from '@/core'\n\nconst logger = createLogger('scheduled')\n\n/** The work one schedule runs. Nothing returns to the platform, so each run reports its own outcome. */\nexport type ScheduledRun<Deps> = (deps: Deps, at: Date) => Promise<void>\n\n/** The cron expressions of a schedule map, as literal types. */\nexport type ScheduleExpression<Schedules extends Readonly<Record<string, string>>> =\n Schedules[keyof Schedules]\n\n/** The Cloudflare `scheduled` export, with the application's dependencies as its second argument. */\nexport type ScheduledHandler<Deps> = (controller: ScheduledController, deps: Deps) => Promise<void>\n\n/** What `defineSchedules` returns: the map, its parser, and the handler factory. */\nexport type AppSchedules<Schedules extends Readonly<Record<string, string>>> = {\n readonly schedules: Schedules\n /** Parses `controller.cron`, a bare string from the platform, into a known expression. */\n readonly schema: z.ZodType<ScheduleExpression<Schedules>>\n /**\n * Route each schedule to its work. One run per expression, so a schedule added without\n * work fails to compile. An expression Wrangler fires that the map does not know is logged\n * once and ignored. A run that throws rejects, so Cloudflare marks the invocation failed.\n */\n handler<Deps>(\n runs: Readonly<Record<ScheduleExpression<Schedules>, ScheduledRun<Deps>>>,\n ): ScheduledHandler<Deps>\n}\n\n/**\n * Define the application's schedules once: `EVERY_MINUTE: '* * * * *'`. Keys name the time,\n * not the work, because one schedule may drive several commands. Wrangler's `triggers.crons`\n * must hold exactly these expressions. Cron does not retry: a run that sweeps many items\n * catches each item's failure itself.\n */\nexport function defineSchedules<const Schedules extends Readonly<Record<string, string>>>(\n schedules: Schedules,\n): AppSchedules<Schedules> {\n const schema = z.enum(schedules)\n return {\n schedules,\n schema,\n handler: (runs) => async (controller, deps) => {\n const { cron } = controller\n if (!schema.validate(cron)) {\n logger.error('scheduled_unknown_cron', { details: { cron } })\n return\n }\n await runs[cron](deps, new Date(controller.scheduledTime))\n },\n }\n}\n\n/**\n * The id of a command a schedule issues: `cron:<Name>:<scheduledTime>`. A doubled trigger for\n * the same time is then a duplicate by construction, and the unit of work skips it.\n */\nexport function scheduledMessageId(name: string, at: Date): MessageId {\n return `cron:${name}:${String(at.getTime())}`\n}\n"],"mappings":";;;;AAIA,MAAM,SAAS,aAAa,WAAW;;;;;;;AAiCvC,SAAgB,gBACd,WACyB;CACzB,MAAM,SAAS,EAAE,KAAK,SAAS;CAC/B,OAAO;EACL;EACA;EACA,UAAU,SAAS,OAAO,YAAY,SAAS;GAC7C,MAAM,EAAE,SAAS;GACjB,IAAI,CAAC,OAAO,SAAS,IAAI,GAAG;IAC1B,OAAO,MAAM,0BAA0B,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC;IAC5D;GACF;GACA,MAAM,KAAK,KAAK,CAAC,MAAM,IAAI,KAAK,WAAW,aAAa,CAAC;EAC3D;CACF;AACF;;;;;AAMA,SAAgB,mBAAmB,MAAc,IAAqB;CACpE,OAAO,QAAQ,KAAK,GAAG,OAAO,GAAG,QAAQ,CAAC;AAC5C"}
|
package/dist/cloudflare.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { s as ITransaction, v as IMessageStore } from "./index-
|
|
3
|
-
import { n as DrizzleSchema, t as eventCollector } from "./unit-of-work-context-
|
|
1
|
+
import { W as DomainEvent, et as D1ConstraintKind, nt as DatabaseFailure, q as MessageId, tt as DatabaseError } from "./index-6XMPJu7u.js";
|
|
2
|
+
import { s as ITransaction, v as IMessageStore } from "./index-_Cihfq1J.js";
|
|
3
|
+
import { n as DrizzleSchema, t as eventCollector } from "./unit-of-work-context-BWTJfYPW.js";
|
|
4
4
|
import { BatchItem } from "drizzle-orm/batch";
|
|
5
5
|
import { AnyD1Database, DrizzleD1Database } from "drizzle-orm/d1";
|
|
6
6
|
//#region src/infrastructure/cloudflare/d1-database-types.d.ts
|
package/dist/cloudflare.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { i as MessageAlreadyProcessedError } from "./application-
|
|
3
|
-
import { i as stageD1Statement, n as eventCollector, r as runWithUnitOfWorkContext, t as collectD1Statements } from "./unit-of-work-context-
|
|
1
|
+
import { E as DatabaseError, U as AppError } from "./core-DC_4pOrI.js";
|
|
2
|
+
import { i as MessageAlreadyProcessedError } from "./application-DYfcAy-Q.js";
|
|
3
|
+
import { i as stageD1Statement, n as eventCollector, r as runWithUnitOfWorkContext, t as collectD1Statements } from "./unit-of-work-context-BFCmU92Z.js";
|
|
4
4
|
import { DrizzleQueryError } from "drizzle-orm/errors";
|
|
5
5
|
import { eq, sql } from "drizzle-orm";
|
|
6
6
|
import { index, integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
|