@web-ts-toolkit/email-service 0.0.0-stage → 0.72.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/LICENSE +201 -0
- package/README.md +446 -2
- package/index.d.mts +206 -0
- package/index.d.ts +206 -0
- package/index.js +4289 -0
- package/index.mjs +4244 -0
- package/mongoose.d.mts +24 -0
- package/mongoose.d.ts +24 -0
- package/mongoose.js +3045 -0
- package/mongoose.mjs +3020 -0
- package/package.json +89 -4
- package/provider-HisBc6hk.d.mts +183 -0
- package/provider-HisBc6hk.d.ts +183 -0
- package/sendgrid.d.mts +18 -0
- package/sendgrid.d.ts +18 -0
- package/sendgrid.js +1437 -0
- package/sendgrid.mjs +1410 -0
- package/smtp.d.mts +28 -0
- package/smtp.d.ts +28 -0
- package/smtp.js +1449 -0
- package/smtp.mjs +1412 -0
- package/store-D4YAI6Rk.d.mts +346 -0
- package/store-Vb63Gocz.d.ts +346 -0
package/index.mjs
ADDED
|
@@ -0,0 +1,4244 @@
|
|
|
1
|
+
// src/errors.ts
|
|
2
|
+
var messages = Object.freeze({
|
|
3
|
+
invalid_config: "Invalid email service configuration.",
|
|
4
|
+
invalid_command: "Invalid email command.",
|
|
5
|
+
invalid_input: "Invalid template input.",
|
|
6
|
+
invalid_data: "Invalid prepared template data.",
|
|
7
|
+
invalid_snapshot: "Invalid prepared email snapshot.",
|
|
8
|
+
preparation_failed: "Email preparation failed.",
|
|
9
|
+
template_not_found: "Email template not found.",
|
|
10
|
+
template_source: "Email template source could not be loaded.",
|
|
11
|
+
template_render: "Email template could not be rendered.",
|
|
12
|
+
provider_mismatch: "Email provider does not match the template or snapshot.",
|
|
13
|
+
expired: "Email has expired.",
|
|
14
|
+
idempotency_conflict: "Email admission key was used with different intent.",
|
|
15
|
+
not_found: "Email job not found.",
|
|
16
|
+
resolution_conflict: "Unknown attempt cannot be resolved with this action.",
|
|
17
|
+
store_capacity: "Email store is at capacity.",
|
|
18
|
+
store_unavailable: "Email store is unavailable.",
|
|
19
|
+
store_incompatible: "Email store does not meet the required guarantees.",
|
|
20
|
+
write_unconfirmed: "Email store write not confirmed; it may have committed.",
|
|
21
|
+
invalid_cursor: "Invalid email activity cursor.",
|
|
22
|
+
aborted: "Email operation was aborted.",
|
|
23
|
+
deadline: "Email operation deadline elapsed.",
|
|
24
|
+
busy: "Email service has no available capacity for this operation.",
|
|
25
|
+
closed: "Email service is closed."
|
|
26
|
+
});
|
|
27
|
+
var EmailError = class extends Error {
|
|
28
|
+
/** `write_unconfirmed` does not mean that a dispatched mutation failed to commit. */
|
|
29
|
+
code;
|
|
30
|
+
constructor(code) {
|
|
31
|
+
const safeCode = typeof code === "string" && Object.hasOwn(messages, code) ? code : "invalid_config";
|
|
32
|
+
super(messages[safeCode]);
|
|
33
|
+
this.name = "EmailError";
|
|
34
|
+
this.code = safeCode;
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
// src/constants.ts
|
|
39
|
+
var KiB = 1024;
|
|
40
|
+
var MiB = 1024 * KiB;
|
|
41
|
+
var DAY_MS = 864e5;
|
|
42
|
+
function bounded(defaultValue, min, max) {
|
|
43
|
+
return Object.freeze({ default: defaultValue, min, max });
|
|
44
|
+
}
|
|
45
|
+
var EMAIL_FORMAT_VERSION = 1;
|
|
46
|
+
var MAX_UNIX_MS = 253402300799999;
|
|
47
|
+
var CLOCK_MARGIN_MS = 1e3;
|
|
48
|
+
var DEFAULT_EXPIRY_MS = DAY_MS;
|
|
49
|
+
var MAX_EXPIRY_MS = 30 * DAY_MS;
|
|
50
|
+
var MAX_PREPARED_AT_SKEW_MS = 6e4;
|
|
51
|
+
var MESSAGE_LIMITS = Object.freeze({
|
|
52
|
+
scopeBytes: 64,
|
|
53
|
+
identifierBytes: 128,
|
|
54
|
+
jsonDepth: 12,
|
|
55
|
+
jsonValues: 2048,
|
|
56
|
+
jsonKeyBytes: 128,
|
|
57
|
+
intentBytes: 16 * KiB,
|
|
58
|
+
dataBytes: 64 * KiB,
|
|
59
|
+
snapshotBytes: MiB,
|
|
60
|
+
recipients: 50,
|
|
61
|
+
addressBytes: 254,
|
|
62
|
+
localPartBytes: 64,
|
|
63
|
+
displayNameBytes: 128,
|
|
64
|
+
subjectBytes: 512,
|
|
65
|
+
templateSourceBytes: 256 * KiB,
|
|
66
|
+
htmlBytes: 512 * KiB,
|
|
67
|
+
textBytes: 256 * KiB,
|
|
68
|
+
correlationEntries: 8,
|
|
69
|
+
correlationKeyBytes: 32,
|
|
70
|
+
correlationValueBytes: 96,
|
|
71
|
+
attachments: 5,
|
|
72
|
+
filenameBytes: 128,
|
|
73
|
+
contentTypeBytes: 127,
|
|
74
|
+
attachmentBytes: 2 * MiB,
|
|
75
|
+
totalAttachmentBytes: 5 * MiB
|
|
76
|
+
});
|
|
77
|
+
var PRIORITY = bounded(0, 0, 9);
|
|
78
|
+
var TEMPLATE_CACHE_ENTRIES = bounded(32, 0, 128);
|
|
79
|
+
var TEMPLATE_MAX_PENDING = bounded(8, 1, 32);
|
|
80
|
+
var MAX_BATCH_ITEMS = 100;
|
|
81
|
+
var CALL_BUDGETS = Object.freeze({
|
|
82
|
+
prepare: bounded(5e3, 50, 3e4),
|
|
83
|
+
admissionOrAdmin: bounded(1e4, 50, 6e4),
|
|
84
|
+
batchOrRun: bounded(3e4, 50, 12e4),
|
|
85
|
+
shutdown: bounded(15e3, 50, 6e4)
|
|
86
|
+
});
|
|
87
|
+
var DEFAULT_RETRY_POLICY = Object.freeze({
|
|
88
|
+
maxAttempts: 3,
|
|
89
|
+
baseDelayMs: 1e3,
|
|
90
|
+
maxDelayMs: 6e4
|
|
91
|
+
});
|
|
92
|
+
var RETRY_POLICY_BOUNDS = Object.freeze({
|
|
93
|
+
maxAttempts: bounded(DEFAULT_RETRY_POLICY.maxAttempts, 1, 10),
|
|
94
|
+
baseDelayMs: bounded(DEFAULT_RETRY_POLICY.baseDelayMs, 100, 6e4),
|
|
95
|
+
// Also require maxDelayMs >= the configured baseDelayMs.
|
|
96
|
+
maxDelayMs: bounded(DEFAULT_RETRY_POLICY.maxDelayMs, 100, 36e5)
|
|
97
|
+
});
|
|
98
|
+
var MAX_MANUAL_ATTEMPTS = 1;
|
|
99
|
+
var MAX_ATTEMPT_LEDGER = RETRY_POLICY_BOUNDS.maxAttempts.max + MAX_MANUAL_ATTEMPTS;
|
|
100
|
+
var MAX_RATE_DEFERRAL_MS = 30 * DAY_MS;
|
|
101
|
+
var DEFAULT_RETENTION_POLICY = Object.freeze({
|
|
102
|
+
payloadMs: 7 * DAY_MS,
|
|
103
|
+
historyMs: 30 * DAY_MS,
|
|
104
|
+
idempotencyMs: 30 * DAY_MS
|
|
105
|
+
});
|
|
106
|
+
var RETENTION_POLICY_BOUNDS = Object.freeze({
|
|
107
|
+
payloadMs: bounded(DEFAULT_RETENTION_POLICY.payloadMs, 0, 30 * DAY_MS),
|
|
108
|
+
historyMs: bounded(DEFAULT_RETENTION_POLICY.historyMs, DAY_MS, 90 * DAY_MS),
|
|
109
|
+
idempotencyMs: bounded(DEFAULT_RETENTION_POLICY.idempotencyMs, DAY_MS, 90 * DAY_MS)
|
|
110
|
+
});
|
|
111
|
+
var DEFAULT_WORKER_LIMITS = Object.freeze({
|
|
112
|
+
maxConcurrency: 4,
|
|
113
|
+
storeTimeoutMs: 5e3,
|
|
114
|
+
leaseMs: 6e4,
|
|
115
|
+
preHandoffTimeoutMs: 8e3,
|
|
116
|
+
attachmentTimeoutMs: 5e3,
|
|
117
|
+
rateTimeoutMs: 500,
|
|
118
|
+
providerTimeoutMs: 15e3,
|
|
119
|
+
finalizeGraceMs: 1e4
|
|
120
|
+
});
|
|
121
|
+
var WORKER_LIMIT_BOUNDS = Object.freeze({
|
|
122
|
+
maxConcurrency: bounded(DEFAULT_WORKER_LIMITS.maxConcurrency, 1, 16),
|
|
123
|
+
storeTimeoutMs: bounded(DEFAULT_WORKER_LIMITS.storeTimeoutMs, 50, 3e4),
|
|
124
|
+
leaseMs: bounded(DEFAULT_WORKER_LIMITS.leaseMs, 5e3, 3e5),
|
|
125
|
+
preHandoffTimeoutMs: bounded(DEFAULT_WORKER_LIMITS.preHandoffTimeoutMs, 50, 6e4),
|
|
126
|
+
attachmentTimeoutMs: bounded(DEFAULT_WORKER_LIMITS.attachmentTimeoutMs, 50, 3e4),
|
|
127
|
+
rateTimeoutMs: bounded(DEFAULT_WORKER_LIMITS.rateTimeoutMs, 10, 5e3),
|
|
128
|
+
providerTimeoutMs: bounded(DEFAULT_WORKER_LIMITS.providerTimeoutMs, 50, 6e4),
|
|
129
|
+
finalizeGraceMs: bounded(DEFAULT_WORKER_LIMITS.finalizeGraceMs, 100, 3e4)
|
|
130
|
+
});
|
|
131
|
+
var RUN_CLAIM_LIMIT = bounded(20, 1, 100);
|
|
132
|
+
var RUN_MAINTENANCE_LIMIT = bounded(10, 0, 100);
|
|
133
|
+
var ACTIVITY_PAGE_LIMIT = bounded(25, 1, 100);
|
|
134
|
+
var MAX_ACTIVITY_CURSOR_BYTES = 512;
|
|
135
|
+
var ADMIN_MAINTENANCE_LIMIT = bounded(20, 1, 100);
|
|
136
|
+
var MAX_OBSERVER_PENDING = 1;
|
|
137
|
+
var PROJECTION_PERMIT_MS = 6e4;
|
|
138
|
+
var PROJECTION_DRAIN_MS = WORKER_LIMIT_BOUNDS.storeTimeoutMs.max + CLOCK_MARGIN_MS;
|
|
139
|
+
var STORE_PRIMITIVE_TIMEOUT_MS = 5e3;
|
|
140
|
+
var MAX_STORE_CANDIDATES = 16;
|
|
141
|
+
var MAX_STORE_CAS_SUBMISSIONS = 3;
|
|
142
|
+
var MEMORY_MAX_JOBS = bounded(256, 1, 4096);
|
|
143
|
+
var MONGOOSE_DEFAULT_NAMES = Object.freeze({
|
|
144
|
+
jobsCollection: "email_jobs",
|
|
145
|
+
activitiesCollection: "email_activities",
|
|
146
|
+
jobsModelName: "EmailJobV1",
|
|
147
|
+
activitiesModelName: "EmailActivityV1"
|
|
148
|
+
});
|
|
149
|
+
var SMTP_DEFAULT_PORTS = Object.freeze({ implicit: 465, starttls: 587 });
|
|
150
|
+
var SENDGRID_REQUEST_MAX_BYTES = 8 * MiB;
|
|
151
|
+
var SENDGRID_RESPONSE_MAX_BYTES = 64 * KiB;
|
|
152
|
+
|
|
153
|
+
// src/internal/budget.ts
|
|
154
|
+
import { addAbortListener as addAbortListener2 } from "events";
|
|
155
|
+
import { performance } from "perf_hooks";
|
|
156
|
+
import { setTimeout as sleep } from "timers/promises";
|
|
157
|
+
import { types as types3 } from "util";
|
|
158
|
+
|
|
159
|
+
// src/internal/callbacks.ts
|
|
160
|
+
import { addAbortListener } from "events";
|
|
161
|
+
import { types as types2 } from "util";
|
|
162
|
+
|
|
163
|
+
// src/internal/validation.ts
|
|
164
|
+
import { Buffer } from "buffer";
|
|
165
|
+
import { types } from "util";
|
|
166
|
+
function invalid(code) {
|
|
167
|
+
throw new EmailError(code);
|
|
168
|
+
}
|
|
169
|
+
function allowedErrorCode(error, allowed) {
|
|
170
|
+
if (typeof error !== "object" || error === null || types.isProxy(error)) return;
|
|
171
|
+
const code = Object.getOwnPropertyDescriptor(error, "code")?.value;
|
|
172
|
+
return allowed.find((candidate) => candidate === code);
|
|
173
|
+
}
|
|
174
|
+
function dataObject(value, code) {
|
|
175
|
+
if (typeof value !== "object" || value === null || types.isProxy(value)) invalid(code);
|
|
176
|
+
return value;
|
|
177
|
+
}
|
|
178
|
+
function isArray(value, code) {
|
|
179
|
+
return Array.isArray(dataObject(value, code));
|
|
180
|
+
}
|
|
181
|
+
function plainKeys(value, maxKeys, code) {
|
|
182
|
+
const object = dataObject(value, code);
|
|
183
|
+
const proto = Object.getPrototypeOf(object);
|
|
184
|
+
if (Array.isArray(object) || proto !== null && proto !== Object.prototype) invalid(code);
|
|
185
|
+
const keys = Reflect.ownKeys(object);
|
|
186
|
+
if (keys.length > maxKeys || keys.some((key) => typeof key !== "string")) invalid(code);
|
|
187
|
+
return keys;
|
|
188
|
+
}
|
|
189
|
+
function ownData(value, key, code) {
|
|
190
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
191
|
+
if (!descriptor?.enumerable || !Object.hasOwn(descriptor, "value")) invalid(code);
|
|
192
|
+
return descriptor.value;
|
|
193
|
+
}
|
|
194
|
+
function readRecord(value, required, optional, code) {
|
|
195
|
+
const keys = plainKeys(value, required.length + optional.length, code);
|
|
196
|
+
const copy = /* @__PURE__ */ Object.create(null);
|
|
197
|
+
for (const key of keys) {
|
|
198
|
+
if (!required.includes(key) && !optional.includes(key)) invalid(code);
|
|
199
|
+
copy[key] = ownData(value, key, code);
|
|
200
|
+
}
|
|
201
|
+
for (const key of required) {
|
|
202
|
+
if (!Object.hasOwn(copy, key)) invalid(code);
|
|
203
|
+
}
|
|
204
|
+
return copy;
|
|
205
|
+
}
|
|
206
|
+
function denseArrayLength(value, maxLength, code) {
|
|
207
|
+
const object = dataObject(value, code);
|
|
208
|
+
if (!Array.isArray(object) || Object.getPrototypeOf(object) !== Array.prototype) invalid(code);
|
|
209
|
+
const { length } = object;
|
|
210
|
+
if (length > maxLength || Reflect.ownKeys(object).length !== length + 1) invalid(code);
|
|
211
|
+
return length;
|
|
212
|
+
}
|
|
213
|
+
function readArray(value, maxLength, code, read) {
|
|
214
|
+
const length = denseArrayLength(value, maxLength, code);
|
|
215
|
+
const copy = [];
|
|
216
|
+
for (let i = 0; i < length; i++) copy.push(read(ownData(value, String(i), code)));
|
|
217
|
+
return Object.freeze(copy);
|
|
218
|
+
}
|
|
219
|
+
function integer(value, min, max, code) {
|
|
220
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < min || value > max) invalid(code);
|
|
221
|
+
return value === 0 ? 0 : value;
|
|
222
|
+
}
|
|
223
|
+
function boundedOption(value, bounds, code = "invalid_config") {
|
|
224
|
+
return value === void 0 ? bounds.default : integer(value, bounds.min, bounds.max, code);
|
|
225
|
+
}
|
|
226
|
+
function unixMs(value, code) {
|
|
227
|
+
return integer(value, 0, MAX_UNIX_MS, code);
|
|
228
|
+
}
|
|
229
|
+
function utf8Length(value, maxBytes, code) {
|
|
230
|
+
if (value.length > maxBytes || /[\uD800-\uDFFF]/u.test(value)) invalid(code);
|
|
231
|
+
const bytes = Buffer.byteLength(value, "utf8");
|
|
232
|
+
if (bytes > maxBytes) invalid(code);
|
|
233
|
+
return bytes;
|
|
234
|
+
}
|
|
235
|
+
function utf8String(value, maxBytes, code) {
|
|
236
|
+
if (typeof value !== "string") invalid(code);
|
|
237
|
+
utf8Length(value, maxBytes, code);
|
|
238
|
+
return value;
|
|
239
|
+
}
|
|
240
|
+
function headerString(value, maxBytes, code) {
|
|
241
|
+
const text = utf8String(value, maxBytes, code);
|
|
242
|
+
for (let i = 0; i < text.length; i++) {
|
|
243
|
+
const ch = text.charCodeAt(i);
|
|
244
|
+
if (ch < 32 || ch === 127) invalid(code);
|
|
245
|
+
}
|
|
246
|
+
return text;
|
|
247
|
+
}
|
|
248
|
+
function opaqueToken(value, maxBytes, code) {
|
|
249
|
+
if (typeof value !== "string" || value.length > maxBytes || !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(value)) {
|
|
250
|
+
invalid(code);
|
|
251
|
+
}
|
|
252
|
+
return value;
|
|
253
|
+
}
|
|
254
|
+
function scopeToken(value, code = "invalid_command") {
|
|
255
|
+
return opaqueToken(value, MESSAGE_LIMITS.scopeBytes, code);
|
|
256
|
+
}
|
|
257
|
+
function identifier(value, code) {
|
|
258
|
+
return opaqueToken(value, MESSAGE_LIMITS.identifierBytes, code);
|
|
259
|
+
}
|
|
260
|
+
function hashToken(value, code) {
|
|
261
|
+
if (typeof value !== "string" || value.length !== 64 || !/^[0-9a-f]{64}$/.test(value)) invalid(code);
|
|
262
|
+
return value;
|
|
263
|
+
}
|
|
264
|
+
function jsonKey(key, code) {
|
|
265
|
+
utf8Length(key, MESSAGE_LIMITS.jsonKeyBytes, code);
|
|
266
|
+
if (key === "__proto__" || key === "prototype" || key === "constructor" || key.includes(".") || key.includes("$") || key.includes("\0")) {
|
|
267
|
+
invalid(code);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// src/internal/callbacks.ts
|
|
272
|
+
var promiseThen = Promise.prototype.then;
|
|
273
|
+
var CallbackSlot = class {
|
|
274
|
+
#pending = 0;
|
|
275
|
+
#closed = false;
|
|
276
|
+
#release;
|
|
277
|
+
constructor(release) {
|
|
278
|
+
this.#release = release;
|
|
279
|
+
}
|
|
280
|
+
get pending() {
|
|
281
|
+
return this.#pending;
|
|
282
|
+
}
|
|
283
|
+
hold(task) {
|
|
284
|
+
const settled = () => {
|
|
285
|
+
this.#pending--;
|
|
286
|
+
if (this.#closed && this.#pending === 0) this.#release();
|
|
287
|
+
};
|
|
288
|
+
void promiseThen.call(task, settled, settled);
|
|
289
|
+
this.#pending++;
|
|
290
|
+
}
|
|
291
|
+
close() {
|
|
292
|
+
if (this.#closed) return;
|
|
293
|
+
this.#closed = true;
|
|
294
|
+
if (this.#pending === 0) this.#release();
|
|
295
|
+
}
|
|
296
|
+
};
|
|
297
|
+
function requireCallback(value, code = "invalid_config") {
|
|
298
|
+
if (typeof value !== "function" || types2.isProxy(value)) invalid(code);
|
|
299
|
+
return value;
|
|
300
|
+
}
|
|
301
|
+
function readPortMember(target, key) {
|
|
302
|
+
if (typeof target !== "object" || target === null) invalid("invalid_config");
|
|
303
|
+
let owner = target;
|
|
304
|
+
while (owner && owner !== Object.prototype) {
|
|
305
|
+
if (types2.isProxy(owner)) invalid("invalid_config");
|
|
306
|
+
const descriptor = Object.getOwnPropertyDescriptor(owner, key);
|
|
307
|
+
if (descriptor) {
|
|
308
|
+
if (!Object.hasOwn(descriptor, "value")) invalid("invalid_config");
|
|
309
|
+
return descriptor.value;
|
|
310
|
+
}
|
|
311
|
+
owner = Object.getPrototypeOf(owner);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
function bindMethod(target, key) {
|
|
315
|
+
const method = requireCallback(readPortMember(target, key));
|
|
316
|
+
return ((...args) => Reflect.apply(method, target, args));
|
|
317
|
+
}
|
|
318
|
+
function dataThen(value) {
|
|
319
|
+
if (value === null || typeof value !== "object" && typeof value !== "function") return void 0;
|
|
320
|
+
let owner = value;
|
|
321
|
+
while (owner && owner !== Object.prototype && !types2.isProxy(owner)) {
|
|
322
|
+
const descriptor = Object.getOwnPropertyDescriptor(owner, "then");
|
|
323
|
+
if (descriptor) return typeof descriptor.value === "function" ? descriptor.value : void 0;
|
|
324
|
+
owner = Object.getPrototypeOf(owner);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
function observeThenable(receiver, then, capture) {
|
|
328
|
+
return new Promise((resolve, reject) => {
|
|
329
|
+
let settled = false;
|
|
330
|
+
const fail = (error) => {
|
|
331
|
+
if (settled) return;
|
|
332
|
+
settled = true;
|
|
333
|
+
reject(error);
|
|
334
|
+
};
|
|
335
|
+
const fulfill = (raw) => {
|
|
336
|
+
if (settled) return;
|
|
337
|
+
settled = true;
|
|
338
|
+
try {
|
|
339
|
+
const result = capture(raw);
|
|
340
|
+
resolve(() => result);
|
|
341
|
+
} catch (error) {
|
|
342
|
+
resolve(() => {
|
|
343
|
+
throw error;
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
};
|
|
347
|
+
try {
|
|
348
|
+
Reflect.apply(then, receiver, [fulfill, fail]);
|
|
349
|
+
} catch (error) {
|
|
350
|
+
fail(error);
|
|
351
|
+
}
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
function pendingCallback(value) {
|
|
355
|
+
if (types2.isPromise(value)) return Promise.resolve(value);
|
|
356
|
+
const then = dataThen(value);
|
|
357
|
+
if (then) return observeThenable(value, then, () => void 0);
|
|
358
|
+
}
|
|
359
|
+
function runSyncCallback(budget, slot, code, invoke) {
|
|
360
|
+
budget.check();
|
|
361
|
+
let value;
|
|
362
|
+
try {
|
|
363
|
+
value = invoke();
|
|
364
|
+
if (types2.isPromise(value)) slot.hold(Promise.resolve(value));
|
|
365
|
+
} catch {
|
|
366
|
+
budget.check();
|
|
367
|
+
return invalid(code);
|
|
368
|
+
}
|
|
369
|
+
budget.check();
|
|
370
|
+
if (types2.isPromise(value)) invalid(code);
|
|
371
|
+
return value;
|
|
372
|
+
}
|
|
373
|
+
async function runHostCallback(budget, slot, code, invoke, accept, knownErrors = []) {
|
|
374
|
+
budget.check();
|
|
375
|
+
const capture = (raw) => {
|
|
376
|
+
budget.check();
|
|
377
|
+
const result = accept(raw);
|
|
378
|
+
budget.check();
|
|
379
|
+
return result;
|
|
380
|
+
};
|
|
381
|
+
let value;
|
|
382
|
+
let task;
|
|
383
|
+
let read = capture;
|
|
384
|
+
try {
|
|
385
|
+
value = invoke();
|
|
386
|
+
if (types2.isPromise(value)) task = Promise.resolve(value);
|
|
387
|
+
else {
|
|
388
|
+
const then = dataThen(value);
|
|
389
|
+
if (then) {
|
|
390
|
+
budget.check();
|
|
391
|
+
task = observeThenable(value, then, capture);
|
|
392
|
+
read = (readCaptured) => readCaptured();
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
if (task) slot.hold(task);
|
|
396
|
+
} catch (error) {
|
|
397
|
+
budget.check();
|
|
398
|
+
return invalid(allowedErrorCode(error, knownErrors) ?? code);
|
|
399
|
+
}
|
|
400
|
+
budget.check();
|
|
401
|
+
if (!task) return capture(value);
|
|
402
|
+
return new Promise((resolve, reject) => {
|
|
403
|
+
const abort = addAbortListener(budget.signal, () => {
|
|
404
|
+
try {
|
|
405
|
+
budget.check();
|
|
406
|
+
} catch (error) {
|
|
407
|
+
reject(error);
|
|
408
|
+
}
|
|
409
|
+
});
|
|
410
|
+
const settle = (receive) => {
|
|
411
|
+
abort[Symbol.dispose]();
|
|
412
|
+
try {
|
|
413
|
+
budget.check();
|
|
414
|
+
resolve(receive());
|
|
415
|
+
} catch (error) {
|
|
416
|
+
reject(error);
|
|
417
|
+
}
|
|
418
|
+
};
|
|
419
|
+
try {
|
|
420
|
+
void promiseThen.call(
|
|
421
|
+
task,
|
|
422
|
+
(result) => settle(() => read(result)),
|
|
423
|
+
(error) => settle(() => invalid(allowedErrorCode(error, knownErrors) ?? code))
|
|
424
|
+
);
|
|
425
|
+
} catch {
|
|
426
|
+
settle(() => invalid(code));
|
|
427
|
+
}
|
|
428
|
+
});
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
// src/internal/budget.ts
|
|
432
|
+
var systemEmailClock = Object.freeze({
|
|
433
|
+
now: Date.now,
|
|
434
|
+
monotonicNow: () => performance.now(),
|
|
435
|
+
sleep: (ms, signal) => sleep(ms, void 0, { signal })
|
|
436
|
+
});
|
|
437
|
+
function readClock(value) {
|
|
438
|
+
if (value === void 0) return systemEmailClock;
|
|
439
|
+
return Object.freeze({
|
|
440
|
+
now: bindMethod(value, "now"),
|
|
441
|
+
monotonicNow: bindMethod(value, "monotonicNow"),
|
|
442
|
+
sleep: bindMethod(value, "sleep")
|
|
443
|
+
});
|
|
444
|
+
}
|
|
445
|
+
function readCallOptions(input, bounds) {
|
|
446
|
+
const code = "invalid_config";
|
|
447
|
+
const { signal, timeoutMs } = readRecord(input, [], ["signal", "timeoutMs"], code);
|
|
448
|
+
const timeout = boundedOption(timeoutMs, bounds, code);
|
|
449
|
+
if (signal === void 0) return { timeoutMs: timeout };
|
|
450
|
+
try {
|
|
451
|
+
if (!types3.isProxy(signal) && signal instanceof AbortSignal && typeof Reflect.get(AbortSignal.prototype, "aborted", signal) === "boolean") {
|
|
452
|
+
return { signal, timeoutMs: timeout };
|
|
453
|
+
}
|
|
454
|
+
} catch {
|
|
455
|
+
invalid(code);
|
|
456
|
+
}
|
|
457
|
+
return invalid(code);
|
|
458
|
+
}
|
|
459
|
+
function monotonicNow(clock) {
|
|
460
|
+
try {
|
|
461
|
+
const now = clock.monotonicNow();
|
|
462
|
+
if (Number.isFinite(now)) return now;
|
|
463
|
+
} catch {
|
|
464
|
+
invalid("invalid_config");
|
|
465
|
+
}
|
|
466
|
+
return invalid("invalid_config");
|
|
467
|
+
}
|
|
468
|
+
function createBudget(clock, timeoutMs, external) {
|
|
469
|
+
return createBudgetUntil(clock, monotonicNow(clock) + timeoutMs, external);
|
|
470
|
+
}
|
|
471
|
+
function createBudgetUntil(clock, end, external) {
|
|
472
|
+
const operation = new AbortController();
|
|
473
|
+
const timer = new AbortController();
|
|
474
|
+
let externalListener;
|
|
475
|
+
let closed = false;
|
|
476
|
+
let reason;
|
|
477
|
+
function close() {
|
|
478
|
+
if (closed) return;
|
|
479
|
+
closed = true;
|
|
480
|
+
externalListener?.[Symbol.dispose]();
|
|
481
|
+
timer.abort();
|
|
482
|
+
}
|
|
483
|
+
function stop(code) {
|
|
484
|
+
if (closed) return;
|
|
485
|
+
reason = code;
|
|
486
|
+
close();
|
|
487
|
+
operation.abort(new EmailError(code));
|
|
488
|
+
}
|
|
489
|
+
function remainingMs() {
|
|
490
|
+
if (closed) return 0;
|
|
491
|
+
if (external?.aborted) {
|
|
492
|
+
stop("aborted");
|
|
493
|
+
} else {
|
|
494
|
+
try {
|
|
495
|
+
const remaining = end - monotonicNow(clock);
|
|
496
|
+
if (remaining > 0) return remaining;
|
|
497
|
+
stop("deadline");
|
|
498
|
+
} catch {
|
|
499
|
+
stop("invalid_config");
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
return 0;
|
|
503
|
+
}
|
|
504
|
+
function arm(remaining) {
|
|
505
|
+
void Promise.resolve(clock.sleep(Math.ceil(remaining), timer.signal)).then(
|
|
506
|
+
() => {
|
|
507
|
+
try {
|
|
508
|
+
const left = remainingMs();
|
|
509
|
+
if (left <= 0) return;
|
|
510
|
+
if (left >= remaining) stop("invalid_config");
|
|
511
|
+
else arm(left);
|
|
512
|
+
} catch {
|
|
513
|
+
stop("invalid_config");
|
|
514
|
+
}
|
|
515
|
+
},
|
|
516
|
+
() => stop("invalid_config")
|
|
517
|
+
);
|
|
518
|
+
}
|
|
519
|
+
try {
|
|
520
|
+
if (external && !external.aborted) externalListener = addAbortListener2(external, () => stop("aborted"));
|
|
521
|
+
const remaining = remainingMs();
|
|
522
|
+
if (remaining > 0) arm(remaining);
|
|
523
|
+
} catch {
|
|
524
|
+
stop("invalid_config");
|
|
525
|
+
}
|
|
526
|
+
return {
|
|
527
|
+
signal: operation.signal,
|
|
528
|
+
deadline: end,
|
|
529
|
+
remainingMs,
|
|
530
|
+
check() {
|
|
531
|
+
remainingMs();
|
|
532
|
+
if (reason) invalid(reason);
|
|
533
|
+
if (closed) invalid("aborted");
|
|
534
|
+
},
|
|
535
|
+
close
|
|
536
|
+
};
|
|
537
|
+
}
|
|
538
|
+
function createChildBudget(clock, parent, maxMs) {
|
|
539
|
+
return createChildBudgetUntil(clock, parent, monotonicNow(clock) + maxMs);
|
|
540
|
+
}
|
|
541
|
+
function createChildBudgetUntil(clock, parent, end, stop) {
|
|
542
|
+
parent.check();
|
|
543
|
+
const signal = stop ? AbortSignal.any([parent.signal, stop]) : parent.signal;
|
|
544
|
+
const child = createBudgetUntil(clock, Math.min(parent.deadline, end), signal);
|
|
545
|
+
return {
|
|
546
|
+
signal: child.signal,
|
|
547
|
+
deadline: child.deadline,
|
|
548
|
+
remainingMs: () => Math.min(parent.remainingMs(), child.remainingMs()),
|
|
549
|
+
check() {
|
|
550
|
+
parent.check();
|
|
551
|
+
child.check();
|
|
552
|
+
},
|
|
553
|
+
close: child.close
|
|
554
|
+
};
|
|
555
|
+
}
|
|
556
|
+
function waitForAbort(signal) {
|
|
557
|
+
if (signal.aborted) return Promise.resolve();
|
|
558
|
+
return new Promise((resolve) => {
|
|
559
|
+
const listener = addAbortListener2(signal, () => {
|
|
560
|
+
listener[Symbol.dispose]();
|
|
561
|
+
resolve();
|
|
562
|
+
});
|
|
563
|
+
});
|
|
564
|
+
}
|
|
565
|
+
function syncStage(budget, code, run) {
|
|
566
|
+
budget.check();
|
|
567
|
+
let result;
|
|
568
|
+
try {
|
|
569
|
+
result = run();
|
|
570
|
+
} catch {
|
|
571
|
+
budget.check();
|
|
572
|
+
return invalid(code);
|
|
573
|
+
}
|
|
574
|
+
budget.check();
|
|
575
|
+
return result;
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
// src/internal/canonical-json.ts
|
|
579
|
+
import { createHash } from "crypto";
|
|
580
|
+
var treeLimits = { depth: MESSAGE_LIMITS.jsonDepth, values: MESSAGE_LIMITS.jsonValues };
|
|
581
|
+
function canonicalJson(input, maxBytes, code = "invalid_snapshot", limits = treeLimits) {
|
|
582
|
+
let bytesLeft = maxBytes;
|
|
583
|
+
let valuesLeft = limits.values;
|
|
584
|
+
const chunks = [];
|
|
585
|
+
const ancestors = /* @__PURE__ */ new Set();
|
|
586
|
+
function append(text, bytes = text.length) {
|
|
587
|
+
if (bytes > bytesLeft) invalid(code);
|
|
588
|
+
bytesLeft -= bytes;
|
|
589
|
+
chunks.push(text);
|
|
590
|
+
}
|
|
591
|
+
function appendString(text) {
|
|
592
|
+
let bytes = 2 + utf8Length(text, bytesLeft - 2, code);
|
|
593
|
+
for (let i = 0; i < text.length; i++) {
|
|
594
|
+
const ch = text.charCodeAt(i);
|
|
595
|
+
if (ch === 34 || ch === 92 || ch === 8 || ch === 9 || ch === 10 || ch === 12 || ch === 13) bytes++;
|
|
596
|
+
else if (ch < 32) bytes += 5;
|
|
597
|
+
if (bytes > bytesLeft) invalid(code);
|
|
598
|
+
}
|
|
599
|
+
append(JSON.stringify(text), bytes);
|
|
600
|
+
}
|
|
601
|
+
function visit(value2, depth) {
|
|
602
|
+
if (depth > limits.depth || --valuesLeft < 0 || bytesLeft < 1) invalid(code);
|
|
603
|
+
switch (typeof value2) {
|
|
604
|
+
case "string":
|
|
605
|
+
appendString(value2);
|
|
606
|
+
return value2;
|
|
607
|
+
case "number":
|
|
608
|
+
if (!Number.isFinite(value2) || Number.isInteger(value2) && !Number.isSafeInteger(value2)) invalid(code);
|
|
609
|
+
append(JSON.stringify(value2));
|
|
610
|
+
return value2 === 0 ? 0 : value2;
|
|
611
|
+
case "boolean":
|
|
612
|
+
append(value2 ? "true" : "false");
|
|
613
|
+
return value2;
|
|
614
|
+
case "object":
|
|
615
|
+
if (value2 === null) {
|
|
616
|
+
append("null");
|
|
617
|
+
return null;
|
|
618
|
+
}
|
|
619
|
+
break;
|
|
620
|
+
default:
|
|
621
|
+
invalid(code);
|
|
622
|
+
}
|
|
623
|
+
if (ancestors.has(value2)) invalid(code);
|
|
624
|
+
ancestors.add(value2);
|
|
625
|
+
try {
|
|
626
|
+
const maxChildren = depth === limits.depth ? 0 : valuesLeft;
|
|
627
|
+
if (isArray(value2, code)) {
|
|
628
|
+
const length = denseArrayLength(value2, maxChildren, code);
|
|
629
|
+
if (length && 2 * length + 1 > bytesLeft) invalid(code);
|
|
630
|
+
const copy2 = [];
|
|
631
|
+
append("[");
|
|
632
|
+
for (let i = 0; i < length; i++) {
|
|
633
|
+
if (i) append(",");
|
|
634
|
+
copy2.push(visit(ownData(value2, String(i), code), depth + 1));
|
|
635
|
+
}
|
|
636
|
+
append("]");
|
|
637
|
+
return Object.freeze(copy2);
|
|
638
|
+
}
|
|
639
|
+
const keys = plainKeys(value2, maxChildren, code);
|
|
640
|
+
if (keys.length && 5 * keys.length + 1 > bytesLeft) invalid(code);
|
|
641
|
+
for (const key of keys) jsonKey(key, code);
|
|
642
|
+
const copy = /* @__PURE__ */ Object.create(null);
|
|
643
|
+
append("{");
|
|
644
|
+
for (const [index, key] of keys.sort().entries()) {
|
|
645
|
+
if (index) append(",");
|
|
646
|
+
appendString(key);
|
|
647
|
+
append(":");
|
|
648
|
+
copy[key] = visit(ownData(value2, key, code), depth + 1);
|
|
649
|
+
}
|
|
650
|
+
append("}");
|
|
651
|
+
return Object.freeze(copy);
|
|
652
|
+
} finally {
|
|
653
|
+
ancestors.delete(value2);
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
const value = visit(input, 0);
|
|
657
|
+
return { value, encoded: chunks.join("") };
|
|
658
|
+
}
|
|
659
|
+
function copyJsonObject(input, maxBytes, code) {
|
|
660
|
+
if (typeof input !== "object" || input === null || isArray(input, code)) invalid(code);
|
|
661
|
+
return canonicalJson(input, maxBytes, code).value;
|
|
662
|
+
}
|
|
663
|
+
function sha256(input) {
|
|
664
|
+
return createHash("sha256").update(input).digest("hex");
|
|
665
|
+
}
|
|
666
|
+
function hashJson(input, maxBytes, code = "invalid_snapshot") {
|
|
667
|
+
return sha256(canonicalJson(input, maxBytes, code).encoded);
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
// src/internal/message-codecs.ts
|
|
671
|
+
import { isIP } from "net";
|
|
672
|
+
import { types as types4 } from "util";
|
|
673
|
+
var L = MESSAGE_LIMITS;
|
|
674
|
+
var SNAPSHOT = "invalid_snapshot";
|
|
675
|
+
var DOT_ATOM = /^[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*$/;
|
|
676
|
+
var DNS_LABEL = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/;
|
|
677
|
+
var MIME_TYPE = /^[-a-z0-9!#$%&'*+.^_`{|}~]+\/[-a-z0-9!#$%&'*+.^_`{|}~]+$/;
|
|
678
|
+
function validateProviderRef(input, code = SNAPSHOT) {
|
|
679
|
+
const { kind, key, mode } = readRecord(input, ["kind", "key", "mode"], [], code);
|
|
680
|
+
const profile = identifier(key, code);
|
|
681
|
+
if (kind === "smtp" && mode === "live") return Object.freeze({ kind, key: profile, mode });
|
|
682
|
+
if (kind === "sendgrid" && (mode === "live" || mode === "sandbox")) {
|
|
683
|
+
return Object.freeze({ kind, key: profile, mode });
|
|
684
|
+
}
|
|
685
|
+
return invalid(code);
|
|
686
|
+
}
|
|
687
|
+
function validateTemplateIdentity(input, code = SNAPSHOT) {
|
|
688
|
+
const { key, revision } = readRecord(input, ["key", "revision"], [], code);
|
|
689
|
+
return Object.freeze({ key: identifier(key, code), revision: identifier(revision, code) });
|
|
690
|
+
}
|
|
691
|
+
function sendGridTemplateId(input, code = SNAPSHOT) {
|
|
692
|
+
if (typeof input !== "string" || input.length !== 34 || !/^d-[0-9a-fA-F]{32}$/.test(input)) invalid(code);
|
|
693
|
+
return input;
|
|
694
|
+
}
|
|
695
|
+
function validateMailbox(input, code = SNAPSHOT) {
|
|
696
|
+
const mailbox = readRecord(input, ["address"], ["name"], code);
|
|
697
|
+
const address = headerString(mailbox.address, L.addressBytes, code);
|
|
698
|
+
const at = address.indexOf("@");
|
|
699
|
+
const local = address.slice(0, at);
|
|
700
|
+
const domain = address.slice(at + 1);
|
|
701
|
+
if (at < 1 || at > L.localPartBytes || !DOT_ATOM.test(local) || !domain.split(".").every((label) => DNS_LABEL.test(label)) || isIP(domain) !== 0) {
|
|
702
|
+
invalid(code);
|
|
703
|
+
}
|
|
704
|
+
return Object.freeze({
|
|
705
|
+
address,
|
|
706
|
+
...Object.hasOwn(mailbox, "name") ? { name: headerString(mailbox.name, L.displayNameBytes, code) } : {}
|
|
707
|
+
});
|
|
708
|
+
}
|
|
709
|
+
function validateEnvelope(input, kind, code = SNAPSHOT) {
|
|
710
|
+
const envelope = readRecord(input, ["from", "to", "cc", "bcc"], ["replyTo"], code);
|
|
711
|
+
const seen = /* @__PURE__ */ new Set();
|
|
712
|
+
const recipient = (raw) => {
|
|
713
|
+
const mailbox = validateMailbox(raw, code);
|
|
714
|
+
const address = mailbox.address.toLowerCase();
|
|
715
|
+
if (seen.has(address)) invalid(code);
|
|
716
|
+
seen.add(address);
|
|
717
|
+
return mailbox;
|
|
718
|
+
};
|
|
719
|
+
const from = validateMailbox(envelope.from, code);
|
|
720
|
+
const to = readArray(envelope.to, L.recipients, code, recipient);
|
|
721
|
+
const cc = readArray(envelope.cc, L.recipients - to.length, code, recipient);
|
|
722
|
+
const bcc = readArray(envelope.bcc, L.recipients - to.length - cc.length, code, recipient);
|
|
723
|
+
if (seen.size === 0 || kind === "sendgrid" && to.length === 0) invalid(code);
|
|
724
|
+
return Object.freeze({
|
|
725
|
+
from,
|
|
726
|
+
to,
|
|
727
|
+
cc,
|
|
728
|
+
bcc,
|
|
729
|
+
...Object.hasOwn(envelope, "replyTo") ? { replyTo: validateMailbox(envelope.replyTo, code) } : {}
|
|
730
|
+
});
|
|
731
|
+
}
|
|
732
|
+
function validateCorrelation(input, code = SNAPSHOT) {
|
|
733
|
+
const keys = plainKeys(input, L.correlationEntries, code);
|
|
734
|
+
const copy = /* @__PURE__ */ Object.create(null);
|
|
735
|
+
for (const key of keys) {
|
|
736
|
+
jsonKey(key, code);
|
|
737
|
+
opaqueToken(key, L.correlationKeyBytes, code);
|
|
738
|
+
copy[key] = opaqueToken(ownData(input, key, code), L.correlationValueBytes, code);
|
|
739
|
+
}
|
|
740
|
+
return Object.freeze(copy);
|
|
741
|
+
}
|
|
742
|
+
function validateAttachmentRef(input, code = SNAPSHOT) {
|
|
743
|
+
const ref = readRecord(
|
|
744
|
+
input,
|
|
745
|
+
["resolverKey", "id", "version", "filename", "contentType", "byteLength", "sha256"],
|
|
746
|
+
[],
|
|
747
|
+
code
|
|
748
|
+
);
|
|
749
|
+
const filename = headerString(ref.filename, L.filenameBytes, code);
|
|
750
|
+
if (!filename || filename === "." || filename === ".." || /[/\\:]/.test(filename)) invalid(code);
|
|
751
|
+
const contentType = headerString(ref.contentType, L.contentTypeBytes, code);
|
|
752
|
+
if (!MIME_TYPE.test(contentType)) invalid(code);
|
|
753
|
+
return Object.freeze({
|
|
754
|
+
resolverKey: identifier(ref.resolverKey, code),
|
|
755
|
+
id: identifier(ref.id, code),
|
|
756
|
+
version: identifier(ref.version, code),
|
|
757
|
+
filename,
|
|
758
|
+
contentType,
|
|
759
|
+
byteLength: integer(ref.byteLength, 1, L.attachmentBytes, code),
|
|
760
|
+
sha256: hashToken(ref.sha256, code)
|
|
761
|
+
});
|
|
762
|
+
}
|
|
763
|
+
function validateAttachmentRefs(input, code = SNAPSHOT) {
|
|
764
|
+
let total = 0;
|
|
765
|
+
return readArray(input, L.attachments, code, (raw) => {
|
|
766
|
+
const ref = validateAttachmentRef(raw, code);
|
|
767
|
+
total += ref.byteLength;
|
|
768
|
+
if (total > L.totalAttachmentBytes) invalid(code);
|
|
769
|
+
return ref;
|
|
770
|
+
});
|
|
771
|
+
}
|
|
772
|
+
function copyAttachmentBytes(ref, input, code = SNAPSHOT) {
|
|
773
|
+
if (!types4.isUint8Array(input)) invalid(code);
|
|
774
|
+
const typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);
|
|
775
|
+
const buffer = Reflect.get(typedArrayPrototype, "buffer", input);
|
|
776
|
+
const offset = Reflect.get(typedArrayPrototype, "byteOffset", input);
|
|
777
|
+
const length = Reflect.get(typedArrayPrototype, "byteLength", input);
|
|
778
|
+
if (types4.isSharedArrayBuffer(buffer) || length !== ref.byteLength || length < 1 || length > L.attachmentBytes) {
|
|
779
|
+
invalid(code);
|
|
780
|
+
}
|
|
781
|
+
const bytes = new Uint8Array(new Uint8Array(buffer, offset, length));
|
|
782
|
+
if (sha256(bytes) !== ref.sha256) invalid(code);
|
|
783
|
+
return bytes;
|
|
784
|
+
}
|
|
785
|
+
function validateSubject(input, code = SNAPSHOT) {
|
|
786
|
+
const subject = headerString(input, L.subjectBytes, code);
|
|
787
|
+
if (!subject.trim()) invalid(code);
|
|
788
|
+
return subject;
|
|
789
|
+
}
|
|
790
|
+
function smtpParts(subject, html, text, code) {
|
|
791
|
+
if (!html && !text) invalid(code);
|
|
792
|
+
return Object.freeze({ subject, ...html === void 0 ? {} : { html }, ...text === void 0 ? {} : { text } });
|
|
793
|
+
}
|
|
794
|
+
function validateSmtpContent(input, code = SNAPSHOT) {
|
|
795
|
+
const content = readRecord(input, ["subject"], ["html", "text"], code);
|
|
796
|
+
return smtpParts(
|
|
797
|
+
validateSubject(content.subject, code),
|
|
798
|
+
Object.hasOwn(content, "html") ? utf8String(content.html, L.htmlBytes, code) : void 0,
|
|
799
|
+
Object.hasOwn(content, "text") ? utf8String(content.text, L.textBytes, code) : void 0,
|
|
800
|
+
code
|
|
801
|
+
);
|
|
802
|
+
}
|
|
803
|
+
function validateExpiry(input, preparedAt, scheduleAt, code = SNAPSHOT) {
|
|
804
|
+
const expiresAt = unixMs(input, code);
|
|
805
|
+
if (expiresAt <= preparedAt || expiresAt - preparedAt > MAX_EXPIRY_MS || scheduleAt !== null && scheduleAt >= expiresAt) {
|
|
806
|
+
invalid(code);
|
|
807
|
+
}
|
|
808
|
+
return expiresAt;
|
|
809
|
+
}
|
|
810
|
+
function hashSnapshot(snapshot) {
|
|
811
|
+
return sha256(
|
|
812
|
+
canonicalJson(snapshot, L.snapshotBytes, SNAPSHOT, { depth: L.jsonDepth + 1, values: L.jsonValues + 256 }).encoded
|
|
813
|
+
);
|
|
814
|
+
}
|
|
815
|
+
function readSnapshot(input) {
|
|
816
|
+
const dto = readRecord(
|
|
817
|
+
input,
|
|
818
|
+
[
|
|
819
|
+
"version",
|
|
820
|
+
"kind",
|
|
821
|
+
"provider",
|
|
822
|
+
"template",
|
|
823
|
+
"envelope",
|
|
824
|
+
"preparedAt",
|
|
825
|
+
"expiresAt",
|
|
826
|
+
"priority",
|
|
827
|
+
"attachments",
|
|
828
|
+
"correlation"
|
|
829
|
+
],
|
|
830
|
+
["subject", "html", "text", "templateId", "data"],
|
|
831
|
+
SNAPSHOT
|
|
832
|
+
);
|
|
833
|
+
if (dto.version !== EMAIL_FORMAT_VERSION || dto.kind !== "smtp" && dto.kind !== "sendgrid") invalid(SNAPSHOT);
|
|
834
|
+
const provider = validateProviderRef(dto.provider);
|
|
835
|
+
if (provider.kind !== dto.kind) invalid("provider_mismatch");
|
|
836
|
+
const preparedAt = unixMs(dto.preparedAt, SNAPSHOT);
|
|
837
|
+
const common = {
|
|
838
|
+
version: EMAIL_FORMAT_VERSION,
|
|
839
|
+
template: validateTemplateIdentity(dto.template),
|
|
840
|
+
envelope: validateEnvelope(dto.envelope, provider.kind),
|
|
841
|
+
preparedAt,
|
|
842
|
+
expiresAt: validateExpiry(dto.expiresAt, preparedAt, null),
|
|
843
|
+
priority: integer(dto.priority, PRIORITY.min, PRIORITY.max, SNAPSHOT),
|
|
844
|
+
attachments: validateAttachmentRefs(dto.attachments),
|
|
845
|
+
correlation: validateCorrelation(dto.correlation)
|
|
846
|
+
};
|
|
847
|
+
if (provider.kind === "smtp") {
|
|
848
|
+
if (Object.hasOwn(dto, "templateId") || Object.hasOwn(dto, "data")) invalid(SNAPSHOT);
|
|
849
|
+
const content = validateSmtpContent({
|
|
850
|
+
subject: dto.subject,
|
|
851
|
+
...Object.hasOwn(dto, "html") ? { html: dto.html } : {},
|
|
852
|
+
...Object.hasOwn(dto, "text") ? { text: dto.text } : {}
|
|
853
|
+
});
|
|
854
|
+
return Object.freeze({ ...common, kind: provider.kind, provider, ...content });
|
|
855
|
+
}
|
|
856
|
+
if (Object.hasOwn(dto, "subject") || Object.hasOwn(dto, "html") || Object.hasOwn(dto, "text")) invalid(SNAPSHOT);
|
|
857
|
+
return Object.freeze({
|
|
858
|
+
...common,
|
|
859
|
+
kind: provider.kind,
|
|
860
|
+
provider,
|
|
861
|
+
templateId: sendGridTemplateId(dto.templateId),
|
|
862
|
+
data: copyJsonObject(dto.data, L.dataBytes, SNAPSHOT)
|
|
863
|
+
});
|
|
864
|
+
}
|
|
865
|
+
function validateSnapshot(input) {
|
|
866
|
+
const snapshot = readSnapshot(input);
|
|
867
|
+
return { snapshot, snapshotHash: hashSnapshot(snapshot) };
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
// src/internal/command-codecs.ts
|
|
871
|
+
function validateAdmissionKey(input, code = "invalid_command") {
|
|
872
|
+
const key = readRecord(input, ["kind"], ["idempotencyKey", "batchId", "itemId"], code);
|
|
873
|
+
if (key.kind === "single" && !Object.hasOwn(key, "batchId") && !Object.hasOwn(key, "itemId")) {
|
|
874
|
+
return Object.freeze({ kind: key.kind, idempotencyKey: identifier(key.idempotencyKey, code) });
|
|
875
|
+
}
|
|
876
|
+
if (key.kind === "batch" && !Object.hasOwn(key, "idempotencyKey")) {
|
|
877
|
+
return Object.freeze({
|
|
878
|
+
kind: key.kind,
|
|
879
|
+
batchId: identifier(key.batchId, code),
|
|
880
|
+
itemId: identifier(key.itemId, code)
|
|
881
|
+
});
|
|
882
|
+
}
|
|
883
|
+
return invalid(code);
|
|
884
|
+
}
|
|
885
|
+
function encodeAdmissionKey(key) {
|
|
886
|
+
return key.kind === "single" ? `s:${key.idempotencyKey}` : `b:${key.batchId}:${key.itemId}`;
|
|
887
|
+
}
|
|
888
|
+
function sameCommandMetadata(key, templateKey, provider, scheduleAt, expected) {
|
|
889
|
+
return encodeAdmissionKey(key) === encodeAdmissionKey(expected.key) && templateKey === expected.templateKey && provider.kind === expected.provider.kind && provider.key === expected.provider.key && provider.mode === expected.provider.mode && scheduleAt === expected.scheduleAt;
|
|
890
|
+
}
|
|
891
|
+
function fingerprintFor(identity) {
|
|
892
|
+
const { scope, key, templateKey, provider, scheduleAt, intentHash } = identity;
|
|
893
|
+
return hashJson(
|
|
894
|
+
[EMAIL_FORMAT_VERSION, scope, key, templateKey, provider, scheduleAt, intentHash],
|
|
895
|
+
MESSAGE_LIMITS.intentBytes
|
|
896
|
+
);
|
|
897
|
+
}
|
|
898
|
+
function parseCommandIdentity(scope, command) {
|
|
899
|
+
const code = "invalid_command";
|
|
900
|
+
const parsedScope = scopeToken(scope, code);
|
|
901
|
+
const raw = readRecord(command, ["key", "templateKey", "input", "provider", "intent"], ["scheduleAt"], code);
|
|
902
|
+
const key = validateAdmissionKey(raw.key, code);
|
|
903
|
+
const templateKey = identifier(raw.templateKey, code);
|
|
904
|
+
const provider = validateProviderRef(raw.provider, code);
|
|
905
|
+
const scheduleAt = raw.scheduleAt === void 0 ? null : unixMs(raw.scheduleAt, code);
|
|
906
|
+
const intent = canonicalJson(raw.intent, MESSAGE_LIMITS.intentBytes, code);
|
|
907
|
+
const identity = { scope: parsedScope, key, templateKey, provider, scheduleAt, intentHash: sha256(intent.encoded) };
|
|
908
|
+
return Object.freeze({
|
|
909
|
+
identity: Object.freeze({ ...identity, fingerprint: fingerprintFor(identity) }),
|
|
910
|
+
command: Object.freeze({
|
|
911
|
+
key,
|
|
912
|
+
templateKey,
|
|
913
|
+
provider,
|
|
914
|
+
input: raw.input,
|
|
915
|
+
intent: intent.value,
|
|
916
|
+
...scheduleAt === null ? {} : { scheduleAt }
|
|
917
|
+
})
|
|
918
|
+
});
|
|
919
|
+
}
|
|
920
|
+
function validatePreparedCommand(scope, input) {
|
|
921
|
+
const expectedScope = scopeToken(scope);
|
|
922
|
+
const code = "invalid_snapshot";
|
|
923
|
+
const dto = readRecord(
|
|
924
|
+
input,
|
|
925
|
+
["version", "scope", "key", "scheduleAt", "intentHash", "fingerprint", "snapshotHash", "snapshot"],
|
|
926
|
+
[],
|
|
927
|
+
code
|
|
928
|
+
);
|
|
929
|
+
if (dto.version !== EMAIL_FORMAT_VERSION || scopeToken(dto.scope, code) !== expectedScope) invalid(code);
|
|
930
|
+
const key = validateAdmissionKey(dto.key, code);
|
|
931
|
+
const scheduleAt = dto.scheduleAt === null ? null : unixMs(dto.scheduleAt, code);
|
|
932
|
+
const intentHash = hashToken(dto.intentHash, code);
|
|
933
|
+
const fingerprint = hashToken(dto.fingerprint, code);
|
|
934
|
+
const storedSnapshotHash = hashToken(dto.snapshotHash, code);
|
|
935
|
+
const { snapshot, snapshotHash } = validateSnapshot(dto.snapshot);
|
|
936
|
+
validateExpiry(snapshot.expiresAt, snapshot.preparedAt, scheduleAt);
|
|
937
|
+
if (snapshotHash !== storedSnapshotHash || fingerprint !== fingerprintFor({
|
|
938
|
+
scope: expectedScope,
|
|
939
|
+
key,
|
|
940
|
+
templateKey: snapshot.template.key,
|
|
941
|
+
provider: snapshot.provider,
|
|
942
|
+
scheduleAt,
|
|
943
|
+
intentHash
|
|
944
|
+
})) {
|
|
945
|
+
invalid(code);
|
|
946
|
+
}
|
|
947
|
+
return Object.freeze({
|
|
948
|
+
version: EMAIL_FORMAT_VERSION,
|
|
949
|
+
scope: expectedScope,
|
|
950
|
+
key,
|
|
951
|
+
scheduleAt,
|
|
952
|
+
intentHash,
|
|
953
|
+
fingerprint,
|
|
954
|
+
snapshotHash,
|
|
955
|
+
snapshot
|
|
956
|
+
});
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
// src/templates/local-sources.ts
|
|
960
|
+
import { Buffer as Buffer2 } from "buffer";
|
|
961
|
+
import { addAbortListener as addAbortListener3 } from "events";
|
|
962
|
+
import { constants } from "fs";
|
|
963
|
+
import { open } from "fs/promises";
|
|
964
|
+
import { TextDecoder } from "util";
|
|
965
|
+
var LIMIT = MESSAGE_LIMITS.templateSourceBytes;
|
|
966
|
+
var SOURCE_ERROR = "template_source";
|
|
967
|
+
function readSourceConfig(input) {
|
|
968
|
+
const code = "invalid_config";
|
|
969
|
+
const source = readRecord(input, ["kind"], ["content", "path", "load"], code);
|
|
970
|
+
if (Object.keys(source).length !== 2) invalid(code);
|
|
971
|
+
if (source.kind === "inline" && typeof source.content === "string") {
|
|
972
|
+
return Object.freeze({ kind: source.kind, content: source.content });
|
|
973
|
+
}
|
|
974
|
+
if (source.kind === "file" && typeof source.path === "string" && source.path && !source.path.includes("\0")) {
|
|
975
|
+
return Object.freeze({ kind: source.kind, path: source.path });
|
|
976
|
+
}
|
|
977
|
+
if (source.kind === "async") {
|
|
978
|
+
const load = requireCallback(source.load);
|
|
979
|
+
return Object.freeze({ kind: source.kind, load });
|
|
980
|
+
}
|
|
981
|
+
return invalid(code);
|
|
982
|
+
}
|
|
983
|
+
async function readFileSource(path, budget) {
|
|
984
|
+
const file = await open(path, constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOCTTY);
|
|
985
|
+
let closing;
|
|
986
|
+
const close = () => {
|
|
987
|
+
if (!closing) {
|
|
988
|
+
closing = Promise.resolve().then(() => file.close());
|
|
989
|
+
void closing.catch(() => void 0);
|
|
990
|
+
}
|
|
991
|
+
return closing;
|
|
992
|
+
};
|
|
993
|
+
const abort = addAbortListener3(budget.signal, () => {
|
|
994
|
+
void close();
|
|
995
|
+
});
|
|
996
|
+
try {
|
|
997
|
+
budget.check();
|
|
998
|
+
const info = await file.stat();
|
|
999
|
+
budget.check();
|
|
1000
|
+
if (!info.isFile() || info.size > LIMIT) invalid(SOURCE_ERROR);
|
|
1001
|
+
const buffer = Buffer2.allocUnsafe(LIMIT + 1);
|
|
1002
|
+
let length = 0;
|
|
1003
|
+
while (length < buffer.length) {
|
|
1004
|
+
const { bytesRead } = await file.read(buffer, length, buffer.length - length, null);
|
|
1005
|
+
budget.check();
|
|
1006
|
+
if (bytesRead === 0) break;
|
|
1007
|
+
length += bytesRead;
|
|
1008
|
+
}
|
|
1009
|
+
if (length > LIMIT) invalid(SOURCE_ERROR);
|
|
1010
|
+
return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(buffer.subarray(0, length));
|
|
1011
|
+
} finally {
|
|
1012
|
+
abort[Symbol.dispose]();
|
|
1013
|
+
await close();
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1016
|
+
async function loadLocalSource(source, budget, slot) {
|
|
1017
|
+
budget.check();
|
|
1018
|
+
if (source.kind === "inline")
|
|
1019
|
+
return syncStage(budget, SOURCE_ERROR, () => utf8String(source.content, LIMIT, SOURCE_ERROR));
|
|
1020
|
+
if (source.kind === "async") {
|
|
1021
|
+
const { load } = source;
|
|
1022
|
+
return runHostCallback(
|
|
1023
|
+
budget,
|
|
1024
|
+
slot,
|
|
1025
|
+
SOURCE_ERROR,
|
|
1026
|
+
() => load({ signal: budget.signal }),
|
|
1027
|
+
(result) => utf8String(result, LIMIT, SOURCE_ERROR)
|
|
1028
|
+
);
|
|
1029
|
+
}
|
|
1030
|
+
try {
|
|
1031
|
+
const content = await readFileSource(source.path, budget);
|
|
1032
|
+
budget.check();
|
|
1033
|
+
return content;
|
|
1034
|
+
} catch {
|
|
1035
|
+
budget.check();
|
|
1036
|
+
return invalid(SOURCE_ERROR);
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
// src/templates/local-renderer.ts
|
|
1041
|
+
var RENDER_ERROR = "template_render";
|
|
1042
|
+
function createLocalRenderer(cacheEntries, rawHelpers) {
|
|
1043
|
+
const code = "invalid_config";
|
|
1044
|
+
const helpers = /* @__PURE__ */ new Map();
|
|
1045
|
+
if (rawHelpers !== void 0) {
|
|
1046
|
+
for (const key of plainKeys(rawHelpers, Infinity, code)) {
|
|
1047
|
+
if (!key || ["__proto__", "prototype", "constructor", "helperMissing", "blockHelperMissing"].includes(key)) {
|
|
1048
|
+
invalid(code);
|
|
1049
|
+
}
|
|
1050
|
+
helpers.set(key, requireCallback(ownData(rawHelpers, key, code)));
|
|
1051
|
+
}
|
|
1052
|
+
}
|
|
1053
|
+
const cache = /* @__PURE__ */ new Map();
|
|
1054
|
+
const loading = /* @__PURE__ */ new Set();
|
|
1055
|
+
let environment;
|
|
1056
|
+
let renderFrame;
|
|
1057
|
+
async function getEnvironment(budget) {
|
|
1058
|
+
budget.check();
|
|
1059
|
+
if (environment) return environment;
|
|
1060
|
+
try {
|
|
1061
|
+
const { default: Handlebars } = await import("handlebars/dist/cjs/handlebars.js");
|
|
1062
|
+
return syncStage(budget, RENDER_ERROR, () => {
|
|
1063
|
+
if (environment) return environment;
|
|
1064
|
+
const instance = Handlebars.create();
|
|
1065
|
+
instance.unregisterHelper("log");
|
|
1066
|
+
for (const [key, helper] of helpers) {
|
|
1067
|
+
instance.registerHelper(key, function(...args) {
|
|
1068
|
+
const frame = renderFrame;
|
|
1069
|
+
if (!frame) invalid(RENDER_ERROR);
|
|
1070
|
+
return runSyncCallback(frame.budget, frame.slot, RENDER_ERROR, () => Reflect.apply(helper, this, args));
|
|
1071
|
+
});
|
|
1072
|
+
}
|
|
1073
|
+
environment = instance;
|
|
1074
|
+
return instance;
|
|
1075
|
+
});
|
|
1076
|
+
} catch {
|
|
1077
|
+
budget.check();
|
|
1078
|
+
return invalid(RENDER_ERROR);
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
function compile(engine, source, noEscape) {
|
|
1082
|
+
const delegate = engine.compile(source, { strict: true, noEscape });
|
|
1083
|
+
return (values) => delegate(values, { allowProtoMethodsByDefault: false, allowProtoPropertiesByDefault: false });
|
|
1084
|
+
}
|
|
1085
|
+
function renderParts({ subject, html, text }, values, budget, slot) {
|
|
1086
|
+
const previous = renderFrame;
|
|
1087
|
+
renderFrame = { budget, slot };
|
|
1088
|
+
try {
|
|
1089
|
+
return smtpParts(
|
|
1090
|
+
syncStage(budget, RENDER_ERROR, () => validateSubject(subject(values), RENDER_ERROR)),
|
|
1091
|
+
html ? syncStage(budget, RENDER_ERROR, () => utf8String(html(values), MESSAGE_LIMITS.htmlBytes, RENDER_ERROR)) : void 0,
|
|
1092
|
+
text ? syncStage(budget, RENDER_ERROR, () => utf8String(text(values), MESSAGE_LIMITS.textBytes, RENDER_ERROR)) : void 0,
|
|
1093
|
+
RENDER_ERROR
|
|
1094
|
+
);
|
|
1095
|
+
} finally {
|
|
1096
|
+
renderFrame = previous;
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
return {
|
|
1100
|
+
invalidate(key) {
|
|
1101
|
+
if (key === void 0) cache.clear();
|
|
1102
|
+
else cache.delete(key);
|
|
1103
|
+
for (const entry of loading) {
|
|
1104
|
+
if (key === void 0 || key === entry.key) entry.valid = false;
|
|
1105
|
+
}
|
|
1106
|
+
},
|
|
1107
|
+
async render(key, sources, values, budget, slot) {
|
|
1108
|
+
budget.check();
|
|
1109
|
+
const hit = cache.get(key);
|
|
1110
|
+
if (hit) {
|
|
1111
|
+
cache.delete(key);
|
|
1112
|
+
cache.set(key, hit);
|
|
1113
|
+
return renderParts(hit, values, budget, slot);
|
|
1114
|
+
}
|
|
1115
|
+
const entry = { key, valid: true };
|
|
1116
|
+
loading.add(entry);
|
|
1117
|
+
try {
|
|
1118
|
+
const subject = await loadLocalSource(sources.subject, budget, slot);
|
|
1119
|
+
const html = sources.html ? await loadLocalSource(sources.html, budget, slot) : void 0;
|
|
1120
|
+
const text = sources.text ? await loadLocalSource(sources.text, budget, slot) : void 0;
|
|
1121
|
+
const engine = await getEnvironment(budget);
|
|
1122
|
+
const compiled = syncStage(budget, RENDER_ERROR, () => ({
|
|
1123
|
+
subject: compile(engine, subject, true),
|
|
1124
|
+
...html === void 0 ? {} : { html: compile(engine, html, false) },
|
|
1125
|
+
...text === void 0 ? {} : { text: compile(engine, text, true) }
|
|
1126
|
+
}));
|
|
1127
|
+
const content = renderParts(compiled, values, budget, slot);
|
|
1128
|
+
budget.check();
|
|
1129
|
+
if (entry.valid && cacheEntries > 0) {
|
|
1130
|
+
cache.delete(key);
|
|
1131
|
+
cache.set(key, compiled);
|
|
1132
|
+
const oldest = cache.keys().next();
|
|
1133
|
+
if (cache.size > cacheEntries && !oldest.done) cache.delete(oldest.value);
|
|
1134
|
+
}
|
|
1135
|
+
return content;
|
|
1136
|
+
} finally {
|
|
1137
|
+
loading.delete(entry);
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
};
|
|
1141
|
+
}
|
|
1142
|
+
|
|
1143
|
+
// src/templates/registry.ts
|
|
1144
|
+
function defineLocalTemplate(definition) {
|
|
1145
|
+
return definition;
|
|
1146
|
+
}
|
|
1147
|
+
function defineSendGridTemplate(definition) {
|
|
1148
|
+
return definition;
|
|
1149
|
+
}
|
|
1150
|
+
function readDefinition(value) {
|
|
1151
|
+
const code = "invalid_config";
|
|
1152
|
+
const raw = readRecord(
|
|
1153
|
+
value,
|
|
1154
|
+
["kind", "revision", "parseInput", "parseData", "prepare"],
|
|
1155
|
+
["defaults", "subject", "html", "text", "templateId"],
|
|
1156
|
+
code
|
|
1157
|
+
);
|
|
1158
|
+
const defaults = readRecord(raw.defaults === void 0 ? {} : raw.defaults, [], ["from", "replyTo"], code);
|
|
1159
|
+
const base = {
|
|
1160
|
+
revision: identifier(raw.revision, code),
|
|
1161
|
+
defaults: Object.freeze({
|
|
1162
|
+
...defaults.from === void 0 ? {} : { from: validateMailbox(defaults.from, code) },
|
|
1163
|
+
...defaults.replyTo === void 0 ? {} : { replyTo: validateMailbox(defaults.replyTo, code) }
|
|
1164
|
+
}),
|
|
1165
|
+
parseInput: requireCallback(raw.parseInput),
|
|
1166
|
+
parseData: requireCallback(raw.parseData),
|
|
1167
|
+
// Dispatch always pairs this callback with the input parser of this same definition.
|
|
1168
|
+
prepare: requireCallback(raw.prepare)
|
|
1169
|
+
};
|
|
1170
|
+
if (raw.kind === "sendgrid" && !["subject", "html", "text"].some((key) => Object.hasOwn(raw, key))) {
|
|
1171
|
+
return Object.freeze({ ...base, kind: raw.kind, templateId: sendGridTemplateId(raw.templateId, code) });
|
|
1172
|
+
}
|
|
1173
|
+
if (raw.kind === "handlebars" && !Object.hasOwn(raw, "templateId")) {
|
|
1174
|
+
const subject = readSourceConfig(raw.subject);
|
|
1175
|
+
const html = raw.html === void 0 ? void 0 : readSourceConfig(raw.html);
|
|
1176
|
+
const text = raw.text === void 0 ? void 0 : readSourceConfig(raw.text);
|
|
1177
|
+
if (!html && !text) invalid(code);
|
|
1178
|
+
return Object.freeze({ ...base, kind: raw.kind, subject, ...html ? { html } : {}, ...text ? { text } : {} });
|
|
1179
|
+
}
|
|
1180
|
+
return invalid(code);
|
|
1181
|
+
}
|
|
1182
|
+
function captureFields(raw, definition, context, scheduleAt, budget, slot) {
|
|
1183
|
+
const code = "invalid_snapshot";
|
|
1184
|
+
const fields = readRecord(
|
|
1185
|
+
raw,
|
|
1186
|
+
["values"],
|
|
1187
|
+
["from", "replyTo", "to", "cc", "bcc", "expiresAt", "priority", "attachments", "correlation"],
|
|
1188
|
+
code
|
|
1189
|
+
);
|
|
1190
|
+
const from = fields.from === void 0 ? definition.defaults.from : fields.from;
|
|
1191
|
+
const replyTo = fields.replyTo === void 0 ? definition.defaults.replyTo : fields.replyTo;
|
|
1192
|
+
const envelope = validateEnvelope(
|
|
1193
|
+
{
|
|
1194
|
+
from,
|
|
1195
|
+
to: fields.to === void 0 ? [] : fields.to,
|
|
1196
|
+
cc: fields.cc === void 0 ? [] : fields.cc,
|
|
1197
|
+
bcc: fields.bcc === void 0 ? [] : fields.bcc,
|
|
1198
|
+
...replyTo === void 0 ? {} : { replyTo }
|
|
1199
|
+
},
|
|
1200
|
+
context.provider.kind
|
|
1201
|
+
);
|
|
1202
|
+
const expiresAt = validateExpiry(
|
|
1203
|
+
fields.expiresAt === void 0 ? context.now + DEFAULT_EXPIRY_MS : fields.expiresAt,
|
|
1204
|
+
context.now,
|
|
1205
|
+
scheduleAt
|
|
1206
|
+
);
|
|
1207
|
+
const priority = boundedOption(fields.priority, PRIORITY, code);
|
|
1208
|
+
const attachments = validateAttachmentRefs(fields.attachments === void 0 ? [] : fields.attachments);
|
|
1209
|
+
const correlation = validateCorrelation(fields.correlation === void 0 ? {} : fields.correlation);
|
|
1210
|
+
const values = copyJsonObject(fields.values, MESSAGE_LIMITS.dataBytes, "invalid_data");
|
|
1211
|
+
const { parseData } = definition;
|
|
1212
|
+
const parsed = runSyncCallback(budget, slot, "invalid_data", () => parseData(values));
|
|
1213
|
+
const data = parsed === values ? values : copyJsonObject(parsed, MESSAGE_LIMITS.dataBytes, "invalid_data");
|
|
1214
|
+
budget.check();
|
|
1215
|
+
return { envelope, expiresAt, priority, attachments, correlation, data };
|
|
1216
|
+
}
|
|
1217
|
+
var registryPreparations = /* @__PURE__ */ new WeakMap();
|
|
1218
|
+
function findRegistryPreparation(registry) {
|
|
1219
|
+
return registryPreparations.get(registry);
|
|
1220
|
+
}
|
|
1221
|
+
function createEmailTemplateRegistry(definitions, options = {}) {
|
|
1222
|
+
const code = "invalid_config";
|
|
1223
|
+
const config = readRecord(options, [], ["clock", "cacheEntries", "maxPending", "helpers"], code);
|
|
1224
|
+
const clock = readClock(config.clock);
|
|
1225
|
+
const maxPending = boundedOption(config.maxPending, TEMPLATE_MAX_PENDING);
|
|
1226
|
+
const renderer = createLocalRenderer(boundedOption(config.cacheEntries, TEMPLATE_CACHE_ENTRIES), config.helpers);
|
|
1227
|
+
const registered = /* @__PURE__ */ new Map();
|
|
1228
|
+
for (const key of plainKeys(definitions, Infinity, code)) {
|
|
1229
|
+
registered.set(identifier(key, code), readDefinition(ownData(definitions, key, code)));
|
|
1230
|
+
}
|
|
1231
|
+
let pending = 0;
|
|
1232
|
+
async function prepareParsed({ identity, command: safe }, budget) {
|
|
1233
|
+
budget.check();
|
|
1234
|
+
const { templateKey, provider, key, scheduleAt } = identity;
|
|
1235
|
+
const definition = registered.get(templateKey);
|
|
1236
|
+
if (!definition) invalid("template_not_found");
|
|
1237
|
+
if ((definition.kind === "handlebars" ? "smtp" : "sendgrid") !== provider.kind) invalid("provider_mismatch");
|
|
1238
|
+
if (pending >= maxPending) invalid("busy");
|
|
1239
|
+
pending++;
|
|
1240
|
+
const slot = new CallbackSlot(() => pending--);
|
|
1241
|
+
try {
|
|
1242
|
+
const now = syncStage(budget, code, () => unixMs(clock.now(), code));
|
|
1243
|
+
const context = Object.freeze({
|
|
1244
|
+
scope: identity.scope,
|
|
1245
|
+
key,
|
|
1246
|
+
templateKey,
|
|
1247
|
+
provider,
|
|
1248
|
+
now,
|
|
1249
|
+
signal: budget.signal
|
|
1250
|
+
});
|
|
1251
|
+
const { parseInput, prepare } = definition;
|
|
1252
|
+
const input = runSyncCallback(budget, slot, "invalid_input", () => parseInput(safe.input));
|
|
1253
|
+
const { data, ...fields } = await runHostCallback(
|
|
1254
|
+
budget,
|
|
1255
|
+
slot,
|
|
1256
|
+
"preparation_failed",
|
|
1257
|
+
() => prepare(input, context),
|
|
1258
|
+
(raw) => captureFields(raw, definition, context, scheduleAt, budget, slot)
|
|
1259
|
+
);
|
|
1260
|
+
budget.check();
|
|
1261
|
+
const base = {
|
|
1262
|
+
...fields,
|
|
1263
|
+
version: EMAIL_FORMAT_VERSION,
|
|
1264
|
+
template: Object.freeze({ key: templateKey, revision: definition.revision }),
|
|
1265
|
+
preparedAt: now
|
|
1266
|
+
};
|
|
1267
|
+
let snapshot;
|
|
1268
|
+
if (provider.kind === "smtp" && definition.kind === "handlebars") {
|
|
1269
|
+
const content = await renderer.render(templateKey, definition, data, budget, slot);
|
|
1270
|
+
snapshot = Object.freeze({ ...base, kind: provider.kind, provider, ...content });
|
|
1271
|
+
} else if (provider.kind === "sendgrid" && definition.kind === "sendgrid") {
|
|
1272
|
+
snapshot = Object.freeze({ ...base, kind: provider.kind, provider, templateId: definition.templateId, data });
|
|
1273
|
+
} else {
|
|
1274
|
+
return invalid("provider_mismatch");
|
|
1275
|
+
}
|
|
1276
|
+
budget.check();
|
|
1277
|
+
const snapshotHash = hashSnapshot(snapshot);
|
|
1278
|
+
budget.check();
|
|
1279
|
+
return Object.freeze({
|
|
1280
|
+
version: EMAIL_FORMAT_VERSION,
|
|
1281
|
+
scope: identity.scope,
|
|
1282
|
+
key,
|
|
1283
|
+
scheduleAt,
|
|
1284
|
+
intentHash: identity.intentHash,
|
|
1285
|
+
fingerprint: identity.fingerprint,
|
|
1286
|
+
snapshotHash,
|
|
1287
|
+
snapshot
|
|
1288
|
+
});
|
|
1289
|
+
} finally {
|
|
1290
|
+
slot.close();
|
|
1291
|
+
}
|
|
1292
|
+
}
|
|
1293
|
+
const registry = Object.freeze({
|
|
1294
|
+
invalidate(key) {
|
|
1295
|
+
if (key !== void 0) identifier(key, code);
|
|
1296
|
+
renderer.invalidate(key);
|
|
1297
|
+
},
|
|
1298
|
+
async prepare(scope, command, options2 = {}) {
|
|
1299
|
+
const call = readCallOptions(options2, CALL_BUDGETS.prepare);
|
|
1300
|
+
const budget = createBudget(clock, call.timeoutMs, call.signal);
|
|
1301
|
+
try {
|
|
1302
|
+
budget.check();
|
|
1303
|
+
return await prepareParsed(parseCommandIdentity(scope, command), budget);
|
|
1304
|
+
} finally {
|
|
1305
|
+
budget.close();
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
});
|
|
1309
|
+
registryPreparations.set(registry, async (parsed, parent) => {
|
|
1310
|
+
const budget = createChildBudget(clock, parent, CALL_BUDGETS.prepare.default);
|
|
1311
|
+
try {
|
|
1312
|
+
return await prepareParsed(parsed, budget);
|
|
1313
|
+
} finally {
|
|
1314
|
+
budget.close();
|
|
1315
|
+
}
|
|
1316
|
+
});
|
|
1317
|
+
return registry;
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1320
|
+
// src/service.ts
|
|
1321
|
+
import { randomUUID } from "crypto";
|
|
1322
|
+
import { types as types6 } from "util";
|
|
1323
|
+
|
|
1324
|
+
// src/internal/activity-codecs.ts
|
|
1325
|
+
import { Buffer as Buffer3 } from "buffer";
|
|
1326
|
+
|
|
1327
|
+
// src/internal/attempt-codecs.ts
|
|
1328
|
+
var smtpStages = ["connect", "tls", "auth", "envelope", "data"];
|
|
1329
|
+
var providerStages = [...smtpStages, "http"];
|
|
1330
|
+
var evidence = Object.freeze({
|
|
1331
|
+
smtp_accepted: ["accepted", "never", ["data"], "smtp"],
|
|
1332
|
+
smtp_partial: ["partially_accepted", "never", ["data"], "smtp"],
|
|
1333
|
+
smtp_transient_reply: ["rejected", "safe_transient", smtpStages, "smtp"],
|
|
1334
|
+
smtp_permanent_reply: ["rejected", "never", smtpStages, "smtp"],
|
|
1335
|
+
sendgrid_accepted: ["accepted", "never", ["http"], "sendgrid"],
|
|
1336
|
+
sendgrid_validated: ["validated", "never", ["http"], "sendgrid"],
|
|
1337
|
+
sendgrid_throttled: ["rejected", "safe_transient", ["http"], "sendgrid"],
|
|
1338
|
+
sendgrid_rejected: ["rejected", "never", ["http"], "sendgrid"],
|
|
1339
|
+
not_transmitted: ["unsubmitted", "safe_transient", providerStages, "provider"],
|
|
1340
|
+
provider_configuration: ["unsubmitted", "never", providerStages, "provider"],
|
|
1341
|
+
transport_uncertain: ["unknown", "never", providerStages, "provider"],
|
|
1342
|
+
provider_timeout: ["unknown", "never", providerStages, "provider"],
|
|
1343
|
+
provider_aborted: ["unknown", "never", providerStages, "provider"],
|
|
1344
|
+
attachment_unavailable: ["unsubmitted", "safe_transient", ["attachment"], "pre"],
|
|
1345
|
+
attachment_timeout: ["unsubmitted", "safe_transient", ["attachment"], "pre"],
|
|
1346
|
+
attachment_invalid: ["unsubmitted", "never", ["attachment"], "pre"],
|
|
1347
|
+
attachment_resolver_error: ["unsubmitted", "never", ["attachment"], "pre"],
|
|
1348
|
+
rate_deferred: ["unsubmitted", "safe_transient", ["rate_limit"], "pre"],
|
|
1349
|
+
rate_timeout: ["unsubmitted", "safe_transient", ["rate_limit"], "pre"],
|
|
1350
|
+
rate_error: ["unsubmitted", "never", ["rate_limit"], "pre"],
|
|
1351
|
+
profile_unavailable: ["unsubmitted", "never", ["pre_handoff"], "pre"],
|
|
1352
|
+
provider_preflight_error: ["unsubmitted", "never", ["pre_handoff"], "pre"],
|
|
1353
|
+
pre_handoff_timeout: ["unsubmitted", "safe_transient", ["pre_handoff"], "pre"],
|
|
1354
|
+
worker_stopped: ["unsubmitted", "safe_transient", ["pre_handoff"], "pre"],
|
|
1355
|
+
pre_handoff_lease_expired: ["unsubmitted", "safe_transient", ["pre_handoff"], "recovery"],
|
|
1356
|
+
launch_window_closed: ["unsubmitted", "safe_transient", ["pre_handoff"], "launch"],
|
|
1357
|
+
post_handoff_lease_expired: ["unknown", "never", ["pre_handoff"], "recovery"],
|
|
1358
|
+
expired: ["unsubmitted", "never", ["pre_handoff"], "pre"],
|
|
1359
|
+
cancelled: ["unsubmitted", "never", ["pre_handoff"], "cancel"]
|
|
1360
|
+
});
|
|
1361
|
+
function readAttemptReason(value, code) {
|
|
1362
|
+
if (typeof value !== "string" || !Object.hasOwn(evidence, value)) invalid(code);
|
|
1363
|
+
return value;
|
|
1364
|
+
}
|
|
1365
|
+
function attemptOutcome(reason) {
|
|
1366
|
+
return evidence[reason][0];
|
|
1367
|
+
}
|
|
1368
|
+
function isSafeTransient(reason) {
|
|
1369
|
+
return evidence[reason][1] === "safe_transient";
|
|
1370
|
+
}
|
|
1371
|
+
function recipientCounts(envelope) {
|
|
1372
|
+
return Object.freeze({ to: envelope.to.length, cc: envelope.cc.length, bcc: envelope.bcc.length });
|
|
1373
|
+
}
|
|
1374
|
+
function smtpMessageId(attemptId) {
|
|
1375
|
+
return `<${attemptId}@email.invalid>`;
|
|
1376
|
+
}
|
|
1377
|
+
function readHint(input, reason, code) {
|
|
1378
|
+
if (reason !== "rate_deferred" && reason !== "sendgrid_throttled") invalid(code);
|
|
1379
|
+
const raw = readRecord(input, [], ["delayMs", "notBefore"], code);
|
|
1380
|
+
const hasDelay = Object.hasOwn(raw, "delayMs");
|
|
1381
|
+
const hasFloor = Object.hasOwn(raw, "notBefore");
|
|
1382
|
+
if (!hasDelay && (!hasFloor || reason === "rate_deferred")) invalid(code);
|
|
1383
|
+
return Object.freeze({
|
|
1384
|
+
...hasDelay ? {
|
|
1385
|
+
delayMs: reason === "rate_deferred" ? integer(raw.delayMs, 1, MAX_RATE_DEFERRAL_MS, code) : integer(raw.delayMs, 0, Number.MAX_SAFE_INTEGER, code)
|
|
1386
|
+
} : {},
|
|
1387
|
+
...hasFloor ? { notBefore: unixMs(raw.notBefore, code) } : {}
|
|
1388
|
+
});
|
|
1389
|
+
}
|
|
1390
|
+
function readAttemptResult(input, code = "invalid_command", projected = false) {
|
|
1391
|
+
const raw = readRecord(
|
|
1392
|
+
input,
|
|
1393
|
+
["outcome", "retry", "stage", "reason"],
|
|
1394
|
+
["retryHint", "recipients", "messageId", "providerMessageId"],
|
|
1395
|
+
code
|
|
1396
|
+
);
|
|
1397
|
+
const reason = readAttemptReason(raw.reason, code);
|
|
1398
|
+
const [outcome, retry, stages2, origin] = evidence[reason];
|
|
1399
|
+
const stage = stages2.find((value) => value === raw.stage);
|
|
1400
|
+
if (raw.outcome !== outcome || raw.retry !== retry || !stage) invalid(code);
|
|
1401
|
+
const hasHint = Object.hasOwn(raw, "retryHint");
|
|
1402
|
+
if (projected && hasHint || !projected && reason === "rate_deferred" && !hasHint) invalid(code);
|
|
1403
|
+
const smtpSuccess = reason === "smtp_accepted" || reason === "smtp_partial";
|
|
1404
|
+
const hasRecipients = Object.hasOwn(raw, "recipients");
|
|
1405
|
+
if (smtpSuccess && !hasRecipients) invalid(code);
|
|
1406
|
+
let recipients;
|
|
1407
|
+
if (hasRecipients) {
|
|
1408
|
+
if (origin !== "smtp" && origin !== "provider" || stage !== "envelope" && stage !== "data") invalid(code);
|
|
1409
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1410
|
+
recipients = readArray(raw.recipients, MESSAGE_LIMITS.recipients, code, (value) => {
|
|
1411
|
+
const { group, index: rawIndex, status } = readRecord(value, ["group", "index", "status"], [], code);
|
|
1412
|
+
if (group !== "to" && group !== "cc" && group !== "bcc") invalid(code);
|
|
1413
|
+
if (status !== "rejected" && (status !== "accepted" || !smtpSuccess)) invalid(code);
|
|
1414
|
+
const index = integer(rawIndex, 0, MESSAGE_LIMITS.recipients - 1, code);
|
|
1415
|
+
const key = `${group}:${index}`;
|
|
1416
|
+
if (seen.has(key)) invalid(code);
|
|
1417
|
+
seen.add(key);
|
|
1418
|
+
return Object.freeze({ group, index, status });
|
|
1419
|
+
});
|
|
1420
|
+
const accepted = recipients.filter(({ status }) => status === "accepted").length;
|
|
1421
|
+
if (reason === "smtp_accepted" && (!accepted || accepted !== recipients.length) || reason === "smtp_partial" && (!accepted || accepted === recipients.length)) {
|
|
1422
|
+
invalid(code);
|
|
1423
|
+
}
|
|
1424
|
+
}
|
|
1425
|
+
const hasMessageId = Object.hasOwn(raw, "messageId");
|
|
1426
|
+
const { messageId, providerMessageId } = raw;
|
|
1427
|
+
if (hasMessageId && (!smtpSuccess || typeof messageId !== "string" || messageId.length !== 52)) invalid(code);
|
|
1428
|
+
const hasProviderId = Object.hasOwn(raw, "providerMessageId");
|
|
1429
|
+
if (hasProviderId && (reason !== "sendgrid_accepted" || typeof providerMessageId !== "string" || providerMessageId.length > 128 || !/^[A-Za-z0-9][A-Za-z0-9._=-]{0,127}$/.test(providerMessageId))) {
|
|
1430
|
+
invalid(code);
|
|
1431
|
+
}
|
|
1432
|
+
return Object.freeze({
|
|
1433
|
+
outcome,
|
|
1434
|
+
retry,
|
|
1435
|
+
stage,
|
|
1436
|
+
reason,
|
|
1437
|
+
...hasHint ? { retryHint: readHint(raw.retryHint, reason, code) } : {},
|
|
1438
|
+
...recipients === void 0 ? {} : { recipients },
|
|
1439
|
+
...typeof messageId === "string" ? { messageId } : {},
|
|
1440
|
+
...typeof providerMessageId === "string" ? { providerMessageId } : {}
|
|
1441
|
+
});
|
|
1442
|
+
}
|
|
1443
|
+
function assertEvidencePhase(reason, phase, source, code) {
|
|
1444
|
+
const origin = evidence[reason][3];
|
|
1445
|
+
if (source === "ledger") {
|
|
1446
|
+
if (origin === "recovery" && reason === "post_handoff_lease_expired" === (phase === "handed_off")) return;
|
|
1447
|
+
if (origin === "cancel" && phase === "pre_handoff") return;
|
|
1448
|
+
}
|
|
1449
|
+
const allowed = phase === "pre_handoff" ? origin === "pre" : origin === "smtp" || origin === "sendgrid" || origin === "provider" || origin === "launch";
|
|
1450
|
+
if (!allowed) invalid(code);
|
|
1451
|
+
}
|
|
1452
|
+
function assertEvidenceContext(result, provider, attemptId, counts, code) {
|
|
1453
|
+
const { reason, stage, recipients, messageId } = result;
|
|
1454
|
+
const origin = evidence[reason][3];
|
|
1455
|
+
if (origin === "smtp" && provider.kind !== "smtp" || origin === "sendgrid" && provider.kind !== "sendgrid" || origin === "provider" && (provider.kind === "smtp" ? stage === "http" : stage !== "http" && stage !== "connect" && stage !== "tls") || reason === "sendgrid_accepted" && provider.mode !== "live" || reason === "sendgrid_validated" && provider.mode !== "sandbox" || messageId !== void 0 && messageId !== smtpMessageId(attemptId)) {
|
|
1456
|
+
invalid(code);
|
|
1457
|
+
}
|
|
1458
|
+
if (recipients) {
|
|
1459
|
+
if (provider.kind !== "smtp") invalid(code);
|
|
1460
|
+
if (counts) {
|
|
1461
|
+
if (recipients.some(({ group, index }) => index >= counts[group])) invalid(code);
|
|
1462
|
+
const needsPartition = reason === "smtp_accepted" || reason === "smtp_partial" || stage === "envelope" && (reason === "smtp_transient_reply" || reason === "smtp_permanent_reply");
|
|
1463
|
+
if (needsPartition && recipients.length !== counts.to + counts.cc + counts.bcc) invalid(code);
|
|
1464
|
+
}
|
|
1465
|
+
}
|
|
1466
|
+
}
|
|
1467
|
+
function readProviderResult(input, provider, attemptId, envelope) {
|
|
1468
|
+
const code = "invalid_command";
|
|
1469
|
+
const result = readAttemptResult(input, code);
|
|
1470
|
+
const origin = evidence[result.reason][3];
|
|
1471
|
+
if (origin !== "smtp" && origin !== "sendgrid" && origin !== "provider") invalid(code);
|
|
1472
|
+
assertEvidenceContext(result, provider, attemptId, recipientCounts(envelope), code);
|
|
1473
|
+
return result;
|
|
1474
|
+
}
|
|
1475
|
+
function lifecycleEvidence(reason) {
|
|
1476
|
+
const [outcome, retry] = evidence[reason];
|
|
1477
|
+
return Object.freeze({ outcome, retry, reason, stage: "pre_handoff" });
|
|
1478
|
+
}
|
|
1479
|
+
function attemptEffect(result, attemptId, ordinal, manual, policy, expiresAt, now) {
|
|
1480
|
+
const { outcome, reason } = result;
|
|
1481
|
+
if (outcome !== "unsubmitted" && outcome !== "rejected") return { disposition: outcome, reason };
|
|
1482
|
+
if (reason === "cancelled" || reason === "expired") return { disposition: reason, reason };
|
|
1483
|
+
const disposition = outcome === "unsubmitted" ? "failed" : "rejected";
|
|
1484
|
+
if (result.retry === "never") return { disposition, reason };
|
|
1485
|
+
if (now >= expiresAt) return { disposition: "expired", reason: "expired" };
|
|
1486
|
+
if (manual || ordinal >= policy.maxAttempts) return { disposition, reason: "attempts_exhausted" };
|
|
1487
|
+
const cap = Math.min(policy.maxDelayMs, policy.baseDelayMs * 2 ** (ordinal - 1));
|
|
1488
|
+
const half = Math.floor(cap / 2);
|
|
1489
|
+
const jitter = half + Number.parseInt(sha256(attemptId).slice(0, 8), 16) % (cap - half + 1);
|
|
1490
|
+
const delay = Math.max(jitter, result.retryHint?.delayMs ?? 0);
|
|
1491
|
+
const retryAt = Math.max(now + Math.min(delay, MAX_UNIX_MS - now), result.retryHint?.notBefore ?? 0);
|
|
1492
|
+
if (retryAt >= expiresAt) return { disposition: "expired", reason: "expired" };
|
|
1493
|
+
return { disposition: "retry_scheduled", reason, retryAt };
|
|
1494
|
+
}
|
|
1495
|
+
|
|
1496
|
+
// src/internal/store-codecs.ts
|
|
1497
|
+
var REQUEST = "invalid_command";
|
|
1498
|
+
var LEASE = WORKER_LIMIT_BOUNDS.leaseMs;
|
|
1499
|
+
function readStoreId(value, code = REQUEST) {
|
|
1500
|
+
if (typeof value !== "string" || value.length !== 36 || !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(value)) {
|
|
1501
|
+
invalid(code);
|
|
1502
|
+
}
|
|
1503
|
+
return value;
|
|
1504
|
+
}
|
|
1505
|
+
function readLeaseToken(value, code = REQUEST) {
|
|
1506
|
+
if (typeof value !== "string" || value.length < 22 || value.length > 128 || !/^[A-Za-z0-9_-]+$/.test(value) || /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value)) {
|
|
1507
|
+
invalid(code);
|
|
1508
|
+
}
|
|
1509
|
+
return value;
|
|
1510
|
+
}
|
|
1511
|
+
function readLeaseMs(value) {
|
|
1512
|
+
return integer(value, LEASE.min, LEASE.max, REQUEST);
|
|
1513
|
+
}
|
|
1514
|
+
function timeAfter(start, delayMs) {
|
|
1515
|
+
return delayMs <= MAX_UNIX_MS - start ? start + delayMs : void 0;
|
|
1516
|
+
}
|
|
1517
|
+
function readStoreCall(input, worker = false) {
|
|
1518
|
+
const code = "invalid_config";
|
|
1519
|
+
const raw = readRecord(input, ["signal", "timeoutMs"], [], code);
|
|
1520
|
+
const max = worker ? WORKER_LIMIT_BOUNDS.storeTimeoutMs.max : CALL_BUDGETS.admissionOrAdmin.max;
|
|
1521
|
+
const timeoutMs = integer(raw.timeoutMs, 1, max, code);
|
|
1522
|
+
const call = readCallOptions(raw, { default: STORE_PRIMITIVE_TIMEOUT_MS, min: 1, max });
|
|
1523
|
+
if (!call.signal) invalid(code);
|
|
1524
|
+
return { signal: call.signal, timeoutMs: worker ? timeoutMs : Math.min(timeoutMs, STORE_PRIMITIVE_TIMEOUT_MS) };
|
|
1525
|
+
}
|
|
1526
|
+
function readStoreNext(value, read) {
|
|
1527
|
+
const code = "store_incompatible";
|
|
1528
|
+
const raw = readRecord(value, ["status"], ["value"], code);
|
|
1529
|
+
if (raw.status === "applied" && Object.hasOwn(raw, "value")) {
|
|
1530
|
+
return Object.freeze({ status: raw.status, value: read(raw.value) });
|
|
1531
|
+
}
|
|
1532
|
+
if ((raw.status === "none" || raw.status === "contended") && !Object.hasOwn(raw, "value")) {
|
|
1533
|
+
return Object.freeze({ status: raw.status });
|
|
1534
|
+
}
|
|
1535
|
+
return invalid(code);
|
|
1536
|
+
}
|
|
1537
|
+
function readRetryPolicy(input, code = REQUEST) {
|
|
1538
|
+
const raw = readRecord(input, ["maxAttempts", "baseDelayMs", "maxDelayMs"], [], code);
|
|
1539
|
+
const bounds = RETRY_POLICY_BOUNDS;
|
|
1540
|
+
const baseDelayMs = integer(raw.baseDelayMs, bounds.baseDelayMs.min, bounds.baseDelayMs.max, code);
|
|
1541
|
+
return Object.freeze({
|
|
1542
|
+
maxAttempts: integer(raw.maxAttempts, bounds.maxAttempts.min, bounds.maxAttempts.max, code),
|
|
1543
|
+
baseDelayMs,
|
|
1544
|
+
maxDelayMs: integer(raw.maxDelayMs, baseDelayMs, bounds.maxDelayMs.max, code)
|
|
1545
|
+
});
|
|
1546
|
+
}
|
|
1547
|
+
function readRetentionPolicy(input, code = REQUEST) {
|
|
1548
|
+
const { payloadMs, historyMs, idempotencyMs } = readRecord(
|
|
1549
|
+
input,
|
|
1550
|
+
["payloadMs", "historyMs", "idempotencyMs"],
|
|
1551
|
+
[],
|
|
1552
|
+
code
|
|
1553
|
+
);
|
|
1554
|
+
const bounds = RETENTION_POLICY_BOUNDS;
|
|
1555
|
+
return Object.freeze({
|
|
1556
|
+
payloadMs: integer(payloadMs, bounds.payloadMs.min, bounds.payloadMs.max, code),
|
|
1557
|
+
historyMs: integer(historyMs, bounds.historyMs.min, bounds.historyMs.max, code),
|
|
1558
|
+
idempotencyMs: integer(idempotencyMs, bounds.idempotencyMs.min, bounds.idempotencyMs.max, code)
|
|
1559
|
+
});
|
|
1560
|
+
}
|
|
1561
|
+
function readStoreAdmission(scope, input) {
|
|
1562
|
+
const raw = readRecord(input, ["command", "jobId", "retry", "retention"], [], REQUEST);
|
|
1563
|
+
const command = validatePreparedCommand(scope, raw.command);
|
|
1564
|
+
return Object.freeze({
|
|
1565
|
+
command,
|
|
1566
|
+
admissionKey: encodeAdmissionKey(command.key),
|
|
1567
|
+
jobId: readStoreId(raw.jobId),
|
|
1568
|
+
retry: readRetryPolicy(raw.retry),
|
|
1569
|
+
retention: readRetentionPolicy(raw.retention)
|
|
1570
|
+
});
|
|
1571
|
+
}
|
|
1572
|
+
function readFence(input) {
|
|
1573
|
+
const { jobId, attemptId, token } = readRecord(input, ["jobId", "attemptId", "token"], [], REQUEST);
|
|
1574
|
+
return Object.freeze({ jobId: readStoreId(jobId), attemptId: readStoreId(attemptId), token: readLeaseToken(token) });
|
|
1575
|
+
}
|
|
1576
|
+
function readClaim(input) {
|
|
1577
|
+
const { attemptId, token, leaseMs } = readRecord(input, ["attemptId", "token", "leaseMs"], [], REQUEST);
|
|
1578
|
+
return Object.freeze({
|
|
1579
|
+
attemptId: readStoreId(attemptId),
|
|
1580
|
+
token: readLeaseToken(token),
|
|
1581
|
+
leaseMs: readLeaseMs(leaseMs)
|
|
1582
|
+
});
|
|
1583
|
+
}
|
|
1584
|
+
function readFinish(input) {
|
|
1585
|
+
const { fence, phase, operationId, result } = readRecord(
|
|
1586
|
+
input,
|
|
1587
|
+
["fence", "phase", "operationId", "result"],
|
|
1588
|
+
[],
|
|
1589
|
+
REQUEST
|
|
1590
|
+
);
|
|
1591
|
+
if (phase !== "pre_handoff" && phase !== "handed_off") invalid(REQUEST);
|
|
1592
|
+
const evidence2 = readAttemptResult(result);
|
|
1593
|
+
assertEvidencePhase(evidence2.reason, phase, "owner", REQUEST);
|
|
1594
|
+
return Object.freeze({ fence: readFence(fence), phase, operationId: readStoreId(operationId), result: evidence2 });
|
|
1595
|
+
}
|
|
1596
|
+
function readResolution(input) {
|
|
1597
|
+
const raw = readRecord(input, ["jobId", "attemptId", "action"], ["acknowledgeDuplicateRisk"], REQUEST);
|
|
1598
|
+
const ids = { jobId: readStoreId(raw.jobId), attemptId: readStoreId(raw.attemptId) };
|
|
1599
|
+
if (raw.action === "dismiss" && !Object.hasOwn(raw, "acknowledgeDuplicateRisk")) {
|
|
1600
|
+
return Object.freeze({ ...ids, action: raw.action });
|
|
1601
|
+
}
|
|
1602
|
+
if (raw.action === "redrive" && raw.acknowledgeDuplicateRisk === true) {
|
|
1603
|
+
return Object.freeze({ ...ids, action: raw.action, acknowledgeDuplicateRisk: true });
|
|
1604
|
+
}
|
|
1605
|
+
return invalid(REQUEST);
|
|
1606
|
+
}
|
|
1607
|
+
|
|
1608
|
+
// src/internal/activity-codecs.ts
|
|
1609
|
+
var ACTIVITY_BYTES = 8192;
|
|
1610
|
+
var dispositions = [
|
|
1611
|
+
"accepted",
|
|
1612
|
+
"partially_accepted",
|
|
1613
|
+
"validated",
|
|
1614
|
+
"rejected",
|
|
1615
|
+
"unknown",
|
|
1616
|
+
"failed",
|
|
1617
|
+
"expired",
|
|
1618
|
+
"cancelled"
|
|
1619
|
+
];
|
|
1620
|
+
function readDisposition(input, code) {
|
|
1621
|
+
const disposition = dispositions.find((value) => value === input);
|
|
1622
|
+
if (disposition) return disposition;
|
|
1623
|
+
if (input === "retry_scheduled") return input;
|
|
1624
|
+
return invalid(code);
|
|
1625
|
+
}
|
|
1626
|
+
function assertActivityDisposition(result, disposition, code) {
|
|
1627
|
+
const { outcome, reason } = result;
|
|
1628
|
+
if (outcome !== "rejected" && outcome !== "unsubmitted") {
|
|
1629
|
+
if (disposition !== outcome) invalid(code);
|
|
1630
|
+
} else if (reason === "expired" || reason === "cancelled") {
|
|
1631
|
+
if (disposition !== reason) invalid(code);
|
|
1632
|
+
} else if (disposition !== (outcome === "rejected" ? "rejected" : "failed") && !(result.retry === "safe_transient" && (disposition === "expired" || disposition === "retry_scheduled"))) {
|
|
1633
|
+
invalid(code);
|
|
1634
|
+
}
|
|
1635
|
+
}
|
|
1636
|
+
function readActivity(scope, input, code = "store_incompatible") {
|
|
1637
|
+
const raw = readRecord(
|
|
1638
|
+
input,
|
|
1639
|
+
[
|
|
1640
|
+
"version",
|
|
1641
|
+
"scope",
|
|
1642
|
+
"jobId",
|
|
1643
|
+
"attemptId",
|
|
1644
|
+
"ordinal",
|
|
1645
|
+
"provider",
|
|
1646
|
+
"template",
|
|
1647
|
+
"correlation",
|
|
1648
|
+
"startedAt",
|
|
1649
|
+
"finishedAt",
|
|
1650
|
+
"result",
|
|
1651
|
+
"disposition"
|
|
1652
|
+
],
|
|
1653
|
+
["handedOffAt"],
|
|
1654
|
+
code
|
|
1655
|
+
);
|
|
1656
|
+
if (raw.version !== EMAIL_FORMAT_VERSION || scopeToken(raw.scope, code) !== scope) invalid(code);
|
|
1657
|
+
const jobId = readStoreId(raw.jobId, code);
|
|
1658
|
+
const attemptId = readStoreId(raw.attemptId, code);
|
|
1659
|
+
const provider = validateProviderRef(raw.provider, code);
|
|
1660
|
+
const startedAt = unixMs(raw.startedAt, code);
|
|
1661
|
+
const finishedAt = unixMs(raw.finishedAt, code);
|
|
1662
|
+
const handedOffAt = Object.hasOwn(raw, "handedOffAt") ? unixMs(raw.handedOffAt, code) : void 0;
|
|
1663
|
+
if (finishedAt < startedAt || handedOffAt !== void 0 && (handedOffAt < startedAt || handedOffAt > finishedAt)) {
|
|
1664
|
+
invalid(code);
|
|
1665
|
+
}
|
|
1666
|
+
const result = readAttemptResult(raw.result, code, true);
|
|
1667
|
+
assertEvidencePhase(result.reason, handedOffAt === void 0 ? "pre_handoff" : "handed_off", "ledger", code);
|
|
1668
|
+
assertEvidenceContext(result, provider, attemptId, void 0, code);
|
|
1669
|
+
const disposition = readDisposition(raw.disposition, code);
|
|
1670
|
+
assertActivityDisposition(result, disposition, code);
|
|
1671
|
+
return Object.freeze({
|
|
1672
|
+
version: EMAIL_FORMAT_VERSION,
|
|
1673
|
+
scope,
|
|
1674
|
+
jobId,
|
|
1675
|
+
attemptId,
|
|
1676
|
+
ordinal: integer(raw.ordinal, 1, MAX_ATTEMPT_LEDGER, code),
|
|
1677
|
+
provider,
|
|
1678
|
+
template: validateTemplateIdentity(raw.template, code),
|
|
1679
|
+
correlation: validateCorrelation(raw.correlation, code),
|
|
1680
|
+
startedAt,
|
|
1681
|
+
...handedOffAt === void 0 ? {} : { handedOffAt },
|
|
1682
|
+
finishedAt,
|
|
1683
|
+
result,
|
|
1684
|
+
disposition
|
|
1685
|
+
});
|
|
1686
|
+
}
|
|
1687
|
+
function activityFor(job, commit) {
|
|
1688
|
+
const { outcome, retry, stage, reason, recipients, messageId, providerMessageId } = commit.result;
|
|
1689
|
+
return readActivity(job.scope, {
|
|
1690
|
+
version: EMAIL_FORMAT_VERSION,
|
|
1691
|
+
scope: job.scope,
|
|
1692
|
+
jobId: job.jobId,
|
|
1693
|
+
attemptId: commit.attemptId,
|
|
1694
|
+
ordinal: commit.ordinal,
|
|
1695
|
+
provider: job.provider,
|
|
1696
|
+
template: job.template,
|
|
1697
|
+
correlation: job.correlation,
|
|
1698
|
+
startedAt: commit.startedAt,
|
|
1699
|
+
...commit.handedOffAt === void 0 ? {} : { handedOffAt: commit.handedOffAt },
|
|
1700
|
+
finishedAt: commit.finishedAt,
|
|
1701
|
+
disposition: commit.disposition,
|
|
1702
|
+
result: {
|
|
1703
|
+
outcome,
|
|
1704
|
+
retry,
|
|
1705
|
+
stage,
|
|
1706
|
+
reason,
|
|
1707
|
+
...recipients === void 0 ? {} : { recipients },
|
|
1708
|
+
...messageId === void 0 ? {} : { messageId },
|
|
1709
|
+
...providerMessageId === void 0 ? {} : { providerMessageId }
|
|
1710
|
+
}
|
|
1711
|
+
});
|
|
1712
|
+
}
|
|
1713
|
+
function activityDigest(activity) {
|
|
1714
|
+
return hashJson(activity, ACTIVITY_BYTES, "store_incompatible");
|
|
1715
|
+
}
|
|
1716
|
+
function readStoredActivity(scope, input, code = "store_incompatible") {
|
|
1717
|
+
const raw = readRecord(input, ["activity", "digest"], [], code);
|
|
1718
|
+
const activity = readActivity(scope, raw.activity, code);
|
|
1719
|
+
const digest = hashToken(raw.digest, code);
|
|
1720
|
+
if (activityDigest(activity) !== digest) invalid(code);
|
|
1721
|
+
return Object.freeze({ activity, digest });
|
|
1722
|
+
}
|
|
1723
|
+
function readProjectionPermit(scope, input) {
|
|
1724
|
+
const code = "invalid_command";
|
|
1725
|
+
const {
|
|
1726
|
+
activity,
|
|
1727
|
+
digest,
|
|
1728
|
+
permitUntil: rawUntil
|
|
1729
|
+
} = readRecord(input, ["activity", "digest", "permitUntil"], [], code);
|
|
1730
|
+
const stored = readStoredActivity(scope, { activity, digest }, code);
|
|
1731
|
+
const permitUntil = unixMs(rawUntil, code);
|
|
1732
|
+
if (permitUntil - stored.activity.finishedAt < PROJECTION_PERMIT_MS) invalid(code);
|
|
1733
|
+
return Object.freeze({ ...stored, permitUntil });
|
|
1734
|
+
}
|
|
1735
|
+
function compareAscii(a, b) {
|
|
1736
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
1737
|
+
}
|
|
1738
|
+
function compareActivity(a, b) {
|
|
1739
|
+
return b.finishedAt - a.finishedAt || compareAscii(a.jobId, b.jobId) || compareAscii(a.attemptId, b.attemptId);
|
|
1740
|
+
}
|
|
1741
|
+
function cursorPayload(criteria, position) {
|
|
1742
|
+
return {
|
|
1743
|
+
v: EMAIL_FORMAT_VERSION,
|
|
1744
|
+
s: criteria.scope,
|
|
1745
|
+
j: criteria.jobId,
|
|
1746
|
+
f: criteria.from,
|
|
1747
|
+
b: criteria.before,
|
|
1748
|
+
p: [position.finishedAt, position.jobId, position.attemptId]
|
|
1749
|
+
};
|
|
1750
|
+
}
|
|
1751
|
+
function encodeCursor(criteria, position) {
|
|
1752
|
+
const code = "invalid_cursor";
|
|
1753
|
+
const { encoded } = canonicalJson(cursorPayload(criteria, position), MAX_ACTIVITY_CURSOR_BYTES, code);
|
|
1754
|
+
const cursor = Buffer3.from(encoded).toString("base64url");
|
|
1755
|
+
if (cursor.length > MAX_ACTIVITY_CURSOR_BYTES) invalid(code);
|
|
1756
|
+
return cursor;
|
|
1757
|
+
}
|
|
1758
|
+
function decodeCursor(criteria, cursor) {
|
|
1759
|
+
const code = "invalid_cursor";
|
|
1760
|
+
if (typeof cursor !== "string" || cursor.length === 0 || cursor.length > MAX_ACTIVITY_CURSOR_BYTES || !/^[A-Za-z0-9_-]+$/.test(cursor)) {
|
|
1761
|
+
invalid(code);
|
|
1762
|
+
}
|
|
1763
|
+
let input;
|
|
1764
|
+
try {
|
|
1765
|
+
input = JSON.parse(Buffer3.from(cursor, "base64url").toString("utf8"));
|
|
1766
|
+
} catch {
|
|
1767
|
+
invalid(code);
|
|
1768
|
+
}
|
|
1769
|
+
const { p } = readRecord(input, ["v", "s", "j", "f", "b", "p"], [], code);
|
|
1770
|
+
const tuple = readArray(p, 3, code, (entry) => entry);
|
|
1771
|
+
const position = Object.freeze({
|
|
1772
|
+
finishedAt: unixMs(tuple[0], code),
|
|
1773
|
+
jobId: readStoreId(tuple[1], code),
|
|
1774
|
+
attemptId: readStoreId(tuple[2], code)
|
|
1775
|
+
});
|
|
1776
|
+
if (criteria.jobId !== null && position.jobId !== criteria.jobId || criteria.from !== null && position.finishedAt < criteria.from || criteria.before !== null && position.finishedAt >= criteria.before || encodeCursor(criteria, position) !== cursor) {
|
|
1777
|
+
invalid(code);
|
|
1778
|
+
}
|
|
1779
|
+
return position;
|
|
1780
|
+
}
|
|
1781
|
+
function readActivityCriteria(scope, input) {
|
|
1782
|
+
const code = "invalid_command";
|
|
1783
|
+
const raw = readRecord(input, [], ["jobId", "from", "before", "limit", "cursor"], code);
|
|
1784
|
+
const jobId = Object.hasOwn(raw, "jobId") ? readStoreId(raw.jobId, code) : null;
|
|
1785
|
+
const from = Object.hasOwn(raw, "from") ? unixMs(raw.from, code) : null;
|
|
1786
|
+
const before = Object.hasOwn(raw, "before") ? unixMs(raw.before, code) : null;
|
|
1787
|
+
if (from !== null && before !== null && from > before) invalid(code);
|
|
1788
|
+
const limit = Object.hasOwn(raw, "limit") ? integer(raw.limit, ACTIVITY_PAGE_LIMIT.min, ACTIVITY_PAGE_LIMIT.max, code) : ACTIVITY_PAGE_LIMIT.default;
|
|
1789
|
+
const criteria = { scope, jobId, from, before, limit };
|
|
1790
|
+
return Object.freeze({
|
|
1791
|
+
...criteria,
|
|
1792
|
+
...Object.hasOwn(raw, "cursor") ? { after: decodeCursor(criteria, raw.cursor) } : {}
|
|
1793
|
+
});
|
|
1794
|
+
}
|
|
1795
|
+
function activityQuery(criteria) {
|
|
1796
|
+
const { jobId, from, before, limit, after } = criteria;
|
|
1797
|
+
return Object.freeze({
|
|
1798
|
+
...jobId === null ? {} : { jobId },
|
|
1799
|
+
...from === null ? {} : { from },
|
|
1800
|
+
...before === null ? {} : { before },
|
|
1801
|
+
limit,
|
|
1802
|
+
...after === void 0 ? {} : { cursor: encodeCursor(criteria, after) }
|
|
1803
|
+
});
|
|
1804
|
+
}
|
|
1805
|
+
function readOrderedActivities(criteria, input, maxRows) {
|
|
1806
|
+
const code = "store_incompatible";
|
|
1807
|
+
let previous = criteria.after;
|
|
1808
|
+
return readArray(input, maxRows, code, (row) => {
|
|
1809
|
+
const activity = readActivity(criteria.scope, row);
|
|
1810
|
+
if (previous && compareActivity(previous, activity) >= 0 || criteria.jobId !== null && criteria.jobId !== activity.jobId || criteria.from !== null && activity.finishedAt < criteria.from || criteria.before !== null && activity.finishedAt >= criteria.before) {
|
|
1811
|
+
invalid(code);
|
|
1812
|
+
}
|
|
1813
|
+
previous = activity;
|
|
1814
|
+
return activity;
|
|
1815
|
+
});
|
|
1816
|
+
}
|
|
1817
|
+
function activityPage(criteria, ordered) {
|
|
1818
|
+
const rows = readOrderedActivities(criteria, ordered, criteria.limit + 1);
|
|
1819
|
+
const more = rows.length > criteria.limit;
|
|
1820
|
+
const items = more ? Object.freeze(rows.slice(0, criteria.limit)) : rows;
|
|
1821
|
+
const last = items.at(-1);
|
|
1822
|
+
return Object.freeze({ items, ...more && last ? { nextCursor: encodeCursor(criteria, last) } : {} });
|
|
1823
|
+
}
|
|
1824
|
+
function readActivityPage(criteria, input) {
|
|
1825
|
+
const code = "store_incompatible";
|
|
1826
|
+
const raw = readRecord(input, ["items"], ["nextCursor"], code);
|
|
1827
|
+
const items = readOrderedActivities(criteria, raw.items, criteria.limit);
|
|
1828
|
+
if (!Object.hasOwn(raw, "nextCursor")) return Object.freeze({ items });
|
|
1829
|
+
const last = items.at(-1);
|
|
1830
|
+
if (!last || items.length !== criteria.limit || raw.nextCursor !== encodeCursor(criteria, last)) invalid(code);
|
|
1831
|
+
return Object.freeze({ items, nextCursor: raw.nextCursor });
|
|
1832
|
+
}
|
|
1833
|
+
|
|
1834
|
+
// src/internal/job-summary.ts
|
|
1835
|
+
var STORED = "store_incompatible";
|
|
1836
|
+
var COMMON = [
|
|
1837
|
+
"version",
|
|
1838
|
+
"scope",
|
|
1839
|
+
"jobId",
|
|
1840
|
+
"key",
|
|
1841
|
+
"provider",
|
|
1842
|
+
"template",
|
|
1843
|
+
"correlation",
|
|
1844
|
+
"scheduleAt",
|
|
1845
|
+
"createdAt",
|
|
1846
|
+
"updatedAt",
|
|
1847
|
+
"expiresAt",
|
|
1848
|
+
"priority",
|
|
1849
|
+
"attemptCount",
|
|
1850
|
+
"unknownOpen",
|
|
1851
|
+
"resolutions",
|
|
1852
|
+
"state"
|
|
1853
|
+
];
|
|
1854
|
+
function readUnknownResolution(input) {
|
|
1855
|
+
const { attemptId, at, action } = readRecord(input, ["attemptId", "at", "action"], [], STORED);
|
|
1856
|
+
if (action !== "dismiss" && action !== "redrive") invalid(STORED);
|
|
1857
|
+
return Object.freeze({ attemptId: readStoreId(attemptId, STORED), at: unixMs(at, STORED), action });
|
|
1858
|
+
}
|
|
1859
|
+
function readJobSummary(scope, input) {
|
|
1860
|
+
const raw = readRecord(
|
|
1861
|
+
input,
|
|
1862
|
+
COMMON,
|
|
1863
|
+
["latestAttempt", "nextAt", "phase", "disposition", "terminalReason", "terminalAt"],
|
|
1864
|
+
STORED
|
|
1865
|
+
);
|
|
1866
|
+
if (raw.version !== EMAIL_FORMAT_VERSION || scopeToken(raw.scope, STORED) !== scope) invalid(STORED);
|
|
1867
|
+
const createdAt = unixMs(raw.createdAt, STORED);
|
|
1868
|
+
const updatedAt = unixMs(raw.updatedAt, STORED);
|
|
1869
|
+
const expiresAt = unixMs(raw.expiresAt, STORED);
|
|
1870
|
+
const scheduleAt = raw.scheduleAt === null ? null : unixMs(raw.scheduleAt, STORED);
|
|
1871
|
+
const firstDue = Math.max(createdAt, scheduleAt ?? createdAt);
|
|
1872
|
+
if (updatedAt < createdAt || firstDue >= expiresAt) invalid(STORED);
|
|
1873
|
+
let state;
|
|
1874
|
+
if (raw.state === "queued") {
|
|
1875
|
+
readRecord(raw, [...COMMON, "nextAt"], ["latestAttempt"], STORED);
|
|
1876
|
+
const nextAt = unixMs(raw.nextAt, STORED);
|
|
1877
|
+
if (nextAt < firstDue || nextAt >= expiresAt) invalid(STORED);
|
|
1878
|
+
state = { state: raw.state, nextAt };
|
|
1879
|
+
} else if (raw.state === "leased") {
|
|
1880
|
+
readRecord(raw, [...COMMON, "phase"], ["latestAttempt"], STORED);
|
|
1881
|
+
if (raw.phase !== "pre_handoff" && raw.phase !== "handed_off") invalid(STORED);
|
|
1882
|
+
state = { state: raw.state, phase: raw.phase };
|
|
1883
|
+
} else if (raw.state === "terminal") {
|
|
1884
|
+
readRecord(raw, [...COMMON, "disposition", "terminalAt", "terminalReason"], ["latestAttempt"], STORED);
|
|
1885
|
+
const terminalAt = unixMs(raw.terminalAt, STORED);
|
|
1886
|
+
const disposition = readDisposition(raw.disposition, STORED);
|
|
1887
|
+
if (terminalAt < createdAt || terminalAt > updatedAt || disposition === "retry_scheduled") invalid(STORED);
|
|
1888
|
+
state = {
|
|
1889
|
+
state: raw.state,
|
|
1890
|
+
disposition,
|
|
1891
|
+
terminalAt,
|
|
1892
|
+
terminalReason: raw.terminalReason === "attempts_exhausted" ? raw.terminalReason : readAttemptReason(raw.terminalReason, STORED)
|
|
1893
|
+
};
|
|
1894
|
+
} else {
|
|
1895
|
+
return invalid(STORED);
|
|
1896
|
+
}
|
|
1897
|
+
const active = Number(state.state === "leased");
|
|
1898
|
+
const attemptCount = integer(raw.attemptCount, active, MAX_ATTEMPT_LEDGER, STORED);
|
|
1899
|
+
const latest = Object.hasOwn(raw, "latestAttempt") ? readLatestAttempt(raw.latestAttempt) : void 0;
|
|
1900
|
+
const hasFinalized = attemptCount > active;
|
|
1901
|
+
if (latest !== void 0 !== hasFinalized) invalid(STORED);
|
|
1902
|
+
const { unknownOpen } = raw;
|
|
1903
|
+
if (typeof unknownOpen !== "boolean" || unknownOpen && !(state.state === "terminal" && state.disposition === "unknown")) {
|
|
1904
|
+
invalid(STORED);
|
|
1905
|
+
}
|
|
1906
|
+
const resolutions = readArray(raw.resolutions, Math.min(2, attemptCount - active), STORED, readUnknownResolution);
|
|
1907
|
+
return Object.freeze({
|
|
1908
|
+
version: EMAIL_FORMAT_VERSION,
|
|
1909
|
+
scope,
|
|
1910
|
+
jobId: readStoreId(raw.jobId, STORED),
|
|
1911
|
+
key: validateAdmissionKey(raw.key, STORED),
|
|
1912
|
+
provider: validateProviderRef(raw.provider, STORED),
|
|
1913
|
+
template: validateTemplateIdentity(raw.template, STORED),
|
|
1914
|
+
correlation: validateCorrelation(raw.correlation, STORED),
|
|
1915
|
+
scheduleAt,
|
|
1916
|
+
createdAt,
|
|
1917
|
+
updatedAt,
|
|
1918
|
+
expiresAt,
|
|
1919
|
+
priority: integer(raw.priority, PRIORITY.min, PRIORITY.max, STORED),
|
|
1920
|
+
attemptCount,
|
|
1921
|
+
...latest === void 0 ? {} : { latestAttempt: latest },
|
|
1922
|
+
unknownOpen,
|
|
1923
|
+
resolutions,
|
|
1924
|
+
...state
|
|
1925
|
+
});
|
|
1926
|
+
}
|
|
1927
|
+
function matchesAdmissionJob(job, identity, status) {
|
|
1928
|
+
return job.scope === identity.scope && sameCommandMetadata(job.key, job.template.key, job.provider, job.scheduleAt, identity) && (status === "replayed" || job.state === "queued" && job.attemptCount === 0 && job.createdAt === job.updatedAt && job.nextAt === Math.max(job.createdAt, job.scheduleAt ?? job.createdAt));
|
|
1929
|
+
}
|
|
1930
|
+
function readLatestAttempt(input) {
|
|
1931
|
+
const latest = readRecord(input, ["attemptId", "outcome", "reason"], [], STORED);
|
|
1932
|
+
const reason = readAttemptReason(latest.reason, STORED);
|
|
1933
|
+
const outcome = attemptOutcome(reason);
|
|
1934
|
+
if (latest.outcome !== outcome) invalid(STORED);
|
|
1935
|
+
return Object.freeze({ attemptId: readStoreId(latest.attemptId, STORED), outcome, reason });
|
|
1936
|
+
}
|
|
1937
|
+
|
|
1938
|
+
// src/internal/store-call.ts
|
|
1939
|
+
import { types as types5 } from "util";
|
|
1940
|
+
var STORE_PERSISTENCE_ERRORS = [
|
|
1941
|
+
"store_capacity",
|
|
1942
|
+
"store_unavailable",
|
|
1943
|
+
"store_incompatible",
|
|
1944
|
+
"write_unconfirmed"
|
|
1945
|
+
];
|
|
1946
|
+
var STOP_ERRORS = ["aborted", "deadline"];
|
|
1947
|
+
async function runStoreCall(clock, parent, options) {
|
|
1948
|
+
let budget;
|
|
1949
|
+
try {
|
|
1950
|
+
budget = createChildBudgetUntil(
|
|
1951
|
+
clock,
|
|
1952
|
+
parent,
|
|
1953
|
+
Math.min(monotonicNow(clock) + options.maxMs, options.deadline ?? Infinity)
|
|
1954
|
+
);
|
|
1955
|
+
const mutation = options.effect === "mutation";
|
|
1956
|
+
options.beforeInvoke?.();
|
|
1957
|
+
budget.check();
|
|
1958
|
+
const dispatchedAt = monotonicNow(clock);
|
|
1959
|
+
const timeoutMs = Math.floor(budget.deadline - dispatchedAt);
|
|
1960
|
+
if (timeoutMs < 1 || budget.signal.aborted) {
|
|
1961
|
+
budget.check();
|
|
1962
|
+
invalid("deadline");
|
|
1963
|
+
}
|
|
1964
|
+
const call = Object.freeze({ timeoutMs, signal: budget.signal });
|
|
1965
|
+
let raw;
|
|
1966
|
+
try {
|
|
1967
|
+
const pending = options.invoke(call, dispatchedAt);
|
|
1968
|
+
raw = types5.isPromise(pending) ? await pending : pending;
|
|
1969
|
+
} catch (error) {
|
|
1970
|
+
const known = allowedErrorCode(error, options.definite ?? []) ?? allowedErrorCode(error, STORE_PERSISTENCE_ERRORS) ?? allowedErrorCode(error, ["busy"]);
|
|
1971
|
+
if (mutation) return invalid(known ?? "write_unconfirmed");
|
|
1972
|
+
budget.check();
|
|
1973
|
+
if (known === "write_unconfirmed") invalid("store_unavailable");
|
|
1974
|
+
return invalid(known ?? allowedErrorCode(error, STOP_ERRORS) ?? "store_unavailable");
|
|
1975
|
+
}
|
|
1976
|
+
try {
|
|
1977
|
+
budget.check();
|
|
1978
|
+
let captured;
|
|
1979
|
+
try {
|
|
1980
|
+
captured = options.accept(raw);
|
|
1981
|
+
} catch {
|
|
1982
|
+
budget.check();
|
|
1983
|
+
return invalid("store_incompatible");
|
|
1984
|
+
}
|
|
1985
|
+
budget.check();
|
|
1986
|
+
return captured;
|
|
1987
|
+
} catch (error) {
|
|
1988
|
+
if (mutation) invalid("write_unconfirmed");
|
|
1989
|
+
throw error;
|
|
1990
|
+
}
|
|
1991
|
+
} catch (error) {
|
|
1992
|
+
options.onError?.(error);
|
|
1993
|
+
throw error;
|
|
1994
|
+
} finally {
|
|
1995
|
+
budget?.close();
|
|
1996
|
+
}
|
|
1997
|
+
}
|
|
1998
|
+
|
|
1999
|
+
// src/service.ts
|
|
2000
|
+
var PREPARATION_ERRORS = [
|
|
2001
|
+
"invalid_config",
|
|
2002
|
+
"invalid_command",
|
|
2003
|
+
"invalid_input",
|
|
2004
|
+
"invalid_data",
|
|
2005
|
+
"invalid_snapshot",
|
|
2006
|
+
"preparation_failed",
|
|
2007
|
+
"template_not_found",
|
|
2008
|
+
"template_source",
|
|
2009
|
+
"template_render",
|
|
2010
|
+
"provider_mismatch",
|
|
2011
|
+
"expired",
|
|
2012
|
+
"aborted",
|
|
2013
|
+
"deadline",
|
|
2014
|
+
"busy"
|
|
2015
|
+
];
|
|
2016
|
+
var UNCONFIRMED = ["write_unconfirmed"];
|
|
2017
|
+
var CONFLICT = ["idempotency_conflict"];
|
|
2018
|
+
var INSERT_REJECTIONS = ["invalid_command", "invalid_snapshot", "provider_mismatch", "expired"];
|
|
2019
|
+
var CONFIG = "invalid_config";
|
|
2020
|
+
var STORED2 = "store_incompatible";
|
|
2021
|
+
var injectedRegistrySlots = /* @__PURE__ */ new WeakMap();
|
|
2022
|
+
var serviceAdmissions = /* @__PURE__ */ new WeakMap();
|
|
2023
|
+
function findServiceAdmission(service) {
|
|
2024
|
+
return serviceAdmissions.get(service);
|
|
2025
|
+
}
|
|
2026
|
+
function createEmailService(options) {
|
|
2027
|
+
return createEmailServiceWithClock(options, systemEmailClock);
|
|
2028
|
+
}
|
|
2029
|
+
function createEmailServiceWithClock(options, clock) {
|
|
2030
|
+
const raw = readRecord(options, ["scope", "store", "registry"], ["retry", "retention"], CONFIG);
|
|
2031
|
+
const scope = scopeToken(raw.scope, CONFIG);
|
|
2032
|
+
const retry = readRetryPolicy(readPolicy(raw.retry, DEFAULT_RETRY_POLICY), CONFIG);
|
|
2033
|
+
const retention = readRetentionPolicy(readPolicy(raw.retention, DEFAULT_RETENTION_POLICY), CONFIG);
|
|
2034
|
+
const find = bindMethod(raw.store, "findAdmission");
|
|
2035
|
+
const insert = bindMethod(raw.store, "insert");
|
|
2036
|
+
if (typeof raw.registry !== "object" || raw.registry === null || types6.isProxy(raw.registry)) invalid(CONFIG);
|
|
2037
|
+
const registry = raw.registry;
|
|
2038
|
+
const prepare = bindMethod(registry, "prepare");
|
|
2039
|
+
const internalPrepare = findRegistryPreparation(registry);
|
|
2040
|
+
async function prepareMiss(parsed, parent) {
|
|
2041
|
+
const { identity, command } = parsed;
|
|
2042
|
+
const accept = (value) => {
|
|
2043
|
+
const staged = validatePreparedCommand(scope, value);
|
|
2044
|
+
if (!sameCommandMetadata(
|
|
2045
|
+
staged.key,
|
|
2046
|
+
staged.snapshot.template.key,
|
|
2047
|
+
staged.snapshot.provider,
|
|
2048
|
+
staged.scheduleAt,
|
|
2049
|
+
identity
|
|
2050
|
+
) || staged.intentHash !== identity.intentHash || staged.fingerprint !== identity.fingerprint) {
|
|
2051
|
+
invalid("invalid_snapshot");
|
|
2052
|
+
}
|
|
2053
|
+
return staged;
|
|
2054
|
+
};
|
|
2055
|
+
if (internalPrepare) {
|
|
2056
|
+
let value;
|
|
2057
|
+
try {
|
|
2058
|
+
value = await internalPrepare(parsed, parent);
|
|
2059
|
+
} catch (error) {
|
|
2060
|
+
parent.check();
|
|
2061
|
+
return invalid(allowedErrorCode(error, PREPARATION_ERRORS) ?? "preparation_failed");
|
|
2062
|
+
}
|
|
2063
|
+
parent.check();
|
|
2064
|
+
return accept(value);
|
|
2065
|
+
}
|
|
2066
|
+
parent.check();
|
|
2067
|
+
let slots = injectedRegistrySlots.get(registry);
|
|
2068
|
+
if (!slots) {
|
|
2069
|
+
slots = { pending: 0 };
|
|
2070
|
+
injectedRegistrySlots.set(registry, slots);
|
|
2071
|
+
}
|
|
2072
|
+
if (slots.pending >= TEMPLATE_MAX_PENDING.default) invalid("busy");
|
|
2073
|
+
const budget = createChildBudget(clock, parent, CALL_BUDGETS.prepare.default);
|
|
2074
|
+
const occupied = slots;
|
|
2075
|
+
slots.pending++;
|
|
2076
|
+
const slot = new CallbackSlot(() => occupied.pending--);
|
|
2077
|
+
try {
|
|
2078
|
+
return await runHostCallback(
|
|
2079
|
+
budget,
|
|
2080
|
+
slot,
|
|
2081
|
+
"preparation_failed",
|
|
2082
|
+
() => {
|
|
2083
|
+
const timeoutMs = Math.max(CALL_BUDGETS.prepare.min, Math.ceil(budget.remainingMs()));
|
|
2084
|
+
budget.check();
|
|
2085
|
+
return prepare(scope, command, {
|
|
2086
|
+
signal: budget.signal,
|
|
2087
|
+
// The backing signal still has the exact narrower deadline below the public override floor.
|
|
2088
|
+
timeoutMs
|
|
2089
|
+
});
|
|
2090
|
+
},
|
|
2091
|
+
accept,
|
|
2092
|
+
PREPARATION_ERRORS
|
|
2093
|
+
);
|
|
2094
|
+
} finally {
|
|
2095
|
+
budget.close();
|
|
2096
|
+
slot.close();
|
|
2097
|
+
}
|
|
2098
|
+
}
|
|
2099
|
+
function findWinner(key, budget) {
|
|
2100
|
+
return runStoreCall(clock, budget, {
|
|
2101
|
+
maxMs: STORE_PRIMITIVE_TIMEOUT_MS,
|
|
2102
|
+
effect: "read",
|
|
2103
|
+
invoke: (call) => find(scope, key, call),
|
|
2104
|
+
accept(value) {
|
|
2105
|
+
if (value === null) return null;
|
|
2106
|
+
const raw2 = readRecord(value, ["job", "fingerprint"], [], STORED2);
|
|
2107
|
+
const job = readJobSummary(scope, raw2.job);
|
|
2108
|
+
if (encodeAdmissionKey(job.key) !== encodeAdmissionKey(key)) invalid(STORED2);
|
|
2109
|
+
return { job, fingerprint: hashToken(raw2.fingerprint, STORED2) };
|
|
2110
|
+
}
|
|
2111
|
+
});
|
|
2112
|
+
}
|
|
2113
|
+
function replay(winner, identity) {
|
|
2114
|
+
if (winner.fingerprint !== identity.fingerprint) invalid("idempotency_conflict");
|
|
2115
|
+
const { job } = winner;
|
|
2116
|
+
if (!matchesAdmissionJob(job, identity, "replayed")) invalid(STORED2);
|
|
2117
|
+
return Object.freeze({ status: "replayed", job });
|
|
2118
|
+
}
|
|
2119
|
+
async function insertOrConfirm(command, identity, budget) {
|
|
2120
|
+
budget.check();
|
|
2121
|
+
const admission = Object.freeze({ command, jobId: randomUUID(), retry, retention });
|
|
2122
|
+
try {
|
|
2123
|
+
const job = await runStoreCall(clock, budget, {
|
|
2124
|
+
maxMs: STORE_PRIMITIVE_TIMEOUT_MS,
|
|
2125
|
+
effect: "mutation",
|
|
2126
|
+
definite: INSERT_REJECTIONS,
|
|
2127
|
+
invoke: (call) => insert(scope, admission, call),
|
|
2128
|
+
accept(value) {
|
|
2129
|
+
const raw2 = readRecord(value, ["status"], ["job"], STORED2);
|
|
2130
|
+
if (raw2.status === "duplicate" && !Object.hasOwn(raw2, "job")) return null;
|
|
2131
|
+
if (raw2.status !== "inserted") invalid(STORED2);
|
|
2132
|
+
const job2 = readJobSummary(scope, raw2.job);
|
|
2133
|
+
const { snapshot } = command;
|
|
2134
|
+
if (job2.jobId !== admission.jobId || !matchesAdmissionJob(job2, identity, "enqueued") || job2.template.revision !== snapshot.template.revision || snapshot.preparedAt - job2.createdAt > MAX_PREPARED_AT_SKEW_MS || job2.expiresAt !== snapshot.expiresAt || job2.priority !== snapshot.priority || !sameCorrelation(job2.correlation, snapshot.correlation)) {
|
|
2135
|
+
invalid(STORED2);
|
|
2136
|
+
}
|
|
2137
|
+
return job2;
|
|
2138
|
+
}
|
|
2139
|
+
});
|
|
2140
|
+
if (job) return Object.freeze({ status: "enqueued", job });
|
|
2141
|
+
} catch (error) {
|
|
2142
|
+
if (!allowedErrorCode(error, UNCONFIRMED)) throw error;
|
|
2143
|
+
}
|
|
2144
|
+
try {
|
|
2145
|
+
const winner = await findWinner(identity.key, budget);
|
|
2146
|
+
if (winner) return replay(winner, identity);
|
|
2147
|
+
} catch (error) {
|
|
2148
|
+
if (allowedErrorCode(error, CONFLICT)) throw error;
|
|
2149
|
+
}
|
|
2150
|
+
return invalid("write_unconfirmed");
|
|
2151
|
+
}
|
|
2152
|
+
async function enqueueParsed(parsed, budget) {
|
|
2153
|
+
if (parsed.identity.scope !== scope) invalid("invalid_command");
|
|
2154
|
+
const winner = await findWinner(parsed.identity.key, budget);
|
|
2155
|
+
if (winner) return replay(winner, parsed.identity);
|
|
2156
|
+
return insertOrConfirm(await prepareMiss(parsed, budget), parsed.identity, budget);
|
|
2157
|
+
}
|
|
2158
|
+
async function inOperation(call, run) {
|
|
2159
|
+
const { timeoutMs, signal } = readCallOptions(call, CALL_BUDGETS.admissionOrAdmin);
|
|
2160
|
+
const budget = createBudget(clock, timeoutMs, signal);
|
|
2161
|
+
try {
|
|
2162
|
+
budget.check();
|
|
2163
|
+
return await run(budget);
|
|
2164
|
+
} finally {
|
|
2165
|
+
budget.close();
|
|
2166
|
+
}
|
|
2167
|
+
}
|
|
2168
|
+
const service = Object.freeze({
|
|
2169
|
+
scope,
|
|
2170
|
+
enqueue(command, call = {}) {
|
|
2171
|
+
return inOperation(call, (budget) => enqueueParsed(parseCommandIdentity(scope, command), budget));
|
|
2172
|
+
},
|
|
2173
|
+
enqueuePrepared(input, call = {}) {
|
|
2174
|
+
return inOperation(call, async (budget) => {
|
|
2175
|
+
const command = validatePreparedCommand(scope, input);
|
|
2176
|
+
const identity = {
|
|
2177
|
+
scope,
|
|
2178
|
+
key: command.key,
|
|
2179
|
+
templateKey: command.snapshot.template.key,
|
|
2180
|
+
provider: command.snapshot.provider,
|
|
2181
|
+
scheduleAt: command.scheduleAt,
|
|
2182
|
+
intentHash: command.intentHash,
|
|
2183
|
+
fingerprint: command.fingerprint
|
|
2184
|
+
};
|
|
2185
|
+
const winner = await findWinner(identity.key, budget);
|
|
2186
|
+
return winner ? replay(winner, identity) : insertOrConfirm(command, identity, budget);
|
|
2187
|
+
});
|
|
2188
|
+
}
|
|
2189
|
+
});
|
|
2190
|
+
serviceAdmissions.set(service, enqueueParsed);
|
|
2191
|
+
return service;
|
|
2192
|
+
}
|
|
2193
|
+
function readPolicy(input, defaults) {
|
|
2194
|
+
const result = { ...defaults };
|
|
2195
|
+
const keys = Object.keys(defaults);
|
|
2196
|
+
const raw = readRecord(input === void 0 ? {} : input, [], keys, CONFIG);
|
|
2197
|
+
for (const key of keys) {
|
|
2198
|
+
if (raw[key] !== void 0) result[key] = raw[key];
|
|
2199
|
+
}
|
|
2200
|
+
return result;
|
|
2201
|
+
}
|
|
2202
|
+
function sameCorrelation(left, right) {
|
|
2203
|
+
const keys = Object.keys(left);
|
|
2204
|
+
return keys.length === Object.keys(right).length && keys.every((key) => left[key] === right[key]);
|
|
2205
|
+
}
|
|
2206
|
+
|
|
2207
|
+
// src/worker.ts
|
|
2208
|
+
import { randomBytes, randomUUID as randomUUID3 } from "crypto";
|
|
2209
|
+
|
|
2210
|
+
// src/internal/worker-attempt.ts
|
|
2211
|
+
import { types as types7 } from "util";
|
|
2212
|
+
|
|
2213
|
+
// src/internal/worker-config.ts
|
|
2214
|
+
var CONFIG2 = "invalid_config";
|
|
2215
|
+
function readLimits(input) {
|
|
2216
|
+
const keys = Object.keys(WORKER_LIMIT_BOUNDS);
|
|
2217
|
+
const raw = readRecord(input === void 0 ? {} : input, [], keys, CONFIG2);
|
|
2218
|
+
const limits = {};
|
|
2219
|
+
for (const key of keys) limits[key] = boundedOption(raw[key], WORKER_LIMIT_BOUNDS[key]);
|
|
2220
|
+
const { leaseMs, storeTimeoutMs, providerTimeoutMs, finalizeGraceMs } = limits;
|
|
2221
|
+
if (leaseMs < Math.max(
|
|
2222
|
+
3 * storeTimeoutMs + CLOCK_MARGIN_MS,
|
|
2223
|
+
storeTimeoutMs + providerTimeoutMs + finalizeGraceMs + CLOCK_MARGIN_MS
|
|
2224
|
+
)) {
|
|
2225
|
+
invalid(CONFIG2);
|
|
2226
|
+
}
|
|
2227
|
+
return Object.freeze(limits);
|
|
2228
|
+
}
|
|
2229
|
+
function sameProvider(a, b) {
|
|
2230
|
+
return a.kind === b.kind && a.key === b.key && a.mode === b.mode;
|
|
2231
|
+
}
|
|
2232
|
+
function readProfiles(input) {
|
|
2233
|
+
const profiles = /* @__PURE__ */ new Map();
|
|
2234
|
+
readArray(input, Number.MAX_SAFE_INTEGER, CONFIG2, (provider) => {
|
|
2235
|
+
const ref = validateProviderRef(readPortMember(provider, "ref"), CONFIG2);
|
|
2236
|
+
if (profiles.has(ref.key)) invalid(CONFIG2);
|
|
2237
|
+
profiles.set(ref.key, Object.freeze({ ref, prepare: bindMethod(provider, "prepare") }));
|
|
2238
|
+
});
|
|
2239
|
+
return profiles;
|
|
2240
|
+
}
|
|
2241
|
+
function readResolvers(input) {
|
|
2242
|
+
const resolvers = /* @__PURE__ */ new Map();
|
|
2243
|
+
if (input !== void 0) {
|
|
2244
|
+
for (const key of plainKeys(input, Number.MAX_SAFE_INTEGER, CONFIG2)) {
|
|
2245
|
+
resolvers.set(
|
|
2246
|
+
identifier(key, CONFIG2),
|
|
2247
|
+
requireCallback(ownData(input, key, CONFIG2))
|
|
2248
|
+
);
|
|
2249
|
+
}
|
|
2250
|
+
}
|
|
2251
|
+
return resolvers;
|
|
2252
|
+
}
|
|
2253
|
+
function readLimiter(input) {
|
|
2254
|
+
if (input === void 0) return;
|
|
2255
|
+
const scope = readPortMember(input, "scope");
|
|
2256
|
+
if (scope !== "worker" && scope !== "shared") invalid(CONFIG2);
|
|
2257
|
+
return Object.freeze({ scope, tryAcquire: bindMethod(input, "tryAcquire") });
|
|
2258
|
+
}
|
|
2259
|
+
function readWorkerClock(input) {
|
|
2260
|
+
const clock = readClock(input);
|
|
2261
|
+
let last = -Infinity;
|
|
2262
|
+
return Object.freeze({
|
|
2263
|
+
...clock,
|
|
2264
|
+
monotonicNow() {
|
|
2265
|
+
const now = monotonicNow(clock);
|
|
2266
|
+
if (now < last) invalid(CONFIG2);
|
|
2267
|
+
last = now;
|
|
2268
|
+
return now;
|
|
2269
|
+
}
|
|
2270
|
+
});
|
|
2271
|
+
}
|
|
2272
|
+
function readWorkerConfig(input) {
|
|
2273
|
+
const raw = readRecord(
|
|
2274
|
+
input,
|
|
2275
|
+
["scope", "store", "providers"],
|
|
2276
|
+
["attachmentResolvers", "rateLimiter", "clock", "limits"],
|
|
2277
|
+
CONFIG2
|
|
2278
|
+
);
|
|
2279
|
+
const { store } = raw;
|
|
2280
|
+
return Object.freeze({
|
|
2281
|
+
scope: scopeToken(raw.scope, CONFIG2),
|
|
2282
|
+
limits: readLimits(raw.limits),
|
|
2283
|
+
clock: readWorkerClock(raw.clock),
|
|
2284
|
+
profiles: readProfiles(raw.providers),
|
|
2285
|
+
resolvers: readResolvers(raw.attachmentResolvers),
|
|
2286
|
+
limiter: readLimiter(raw.rateLimiter),
|
|
2287
|
+
store: Object.freeze({
|
|
2288
|
+
claimNext: bindMethod(store, "claimNext"),
|
|
2289
|
+
recoverNext: bindMethod(store, "recoverNext"),
|
|
2290
|
+
expireNext: bindMethod(store, "expireNext"),
|
|
2291
|
+
renew: bindMethod(store, "renew"),
|
|
2292
|
+
markHandoff: bindMethod(store, "markHandoff"),
|
|
2293
|
+
finish: bindMethod(store, "finish"),
|
|
2294
|
+
findAttempt: bindMethod(store, "findAttempt")
|
|
2295
|
+
})
|
|
2296
|
+
});
|
|
2297
|
+
}
|
|
2298
|
+
function readRunOptions(input, limits) {
|
|
2299
|
+
const { limit, concurrency, maintenanceLimit, ...call } = readRecord(
|
|
2300
|
+
input,
|
|
2301
|
+
[],
|
|
2302
|
+
["limit", "concurrency", "maintenanceLimit", "signal", "timeoutMs"],
|
|
2303
|
+
CONFIG2
|
|
2304
|
+
);
|
|
2305
|
+
return Object.freeze({
|
|
2306
|
+
...readCallOptions(call, CALL_BUDGETS.batchOrRun),
|
|
2307
|
+
limit: boundedOption(limit, RUN_CLAIM_LIMIT),
|
|
2308
|
+
concurrency: boundedOption(concurrency, { min: 1, max: limits.maxConcurrency, default: limits.maxConcurrency }),
|
|
2309
|
+
maintenanceLimit: boundedOption(maintenanceLimit, RUN_MAINTENANCE_LIMIT)
|
|
2310
|
+
});
|
|
2311
|
+
}
|
|
2312
|
+
function readShutdownOptions(input) {
|
|
2313
|
+
return readCallOptions(readRecord(input, [], ["timeoutMs"], CONFIG2), CALL_BUDGETS.shutdown);
|
|
2314
|
+
}
|
|
2315
|
+
|
|
2316
|
+
// src/internal/worker-evidence.ts
|
|
2317
|
+
var STORED3 = "store_incompatible";
|
|
2318
|
+
var MAX_ORDINARY_ATTEMPTS = RETRY_POLICY_BOUNDS.maxAttempts.max;
|
|
2319
|
+
function readGrant(times, leaseMs) {
|
|
2320
|
+
const grantedAt = unixMs(times.grantedAt, STORED3);
|
|
2321
|
+
const leaseEndsAt = unixMs(times.leaseEndsAt, STORED3);
|
|
2322
|
+
if (leaseEndsAt - grantedAt !== leaseMs) invalid(STORED3);
|
|
2323
|
+
return Object.freeze({ grantedAt, leaseEndsAt });
|
|
2324
|
+
}
|
|
2325
|
+
function readClaimed(value, scope, expected) {
|
|
2326
|
+
const raw = readRecord(value, ["job", "snapshot", "fence", "lease", "ordinal", "manual"], [], STORED3);
|
|
2327
|
+
const job = readJobSummary(scope, raw.job);
|
|
2328
|
+
const { snapshot } = validateSnapshot(raw.snapshot);
|
|
2329
|
+
const fence = readFence(raw.fence);
|
|
2330
|
+
const lease = readGrant(readRecord(raw.lease, ["grantedAt", "leaseEndsAt"], [], STORED3), expected.leaseMs);
|
|
2331
|
+
const ordinal = integer(raw.ordinal, 1, MAX_ATTEMPT_LEDGER, STORED3);
|
|
2332
|
+
const { manual } = raw;
|
|
2333
|
+
const { grantedAt } = lease;
|
|
2334
|
+
const [redrive, more] = job.resolutions;
|
|
2335
|
+
if (job.state !== "leased" || job.phase !== "pre_handoff" || fence.jobId !== job.jobId || fence.attemptId !== expected.attemptId || fence.token !== expected.token || job.latestAttempt?.attemptId === fence.attemptId || ordinal !== job.attemptCount || typeof manual !== "boolean" || (manual ? redrive?.action !== "redrive" || more !== void 0 || redrive.at < job.createdAt || redrive.at > grantedAt || redrive.attemptId !== job.latestAttempt?.attemptId || job.latestAttempt.outcome !== "unknown" : redrive !== void 0 || ordinal > MAX_ORDINARY_ATTEMPTS || job.latestAttempt !== void 0 && !isSafeTransient(job.latestAttempt.reason)) || grantedAt !== job.updatedAt || grantedAt < (job.scheduleAt ?? job.createdAt) || grantedAt >= job.expiresAt || snapshot.preparedAt - job.createdAt > MAX_PREPARED_AT_SKEW_MS || snapshot.expiresAt !== job.expiresAt || snapshot.priority !== job.priority || !sameProvider(snapshot.provider, job.provider) || snapshot.template.key !== job.template.key || snapshot.template.revision !== job.template.revision || canonicalJson(snapshot.correlation, 4096, STORED3).encoded !== canonicalJson(job.correlation, 4096, STORED3).encoded) {
|
|
2336
|
+
invalid(STORED3);
|
|
2337
|
+
}
|
|
2338
|
+
return Object.freeze({ job, snapshot, fence, lease, ordinal, manual });
|
|
2339
|
+
}
|
|
2340
|
+
function safeLeaseEnd({ dispatchedAt, grant }) {
|
|
2341
|
+
return dispatchedAt + (grant.leaseEndsAt - grant.grantedAt) - CLOCK_MARGIN_MS;
|
|
2342
|
+
}
|
|
2343
|
+
function assertLaterGrant(grant, last, expiresAt, times) {
|
|
2344
|
+
const elapsed = grant.grantedAt - last.grant.grantedAt;
|
|
2345
|
+
if (elapsed < Math.max(0, times.dispatchedAt - last.confirmedAt - CLOCK_MARGIN_MS) || elapsed > times.confirmedAt - last.dispatchedAt + CLOCK_MARGIN_MS || grant.grantedAt >= Math.min(last.grant.leaseEndsAt, expiresAt)) {
|
|
2346
|
+
invalid(STORED3);
|
|
2347
|
+
}
|
|
2348
|
+
}
|
|
2349
|
+
function readRenewed(value, last, claim, leaseMs, times) {
|
|
2350
|
+
const grant = readGrant(readRecord(value, ["grantedAt", "leaseEndsAt"], [], STORED3), leaseMs);
|
|
2351
|
+
assertLaterGrant(grant, last, claim.job.expiresAt, times);
|
|
2352
|
+
if (grant.leaseEndsAt <= last.grant.leaseEndsAt) invalid(STORED3);
|
|
2353
|
+
return grant;
|
|
2354
|
+
}
|
|
2355
|
+
function readHandoff(value, last, claim, leaseMs, times) {
|
|
2356
|
+
const raw = readRecord(value, ["grantedAt", "leaseEndsAt", "handoffAt"], [], STORED3);
|
|
2357
|
+
const grant = readGrant(raw, leaseMs);
|
|
2358
|
+
const handoffAt = unixMs(raw.handoffAt, STORED3);
|
|
2359
|
+
if (handoffAt !== grant.grantedAt) invalid(STORED3);
|
|
2360
|
+
assertLaterGrant(grant, last, claim.job.expiresAt, times);
|
|
2361
|
+
return Object.freeze({ ...grant, handoffAt });
|
|
2362
|
+
}
|
|
2363
|
+
function readCommit(value) {
|
|
2364
|
+
const raw = readRecord(
|
|
2365
|
+
value,
|
|
2366
|
+
["jobId", "attemptId", "ordinal", "operationId", "startedAt", "finishedAt", "result", "disposition", "reason"],
|
|
2367
|
+
["handedOffAt", "retryAt"],
|
|
2368
|
+
STORED3
|
|
2369
|
+
);
|
|
2370
|
+
const startedAt = unixMs(raw.startedAt, STORED3);
|
|
2371
|
+
const finishedAt = unixMs(raw.finishedAt, STORED3);
|
|
2372
|
+
const handedOffAt = Object.hasOwn(raw, "handedOffAt") ? unixMs(raw.handedOffAt, STORED3) : void 0;
|
|
2373
|
+
const retryAt = Object.hasOwn(raw, "retryAt") ? unixMs(raw.retryAt, STORED3) : void 0;
|
|
2374
|
+
const result = readAttemptResult(raw.result, STORED3);
|
|
2375
|
+
const disposition = readDisposition(raw.disposition, STORED3);
|
|
2376
|
+
const reason = raw.reason === "attempts_exhausted" ? raw.reason : readAttemptReason(raw.reason, STORED3);
|
|
2377
|
+
assertEvidencePhase(result.reason, handedOffAt === void 0 ? "pre_handoff" : "handed_off", "ledger", STORED3);
|
|
2378
|
+
assertActivityDisposition(result, disposition, STORED3);
|
|
2379
|
+
const expectedReason = disposition === "expired" ? "expired" : result.retry === "safe_transient" && (disposition === "failed" || disposition === "rejected") ? "attempts_exhausted" : result.reason;
|
|
2380
|
+
if (finishedAt < startedAt || handedOffAt !== void 0 && (handedOffAt < startedAt || handedOffAt > finishedAt) || reason !== expectedReason || retryAt !== void 0 !== (disposition === "retry_scheduled") || retryAt !== void 0 && (retryAt <= finishedAt || retryAt - finishedAt < (result.retryHint?.delayMs ?? 0) || retryAt < (result.retryHint?.notBefore ?? 0))) {
|
|
2381
|
+
invalid(STORED3);
|
|
2382
|
+
}
|
|
2383
|
+
return Object.freeze({
|
|
2384
|
+
jobId: readStoreId(raw.jobId, STORED3),
|
|
2385
|
+
attemptId: readStoreId(raw.attemptId, STORED3),
|
|
2386
|
+
ordinal: integer(raw.ordinal, 1, MAX_ATTEMPT_LEDGER, STORED3),
|
|
2387
|
+
operationId: readStoreId(raw.operationId, STORED3),
|
|
2388
|
+
startedAt,
|
|
2389
|
+
finishedAt,
|
|
2390
|
+
result,
|
|
2391
|
+
disposition,
|
|
2392
|
+
reason,
|
|
2393
|
+
...handedOffAt === void 0 ? {} : { handedOffAt },
|
|
2394
|
+
...retryAt === void 0 ? {} : { retryAt }
|
|
2395
|
+
});
|
|
2396
|
+
}
|
|
2397
|
+
function readRecovery(value) {
|
|
2398
|
+
const commit = readCommit(value);
|
|
2399
|
+
const { result, startedAt, handedOffAt, finishedAt } = commit;
|
|
2400
|
+
if (result.reason !== "pre_handoff_lease_expired" && result.reason !== "post_handoff_lease_expired" || finishedAt - (handedOffAt ?? startedAt) < WORKER_LIMIT_BOUNDS.leaseMs.min) {
|
|
2401
|
+
invalid(STORED3);
|
|
2402
|
+
}
|
|
2403
|
+
return commit;
|
|
2404
|
+
}
|
|
2405
|
+
function readQueuedExpiry(value, scope) {
|
|
2406
|
+
const job = readJobSummary(scope, value);
|
|
2407
|
+
if (job.state !== "terminal" || job.disposition !== "expired" || job.terminalReason !== "expired" || job.terminalAt < job.expiresAt || job.updatedAt !== job.terminalAt) {
|
|
2408
|
+
invalid(STORED3);
|
|
2409
|
+
}
|
|
2410
|
+
return job;
|
|
2411
|
+
}
|
|
2412
|
+
function readOwnedCommit(value, { claim, lease, handoff }, request, providerInvoked, direct) {
|
|
2413
|
+
const commit = readCommit(value);
|
|
2414
|
+
const { attemptId, startedAt, handedOffAt, finishedAt, result, disposition, retryAt } = commit;
|
|
2415
|
+
const { job, snapshot, fence, ordinal, manual } = claim;
|
|
2416
|
+
const { expiresAt } = job;
|
|
2417
|
+
const canHaveRetryBudget = !manual && ordinal < MAX_ORDINARY_ATTEMPTS;
|
|
2418
|
+
const last = handoff && handoff !== "unconfirmed" ? handoff.grant : lease.grant;
|
|
2419
|
+
const markedLeaseMs = claim.lease.leaseEndsAt - claim.lease.grantedAt;
|
|
2420
|
+
if (commit.jobId !== fence.jobId || attemptId !== fence.attemptId || startedAt !== claim.lease.grantedAt || commit.ordinal !== ordinal || finishedAt < last.grantedAt || handoff !== "unconfirmed" && handedOffAt !== handoff?.grant.handoffAt || handedOffAt !== void 0 && (handedOffAt < lease.grant.grantedAt || handedOffAt >= Math.min(expiresAt, lease.grant.leaseEndsAt)) || result.reason === "cancelled" && finishedAt >= expiresAt || result.reason === "expired" && finishedAt < expiresAt || result.reason === "pre_handoff_lease_expired" && finishedAt < lease.grant.leaseEndsAt || result.reason === "post_handoff_lease_expired" && (handedOffAt === void 0 || finishedAt - handedOffAt < markedLeaseMs) || handedOffAt !== void 0 && result.reason !== "post_handoff_lease_expired" && (result.reason === "launch_window_closed" ? providerInvoked || handoff === "unconfirmed" : !providerInvoked) || result.retry === "safe_transient" && finishedAt >= expiresAt && disposition !== "expired" || result.retry === "safe_transient" && finishedAt < expiresAt && disposition === "expired" && !canHaveRetryBudget || retryAt !== void 0 && (!canHaveRetryBudget || retryAt >= expiresAt)) {
|
|
2421
|
+
invalid(STORED3);
|
|
2422
|
+
}
|
|
2423
|
+
assertEvidenceContext(result, snapshot.provider, attemptId, recipientCounts(snapshot.envelope), STORED3);
|
|
2424
|
+
if (request && commit.operationId === request.operationId) {
|
|
2425
|
+
const phase = handedOffAt === void 0 ? "pre_handoff" : "handed_off";
|
|
2426
|
+
if (phase !== request.phase || finishedAt >= last.leaseEndsAt || canonicalJson(result, 8192, STORED3).encoded !== canonicalJson(request.result, 8192, STORED3).encoded) {
|
|
2427
|
+
invalid(STORED3);
|
|
2428
|
+
}
|
|
2429
|
+
} else if (direct) {
|
|
2430
|
+
invalid(STORED3);
|
|
2431
|
+
}
|
|
2432
|
+
return commit;
|
|
2433
|
+
}
|
|
2434
|
+
|
|
2435
|
+
// src/internal/worker-finish.ts
|
|
2436
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
2437
|
+
async function finishAttempt(run, evidence2, providerInvoked, result) {
|
|
2438
|
+
const { clock, store, scope, limits } = run.config;
|
|
2439
|
+
const {
|
|
2440
|
+
claim: { fence },
|
|
2441
|
+
handoff,
|
|
2442
|
+
lease
|
|
2443
|
+
} = evidence2;
|
|
2444
|
+
const now = monotonicNow(clock);
|
|
2445
|
+
const request = result && handoff !== "unconfirmed" ? Object.freeze({ fence, phase: handoff ? "handed_off" : "pre_handoff", operationId: randomUUID2(), result }) : void 0;
|
|
2446
|
+
const leaseEnd = safeLeaseEnd(handoff && handoff !== "unconfirmed" ? handoff : lease);
|
|
2447
|
+
const grace = createBudgetUntil(clock, Math.min(now, run.budget.deadline) + limits.finalizeGraceMs);
|
|
2448
|
+
async function confirm() {
|
|
2449
|
+
try {
|
|
2450
|
+
return await run.callStore(grace, {
|
|
2451
|
+
effect: "read",
|
|
2452
|
+
invoke: (call) => store.findAttempt(scope, fence.jobId, fence.attemptId, call),
|
|
2453
|
+
accept: (value) => value === null ? null : readOwnedCommit(value, evidence2, request, providerInvoked, false)
|
|
2454
|
+
});
|
|
2455
|
+
} catch {
|
|
2456
|
+
return null;
|
|
2457
|
+
}
|
|
2458
|
+
}
|
|
2459
|
+
function write(exact) {
|
|
2460
|
+
return run.callStore(grace, {
|
|
2461
|
+
effect: "mutation",
|
|
2462
|
+
deadline: leaseEnd,
|
|
2463
|
+
invoke: (call) => store.finish(scope, exact, call),
|
|
2464
|
+
accept: (value) => value === null ? null : readOwnedCommit(value, evidence2, exact, providerInvoked, true)
|
|
2465
|
+
});
|
|
2466
|
+
}
|
|
2467
|
+
try {
|
|
2468
|
+
if (!request || now >= leaseEnd) return await confirm();
|
|
2469
|
+
let retry = false;
|
|
2470
|
+
try {
|
|
2471
|
+
const committed = await write(request);
|
|
2472
|
+
if (committed) return committed;
|
|
2473
|
+
} catch (error) {
|
|
2474
|
+
retry = allowedErrorCode(error, ["write_unconfirmed"]) !== void 0;
|
|
2475
|
+
}
|
|
2476
|
+
const winner = await confirm();
|
|
2477
|
+
if (winner || !retry || grace.remainingMs() < 1 || monotonicNow(clock) >= leaseEnd) return winner;
|
|
2478
|
+
try {
|
|
2479
|
+
const committed = await write(request);
|
|
2480
|
+
if (committed) return committed;
|
|
2481
|
+
} catch {
|
|
2482
|
+
}
|
|
2483
|
+
return await confirm();
|
|
2484
|
+
} finally {
|
|
2485
|
+
grace.close();
|
|
2486
|
+
}
|
|
2487
|
+
}
|
|
2488
|
+
|
|
2489
|
+
// src/internal/worker-preflight.ts
|
|
2490
|
+
var stages = {
|
|
2491
|
+
attachment_unavailable: ["attachment", "safe_transient"],
|
|
2492
|
+
attachment_timeout: ["attachment", "safe_transient"],
|
|
2493
|
+
attachment_invalid: ["attachment", "never"],
|
|
2494
|
+
attachment_resolver_error: ["attachment", "never"],
|
|
2495
|
+
rate_deferred: ["rate_limit", "safe_transient"],
|
|
2496
|
+
rate_timeout: ["rate_limit", "safe_transient"],
|
|
2497
|
+
rate_error: ["rate_limit", "never"],
|
|
2498
|
+
profile_unavailable: ["pre_handoff", "never"],
|
|
2499
|
+
provider_preflight_error: ["pre_handoff", "never"],
|
|
2500
|
+
pre_handoff_timeout: ["pre_handoff", "safe_transient"],
|
|
2501
|
+
worker_stopped: ["pre_handoff", "safe_transient"],
|
|
2502
|
+
launch_window_closed: ["pre_handoff", "safe_transient"]
|
|
2503
|
+
};
|
|
2504
|
+
function unsubmitted(reason, delayMs) {
|
|
2505
|
+
const [stage, retry] = stages[reason];
|
|
2506
|
+
return Object.freeze({
|
|
2507
|
+
outcome: "unsubmitted",
|
|
2508
|
+
stage,
|
|
2509
|
+
retry,
|
|
2510
|
+
reason,
|
|
2511
|
+
...delayMs === void 0 ? {} : { retryHint: Object.freeze({ delayMs }) }
|
|
2512
|
+
});
|
|
2513
|
+
}
|
|
2514
|
+
function stoppedPreflight(error) {
|
|
2515
|
+
return unsubmitted(allowedErrorCode(error, ["deadline"]) ? "pre_handoff_timeout" : "worker_stopped");
|
|
2516
|
+
}
|
|
2517
|
+
async function resolveAttachments(config, { snapshot }, budget, slot) {
|
|
2518
|
+
const attachments = [];
|
|
2519
|
+
if (!snapshot.attachments.length) return { attachments: Object.freeze(attachments) };
|
|
2520
|
+
const stage = createChildBudget(config.clock, budget, config.limits.attachmentTimeoutMs);
|
|
2521
|
+
const context = Object.freeze({ scope: config.scope, signal: stage.signal });
|
|
2522
|
+
try {
|
|
2523
|
+
for (const ref of snapshot.attachments) {
|
|
2524
|
+
stage.check();
|
|
2525
|
+
const resolve = config.resolvers.get(ref.resolverKey);
|
|
2526
|
+
if (!resolve) return { result: unsubmitted("attachment_invalid") };
|
|
2527
|
+
const bytes = await runHostCallback(
|
|
2528
|
+
stage,
|
|
2529
|
+
slot,
|
|
2530
|
+
"preparation_failed",
|
|
2531
|
+
() => resolve(ref, context),
|
|
2532
|
+
(value) => {
|
|
2533
|
+
const raw = readRecord(value, ["status"], ["bytes"], "invalid_snapshot");
|
|
2534
|
+
if (raw.status === "unavailable" && !Object.hasOwn(raw, "bytes")) return null;
|
|
2535
|
+
if (raw.status !== "found") invalid("invalid_snapshot");
|
|
2536
|
+
return copyAttachmentBytes(ref, raw.bytes);
|
|
2537
|
+
}
|
|
2538
|
+
);
|
|
2539
|
+
if (!bytes) return { result: unsubmitted("attachment_unavailable") };
|
|
2540
|
+
attachments.push(Object.freeze({ ref, bytes }));
|
|
2541
|
+
}
|
|
2542
|
+
return { attachments: Object.freeze(attachments) };
|
|
2543
|
+
} catch (error) {
|
|
2544
|
+
budget.check();
|
|
2545
|
+
const code = allowedErrorCode(error, ["deadline", "invalid_snapshot"]);
|
|
2546
|
+
return {
|
|
2547
|
+
result: unsubmitted(
|
|
2548
|
+
code === "deadline" ? "attachment_timeout" : code === "invalid_snapshot" ? "attachment_invalid" : "attachment_resolver_error"
|
|
2549
|
+
)
|
|
2550
|
+
};
|
|
2551
|
+
} finally {
|
|
2552
|
+
stage.close();
|
|
2553
|
+
}
|
|
2554
|
+
}
|
|
2555
|
+
async function ratePermission(config, { snapshot }, budget, slot) {
|
|
2556
|
+
if (!config.limiter) return;
|
|
2557
|
+
const { tryAcquire } = config.limiter;
|
|
2558
|
+
const stage = createChildBudget(config.clock, budget, config.limits.rateTimeoutMs);
|
|
2559
|
+
try {
|
|
2560
|
+
const retryAfter = await runHostCallback(
|
|
2561
|
+
stage,
|
|
2562
|
+
slot,
|
|
2563
|
+
"preparation_failed",
|
|
2564
|
+
() => tryAcquire(Object.freeze({ scope: config.scope, provider: snapshot.provider, signal: stage.signal })),
|
|
2565
|
+
(value) => {
|
|
2566
|
+
const raw = readRecord(value, ["status"], ["retryAfterMs"], "invalid_config");
|
|
2567
|
+
if (raw.status === "granted" && !Object.hasOwn(raw, "retryAfterMs")) return void 0;
|
|
2568
|
+
if (raw.status !== "deferred") invalid("invalid_config");
|
|
2569
|
+
return integer(raw.retryAfterMs, 1, MAX_RATE_DEFERRAL_MS, "invalid_config");
|
|
2570
|
+
}
|
|
2571
|
+
);
|
|
2572
|
+
return retryAfter === void 0 ? void 0 : unsubmitted("rate_deferred", retryAfter);
|
|
2573
|
+
} catch (error) {
|
|
2574
|
+
budget.check();
|
|
2575
|
+
return unsubmitted(allowedErrorCode(error, ["deadline"]) ? "rate_timeout" : "rate_error");
|
|
2576
|
+
} finally {
|
|
2577
|
+
stage.close();
|
|
2578
|
+
}
|
|
2579
|
+
}
|
|
2580
|
+
async function prepareAttempt(config, claim, budget, slot) {
|
|
2581
|
+
const { snapshot, fence } = claim;
|
|
2582
|
+
try {
|
|
2583
|
+
budget.check();
|
|
2584
|
+
const profile = config.profiles.get(snapshot.provider.key);
|
|
2585
|
+
if (!profile || !sameProvider(profile.ref, snapshot.provider))
|
|
2586
|
+
return { result: unsubmitted("profile_unavailable") };
|
|
2587
|
+
const resolved = await resolveAttachments(config, claim, budget, slot);
|
|
2588
|
+
if ("result" in resolved) return resolved;
|
|
2589
|
+
let submit;
|
|
2590
|
+
try {
|
|
2591
|
+
const prepared = runSyncCallback(
|
|
2592
|
+
budget,
|
|
2593
|
+
slot,
|
|
2594
|
+
"preparation_failed",
|
|
2595
|
+
() => profile.prepare(
|
|
2596
|
+
Object.freeze({
|
|
2597
|
+
jobId: fence.jobId,
|
|
2598
|
+
attemptId: fence.attemptId,
|
|
2599
|
+
snapshot,
|
|
2600
|
+
attachments: resolved.attachments
|
|
2601
|
+
})
|
|
2602
|
+
)
|
|
2603
|
+
);
|
|
2604
|
+
if (readPortMember(prepared, "then") !== void 0) invalid("preparation_failed");
|
|
2605
|
+
submit = bindMethod(prepared, "submit");
|
|
2606
|
+
} catch {
|
|
2607
|
+
budget.check();
|
|
2608
|
+
return { result: unsubmitted("provider_preflight_error") };
|
|
2609
|
+
}
|
|
2610
|
+
const deferred = await ratePermission(config, claim, budget, slot);
|
|
2611
|
+
if (deferred) return { result: deferred };
|
|
2612
|
+
budget.check();
|
|
2613
|
+
return { submit };
|
|
2614
|
+
} catch (error) {
|
|
2615
|
+
return { result: stoppedPreflight(error) };
|
|
2616
|
+
}
|
|
2617
|
+
}
|
|
2618
|
+
|
|
2619
|
+
// src/internal/worker-attempt.ts
|
|
2620
|
+
var AttemptOwner = class {
|
|
2621
|
+
constructor(run, claim, times) {
|
|
2622
|
+
this.run = run;
|
|
2623
|
+
this.claim = claim;
|
|
2624
|
+
this.lease = { ...times, grant: claim.lease };
|
|
2625
|
+
}
|
|
2626
|
+
run;
|
|
2627
|
+
claim;
|
|
2628
|
+
lease;
|
|
2629
|
+
handoff;
|
|
2630
|
+
#lost = new AbortController();
|
|
2631
|
+
get lost() {
|
|
2632
|
+
return this.#lost.signal;
|
|
2633
|
+
}
|
|
2634
|
+
checkLease() {
|
|
2635
|
+
if (this.lost.aborted || monotonicNow(this.run.config.clock) >= safeLeaseEnd(this.lease)) {
|
|
2636
|
+
this.#lost.abort();
|
|
2637
|
+
invalid("aborted");
|
|
2638
|
+
}
|
|
2639
|
+
}
|
|
2640
|
+
async renewWhile(budget, stopped) {
|
|
2641
|
+
const { clock, limits } = this.run.config;
|
|
2642
|
+
const cadence = Math.floor(limits.leaseMs / 3);
|
|
2643
|
+
const waitSignal = AbortSignal.any([stopped, this.run.noLaunch]);
|
|
2644
|
+
while (!waitSignal.aborted) {
|
|
2645
|
+
try {
|
|
2646
|
+
budget.check();
|
|
2647
|
+
const due = this.lease.dispatchedAt + cadence;
|
|
2648
|
+
if (due >= budget.deadline) return;
|
|
2649
|
+
if (monotonicNow(clock) < due) {
|
|
2650
|
+
const wait = createChildBudgetUntil(clock, budget, due, waitSignal);
|
|
2651
|
+
try {
|
|
2652
|
+
await waitForAbort(wait.signal);
|
|
2653
|
+
if (allowedErrorCode(wait.signal.reason, ["invalid_config"])) invalid("invalid_config");
|
|
2654
|
+
} finally {
|
|
2655
|
+
wait.close();
|
|
2656
|
+
}
|
|
2657
|
+
}
|
|
2658
|
+
if (waitSignal.aborted) return;
|
|
2659
|
+
budget.check();
|
|
2660
|
+
this.checkLease();
|
|
2661
|
+
const grant = await this.#ownerWrite(budget, this.run.config.store.renew, readRenewed);
|
|
2662
|
+
if (!grant) return;
|
|
2663
|
+
this.lease = grant;
|
|
2664
|
+
} catch (error) {
|
|
2665
|
+
if (allowedErrorCode(error, ["invalid_config"])) this.#lost.abort();
|
|
2666
|
+
return;
|
|
2667
|
+
}
|
|
2668
|
+
}
|
|
2669
|
+
}
|
|
2670
|
+
async mark(budget) {
|
|
2671
|
+
const grant = await this.#ownerWrite(budget, this.run.config.store.markHandoff, readHandoff, () => {
|
|
2672
|
+
this.handoff = "unconfirmed";
|
|
2673
|
+
});
|
|
2674
|
+
this.handoff = grant ?? void 0;
|
|
2675
|
+
return grant;
|
|
2676
|
+
}
|
|
2677
|
+
async #ownerWrite(budget, invoke, read, onDispatch) {
|
|
2678
|
+
const {
|
|
2679
|
+
clock,
|
|
2680
|
+
scope,
|
|
2681
|
+
limits: { leaseMs }
|
|
2682
|
+
} = this.run.config;
|
|
2683
|
+
const { claim, lease } = this;
|
|
2684
|
+
const { fence } = claim;
|
|
2685
|
+
let dispatchedAt;
|
|
2686
|
+
try {
|
|
2687
|
+
const grant = await this.run.callStore(budget, {
|
|
2688
|
+
effect: "mutation",
|
|
2689
|
+
authorize: true,
|
|
2690
|
+
deadline: safeLeaseEnd(lease),
|
|
2691
|
+
beforeInvoke: () => this.checkLease(),
|
|
2692
|
+
invoke: (call, start) => {
|
|
2693
|
+
dispatchedAt = start;
|
|
2694
|
+
onDispatch?.();
|
|
2695
|
+
return invoke(scope, fence, leaseMs, call);
|
|
2696
|
+
},
|
|
2697
|
+
accept: (value) => {
|
|
2698
|
+
if (value === null) return null;
|
|
2699
|
+
const times = { dispatchedAt, confirmedAt: monotonicNow(clock) };
|
|
2700
|
+
return Object.freeze({ ...times, grant: read(value, lease, claim, leaseMs, times) });
|
|
2701
|
+
}
|
|
2702
|
+
});
|
|
2703
|
+
if (!grant) this.#lost.abort();
|
|
2704
|
+
return grant;
|
|
2705
|
+
} catch (error) {
|
|
2706
|
+
if (dispatchedAt !== void 0) this.#lost.abort();
|
|
2707
|
+
throw error;
|
|
2708
|
+
}
|
|
2709
|
+
}
|
|
2710
|
+
};
|
|
2711
|
+
async function launch(run, owner, mark, submit, preflight) {
|
|
2712
|
+
const { clock, limits } = run.config;
|
|
2713
|
+
const { provider, envelope, expiresAt } = owner.claim.snapshot;
|
|
2714
|
+
const { attemptId } = owner.claim.fence;
|
|
2715
|
+
const launchEnd = Math.min(
|
|
2716
|
+
preflight.deadline,
|
|
2717
|
+
mark.dispatchedAt + (expiresAt - mark.grant.handoffAt) - CLOCK_MARGIN_MS
|
|
2718
|
+
);
|
|
2719
|
+
const stage = provider.kind === "smtp" ? "data" : "http";
|
|
2720
|
+
const unknown = (reason) => Object.freeze({ outcome: "unknown", retry: "never", stage, reason });
|
|
2721
|
+
let io;
|
|
2722
|
+
try {
|
|
2723
|
+
run.checkLaunch();
|
|
2724
|
+
preflight.check();
|
|
2725
|
+
const now = monotonicNow(clock);
|
|
2726
|
+
if (now >= launchEnd) return;
|
|
2727
|
+
io = createChildBudgetUntil(
|
|
2728
|
+
clock,
|
|
2729
|
+
run.budget,
|
|
2730
|
+
Math.min(now + limits.providerTimeoutMs, safeLeaseEnd(mark) - limits.finalizeGraceMs)
|
|
2731
|
+
);
|
|
2732
|
+
run.checkLaunch();
|
|
2733
|
+
io.check();
|
|
2734
|
+
const before = monotonicNow(clock);
|
|
2735
|
+
const timeoutMs = Math.floor(io.deadline - before);
|
|
2736
|
+
if (before >= launchEnd || timeoutMs < 1 || io.signal.aborted || preflight.signal.aborted || run.noLaunch.aborted)
|
|
2737
|
+
return;
|
|
2738
|
+
try {
|
|
2739
|
+
const returned = submit(Object.freeze({ signal: io.signal, timeoutMs }));
|
|
2740
|
+
const pending = pendingCallback(returned);
|
|
2741
|
+
if (!pending) return unknown("transport_uncertain");
|
|
2742
|
+
const raw = await pending;
|
|
2743
|
+
if (!types7.isPromise(returned)) return unknown("transport_uncertain");
|
|
2744
|
+
let result;
|
|
2745
|
+
try {
|
|
2746
|
+
result = readProviderResult(raw, provider, attemptId, envelope);
|
|
2747
|
+
} catch {
|
|
2748
|
+
return unknown("transport_uncertain");
|
|
2749
|
+
}
|
|
2750
|
+
try {
|
|
2751
|
+
io.check();
|
|
2752
|
+
} catch (error) {
|
|
2753
|
+
const code = allowedErrorCode(error, ["deadline", "aborted"]);
|
|
2754
|
+
return unknown(
|
|
2755
|
+
code === "deadline" ? "provider_timeout" : code === "aborted" ? "provider_aborted" : "transport_uncertain"
|
|
2756
|
+
);
|
|
2757
|
+
}
|
|
2758
|
+
return result;
|
|
2759
|
+
} catch {
|
|
2760
|
+
return unknown("transport_uncertain");
|
|
2761
|
+
}
|
|
2762
|
+
} catch {
|
|
2763
|
+
return;
|
|
2764
|
+
} finally {
|
|
2765
|
+
io?.close();
|
|
2766
|
+
}
|
|
2767
|
+
}
|
|
2768
|
+
async function processOwned(owner, slot) {
|
|
2769
|
+
const { run, claim, lease } = owner;
|
|
2770
|
+
const { clock, limits } = run.config;
|
|
2771
|
+
const deadline = lease.dispatchedAt + limits.preHandoffTimeoutMs;
|
|
2772
|
+
let budget;
|
|
2773
|
+
try {
|
|
2774
|
+
budget = createChildBudgetUntil(clock, run.budget, deadline);
|
|
2775
|
+
const host = createChildBudgetUntil(clock, budget, deadline, AbortSignal.any([run.noLaunch, owner.lost]));
|
|
2776
|
+
const stopRenewal = new AbortController();
|
|
2777
|
+
const renewal = owner.renewWhile(budget, stopRenewal.signal);
|
|
2778
|
+
let preflight;
|
|
2779
|
+
try {
|
|
2780
|
+
preflight = await prepareAttempt(
|
|
2781
|
+
run.config,
|
|
2782
|
+
claim,
|
|
2783
|
+
{
|
|
2784
|
+
...host,
|
|
2785
|
+
check() {
|
|
2786
|
+
host.check();
|
|
2787
|
+
owner.checkLease();
|
|
2788
|
+
}
|
|
2789
|
+
},
|
|
2790
|
+
slot
|
|
2791
|
+
);
|
|
2792
|
+
} finally {
|
|
2793
|
+
stopRenewal.abort();
|
|
2794
|
+
host.close();
|
|
2795
|
+
await renewal;
|
|
2796
|
+
}
|
|
2797
|
+
if ("result" in preflight) return { result: preflight.result, providerInvoked: false };
|
|
2798
|
+
const mark = await owner.mark(budget);
|
|
2799
|
+
if (mark) {
|
|
2800
|
+
const result = await launch(run, owner, mark, preflight.submit, budget);
|
|
2801
|
+
return {
|
|
2802
|
+
result: result ?? unsubmitted("launch_window_closed"),
|
|
2803
|
+
providerInvoked: result !== void 0
|
|
2804
|
+
};
|
|
2805
|
+
}
|
|
2806
|
+
} catch (error) {
|
|
2807
|
+
return { result: stoppedPreflight(error), providerInvoked: false };
|
|
2808
|
+
} finally {
|
|
2809
|
+
budget?.close();
|
|
2810
|
+
}
|
|
2811
|
+
return { providerInvoked: false };
|
|
2812
|
+
}
|
|
2813
|
+
async function processClaim(run, claim, times, slot) {
|
|
2814
|
+
const owner = new AttemptOwner(run, claim, times);
|
|
2815
|
+
const { result, providerInvoked } = await processOwned(owner, slot);
|
|
2816
|
+
const commit = await finishAttempt(run, owner, providerInvoked, owner.lost.aborted ? void 0 : result);
|
|
2817
|
+
return Object.freeze({
|
|
2818
|
+
operation: "claim",
|
|
2819
|
+
jobId: claim.fence.jobId,
|
|
2820
|
+
attemptId: claim.fence.attemptId,
|
|
2821
|
+
providerInvoked,
|
|
2822
|
+
...commit ? { status: commit.disposition, reason: commit.reason } : { status: "unconfirmed" }
|
|
2823
|
+
});
|
|
2824
|
+
}
|
|
2825
|
+
|
|
2826
|
+
// src/internal/worker-run.ts
|
|
2827
|
+
var WorkerRun = class {
|
|
2828
|
+
constructor(config, budget) {
|
|
2829
|
+
this.config = config;
|
|
2830
|
+
this.budget = budget;
|
|
2831
|
+
}
|
|
2832
|
+
config;
|
|
2833
|
+
budget;
|
|
2834
|
+
#noLaunch = new AbortController();
|
|
2835
|
+
#persistenceFailures = 0;
|
|
2836
|
+
get noLaunch() {
|
|
2837
|
+
return this.#noLaunch.signal;
|
|
2838
|
+
}
|
|
2839
|
+
get persistenceFailures() {
|
|
2840
|
+
return this.#persistenceFailures;
|
|
2841
|
+
}
|
|
2842
|
+
canLaunch() {
|
|
2843
|
+
return this.budget.remainingMs() >= 1 && !this.noLaunch.aborted;
|
|
2844
|
+
}
|
|
2845
|
+
checkLaunch() {
|
|
2846
|
+
this.budget.check();
|
|
2847
|
+
if (this.noLaunch.aborted) invalid("aborted");
|
|
2848
|
+
}
|
|
2849
|
+
callStore(budget, operation) {
|
|
2850
|
+
const { clock, limits } = this.config;
|
|
2851
|
+
let invoked = false;
|
|
2852
|
+
return runStoreCall(clock, budget, {
|
|
2853
|
+
...operation,
|
|
2854
|
+
maxMs: Math.min(operation.maxMs ?? limits.storeTimeoutMs, limits.storeTimeoutMs),
|
|
2855
|
+
beforeInvoke: () => {
|
|
2856
|
+
if (operation.authorize) this.checkLaunch();
|
|
2857
|
+
operation.beforeInvoke?.();
|
|
2858
|
+
},
|
|
2859
|
+
invoke: (call, dispatchedAt) => {
|
|
2860
|
+
invoked = true;
|
|
2861
|
+
return operation.invoke(call, dispatchedAt);
|
|
2862
|
+
},
|
|
2863
|
+
onError: () => {
|
|
2864
|
+
if (!invoked) return;
|
|
2865
|
+
this.#persistenceFailures++;
|
|
2866
|
+
this.#noLaunch.abort();
|
|
2867
|
+
}
|
|
2868
|
+
});
|
|
2869
|
+
}
|
|
2870
|
+
};
|
|
2871
|
+
var statuses = {
|
|
2872
|
+
retry_scheduled: "retryScheduled",
|
|
2873
|
+
accepted: "accepted",
|
|
2874
|
+
partially_accepted: "partiallyAccepted",
|
|
2875
|
+
validated: "validated",
|
|
2876
|
+
rejected: "rejected",
|
|
2877
|
+
unknown: "unknown",
|
|
2878
|
+
failed: "failed",
|
|
2879
|
+
expired: "expired",
|
|
2880
|
+
cancelled: "cancelled",
|
|
2881
|
+
unconfirmed: "unconfirmed"
|
|
2882
|
+
};
|
|
2883
|
+
function runReport(stop, items, persistenceFailures) {
|
|
2884
|
+
const counts = {
|
|
2885
|
+
claimed: 0,
|
|
2886
|
+
recovered: 0,
|
|
2887
|
+
expiredInSweep: 0,
|
|
2888
|
+
providerCalls: 0,
|
|
2889
|
+
submitted: 0,
|
|
2890
|
+
retryScheduled: 0,
|
|
2891
|
+
accepted: 0,
|
|
2892
|
+
partiallyAccepted: 0,
|
|
2893
|
+
validated: 0,
|
|
2894
|
+
rejected: 0,
|
|
2895
|
+
unknown: 0,
|
|
2896
|
+
failed: 0,
|
|
2897
|
+
expired: 0,
|
|
2898
|
+
cancelled: 0,
|
|
2899
|
+
unconfirmed: 0,
|
|
2900
|
+
persistenceFailures
|
|
2901
|
+
};
|
|
2902
|
+
for (const item of items) {
|
|
2903
|
+
if (item.operation === "claim") counts.claimed++;
|
|
2904
|
+
else if (item.operation === "recover") counts.recovered++;
|
|
2905
|
+
else counts.expiredInSweep++;
|
|
2906
|
+
counts[statuses[item.status]]++;
|
|
2907
|
+
if (item.providerInvoked) counts.providerCalls++;
|
|
2908
|
+
}
|
|
2909
|
+
counts.submitted = counts.accepted + counts.partiallyAccepted;
|
|
2910
|
+
return Object.freeze({ stop, items: Object.freeze(items), counts: Object.freeze(counts) });
|
|
2911
|
+
}
|
|
2912
|
+
|
|
2913
|
+
// src/worker.ts
|
|
2914
|
+
async function sweep(run, limit, items, invoke, read, entry) {
|
|
2915
|
+
for (let i = 0; i < limit && run.canLaunch(); i++) {
|
|
2916
|
+
try {
|
|
2917
|
+
const next = await run.callStore(run.budget, {
|
|
2918
|
+
effect: "mutation",
|
|
2919
|
+
authorize: true,
|
|
2920
|
+
invoke,
|
|
2921
|
+
accept: (value) => readStoreNext(value, read)
|
|
2922
|
+
});
|
|
2923
|
+
if (next.status !== "applied") return next.status === "contended";
|
|
2924
|
+
items.push(Object.freeze(entry(next.value)));
|
|
2925
|
+
} catch {
|
|
2926
|
+
break;
|
|
2927
|
+
}
|
|
2928
|
+
}
|
|
2929
|
+
return false;
|
|
2930
|
+
}
|
|
2931
|
+
function claimNext(run) {
|
|
2932
|
+
const { clock, scope, store, limits } = run.config;
|
|
2933
|
+
const request = Object.freeze({
|
|
2934
|
+
attemptId: randomUUID3(),
|
|
2935
|
+
token: randomBytes(16).toString("base64url"),
|
|
2936
|
+
leaseMs: limits.leaseMs
|
|
2937
|
+
});
|
|
2938
|
+
let dispatchedAt;
|
|
2939
|
+
return run.callStore(run.budget, {
|
|
2940
|
+
effect: "mutation",
|
|
2941
|
+
authorize: true,
|
|
2942
|
+
maxMs: limits.preHandoffTimeoutMs,
|
|
2943
|
+
invoke(call, start) {
|
|
2944
|
+
dispatchedAt = start;
|
|
2945
|
+
return store.claimNext(scope, request, call);
|
|
2946
|
+
},
|
|
2947
|
+
accept: (value) => readStoreNext(value, (raw) => {
|
|
2948
|
+
const claim = readClaimed(raw, scope, request);
|
|
2949
|
+
return { claim, dispatchedAt, confirmedAt: monotonicNow(clock) };
|
|
2950
|
+
})
|
|
2951
|
+
});
|
|
2952
|
+
}
|
|
2953
|
+
async function drainClaims(run, options, items, slots) {
|
|
2954
|
+
const tasks = [];
|
|
2955
|
+
let active = 0;
|
|
2956
|
+
let settled;
|
|
2957
|
+
let failed = false;
|
|
2958
|
+
let stop = "idle";
|
|
2959
|
+
try {
|
|
2960
|
+
while (run.canLaunch() && !failed) {
|
|
2961
|
+
if (tasks.length === options.limit) {
|
|
2962
|
+
stop = "limit";
|
|
2963
|
+
break;
|
|
2964
|
+
}
|
|
2965
|
+
if (active === options.concurrency || slots.size >= run.config.limits.maxConcurrency) {
|
|
2966
|
+
if (!active) {
|
|
2967
|
+
stop = "callback_capacity";
|
|
2968
|
+
break;
|
|
2969
|
+
}
|
|
2970
|
+
await new Promise((resolve) => {
|
|
2971
|
+
settled = resolve;
|
|
2972
|
+
});
|
|
2973
|
+
continue;
|
|
2974
|
+
}
|
|
2975
|
+
const slot = new CallbackSlot(() => slots.delete(slot));
|
|
2976
|
+
slots.add(slot);
|
|
2977
|
+
let next;
|
|
2978
|
+
try {
|
|
2979
|
+
next = await claimNext(run);
|
|
2980
|
+
} catch {
|
|
2981
|
+
slot.close();
|
|
2982
|
+
break;
|
|
2983
|
+
}
|
|
2984
|
+
if (next.status !== "applied") {
|
|
2985
|
+
slot.close();
|
|
2986
|
+
stop = next.status === "contended" ? "contended" : "idle";
|
|
2987
|
+
break;
|
|
2988
|
+
}
|
|
2989
|
+
const { claim } = next.value;
|
|
2990
|
+
const index = items.length;
|
|
2991
|
+
items.push(
|
|
2992
|
+
Object.freeze({
|
|
2993
|
+
operation: "claim",
|
|
2994
|
+
jobId: claim.fence.jobId,
|
|
2995
|
+
attemptId: claim.fence.attemptId,
|
|
2996
|
+
providerInvoked: false,
|
|
2997
|
+
status: "unconfirmed"
|
|
2998
|
+
})
|
|
2999
|
+
);
|
|
3000
|
+
active++;
|
|
3001
|
+
tasks.push(
|
|
3002
|
+
processClaim(run, claim, next.value, slot).then(
|
|
3003
|
+
(entry) => {
|
|
3004
|
+
items[index] = entry;
|
|
3005
|
+
},
|
|
3006
|
+
() => {
|
|
3007
|
+
failed = true;
|
|
3008
|
+
}
|
|
3009
|
+
).finally(() => {
|
|
3010
|
+
slot.close();
|
|
3011
|
+
active--;
|
|
3012
|
+
const wake = settled;
|
|
3013
|
+
settled = void 0;
|
|
3014
|
+
wake?.();
|
|
3015
|
+
})
|
|
3016
|
+
);
|
|
3017
|
+
}
|
|
3018
|
+
} finally {
|
|
3019
|
+
await Promise.all(tasks);
|
|
3020
|
+
}
|
|
3021
|
+
if (failed) invalid("invalid_config");
|
|
3022
|
+
return stop;
|
|
3023
|
+
}
|
|
3024
|
+
async function runQueue(run, options, slots, shutdown) {
|
|
3025
|
+
const items = [];
|
|
3026
|
+
const { scope, store } = run.config;
|
|
3027
|
+
const contended = await sweep(
|
|
3028
|
+
run,
|
|
3029
|
+
options.maintenanceLimit,
|
|
3030
|
+
items,
|
|
3031
|
+
(call) => store.recoverNext(scope, call),
|
|
3032
|
+
readRecovery,
|
|
3033
|
+
(commit) => ({
|
|
3034
|
+
operation: "recover",
|
|
3035
|
+
jobId: commit.jobId,
|
|
3036
|
+
attemptId: commit.attemptId,
|
|
3037
|
+
status: commit.disposition,
|
|
3038
|
+
reason: commit.reason,
|
|
3039
|
+
providerInvoked: false
|
|
3040
|
+
})
|
|
3041
|
+
) || await sweep(
|
|
3042
|
+
run,
|
|
3043
|
+
options.maintenanceLimit,
|
|
3044
|
+
items,
|
|
3045
|
+
(call) => store.expireNext(scope, call),
|
|
3046
|
+
(value) => readQueuedExpiry(value, scope),
|
|
3047
|
+
(job) => ({
|
|
3048
|
+
operation: "expire",
|
|
3049
|
+
jobId: job.jobId,
|
|
3050
|
+
status: "expired",
|
|
3051
|
+
reason: "expired",
|
|
3052
|
+
providerInvoked: false
|
|
3053
|
+
})
|
|
3054
|
+
);
|
|
3055
|
+
const queueStop = contended ? "contended" : await drainClaims(run, options, items, slots);
|
|
3056
|
+
const timeLeft = run.budget.remainingMs();
|
|
3057
|
+
let stop;
|
|
3058
|
+
if (shutdown.aborted) stop = "shutdown";
|
|
3059
|
+
else if (options.signal?.aborted) stop = "aborted";
|
|
3060
|
+
else if (allowedErrorCode(run.budget.signal.reason, ["deadline"])) stop = "deadline";
|
|
3061
|
+
else if (run.persistenceFailures) stop = "store_error";
|
|
3062
|
+
else if (run.budget.signal.aborted) return invalid("invalid_config");
|
|
3063
|
+
else if (queueStop !== "contended" && slots.size === run.config.limits.maxConcurrency) stop = "callback_capacity";
|
|
3064
|
+
else if (queueStop === "idle" && timeLeft < 1)
|
|
3065
|
+
stop = "deadline";
|
|
3066
|
+
else stop = queueStop;
|
|
3067
|
+
return runReport(stop, items, run.persistenceFailures);
|
|
3068
|
+
}
|
|
3069
|
+
function createEmailWorker(options) {
|
|
3070
|
+
const config = readWorkerConfig(options);
|
|
3071
|
+
const { clock, scope, limits } = config;
|
|
3072
|
+
const shutdown = new AbortController();
|
|
3073
|
+
const slots = /* @__PURE__ */ new Set();
|
|
3074
|
+
let active;
|
|
3075
|
+
const worker = {
|
|
3076
|
+
scope,
|
|
3077
|
+
async run(options2 = {}) {
|
|
3078
|
+
if (shutdown.signal.aborted) invalid("closed");
|
|
3079
|
+
if (active) invalid("busy");
|
|
3080
|
+
const settings = readRunOptions(options2, limits);
|
|
3081
|
+
const done = new AbortController();
|
|
3082
|
+
active = done;
|
|
3083
|
+
try {
|
|
3084
|
+
const signal = settings.signal ? AbortSignal.any([settings.signal, shutdown.signal]) : shutdown.signal;
|
|
3085
|
+
const budget = createBudget(clock, settings.timeoutMs, signal);
|
|
3086
|
+
try {
|
|
3087
|
+
return await runQueue(new WorkerRun(config, budget), settings, slots, shutdown.signal);
|
|
3088
|
+
} finally {
|
|
3089
|
+
budget.close();
|
|
3090
|
+
}
|
|
3091
|
+
} finally {
|
|
3092
|
+
active = void 0;
|
|
3093
|
+
done.abort();
|
|
3094
|
+
}
|
|
3095
|
+
},
|
|
3096
|
+
async shutdown(options2 = {}) {
|
|
3097
|
+
const { timeoutMs } = readShutdownOptions(options2);
|
|
3098
|
+
const done = active;
|
|
3099
|
+
let end;
|
|
3100
|
+
try {
|
|
3101
|
+
if (done) end = monotonicNow(clock) + timeoutMs;
|
|
3102
|
+
} finally {
|
|
3103
|
+
shutdown.abort();
|
|
3104
|
+
}
|
|
3105
|
+
if (done && end !== void 0) {
|
|
3106
|
+
const wait = createBudgetUntil(clock, end, done.signal);
|
|
3107
|
+
try {
|
|
3108
|
+
await waitForAbort(wait.signal);
|
|
3109
|
+
} finally {
|
|
3110
|
+
wait.close();
|
|
3111
|
+
}
|
|
3112
|
+
}
|
|
3113
|
+
return Object.freeze({
|
|
3114
|
+
status: active ? "deadline" : "stopped",
|
|
3115
|
+
activeRun: active !== void 0,
|
|
3116
|
+
pendingCallbacks: [...slots].reduce((sum, slot) => sum + slot.pending, 0)
|
|
3117
|
+
});
|
|
3118
|
+
}
|
|
3119
|
+
};
|
|
3120
|
+
return Object.freeze(worker);
|
|
3121
|
+
}
|
|
3122
|
+
|
|
3123
|
+
// src/batch.ts
|
|
3124
|
+
import { types as types8 } from "util";
|
|
3125
|
+
var STOP_ERRORS2 = ["aborted", "deadline"];
|
|
3126
|
+
var ADMISSION_ERRORS = [
|
|
3127
|
+
...STOP_ERRORS2,
|
|
3128
|
+
...STORE_PERSISTENCE_ERRORS,
|
|
3129
|
+
"invalid_config",
|
|
3130
|
+
"invalid_command",
|
|
3131
|
+
"invalid_input",
|
|
3132
|
+
"invalid_data",
|
|
3133
|
+
"invalid_snapshot",
|
|
3134
|
+
"preparation_failed",
|
|
3135
|
+
"template_not_found",
|
|
3136
|
+
"template_source",
|
|
3137
|
+
"template_render",
|
|
3138
|
+
"provider_mismatch",
|
|
3139
|
+
"expired",
|
|
3140
|
+
"idempotency_conflict",
|
|
3141
|
+
"busy",
|
|
3142
|
+
"closed"
|
|
3143
|
+
];
|
|
3144
|
+
function boundScope(port) {
|
|
3145
|
+
return scopeToken(readPortMember(port, "scope"), "invalid_config");
|
|
3146
|
+
}
|
|
3147
|
+
function readBatch(scope, input) {
|
|
3148
|
+
const code = "invalid_command";
|
|
3149
|
+
const raw = readRecord(input, ["batchId", "items"], [], code);
|
|
3150
|
+
const batchId = identifier(raw.batchId, code);
|
|
3151
|
+
const seen = /* @__PURE__ */ new Set();
|
|
3152
|
+
const items = readArray(raw.items, MAX_BATCH_ITEMS, code, (entry) => {
|
|
3153
|
+
const item = readRecord(entry, ["itemId", "command"], [], code);
|
|
3154
|
+
const itemId = identifier(item.itemId, code);
|
|
3155
|
+
if (seen.has(itemId)) invalid(code);
|
|
3156
|
+
seen.add(itemId);
|
|
3157
|
+
const command = readRecord(item.command, ["templateKey", "input", "provider", "intent"], ["scheduleAt"], code);
|
|
3158
|
+
return { itemId, parsed: parseCommandIdentity(scope, { ...command, key: { kind: "batch", batchId, itemId } }) };
|
|
3159
|
+
});
|
|
3160
|
+
if (!items.length) invalid(code);
|
|
3161
|
+
return { batchId, items };
|
|
3162
|
+
}
|
|
3163
|
+
function stopReason(budget) {
|
|
3164
|
+
if (budget.remainingMs() > 0) return;
|
|
3165
|
+
return allowedErrorCode(budget.signal.reason, STOP_ERRORS2) ?? invalid("invalid_config");
|
|
3166
|
+
}
|
|
3167
|
+
function readAdmissionResult(input, identity) {
|
|
3168
|
+
const code = "write_unconfirmed";
|
|
3169
|
+
const { status, job: raw } = readRecord(input, ["status", "job"], [], code);
|
|
3170
|
+
if (status !== "enqueued" && status !== "replayed") invalid(code);
|
|
3171
|
+
const job = readJobSummary(identity.scope, raw);
|
|
3172
|
+
if (!matchesAdmissionJob(job, identity, status)) invalid(code);
|
|
3173
|
+
return { status, job };
|
|
3174
|
+
}
|
|
3175
|
+
function createEmailBatchService(options) {
|
|
3176
|
+
return createEmailBatchServiceWithClock(options, systemEmailClock);
|
|
3177
|
+
}
|
|
3178
|
+
function createEmailBatchServiceWithClock(options, clock) {
|
|
3179
|
+
const { service, worker } = readRecord(options, ["service", "worker"], [], "invalid_config");
|
|
3180
|
+
const scope = boundScope(service);
|
|
3181
|
+
if (scope !== boundScope(worker)) invalid("invalid_config");
|
|
3182
|
+
const run = bindMethod(worker, "run");
|
|
3183
|
+
const enqueue = bindMethod(service, "enqueue");
|
|
3184
|
+
const admit = findServiceAdmission(service) ?? (async ({ command, identity }, budget) => {
|
|
3185
|
+
if (boundScope(service) !== scope) invalid("invalid_config");
|
|
3186
|
+
const bounds = CALL_BUDGETS.admissionOrAdmin;
|
|
3187
|
+
const timeoutMs = Math.max(bounds.min, Math.min(bounds.max, Math.floor(budget.remainingMs())));
|
|
3188
|
+
budget.check();
|
|
3189
|
+
let raw;
|
|
3190
|
+
try {
|
|
3191
|
+
const pending = enqueue(command, Object.freeze({ signal: budget.signal, timeoutMs }));
|
|
3192
|
+
raw = types8.isPromise(pending) ? await pending : pending;
|
|
3193
|
+
} catch (error) {
|
|
3194
|
+
if (allowedErrorCode(error, ["aborted"]) && allowedErrorCode(budget.signal.reason, ["deadline"])) {
|
|
3195
|
+
invalid("deadline");
|
|
3196
|
+
}
|
|
3197
|
+
throw error;
|
|
3198
|
+
}
|
|
3199
|
+
try {
|
|
3200
|
+
return readAdmissionResult(raw, identity);
|
|
3201
|
+
} catch {
|
|
3202
|
+
return invalid("write_unconfirmed");
|
|
3203
|
+
}
|
|
3204
|
+
});
|
|
3205
|
+
const batch = {
|
|
3206
|
+
async enqueueBatch(input, call = {}) {
|
|
3207
|
+
const { signal, timeoutMs } = readCallOptions(call, CALL_BUDGETS.batchOrRun);
|
|
3208
|
+
const budget = createBudget(clock, timeoutMs, signal);
|
|
3209
|
+
try {
|
|
3210
|
+
const { batchId, items: commands } = readBatch(scope, input);
|
|
3211
|
+
const items = [];
|
|
3212
|
+
const counts = { enqueued: 0, replayed: 0, failed: 0, notStarted: 0, persistenceFailures: 0 };
|
|
3213
|
+
for (const { itemId, parsed } of commands) {
|
|
3214
|
+
if (stopReason(budget)) {
|
|
3215
|
+
counts.notStarted++;
|
|
3216
|
+
items.push(Object.freeze({ itemId, status: "not_started" }));
|
|
3217
|
+
continue;
|
|
3218
|
+
}
|
|
3219
|
+
try {
|
|
3220
|
+
const result = await admit(parsed, budget);
|
|
3221
|
+
counts[result.status]++;
|
|
3222
|
+
items.push(Object.freeze({ itemId, status: result.status, job: result.job }));
|
|
3223
|
+
} catch (error) {
|
|
3224
|
+
const code = allowedErrorCode(error, ADMISSION_ERRORS) ?? "write_unconfirmed";
|
|
3225
|
+
counts.failed++;
|
|
3226
|
+
if (STORE_PERSISTENCE_ERRORS.some((candidate) => candidate === code)) counts.persistenceFailures++;
|
|
3227
|
+
items.push(Object.freeze({ itemId, status: "failed", code }));
|
|
3228
|
+
}
|
|
3229
|
+
}
|
|
3230
|
+
return Object.freeze({ batchId, items: Object.freeze(items), counts: Object.freeze(counts) });
|
|
3231
|
+
} finally {
|
|
3232
|
+
budget.close();
|
|
3233
|
+
}
|
|
3234
|
+
},
|
|
3235
|
+
async run(options2) {
|
|
3236
|
+
if (boundScope(worker) !== scope) invalid("invalid_config");
|
|
3237
|
+
return run(options2);
|
|
3238
|
+
}
|
|
3239
|
+
};
|
|
3240
|
+
return Object.freeze(batch);
|
|
3241
|
+
}
|
|
3242
|
+
|
|
3243
|
+
// src/admin.ts
|
|
3244
|
+
var CONFIG3 = "invalid_config";
|
|
3245
|
+
var STORED4 = "store_incompatible";
|
|
3246
|
+
var STOP_CODES = ["aborted", "deadline", CONFIG3];
|
|
3247
|
+
var RESOLUTION_REJECTIONS = ["not_found", "resolution_conflict", "expired"];
|
|
3248
|
+
var CLEANUP_COUNTERS = {
|
|
3249
|
+
payload_pruned: "payloadsPruned",
|
|
3250
|
+
retirement_started: "retirementsStarted",
|
|
3251
|
+
purged: "jobsPurged"
|
|
3252
|
+
};
|
|
3253
|
+
function createEmailAdmin(options) {
|
|
3254
|
+
return createEmailAdminWithClock(options, systemEmailClock);
|
|
3255
|
+
}
|
|
3256
|
+
function createEmailAdminWithClock(options, clock) {
|
|
3257
|
+
const { scope: input, store, onActivity: callback } = readRecord(options, ["scope", "store"], ["onActivity"], CONFIG3);
|
|
3258
|
+
const scope = scopeToken(input, CONFIG3);
|
|
3259
|
+
const findJob = bindMethod(store, "findJob");
|
|
3260
|
+
const cancel = bindMethod(store, "cancel");
|
|
3261
|
+
const resolveUnknown = bindMethod(store, "resolveUnknown");
|
|
3262
|
+
const listActivities = bindMethod(store, "listActivities");
|
|
3263
|
+
const reserve = bindMethod(store, "reserveProjection");
|
|
3264
|
+
const put = bindMethod(store, "putActivity");
|
|
3265
|
+
const ack = bindMethod(store, "ackProjection");
|
|
3266
|
+
const cleanupNext = bindMethod(store, "cleanupNext");
|
|
3267
|
+
const onActivity = callback === void 0 ? void 0 : requireCallback(callback);
|
|
3268
|
+
let observers = 0;
|
|
3269
|
+
function observe(activity, counts) {
|
|
3270
|
+
if (!onActivity) return;
|
|
3271
|
+
if (observers >= MAX_OBSERVER_PENDING) {
|
|
3272
|
+
counts.observerSkipped++;
|
|
3273
|
+
return;
|
|
3274
|
+
}
|
|
3275
|
+
observers++;
|
|
3276
|
+
counts.observerStarted++;
|
|
3277
|
+
const slot = new CallbackSlot(() => observers--);
|
|
3278
|
+
try {
|
|
3279
|
+
const pending = pendingCallback(onActivity(activity));
|
|
3280
|
+
if (pending) slot.hold(pending);
|
|
3281
|
+
} catch {
|
|
3282
|
+
} finally {
|
|
3283
|
+
slot.close();
|
|
3284
|
+
}
|
|
3285
|
+
}
|
|
3286
|
+
function readJob(jobId, value) {
|
|
3287
|
+
const job = readJobSummary(scope, value);
|
|
3288
|
+
if (job.jobId !== jobId) invalid(STORED4);
|
|
3289
|
+
return job;
|
|
3290
|
+
}
|
|
3291
|
+
function callStore(budget, operation) {
|
|
3292
|
+
return runStoreCall(clock, budget, { ...operation, maxMs: STORE_PRIMITIVE_TIMEOUT_MS });
|
|
3293
|
+
}
|
|
3294
|
+
function write(budget, invoke, accept) {
|
|
3295
|
+
return callStore(budget, { effect: "mutation", invoke, accept });
|
|
3296
|
+
}
|
|
3297
|
+
async function inOperation(options2, run) {
|
|
3298
|
+
const { timeoutMs, signal: source } = readCallOptions(options2, CALL_BUDGETS.admissionOrAdmin);
|
|
3299
|
+
const signal = source && AbortSignal.any([source]);
|
|
3300
|
+
const budget = createBudget(clock, timeoutMs, signal);
|
|
3301
|
+
try {
|
|
3302
|
+
return await run(budget, signal);
|
|
3303
|
+
} finally {
|
|
3304
|
+
budget.close();
|
|
3305
|
+
}
|
|
3306
|
+
}
|
|
3307
|
+
async function maintain(options2, step) {
|
|
3308
|
+
const { limit: input2, ...call } = readRecord(options2, [], ["limit", "signal", "timeoutMs"], CONFIG3);
|
|
3309
|
+
const limit = boundedOption(input2, ADMIN_MAINTENANCE_LIMIT);
|
|
3310
|
+
return inOperation(call, async (budget, signal) => {
|
|
3311
|
+
let stop = "limit";
|
|
3312
|
+
for (let i = 0; i < limit; i++) {
|
|
3313
|
+
try {
|
|
3314
|
+
const next = await step(budget);
|
|
3315
|
+
if (!next) continue;
|
|
3316
|
+
stop = next;
|
|
3317
|
+
} catch (error) {
|
|
3318
|
+
const code = allowedErrorCode(error, STOP_CODES);
|
|
3319
|
+
if (code === CONFIG3) invalid(code);
|
|
3320
|
+
stop = code ?? "store_error";
|
|
3321
|
+
}
|
|
3322
|
+
break;
|
|
3323
|
+
}
|
|
3324
|
+
const persistenceFailures = Number(stop === "store_error");
|
|
3325
|
+
budget.remainingMs();
|
|
3326
|
+
const interrupted = allowedErrorCode(budget.signal.reason, STOP_CODES);
|
|
3327
|
+
if (interrupted === CONFIG3) invalid(interrupted);
|
|
3328
|
+
if (signal?.aborted) stop = "aborted";
|
|
3329
|
+
else if (interrupted) stop = interrupted;
|
|
3330
|
+
return { stop, persistenceFailures };
|
|
3331
|
+
});
|
|
3332
|
+
}
|
|
3333
|
+
const admin = {
|
|
3334
|
+
scope,
|
|
3335
|
+
getJob(jobId, options2 = {}) {
|
|
3336
|
+
return inOperation(options2, (budget) => {
|
|
3337
|
+
const id = readStoreId(jobId);
|
|
3338
|
+
return callStore(budget, {
|
|
3339
|
+
effect: "read",
|
|
3340
|
+
invoke: (call) => findJob(scope, id, call),
|
|
3341
|
+
accept: (value) => value === null ? null : readJob(id, value)
|
|
3342
|
+
});
|
|
3343
|
+
});
|
|
3344
|
+
},
|
|
3345
|
+
cancel(jobId, options2 = {}) {
|
|
3346
|
+
return inOperation(options2, (budget) => {
|
|
3347
|
+
const id = readStoreId(jobId);
|
|
3348
|
+
return write(
|
|
3349
|
+
budget,
|
|
3350
|
+
(call) => cancel(scope, id, call),
|
|
3351
|
+
(value) => {
|
|
3352
|
+
const raw = readRecord(value, ["status"], ["job"], STORED4);
|
|
3353
|
+
const { status } = raw;
|
|
3354
|
+
if (status === "not_found" && !Object.hasOwn(raw, "job")) return Object.freeze({ status });
|
|
3355
|
+
if (status !== "cancelled" && status !== "too_late") invalid(STORED4);
|
|
3356
|
+
const job = readJob(id, raw.job);
|
|
3357
|
+
if (status === "cancelled" !== (job.state === "terminal" && job.disposition === "cancelled")) {
|
|
3358
|
+
invalid(STORED4);
|
|
3359
|
+
}
|
|
3360
|
+
return Object.freeze({ status, job });
|
|
3361
|
+
}
|
|
3362
|
+
);
|
|
3363
|
+
});
|
|
3364
|
+
},
|
|
3365
|
+
resolveUnknown(command, options2 = {}) {
|
|
3366
|
+
return inOperation(options2, (budget) => {
|
|
3367
|
+
const request = readResolution(command);
|
|
3368
|
+
return callStore(budget, {
|
|
3369
|
+
effect: "mutation",
|
|
3370
|
+
definite: RESOLUTION_REJECTIONS,
|
|
3371
|
+
invoke: (call) => resolveUnknown(scope, request, call),
|
|
3372
|
+
accept(value) {
|
|
3373
|
+
const { status, job: raw } = readRecord(value, ["status", "job"], [], STORED4);
|
|
3374
|
+
const job = readJob(request.jobId, raw);
|
|
3375
|
+
const decision = job.resolutions.find(({ attemptId }) => attemptId === request.attemptId);
|
|
3376
|
+
if (decision?.action !== request.action || status !== "resolved" && status !== "replayed") {
|
|
3377
|
+
invalid(STORED4);
|
|
3378
|
+
}
|
|
3379
|
+
if (status === "resolved" && (job.unknownOpen || job.latestAttempt?.attemptId !== request.attemptId || job.latestAttempt.outcome !== "unknown" || job.updatedAt !== decision.at || (decision.action === "redrive" ? job.state !== "queued" || job.nextAt !== decision.at : job.state !== "terminal" || job.disposition !== "unknown"))) {
|
|
3380
|
+
invalid(STORED4);
|
|
3381
|
+
}
|
|
3382
|
+
return Object.freeze({ status, job });
|
|
3383
|
+
}
|
|
3384
|
+
});
|
|
3385
|
+
});
|
|
3386
|
+
},
|
|
3387
|
+
listActivities(query = {}, options2 = {}) {
|
|
3388
|
+
return inOperation(options2, (budget) => {
|
|
3389
|
+
const criteria = readActivityCriteria(scope, query);
|
|
3390
|
+
const request = activityQuery(criteria);
|
|
3391
|
+
return callStore(budget, {
|
|
3392
|
+
effect: "read",
|
|
3393
|
+
invoke: (call) => listActivities(scope, request, call),
|
|
3394
|
+
accept: (value) => readActivityPage(criteria, value)
|
|
3395
|
+
});
|
|
3396
|
+
});
|
|
3397
|
+
},
|
|
3398
|
+
async reconcile(options2 = {}) {
|
|
3399
|
+
const counts = { reserved: 0, acknowledged: 0, permitsExpired: 0, observerStarted: 0, observerSkipped: 0 };
|
|
3400
|
+
const report = await maintain(options2, async (budget) => {
|
|
3401
|
+
const next = await write(
|
|
3402
|
+
budget,
|
|
3403
|
+
(call) => reserve(scope, call),
|
|
3404
|
+
(value) => readStoreNext(value, (permit2) => readProjectionPermit(scope, permit2))
|
|
3405
|
+
);
|
|
3406
|
+
if (next.status !== "applied") return next.status === "none" ? "idle" : "contended";
|
|
3407
|
+
counts.reserved++;
|
|
3408
|
+
const permit = next.value;
|
|
3409
|
+
const present = await write(
|
|
3410
|
+
budget,
|
|
3411
|
+
(call) => put(scope, permit, call),
|
|
3412
|
+
(value) => readStatus(value, ["present", "permit_expired"])
|
|
3413
|
+
);
|
|
3414
|
+
if (present === "permit_expired") {
|
|
3415
|
+
counts.permitsExpired++;
|
|
3416
|
+
return;
|
|
3417
|
+
}
|
|
3418
|
+
const confirmed = await write(
|
|
3419
|
+
budget,
|
|
3420
|
+
(call) => ack(scope, permit, call),
|
|
3421
|
+
(value) => readStatus(value, ["acknowledged", "already_acknowledged", "stale"])
|
|
3422
|
+
);
|
|
3423
|
+
if (confirmed === "stale") return "contended";
|
|
3424
|
+
counts.acknowledged++;
|
|
3425
|
+
if (confirmed === "acknowledged" && budget.remainingMs() > 0) observe(permit.activity, counts);
|
|
3426
|
+
});
|
|
3427
|
+
return Object.freeze({ ...report, ...counts });
|
|
3428
|
+
},
|
|
3429
|
+
async cleanup(options2 = {}) {
|
|
3430
|
+
const counts = { payloadsPruned: 0, retirementsStarted: 0, jobsPurged: 0 };
|
|
3431
|
+
const report = await maintain(options2, async (budget) => {
|
|
3432
|
+
const next = await write(
|
|
3433
|
+
budget,
|
|
3434
|
+
(call) => cleanupNext(scope, call),
|
|
3435
|
+
(value) => readStoreNext(value, (step) => readStatus(step, ["payload_pruned", "retirement_started", "purged"]))
|
|
3436
|
+
);
|
|
3437
|
+
if (next.status !== "applied") return next.status === "none" ? "idle" : "contended";
|
|
3438
|
+
counts[CLEANUP_COUNTERS[next.value]]++;
|
|
3439
|
+
});
|
|
3440
|
+
return Object.freeze({ ...report, ...counts });
|
|
3441
|
+
}
|
|
3442
|
+
};
|
|
3443
|
+
return Object.freeze(admin);
|
|
3444
|
+
}
|
|
3445
|
+
function readStatus(value, allowed) {
|
|
3446
|
+
return allowed.find((status) => status === value) ?? invalid(STORED4);
|
|
3447
|
+
}
|
|
3448
|
+
|
|
3449
|
+
// src/stores/memory.ts
|
|
3450
|
+
import { randomUUID as randomUUID4 } from "crypto";
|
|
3451
|
+
|
|
3452
|
+
// src/internal/job-record.ts
|
|
3453
|
+
var STORED5 = "store_incompatible";
|
|
3454
|
+
function leasePhase(lease) {
|
|
3455
|
+
return lease.handedOffAt === void 0 ? "pre_handoff" : "handed_off";
|
|
3456
|
+
}
|
|
3457
|
+
function terminalState(disposition, terminalReason, now) {
|
|
3458
|
+
return Object.freeze({
|
|
3459
|
+
state: "terminal",
|
|
3460
|
+
disposition,
|
|
3461
|
+
terminalReason,
|
|
3462
|
+
terminalAt: now,
|
|
3463
|
+
...disposition === "unknown" ? {} : { settledAt: now }
|
|
3464
|
+
});
|
|
3465
|
+
}
|
|
3466
|
+
function hasRedrive(job) {
|
|
3467
|
+
return job.resolutions.some(({ action }) => action === "redrive");
|
|
3468
|
+
}
|
|
3469
|
+
function pendingAttempt(job) {
|
|
3470
|
+
return job.attempts.find(({ projectionAckAt }) => projectionAckAt === void 0);
|
|
3471
|
+
}
|
|
3472
|
+
function retirementAt(job) {
|
|
3473
|
+
if (job.state.state !== "terminal" || job.state.settledAt === void 0 || pendingAttempt(job)) return;
|
|
3474
|
+
const { settledAt } = job.state;
|
|
3475
|
+
const payload = timeAfter(settledAt, job.retention.payloadMs);
|
|
3476
|
+
const history = timeAfter(settledAt, job.retention.historyMs);
|
|
3477
|
+
const identity = timeAfter(settledAt, job.retention.idempotencyMs);
|
|
3478
|
+
const drain = job.projectionPermitUntil === void 0 ? 0 : timeAfter(job.projectionPermitUntil, PROJECTION_DRAIN_MS);
|
|
3479
|
+
if (payload === void 0 || history === void 0 || identity === void 0 || drain === void 0) return;
|
|
3480
|
+
return Math.max(payload, history, identity, drain);
|
|
3481
|
+
}
|
|
3482
|
+
function cleanupAt(job) {
|
|
3483
|
+
if (job.retiring) return job.updatedAt;
|
|
3484
|
+
if (job.state.state !== "terminal" || job.state.settledAt === void 0 || pendingAttempt(job)) return;
|
|
3485
|
+
if (job.snapshot) {
|
|
3486
|
+
const payloadAt = timeAfter(job.state.settledAt, job.retention.payloadMs);
|
|
3487
|
+
if (payloadAt === void 0) return;
|
|
3488
|
+
return Math.max(payloadAt, job.attempts.at(-1)?.projectionAckAt ?? 0);
|
|
3489
|
+
}
|
|
3490
|
+
const retireAt = retirementAt(job);
|
|
3491
|
+
return retireAt === void 0 ? void 0 : Math.max(retireAt, job.updatedAt);
|
|
3492
|
+
}
|
|
3493
|
+
function jobSelectors(job) {
|
|
3494
|
+
const { state } = job;
|
|
3495
|
+
const pendingAt = pendingAttempt(job)?.commit.finishedAt;
|
|
3496
|
+
const nextCleanupAt = cleanupAt(job);
|
|
3497
|
+
return {
|
|
3498
|
+
state: state.state,
|
|
3499
|
+
...state.state === "queued" ? { nextAt: state.nextAt, queuedExpiresAt: job.expiresAt } : {},
|
|
3500
|
+
...state.state === "leased" ? { leaseEndsAt: state.lease.leaseEndsAt } : {},
|
|
3501
|
+
...pendingAt === void 0 ? {} : { pendingAt },
|
|
3502
|
+
...nextCleanupAt === void 0 ? {} : { nextCleanupAt }
|
|
3503
|
+
};
|
|
3504
|
+
}
|
|
3505
|
+
function jobSummary(job) {
|
|
3506
|
+
const { state } = job;
|
|
3507
|
+
let summaryState;
|
|
3508
|
+
if (state.state === "terminal") {
|
|
3509
|
+
const { disposition, terminalReason, terminalAt } = state;
|
|
3510
|
+
summaryState = { state: "terminal", disposition, terminalReason, terminalAt };
|
|
3511
|
+
} else if (state.state === "leased") {
|
|
3512
|
+
summaryState = { state: "leased", phase: leasePhase(state.lease) };
|
|
3513
|
+
} else {
|
|
3514
|
+
summaryState = { state: "queued", nextAt: state.nextAt };
|
|
3515
|
+
}
|
|
3516
|
+
const latest = job.attempts.at(-1)?.commit;
|
|
3517
|
+
return Object.freeze({
|
|
3518
|
+
version: EMAIL_FORMAT_VERSION,
|
|
3519
|
+
scope: job.scope,
|
|
3520
|
+
jobId: job.jobId,
|
|
3521
|
+
key: Object.freeze({ ...job.key }),
|
|
3522
|
+
provider: Object.freeze({ ...job.provider }),
|
|
3523
|
+
template: Object.freeze({ ...job.template }),
|
|
3524
|
+
correlation: validateCorrelation(job.correlation, STORED5),
|
|
3525
|
+
scheduleAt: job.scheduleAt,
|
|
3526
|
+
createdAt: job.createdAt,
|
|
3527
|
+
updatedAt: job.updatedAt,
|
|
3528
|
+
expiresAt: job.expiresAt,
|
|
3529
|
+
priority: job.priority,
|
|
3530
|
+
attemptCount: job.attempts.length + Number(state.state === "leased"),
|
|
3531
|
+
...latest ? {
|
|
3532
|
+
latestAttempt: Object.freeze({
|
|
3533
|
+
attemptId: latest.attemptId,
|
|
3534
|
+
outcome: latest.result.outcome,
|
|
3535
|
+
reason: latest.result.reason
|
|
3536
|
+
})
|
|
3537
|
+
} : {},
|
|
3538
|
+
unknownOpen: state.state === "terminal" && state.disposition === "unknown" && state.settledAt === void 0,
|
|
3539
|
+
resolutions: Object.freeze(job.resolutions.map((entry) => Object.freeze({ ...entry }))),
|
|
3540
|
+
...summaryState
|
|
3541
|
+
});
|
|
3542
|
+
}
|
|
3543
|
+
function copyCommit(commit) {
|
|
3544
|
+
return Object.freeze({ ...commit, result: readAttemptResult(commit.result, STORED5) });
|
|
3545
|
+
}
|
|
3546
|
+
function readStoredSnapshot(job, input) {
|
|
3547
|
+
let validated;
|
|
3548
|
+
try {
|
|
3549
|
+
validated = validateSnapshot(input);
|
|
3550
|
+
} catch {
|
|
3551
|
+
return invalid(STORED5);
|
|
3552
|
+
}
|
|
3553
|
+
const { snapshot, snapshotHash } = validated;
|
|
3554
|
+
const metadata = (value, counts) => canonicalJson([value.provider, value.template, value.correlation, counts], 4096, STORED5).encoded;
|
|
3555
|
+
if (snapshotHash !== job.snapshotHash || snapshot.preparedAt - job.createdAt > MAX_PREPARED_AT_SKEW_MS || snapshot.expiresAt !== job.expiresAt || snapshot.priority !== job.priority || metadata(snapshot, recipientCounts(snapshot.envelope)) !== metadata(job, job.recipientCounts)) {
|
|
3556
|
+
invalid(STORED5);
|
|
3557
|
+
}
|
|
3558
|
+
return snapshot;
|
|
3559
|
+
}
|
|
3560
|
+
|
|
3561
|
+
// src/internal/job-transitions.ts
|
|
3562
|
+
function guard(job, { now }, before) {
|
|
3563
|
+
if (unixMs(now, "store_unavailable") < job.updatedAt || before !== void 0 && now >= before) {
|
|
3564
|
+
invalid("store_unavailable");
|
|
3565
|
+
}
|
|
3566
|
+
return {
|
|
3567
|
+
scope: job.scope,
|
|
3568
|
+
jobId: job.jobId,
|
|
3569
|
+
revision: job.revision,
|
|
3570
|
+
state: job.state,
|
|
3571
|
+
...job.retiring ? { retiring: true } : {},
|
|
3572
|
+
atOrAfter: now,
|
|
3573
|
+
...before === void 0 ? {} : { before }
|
|
3574
|
+
};
|
|
3575
|
+
}
|
|
3576
|
+
function replace(job, time, patch, value, before, pendingAck) {
|
|
3577
|
+
const expect = guard(job, time, before);
|
|
3578
|
+
const next = Object.freeze({ ...patch, updatedAt: time.now, revision: time.revision });
|
|
3579
|
+
return {
|
|
3580
|
+
value: value(next),
|
|
3581
|
+
write: { kind: "replace", guard: pendingAck ? { ...expect, pendingAck } : expect, next }
|
|
3582
|
+
};
|
|
3583
|
+
}
|
|
3584
|
+
function newJob(admission, time) {
|
|
3585
|
+
const { command, jobId, retry, retention, admissionKey } = admission;
|
|
3586
|
+
const { scope, key, scheduleAt, fingerprint, snapshotHash, snapshot } = command;
|
|
3587
|
+
const now = unixMs(time.now, "store_unavailable");
|
|
3588
|
+
if (snapshot.preparedAt - now > MAX_PREPARED_AT_SKEW_MS) invalid("invalid_snapshot");
|
|
3589
|
+
const nextAt = Math.max(now, scheduleAt ?? now);
|
|
3590
|
+
if (nextAt >= snapshot.expiresAt) invalid("expired");
|
|
3591
|
+
return Object.freeze({
|
|
3592
|
+
version: EMAIL_FORMAT_VERSION,
|
|
3593
|
+
scope,
|
|
3594
|
+
jobId,
|
|
3595
|
+
key,
|
|
3596
|
+
admissionKey,
|
|
3597
|
+
fingerprint,
|
|
3598
|
+
snapshotHash,
|
|
3599
|
+
snapshot,
|
|
3600
|
+
retry,
|
|
3601
|
+
retention,
|
|
3602
|
+
provider: snapshot.provider,
|
|
3603
|
+
template: snapshot.template,
|
|
3604
|
+
correlation: snapshot.correlation,
|
|
3605
|
+
recipientCounts: recipientCounts(snapshot.envelope),
|
|
3606
|
+
scheduleAt,
|
|
3607
|
+
createdAt: now,
|
|
3608
|
+
updatedAt: now,
|
|
3609
|
+
expiresAt: snapshot.expiresAt,
|
|
3610
|
+
priority: snapshot.priority,
|
|
3611
|
+
revision: time.revision,
|
|
3612
|
+
state: Object.freeze({ state: "queued", nextAt }),
|
|
3613
|
+
attempts: Object.freeze([]),
|
|
3614
|
+
resolutions: Object.freeze([])
|
|
3615
|
+
});
|
|
3616
|
+
}
|
|
3617
|
+
function endOfGrant(now, leaseMs) {
|
|
3618
|
+
return timeAfter(now, leaseMs) ?? invalid("store_unavailable");
|
|
3619
|
+
}
|
|
3620
|
+
function withLease(job, lease) {
|
|
3621
|
+
return { ...job, state: Object.freeze({ state: "leased", lease: Object.freeze(lease) }) };
|
|
3622
|
+
}
|
|
3623
|
+
function liveLease(job, fence, phase, now) {
|
|
3624
|
+
if (job.jobId !== fence.jobId || job.state.state !== "leased") return;
|
|
3625
|
+
const { lease } = job.state;
|
|
3626
|
+
if (lease.attemptId !== fence.attemptId || lease.token !== fence.token || leasePhase(lease) !== phase || now >= lease.leaseEndsAt) {
|
|
3627
|
+
return;
|
|
3628
|
+
}
|
|
3629
|
+
return lease;
|
|
3630
|
+
}
|
|
3631
|
+
function claimJob(job, claim, time) {
|
|
3632
|
+
const { now } = time;
|
|
3633
|
+
if (job.state.state !== "queued" || job.state.nextAt > now || now >= job.expiresAt) return null;
|
|
3634
|
+
const manual = hasRedrive(job);
|
|
3635
|
+
const ordinal = job.attempts.length + 1;
|
|
3636
|
+
if (ordinal > MAX_ATTEMPT_LEDGER || !manual && ordinal > job.retry.maxAttempts) invalid("store_incompatible");
|
|
3637
|
+
if (job.attempts.some(({ commit }) => commit.attemptId === claim.attemptId)) invalid("invalid_command");
|
|
3638
|
+
const snapshot = readStoredSnapshot(job, job.snapshot);
|
|
3639
|
+
const lease = Object.freeze({
|
|
3640
|
+
attemptId: claim.attemptId,
|
|
3641
|
+
token: claim.token,
|
|
3642
|
+
startedAt: now,
|
|
3643
|
+
grantedAt: now,
|
|
3644
|
+
leaseEndsAt: endOfGrant(now, claim.leaseMs)
|
|
3645
|
+
});
|
|
3646
|
+
return replace(
|
|
3647
|
+
job,
|
|
3648
|
+
time,
|
|
3649
|
+
withLease(job, lease),
|
|
3650
|
+
(next) => Object.freeze({
|
|
3651
|
+
job: jobSummary(next),
|
|
3652
|
+
snapshot,
|
|
3653
|
+
fence: Object.freeze({ jobId: job.jobId, attemptId: lease.attemptId, token: lease.token }),
|
|
3654
|
+
lease: Object.freeze({ grantedAt: lease.grantedAt, leaseEndsAt: lease.leaseEndsAt }),
|
|
3655
|
+
ordinal,
|
|
3656
|
+
manual
|
|
3657
|
+
}),
|
|
3658
|
+
Math.min(job.expiresAt, lease.leaseEndsAt)
|
|
3659
|
+
);
|
|
3660
|
+
}
|
|
3661
|
+
function renewJob(job, fence, leaseMs, time) {
|
|
3662
|
+
const lease = liveLease(job, fence, "pre_handoff", time.now);
|
|
3663
|
+
if (!lease || time.now >= job.expiresAt) return null;
|
|
3664
|
+
const grant = Object.freeze({
|
|
3665
|
+
grantedAt: time.now,
|
|
3666
|
+
// A renewal never shortens a still-live grant, even if the caller requests a smaller duration.
|
|
3667
|
+
leaseEndsAt: Math.max(lease.leaseEndsAt, endOfGrant(time.now, leaseMs))
|
|
3668
|
+
});
|
|
3669
|
+
return replace(
|
|
3670
|
+
job,
|
|
3671
|
+
time,
|
|
3672
|
+
withLease(job, { ...lease, ...grant }),
|
|
3673
|
+
() => grant,
|
|
3674
|
+
Math.min(job.expiresAt, lease.leaseEndsAt)
|
|
3675
|
+
);
|
|
3676
|
+
}
|
|
3677
|
+
function markJob(job, fence, leaseMs, time) {
|
|
3678
|
+
const lease = liveLease(job, fence, "pre_handoff", time.now);
|
|
3679
|
+
if (!lease || time.now >= job.expiresAt) return null;
|
|
3680
|
+
const grant = Object.freeze({
|
|
3681
|
+
grantedAt: time.now,
|
|
3682
|
+
handoffAt: time.now,
|
|
3683
|
+
leaseEndsAt: endOfGrant(time.now, leaseMs)
|
|
3684
|
+
});
|
|
3685
|
+
return replace(
|
|
3686
|
+
job,
|
|
3687
|
+
time,
|
|
3688
|
+
withLease(job, {
|
|
3689
|
+
...lease,
|
|
3690
|
+
grantedAt: grant.grantedAt,
|
|
3691
|
+
handedOffAt: grant.handoffAt,
|
|
3692
|
+
leaseEndsAt: grant.leaseEndsAt
|
|
3693
|
+
}),
|
|
3694
|
+
() => grant,
|
|
3695
|
+
Math.min(job.expiresAt, lease.leaseEndsAt, grant.leaseEndsAt)
|
|
3696
|
+
);
|
|
3697
|
+
}
|
|
3698
|
+
function finalize(job, lease, operationId, result, time, owner) {
|
|
3699
|
+
const { now } = time;
|
|
3700
|
+
const { attemptId, startedAt, handedOffAt } = lease;
|
|
3701
|
+
const ordinal = job.attempts.length + 1;
|
|
3702
|
+
const effect = attemptEffect(result, attemptId, ordinal, hasRedrive(job), job.retry, job.expiresAt, now);
|
|
3703
|
+
const commit = Object.freeze({
|
|
3704
|
+
jobId: job.jobId,
|
|
3705
|
+
attemptId,
|
|
3706
|
+
ordinal,
|
|
3707
|
+
operationId,
|
|
3708
|
+
startedAt,
|
|
3709
|
+
...handedOffAt === void 0 ? {} : { handedOffAt },
|
|
3710
|
+
finishedAt: now,
|
|
3711
|
+
result,
|
|
3712
|
+
...effect
|
|
3713
|
+
});
|
|
3714
|
+
const entry = Object.freeze({
|
|
3715
|
+
commit,
|
|
3716
|
+
digest: activityDigest(activityFor(job, commit)),
|
|
3717
|
+
...owner ? { ownerDigest: sha256(lease.token) } : {}
|
|
3718
|
+
});
|
|
3719
|
+
const state = effect.disposition === "retry_scheduled" ? Object.freeze({ state: "queued", nextAt: effect.retryAt }) : terminalState(effect.disposition, effect.reason, now);
|
|
3720
|
+
let before = owner ? lease.leaseEndsAt : void 0;
|
|
3721
|
+
if (result.reason === "cancelled" || result.retry === "safe_transient" && effect.disposition !== "expired") {
|
|
3722
|
+
before = Math.min(before ?? job.expiresAt, job.expiresAt);
|
|
3723
|
+
}
|
|
3724
|
+
return replace(
|
|
3725
|
+
job,
|
|
3726
|
+
time,
|
|
3727
|
+
{ ...job, state, attempts: Object.freeze([...job.attempts, entry]) },
|
|
3728
|
+
() => copyCommit(commit),
|
|
3729
|
+
before
|
|
3730
|
+
);
|
|
3731
|
+
}
|
|
3732
|
+
function finishJob(job, request, time) {
|
|
3733
|
+
const { fence, phase, operationId, result } = request;
|
|
3734
|
+
if (job.jobId !== fence.jobId) return null;
|
|
3735
|
+
assertEvidencePhase(result.reason, phase, "owner", "invalid_command");
|
|
3736
|
+
const previous = job.attempts.find(({ commit }) => commit.attemptId === fence.attemptId);
|
|
3737
|
+
if (previous) {
|
|
3738
|
+
const { commit } = previous;
|
|
3739
|
+
const previousPhase = commit.handedOffAt === void 0 ? "pre_handoff" : "handed_off";
|
|
3740
|
+
if (previous.ownerDigest !== sha256(fence.token) || commit.operationId !== operationId || previousPhase !== phase) {
|
|
3741
|
+
return null;
|
|
3742
|
+
}
|
|
3743
|
+
if (hashJson(result, 8192, "invalid_command") !== hashJson(commit.result, 8192, "store_incompatible")) {
|
|
3744
|
+
invalid("invalid_command");
|
|
3745
|
+
}
|
|
3746
|
+
return { value: copyCommit(commit) };
|
|
3747
|
+
}
|
|
3748
|
+
const lease = liveLease(job, fence, phase, time.now);
|
|
3749
|
+
if (!lease) return null;
|
|
3750
|
+
if (result.reason === "expired" && time.now < job.expiresAt) invalid("invalid_command");
|
|
3751
|
+
assertEvidenceContext(result, job.provider, fence.attemptId, job.recipientCounts, "invalid_command");
|
|
3752
|
+
return finalize(job, lease, operationId, result, time, true);
|
|
3753
|
+
}
|
|
3754
|
+
function recoverJob(job, operationId, time) {
|
|
3755
|
+
if (job.state.state !== "leased" || time.now < job.state.lease.leaseEndsAt) return null;
|
|
3756
|
+
const { lease } = job.state;
|
|
3757
|
+
const reason = lease.handedOffAt === void 0 ? "pre_handoff_lease_expired" : "post_handoff_lease_expired";
|
|
3758
|
+
return finalize(job, lease, operationId, lifecycleEvidence(reason), time, false);
|
|
3759
|
+
}
|
|
3760
|
+
function expireJob(job, time) {
|
|
3761
|
+
if (job.state.state !== "queued" || time.now < job.expiresAt) return null;
|
|
3762
|
+
return replace(job, time, { ...job, state: terminalState("expired", "expired", time.now) }, jobSummary);
|
|
3763
|
+
}
|
|
3764
|
+
function cancelJob(job, operationId, time) {
|
|
3765
|
+
const { state } = job;
|
|
3766
|
+
if (state.state === "terminal") {
|
|
3767
|
+
return {
|
|
3768
|
+
value: Object.freeze({
|
|
3769
|
+
status: state.disposition === "cancelled" ? "cancelled" : "too_late",
|
|
3770
|
+
job: jobSummary(job)
|
|
3771
|
+
})
|
|
3772
|
+
};
|
|
3773
|
+
}
|
|
3774
|
+
if (time.now >= job.expiresAt || state.state === "leased" && state.lease.handedOffAt !== void 0) {
|
|
3775
|
+
return { value: Object.freeze({ status: "too_late", job: jobSummary(job) }) };
|
|
3776
|
+
}
|
|
3777
|
+
if (state.state === "leased") {
|
|
3778
|
+
const decision = finalize(job, state.lease, operationId, lifecycleEvidence("cancelled"), time, false);
|
|
3779
|
+
const { write } = decision;
|
|
3780
|
+
if (write?.kind !== "replace") invalid("store_incompatible");
|
|
3781
|
+
return { write, value: Object.freeze({ status: "cancelled", job: jobSummary(write.next) }) };
|
|
3782
|
+
}
|
|
3783
|
+
return replace(
|
|
3784
|
+
job,
|
|
3785
|
+
time,
|
|
3786
|
+
{ ...job, state: terminalState("cancelled", "cancelled", time.now) },
|
|
3787
|
+
(next) => Object.freeze({ status: "cancelled", job: jobSummary(next) }),
|
|
3788
|
+
job.expiresAt
|
|
3789
|
+
);
|
|
3790
|
+
}
|
|
3791
|
+
function resolveJob(job, request, time) {
|
|
3792
|
+
if (job.jobId !== request.jobId) invalid("not_found");
|
|
3793
|
+
const replay = job.resolutions.find(({ attemptId }) => attemptId === request.attemptId);
|
|
3794
|
+
if (replay) {
|
|
3795
|
+
if (replay.action !== request.action) invalid("resolution_conflict");
|
|
3796
|
+
return { value: Object.freeze({ status: "replayed", job: jobSummary(job) }) };
|
|
3797
|
+
}
|
|
3798
|
+
const { state } = job;
|
|
3799
|
+
if (state.state !== "terminal" || state.disposition !== "unknown" || state.settledAt !== void 0 || job.attempts.at(-1)?.commit.attemptId !== request.attemptId) {
|
|
3800
|
+
invalid("resolution_conflict");
|
|
3801
|
+
}
|
|
3802
|
+
const redrive = request.action === "redrive";
|
|
3803
|
+
if (redrive) {
|
|
3804
|
+
if (hasRedrive(job) || !job.snapshot) invalid("resolution_conflict");
|
|
3805
|
+
if (time.now >= job.expiresAt) invalid("expired");
|
|
3806
|
+
}
|
|
3807
|
+
const resolutions = Object.freeze([
|
|
3808
|
+
...job.resolutions,
|
|
3809
|
+
Object.freeze({ attemptId: request.attemptId, action: request.action, at: time.now })
|
|
3810
|
+
]);
|
|
3811
|
+
const nextState = redrive ? Object.freeze({ state: "queued", nextAt: time.now }) : Object.freeze({ ...state, settledAt: time.now });
|
|
3812
|
+
return replace(
|
|
3813
|
+
job,
|
|
3814
|
+
time,
|
|
3815
|
+
{ ...job, resolutions, state: nextState },
|
|
3816
|
+
(next) => Object.freeze({ status: "resolved", job: jobSummary(next) }),
|
|
3817
|
+
redrive ? job.expiresAt : void 0
|
|
3818
|
+
);
|
|
3819
|
+
}
|
|
3820
|
+
function replaceAttempt(job, previous, entry) {
|
|
3821
|
+
return Object.freeze(job.attempts.map((attempt) => attempt === previous ? Object.freeze(entry) : attempt));
|
|
3822
|
+
}
|
|
3823
|
+
function reserveJobProjection(job, time) {
|
|
3824
|
+
const entry = pendingAttempt(job);
|
|
3825
|
+
if (job.retiring || !entry || entry.commit.finishedAt > time.now) return null;
|
|
3826
|
+
const permitUntil = timeAfter(time.now, PROJECTION_PERMIT_MS) ?? invalid("store_unavailable");
|
|
3827
|
+
const activity = activityFor(job, entry.commit);
|
|
3828
|
+
const permit = Object.freeze({ activity, digest: entry.digest, permitUntil });
|
|
3829
|
+
const attempts = replaceAttempt(job, entry, { ...entry, permitUntil });
|
|
3830
|
+
return replace(
|
|
3831
|
+
job,
|
|
3832
|
+
time,
|
|
3833
|
+
{ ...job, attempts, projectionPermitUntil: Math.max(job.projectionPermitUntil ?? 0, permitUntil) },
|
|
3834
|
+
() => permit,
|
|
3835
|
+
permitUntil
|
|
3836
|
+
);
|
|
3837
|
+
}
|
|
3838
|
+
function matchingProjection(job, permit) {
|
|
3839
|
+
const { scope, jobId, attemptId } = permit.activity;
|
|
3840
|
+
if (!job || job.scope !== scope || job.jobId !== jobId) return;
|
|
3841
|
+
return job.attempts.find(
|
|
3842
|
+
(entry) => entry.commit.attemptId === attemptId && entry.digest === permit.digest && entry.permitUntil !== void 0 && permit.permitUntil <= entry.permitUntil && permit.permitUntil - entry.commit.finishedAt >= PROJECTION_PERMIT_MS
|
|
3843
|
+
);
|
|
3844
|
+
}
|
|
3845
|
+
function assertMatchingActivity(stored, permit) {
|
|
3846
|
+
const { activity } = permit;
|
|
3847
|
+
if (stored.activity.scope !== activity.scope || stored.activity.jobId !== activity.jobId || stored.activity.attemptId !== activity.attemptId || stored.digest !== permit.digest) {
|
|
3848
|
+
invalid("store_incompatible");
|
|
3849
|
+
}
|
|
3850
|
+
}
|
|
3851
|
+
function decideActivityPut(job, permit, existing, now) {
|
|
3852
|
+
if (existing) assertMatchingActivity(existing, permit);
|
|
3853
|
+
if (!existing && now >= permit.permitUntil) return "permit_expired";
|
|
3854
|
+
const entry = matchingProjection(job, permit);
|
|
3855
|
+
if (!entry) invalid("invalid_command");
|
|
3856
|
+
if (existing) return "present";
|
|
3857
|
+
if (entry.projectionAckAt !== void 0 || job?.retiring) invalid("store_incompatible");
|
|
3858
|
+
if (now < permit.permitUntil - PROJECTION_PERMIT_MS) invalid("store_unavailable");
|
|
3859
|
+
return "insert";
|
|
3860
|
+
}
|
|
3861
|
+
function acknowledgeJobProjection(job, permit, proof, time) {
|
|
3862
|
+
const entry = matchingProjection(job, permit);
|
|
3863
|
+
if (!entry) return { value: "stale" };
|
|
3864
|
+
if (proof) assertMatchingActivity(proof, permit);
|
|
3865
|
+
if (entry.projectionAckAt !== void 0) return { value: "already_acknowledged" };
|
|
3866
|
+
if (!proof || job.retiring) return { value: "stale" };
|
|
3867
|
+
if (time.now < permit.permitUntil - PROJECTION_PERMIT_MS) invalid("store_unavailable");
|
|
3868
|
+
const attempts = replaceAttempt(job, entry, { ...entry, projectionAckAt: time.now });
|
|
3869
|
+
return replace(job, time, { ...job, attempts }, () => "acknowledged", void 0, {
|
|
3870
|
+
attemptId: entry.commit.attemptId,
|
|
3871
|
+
digest: entry.digest
|
|
3872
|
+
});
|
|
3873
|
+
}
|
|
3874
|
+
function cleanupJob(job, time) {
|
|
3875
|
+
const due = jobSelectors(job).nextCleanupAt;
|
|
3876
|
+
if (due === void 0 || due > time.now) return null;
|
|
3877
|
+
if (job.retiring) {
|
|
3878
|
+
return {
|
|
3879
|
+
write: {
|
|
3880
|
+
kind: "purge",
|
|
3881
|
+
guard: guard(job, time),
|
|
3882
|
+
attemptIds: Object.freeze(job.attempts.map(({ commit }) => commit.attemptId))
|
|
3883
|
+
},
|
|
3884
|
+
value: "purged"
|
|
3885
|
+
};
|
|
3886
|
+
}
|
|
3887
|
+
if (job.snapshot) {
|
|
3888
|
+
const pruned = { ...job };
|
|
3889
|
+
delete pruned.snapshot;
|
|
3890
|
+
return replace(job, time, pruned, () => "payload_pruned");
|
|
3891
|
+
}
|
|
3892
|
+
return replace(job, time, { ...job, retiring: true }, () => "retirement_started");
|
|
3893
|
+
}
|
|
3894
|
+
|
|
3895
|
+
// src/stores/memory.ts
|
|
3896
|
+
var dueKeys = ["nextAt", "queuedExpiresAt", "leaseEndsAt", "pendingAt", "nextCleanupAt"];
|
|
3897
|
+
function emptyScope() {
|
|
3898
|
+
return {
|
|
3899
|
+
jobs: /* @__PURE__ */ new Map(),
|
|
3900
|
+
identities: /* @__PURE__ */ new Map(),
|
|
3901
|
+
due: { nextAt: [], queuedExpiresAt: [], leaseEndsAt: [], pendingAt: [], nextCleanupAt: [] },
|
|
3902
|
+
activities: [],
|
|
3903
|
+
byJob: /* @__PURE__ */ new Map()
|
|
3904
|
+
};
|
|
3905
|
+
}
|
|
3906
|
+
function lowerBound(ordered, test) {
|
|
3907
|
+
let lo = 0;
|
|
3908
|
+
let hi = ordered.length;
|
|
3909
|
+
while (lo < hi) {
|
|
3910
|
+
const mid = Math.floor((lo + hi) / 2);
|
|
3911
|
+
if (test(ordered[mid])) hi = mid;
|
|
3912
|
+
else lo = mid + 1;
|
|
3913
|
+
}
|
|
3914
|
+
return lo;
|
|
3915
|
+
}
|
|
3916
|
+
function compareDue(a, b) {
|
|
3917
|
+
return a.at - b.at || b.priority - a.priority || compareAscii(a.jobId, b.jobId);
|
|
3918
|
+
}
|
|
3919
|
+
function reindex(rows, previous, next) {
|
|
3920
|
+
const oldKeys = previous && jobSelectors(previous);
|
|
3921
|
+
const newKeys = next && jobSelectors(next);
|
|
3922
|
+
for (const key of dueKeys) {
|
|
3923
|
+
const oldAt = oldKeys?.[key];
|
|
3924
|
+
const newAt = newKeys?.[key];
|
|
3925
|
+
if (oldAt === newAt) continue;
|
|
3926
|
+
const index = rows.due[key];
|
|
3927
|
+
if (previous && oldAt !== void 0) {
|
|
3928
|
+
const entry = { at: oldAt, jobId: previous.jobId, priority: key === "nextAt" ? previous.priority : 0 };
|
|
3929
|
+
index.splice(
|
|
3930
|
+
lowerBound(index, (candidate) => compareDue(candidate, entry) >= 0),
|
|
3931
|
+
1
|
|
3932
|
+
);
|
|
3933
|
+
}
|
|
3934
|
+
if (next && newAt !== void 0) {
|
|
3935
|
+
const entry = { at: newAt, jobId: next.jobId, priority: key === "nextAt" ? next.priority : 0 };
|
|
3936
|
+
index.splice(
|
|
3937
|
+
lowerBound(index, (candidate) => compareDue(candidate, entry) >= 0),
|
|
3938
|
+
0,
|
|
3939
|
+
entry
|
|
3940
|
+
);
|
|
3941
|
+
}
|
|
3942
|
+
}
|
|
3943
|
+
}
|
|
3944
|
+
function putRow(rows, stored) {
|
|
3945
|
+
const { jobId, attemptId } = stored.activity;
|
|
3946
|
+
let job = rows.byJob.get(jobId);
|
|
3947
|
+
if (!job) {
|
|
3948
|
+
job = { byId: /* @__PURE__ */ new Map(), ordered: [] };
|
|
3949
|
+
rows.byJob.set(jobId, job);
|
|
3950
|
+
}
|
|
3951
|
+
job.byId.set(attemptId, stored);
|
|
3952
|
+
const index = (candidate) => compareActivity(candidate.activity, stored.activity) >= 0;
|
|
3953
|
+
job.ordered.splice(lowerBound(job.ordered, index), 0, stored);
|
|
3954
|
+
rows.activities.splice(lowerBound(rows.activities, index), 0, stored);
|
|
3955
|
+
}
|
|
3956
|
+
function removeActivities(rows, jobId, attemptIds) {
|
|
3957
|
+
const job = rows.byJob.get(jobId);
|
|
3958
|
+
if (!job) return;
|
|
3959
|
+
for (const attemptId of attemptIds) {
|
|
3960
|
+
const activity = job.byId.get(attemptId)?.activity;
|
|
3961
|
+
if (!activity) continue;
|
|
3962
|
+
const i = lowerBound(rows.activities, (candidate) => compareActivity(candidate.activity, activity) >= 0);
|
|
3963
|
+
rows.activities.splice(i, 1);
|
|
3964
|
+
}
|
|
3965
|
+
rows.byJob.delete(jobId);
|
|
3966
|
+
}
|
|
3967
|
+
var TIME_MISS = /* @__PURE__ */ Symbol("time_miss");
|
|
3968
|
+
var NONE = Object.freeze({ status: "none" });
|
|
3969
|
+
var CONTENDED = Object.freeze({ status: "contended" });
|
|
3970
|
+
function createMemoryEmailStore(options = {}) {
|
|
3971
|
+
const config = readRecord(options, [], ["clock", "maxJobs"], "invalid_config");
|
|
3972
|
+
const clock = readClock(config.clock);
|
|
3973
|
+
const maxJobs = boundedOption(config.maxJobs, MEMORY_MAX_JOBS);
|
|
3974
|
+
const scopes = /* @__PURE__ */ new Map();
|
|
3975
|
+
let count = 0;
|
|
3976
|
+
let active = false;
|
|
3977
|
+
let lastWall = 0;
|
|
3978
|
+
function wallNow() {
|
|
3979
|
+
let now;
|
|
3980
|
+
try {
|
|
3981
|
+
now = unixMs(clock.now(), "store_unavailable");
|
|
3982
|
+
} catch {
|
|
3983
|
+
return invalid("store_unavailable");
|
|
3984
|
+
}
|
|
3985
|
+
if (now < lastWall) invalid("store_unavailable");
|
|
3986
|
+
lastWall = now;
|
|
3987
|
+
return now;
|
|
3988
|
+
}
|
|
3989
|
+
function elapsedClock() {
|
|
3990
|
+
try {
|
|
3991
|
+
const now = clock.monotonicNow();
|
|
3992
|
+
if (Number.isFinite(now)) return now;
|
|
3993
|
+
} catch {
|
|
3994
|
+
invalid("store_unavailable");
|
|
3995
|
+
}
|
|
3996
|
+
return invalid("store_unavailable");
|
|
3997
|
+
}
|
|
3998
|
+
function atomic(call, run) {
|
|
3999
|
+
if (active) invalid("busy");
|
|
4000
|
+
active = true;
|
|
4001
|
+
try {
|
|
4002
|
+
const signal = call.signal;
|
|
4003
|
+
if (signal && Reflect.get(AbortSignal.prototype, "aborted", signal)) invalid("aborted");
|
|
4004
|
+
const start = elapsedClock();
|
|
4005
|
+
const check = () => {
|
|
4006
|
+
const elapsed = elapsedClock() - start;
|
|
4007
|
+
if (signal && Reflect.get(AbortSignal.prototype, "aborted", signal)) invalid("aborted");
|
|
4008
|
+
if (elapsed < 0) invalid("store_unavailable");
|
|
4009
|
+
if (elapsed >= call.timeoutMs) invalid("deadline");
|
|
4010
|
+
};
|
|
4011
|
+
check();
|
|
4012
|
+
return run(check);
|
|
4013
|
+
} finally {
|
|
4014
|
+
active = false;
|
|
4015
|
+
}
|
|
4016
|
+
}
|
|
4017
|
+
function read(call, worker, get) {
|
|
4018
|
+
return atomic(readStoreCall(call, worker), (check) => {
|
|
4019
|
+
const value = get();
|
|
4020
|
+
check();
|
|
4021
|
+
return value;
|
|
4022
|
+
});
|
|
4023
|
+
}
|
|
4024
|
+
function apply(rows, row, plan, check) {
|
|
4025
|
+
check();
|
|
4026
|
+
if (!plan) return null;
|
|
4027
|
+
const { write } = plan;
|
|
4028
|
+
if (write) {
|
|
4029
|
+
const now = wallNow();
|
|
4030
|
+
check();
|
|
4031
|
+
if (now < write.guard.atOrAfter || write.guard.before !== void 0 && now >= write.guard.before)
|
|
4032
|
+
return TIME_MISS;
|
|
4033
|
+
if (write.kind === "replace") {
|
|
4034
|
+
reindex(rows, row, write.next);
|
|
4035
|
+
rows.jobs.set(row.jobId, write.next);
|
|
4036
|
+
} else {
|
|
4037
|
+
removeActivities(rows, row.jobId, write.attemptIds);
|
|
4038
|
+
reindex(rows, row, void 0);
|
|
4039
|
+
rows.jobs.delete(row.jobId);
|
|
4040
|
+
rows.identities.delete(row.admissionKey);
|
|
4041
|
+
count--;
|
|
4042
|
+
if (rows.jobs.size === 0) scopes.delete(row.scope);
|
|
4043
|
+
}
|
|
4044
|
+
}
|
|
4045
|
+
return plan.value;
|
|
4046
|
+
}
|
|
4047
|
+
function point(scope, jobId, check, decide) {
|
|
4048
|
+
const rows = scopes.get(scopeToken(scope));
|
|
4049
|
+
const row = rows?.jobs.get(jobId);
|
|
4050
|
+
if (!rows || !row) {
|
|
4051
|
+
check();
|
|
4052
|
+
return null;
|
|
4053
|
+
}
|
|
4054
|
+
for (let i = 0; i < MAX_STORE_CAS_SUBMISSIONS; i++) {
|
|
4055
|
+
const value = apply(rows, row, decide(row, { now: wallNow(), revision: randomUUID4() }), check);
|
|
4056
|
+
if (value !== TIME_MISS) return value;
|
|
4057
|
+
}
|
|
4058
|
+
return invalid("busy");
|
|
4059
|
+
}
|
|
4060
|
+
function next(scope, key, check, decide) {
|
|
4061
|
+
const rows = scopes.get(scopeToken(scope));
|
|
4062
|
+
let now = wallNow();
|
|
4063
|
+
let misses = 0;
|
|
4064
|
+
if (rows) {
|
|
4065
|
+
const index = rows.due[key];
|
|
4066
|
+
for (let i = 0; i < MAX_STORE_CANDIDATES && i < index.length; i++) {
|
|
4067
|
+
const candidate = index[i];
|
|
4068
|
+
if (candidate.at > now) break;
|
|
4069
|
+
const row = rows.jobs.get(candidate.jobId);
|
|
4070
|
+
for (; ; ) {
|
|
4071
|
+
const value = apply(rows, row, decide(row, { now, revision: randomUUID4() }), check);
|
|
4072
|
+
if (value === null) break;
|
|
4073
|
+
if (value !== TIME_MISS) return Object.freeze({ status: "applied", value });
|
|
4074
|
+
if (++misses === MAX_STORE_CAS_SUBMISSIONS) return CONTENDED;
|
|
4075
|
+
now = wallNow();
|
|
4076
|
+
}
|
|
4077
|
+
}
|
|
4078
|
+
}
|
|
4079
|
+
check();
|
|
4080
|
+
return misses ? CONTENDED : NONE;
|
|
4081
|
+
}
|
|
4082
|
+
const store = {
|
|
4083
|
+
async ready(options2 = {}) {
|
|
4084
|
+
const call = readCallOptions(options2, CALL_BUDGETS.admissionOrAdmin);
|
|
4085
|
+
atomic({ ...call, timeoutMs: Math.min(call.timeoutMs, STORE_PRIMITIVE_TIMEOUT_MS) }, (check) => {
|
|
4086
|
+
wallNow();
|
|
4087
|
+
check();
|
|
4088
|
+
});
|
|
4089
|
+
},
|
|
4090
|
+
async findAdmission(scope, key, call) {
|
|
4091
|
+
return read(call, false, () => {
|
|
4092
|
+
const rows = scopes.get(scopeToken(scope));
|
|
4093
|
+
const encoded = encodeAdmissionKey(validateAdmissionKey(key));
|
|
4094
|
+
const id = rows?.identities.get(encoded);
|
|
4095
|
+
const row = id && rows?.jobs.get(id);
|
|
4096
|
+
return row ? Object.freeze({ job: jobSummary(row), fingerprint: row.fingerprint }) : null;
|
|
4097
|
+
});
|
|
4098
|
+
},
|
|
4099
|
+
async insert(scope, admission, call) {
|
|
4100
|
+
return atomic(readStoreCall(call), (check) => {
|
|
4101
|
+
const parsed = readStoreAdmission(scope, admission);
|
|
4102
|
+
const rows = scopes.get(parsed.command.scope);
|
|
4103
|
+
if (rows?.identities.has(parsed.admissionKey)) {
|
|
4104
|
+
check();
|
|
4105
|
+
return Object.freeze({ status: "duplicate" });
|
|
4106
|
+
}
|
|
4107
|
+
if (rows?.jobs.has(parsed.jobId)) invalid("invalid_command");
|
|
4108
|
+
const row = newJob(parsed, { now: wallNow(), revision: randomUUID4() });
|
|
4109
|
+
if (count >= maxJobs) invalid("store_capacity");
|
|
4110
|
+
const result = Object.freeze({ status: "inserted", job: jobSummary(row) });
|
|
4111
|
+
check();
|
|
4112
|
+
const target = rows ?? emptyScope();
|
|
4113
|
+
target.identities.set(row.admissionKey, row.jobId);
|
|
4114
|
+
target.jobs.set(row.jobId, row);
|
|
4115
|
+
reindex(target, void 0, row);
|
|
4116
|
+
if (!rows) scopes.set(row.scope, target);
|
|
4117
|
+
count++;
|
|
4118
|
+
return result;
|
|
4119
|
+
});
|
|
4120
|
+
},
|
|
4121
|
+
async findJob(scope, jobId, call) {
|
|
4122
|
+
return read(call, false, () => {
|
|
4123
|
+
const rows = scopes.get(scopeToken(scope));
|
|
4124
|
+
const id = readStoreId(jobId);
|
|
4125
|
+
const job = rows?.jobs.get(id);
|
|
4126
|
+
return job ? jobSummary(job) : null;
|
|
4127
|
+
});
|
|
4128
|
+
},
|
|
4129
|
+
async findAttempt(scope, jobId, attemptId, call) {
|
|
4130
|
+
return read(call, true, () => {
|
|
4131
|
+
const rows = scopes.get(scopeToken(scope));
|
|
4132
|
+
const job = readStoreId(jobId);
|
|
4133
|
+
const id = readStoreId(attemptId);
|
|
4134
|
+
const entry = rows?.jobs.get(job)?.attempts.find(({ commit }) => commit.attemptId === id);
|
|
4135
|
+
return entry ? copyCommit(entry.commit) : null;
|
|
4136
|
+
});
|
|
4137
|
+
},
|
|
4138
|
+
async claimNext(scope, claim, call) {
|
|
4139
|
+
return atomic(readStoreCall(call, true), (check) => {
|
|
4140
|
+
const safe = readClaim(claim);
|
|
4141
|
+
return next(scope, "nextAt", check, (row, time) => claimJob(row, safe, time));
|
|
4142
|
+
});
|
|
4143
|
+
},
|
|
4144
|
+
async renew(scope, fence, leaseMs, call) {
|
|
4145
|
+
return atomic(readStoreCall(call, true), (check) => {
|
|
4146
|
+
const safe = readFence(fence);
|
|
4147
|
+
const duration = readLeaseMs(leaseMs);
|
|
4148
|
+
return point(scope, safe.jobId, check, (row, time) => renewJob(row, safe, duration, time));
|
|
4149
|
+
});
|
|
4150
|
+
},
|
|
4151
|
+
async markHandoff(scope, fence, leaseMs, call) {
|
|
4152
|
+
return atomic(readStoreCall(call, true), (check) => {
|
|
4153
|
+
const safe = readFence(fence);
|
|
4154
|
+
const duration = readLeaseMs(leaseMs);
|
|
4155
|
+
return point(scope, safe.jobId, check, (row, time) => markJob(row, safe, duration, time));
|
|
4156
|
+
});
|
|
4157
|
+
},
|
|
4158
|
+
async finish(scope, finish, call) {
|
|
4159
|
+
return atomic(readStoreCall(call, true), (check) => {
|
|
4160
|
+
const safe = readFinish(finish);
|
|
4161
|
+
return point(scope, safe.fence.jobId, check, (row, time) => finishJob(row, safe, time));
|
|
4162
|
+
});
|
|
4163
|
+
},
|
|
4164
|
+
async recoverNext(scope, call) {
|
|
4165
|
+
return atomic(readStoreCall(call, true), (check) => {
|
|
4166
|
+
const operationId = randomUUID4();
|
|
4167
|
+
return next(scope, "leaseEndsAt", check, (row, time) => recoverJob(row, operationId, time));
|
|
4168
|
+
});
|
|
4169
|
+
},
|
|
4170
|
+
async expireNext(scope, call) {
|
|
4171
|
+
return atomic(readStoreCall(call, true), (check) => next(scope, "queuedExpiresAt", check, expireJob));
|
|
4172
|
+
},
|
|
4173
|
+
async cancel(scope, jobId, call) {
|
|
4174
|
+
return atomic(readStoreCall(call), (check) => {
|
|
4175
|
+
const operationId = randomUUID4();
|
|
4176
|
+
return point(scope, readStoreId(jobId), check, (row, time) => cancelJob(row, operationId, time)) ?? Object.freeze({ status: "not_found" });
|
|
4177
|
+
});
|
|
4178
|
+
},
|
|
4179
|
+
async resolveUnknown(scope, command, call) {
|
|
4180
|
+
return atomic(readStoreCall(call), (check) => {
|
|
4181
|
+
const safe = readResolution(command);
|
|
4182
|
+
return point(scope, safe.jobId, check, (row, time) => resolveJob(row, safe, time)) ?? invalid("not_found");
|
|
4183
|
+
});
|
|
4184
|
+
},
|
|
4185
|
+
async reserveProjection(scope, call) {
|
|
4186
|
+
return atomic(readStoreCall(call), (check) => next(scope, "pendingAt", check, reserveJobProjection));
|
|
4187
|
+
},
|
|
4188
|
+
async putActivity(scope, permit, call) {
|
|
4189
|
+
return atomic(readStoreCall(call), (check) => {
|
|
4190
|
+
const safe = readProjectionPermit(scopeToken(scope), permit);
|
|
4191
|
+
const rows = scopes.get(scope);
|
|
4192
|
+
const { jobId, attemptId } = safe.activity;
|
|
4193
|
+
const existing = rows?.byJob.get(jobId)?.byId.get(attemptId);
|
|
4194
|
+
const decision = decideActivityPut(rows?.jobs.get(jobId), safe, existing, wallNow());
|
|
4195
|
+
check();
|
|
4196
|
+
if (decision !== "insert") return decision;
|
|
4197
|
+
if (!rows) invalid("store_incompatible");
|
|
4198
|
+
const now = wallNow();
|
|
4199
|
+
check();
|
|
4200
|
+
if (now >= safe.permitUntil) return "permit_expired";
|
|
4201
|
+
putRow(rows, Object.freeze({ activity: safe.activity, digest: safe.digest }));
|
|
4202
|
+
return "present";
|
|
4203
|
+
});
|
|
4204
|
+
},
|
|
4205
|
+
async ackProjection(scope, permit, call) {
|
|
4206
|
+
return atomic(readStoreCall(call), (check) => {
|
|
4207
|
+
const safe = readProjectionPermit(scopeToken(scope), permit);
|
|
4208
|
+
const { jobId, attemptId } = safe.activity;
|
|
4209
|
+
const proof = scopes.get(scope)?.byJob.get(jobId)?.byId.get(attemptId);
|
|
4210
|
+
return point(scope, jobId, check, (row, time) => acknowledgeJobProjection(row, safe, proof, time)) ?? "stale";
|
|
4211
|
+
});
|
|
4212
|
+
},
|
|
4213
|
+
async listActivities(scope, query, call) {
|
|
4214
|
+
return read(call, false, () => {
|
|
4215
|
+
const criteria = readActivityCriteria(scopeToken(scope), query);
|
|
4216
|
+
const rows = scopes.get(scope);
|
|
4217
|
+
const { jobId, before, from, after, limit } = criteria;
|
|
4218
|
+
const index = (jobId === null ? rows?.activities : rows?.byJob.get(jobId)?.ordered) ?? [];
|
|
4219
|
+
const start = Math.max(
|
|
4220
|
+
before === null ? 0 : lowerBound(index, ({ activity }) => activity.finishedAt < before),
|
|
4221
|
+
after === void 0 ? 0 : lowerBound(index, ({ activity }) => compareActivity(activity, after) > 0)
|
|
4222
|
+
);
|
|
4223
|
+
const end = from === null ? index.length : lowerBound(index, ({ activity }) => activity.finishedAt < from);
|
|
4224
|
+
const selected = index.slice(start, Math.min(end, start + limit + 1)).map(({ activity }) => activity);
|
|
4225
|
+
return activityPage(criteria, selected);
|
|
4226
|
+
});
|
|
4227
|
+
},
|
|
4228
|
+
async cleanupNext(scope, call) {
|
|
4229
|
+
return atomic(readStoreCall(call), (check) => next(scope, "nextCleanupAt", check, cleanupJob));
|
|
4230
|
+
}
|
|
4231
|
+
};
|
|
4232
|
+
return Object.freeze(store);
|
|
4233
|
+
}
|
|
4234
|
+
export {
|
|
4235
|
+
EmailError,
|
|
4236
|
+
createEmailAdmin,
|
|
4237
|
+
createEmailBatchService,
|
|
4238
|
+
createEmailService,
|
|
4239
|
+
createEmailTemplateRegistry,
|
|
4240
|
+
createEmailWorker,
|
|
4241
|
+
createMemoryEmailStore,
|
|
4242
|
+
defineLocalTemplate,
|
|
4243
|
+
defineSendGridTemplate
|
|
4244
|
+
};
|