@web-ts-toolkit/email-service 0.73.0 → 0.74.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/index.js CHANGED
@@ -32,11 +32,14 @@ var src_exports = {};
32
32
  __export(src_exports, {
33
33
  EmailError: () => EmailError,
34
34
  createEmailAdmin: () => createEmailAdmin,
35
+ createEmailBatchAdmission: () => createEmailBatchAdmission,
35
36
  createEmailBatchService: () => createEmailBatchService,
37
+ createEmailRelay: () => createEmailRelay,
36
38
  createEmailService: () => createEmailService,
37
39
  createEmailTemplateRegistry: () => createEmailTemplateRegistry,
38
40
  createEmailWorker: () => createEmailWorker,
39
41
  createMemoryEmailStore: () => createMemoryEmailStore,
42
+ createSmtpAcceptanceResult: () => createSmtpAcceptanceResult,
40
43
  defineLocalTemplate: () => defineLocalTemplate,
41
44
  defineSendGridTemplate: () => defineSendGridTemplate
42
45
  });
@@ -726,7 +729,7 @@ var import_node_util4 = require("util");
726
729
 
727
730
  // src/internal/smtp-capacity.ts
728
731
  var MIN_RECIPIENTS = MESSAGE_LIMITS.recipients + 1;
729
- var MAX_RECIPIENTS = 1e3;
732
+ var MAX_SMTP_RECIPIENTS = 1e3;
730
733
  var KIB = 1024;
731
734
  var limits = Object.freeze({
732
735
  snapshotBytes: 2 * KIB * KIB,
@@ -754,7 +757,7 @@ function readBinding(input, code) {
754
757
  return Object.freeze({
755
758
  format,
756
759
  namespace: uuidV4(namespace, code),
757
- maxRecipients: integer(maxRecipients, MIN_RECIPIENTS, MAX_RECIPIENTS, code)
760
+ maxRecipients: integer(maxRecipients, MIN_RECIPIENTS, MAX_SMTP_RECIPIENTS, code)
758
761
  });
759
762
  }
760
763
  function readCapacityOption(raw) {
@@ -1102,6 +1105,11 @@ function validatePreparedCommand(scope, input, capacity) {
1102
1105
  });
1103
1106
  }
1104
1107
 
1108
+ // src/internal/smtp-attachments.ts
1109
+ function assertSmtpAttachmentTypes(refs) {
1110
+ if (refs.some(({ contentType }) => /^(?:message|multipart)\//.test(contentType))) invalid("invalid_snapshot");
1111
+ }
1112
+
1105
1113
  // src/templates/local-sources.ts
1106
1114
  var import_node_buffer2 = require("buffer");
1107
1115
  var import_node_events3 = require("events");
@@ -1354,6 +1362,7 @@ function captureFields(raw, definition, context, scheduleAt, budget, slot, capac
1354
1362
  );
1355
1363
  const priority = boundedOption(fields.priority, PRIORITY, code);
1356
1364
  const attachments = validateAttachmentRefs(fields.attachments === void 0 ? [] : fields.attachments);
1365
+ if (context.provider.kind === "smtp") assertSmtpAttachmentTypes(attachments);
1357
1366
  const correlation = validateCorrelation(fields.correlation === void 0 ? {} : fields.correlation);
1358
1367
  const values = copyJsonObject(fields.values, MESSAGE_LIMITS.dataBytes, "invalid_data");
1359
1368
  const { parseData } = definition;
@@ -1541,6 +1550,57 @@ function readRecipientCounts(input, code, capacity) {
1541
1550
  function smtpMessageId(attemptId) {
1542
1551
  return `<${attemptId}@email.invalid>`;
1543
1552
  }
1553
+ function readRecipientResults(input, code, { limit, allowAccepted, ordered }) {
1554
+ const seen = /* @__PURE__ */ new Set();
1555
+ let previous = -1;
1556
+ return readArray(input, limit, code, (value) => {
1557
+ const { group, index: rawIndex, status } = readRecord(value, ["group", "index", "status"], [], code);
1558
+ if (group !== "to" && group !== "cc" && group !== "bcc") invalid(code);
1559
+ if (status !== "rejected" && (status !== "accepted" || !allowAccepted)) invalid(code);
1560
+ const index = integer(rawIndex, 0, limit - 1, code);
1561
+ if (ordered) {
1562
+ const position = recipientGroups.indexOf(group) * limit + index;
1563
+ if (position <= previous) invalid(code);
1564
+ previous = position;
1565
+ } else {
1566
+ const key = `${group}:${index}`;
1567
+ if (seen.has(key)) invalid(code);
1568
+ seen.add(key);
1569
+ }
1570
+ return Object.freeze({ group, index, status });
1571
+ });
1572
+ }
1573
+ function allAccepted(recipients) {
1574
+ return recipients.length !== 0 && recipients.every(({ status }) => status === "accepted");
1575
+ }
1576
+ function createSmtpAcceptanceResult(recipients, messageId) {
1577
+ const code = "invalid_command";
1578
+ if (messageId !== void 0 && (typeof messageId !== "string" || messageId.length !== 52 || messageId !== smtpMessageId(uuidV4(messageId.slice(1, 37), code)))) {
1579
+ invalid(code);
1580
+ }
1581
+ const checked = readRecipientResults(recipients, code, {
1582
+ limit: MAX_SMTP_RECIPIENTS,
1583
+ allowAccepted: true,
1584
+ ordered: false
1585
+ });
1586
+ const data = { retry: "never", stage: "data", ...messageId === void 0 ? {} : { messageId } };
1587
+ if (allAccepted(checked)) {
1588
+ return Object.freeze({ ...data, reason: "smtp_accepted", outcome: "accepted", recipients: checked });
1589
+ }
1590
+ if (!checked.some(({ status }) => status === "accepted")) invalid(code);
1591
+ return Object.freeze({
1592
+ ...data,
1593
+ reason: "smtp_partial",
1594
+ outcome: "partially_accepted",
1595
+ recipients: checked
1596
+ });
1597
+ }
1598
+ function uncertainProviderResult(stage, reason) {
1599
+ const base = { outcome: "unknown", retry: "never", stage };
1600
+ if (reason === "provider_timeout") return { ...base, reason };
1601
+ if (reason === "provider_aborted") return { ...base, reason };
1602
+ return { ...base, reason };
1603
+ }
1544
1604
  function readHint(input, reason, code) {
1545
1605
  if (reason !== "rate_deferred" && reason !== "sendgrid_throttled") invalid(code);
1546
1606
  const raw = readRecord(input, [], ["delayMs", "notBefore"], code);
@@ -1574,24 +1634,10 @@ function readAttemptResult(input, code = "invalid_command", projected = false, c
1574
1634
  let recipients;
1575
1635
  if (hasRecipients) {
1576
1636
  if (origin !== "smtp" && origin !== "provider" || stage !== "envelope" && stage !== "data") invalid(code);
1577
- const seen = /* @__PURE__ */ new Set();
1578
- const limit = recipientLimit(capacity);
1579
- let previous = -1;
1580
- recipients = readArray(raw.recipients, limit, code, (value) => {
1581
- const { group, index: rawIndex, status } = readRecord(value, ["group", "index", "status"], [], code);
1582
- if (group !== "to" && group !== "cc" && group !== "bcc") invalid(code);
1583
- if (status !== "rejected" && (status !== "accepted" || !smtpSuccess)) invalid(code);
1584
- const index = integer(rawIndex, 0, limit - 1, code);
1585
- if (capacity) {
1586
- const position = recipientGroups.indexOf(group) * limit + index;
1587
- if (position <= previous) invalid(code);
1588
- previous = position;
1589
- } else {
1590
- const key = `${group}:${index}`;
1591
- if (seen.has(key)) invalid(code);
1592
- seen.add(key);
1593
- }
1594
- return Object.freeze({ group, index, status });
1637
+ recipients = readRecipientResults(raw.recipients, code, {
1638
+ limit: recipientLimit(capacity),
1639
+ allowAccepted: smtpSuccess,
1640
+ ordered: Boolean(capacity)
1595
1641
  });
1596
1642
  const accepted = recipients.filter(({ status }) => status === "accepted").length;
1597
1643
  if (reason === "smtp_accepted" && (!accepted || accepted !== recipients.length) || reason === "smtp_partial" && (!accepted || accepted === recipients.length)) {
@@ -1702,7 +1748,7 @@ function readStoreCall(input, worker = false, capacity) {
1702
1748
  timeoutMs: worker && !capacity ? timeoutMs : Math.min(timeoutMs, STORE_PRIMITIVE_TIMEOUT_MS)
1703
1749
  };
1704
1750
  }
1705
- function readStoreNext(value, read) {
1751
+ function readStoreNext(value, read, kind) {
1706
1752
  const code = "store_incompatible";
1707
1753
  const raw = readRecord(value, ["status"], ["value"], code);
1708
1754
  if (raw.status === "applied" && Object.hasOwn(raw, "value")) {
@@ -1711,6 +1757,9 @@ function readStoreNext(value, read) {
1711
1757
  if ((raw.status === "none" || raw.status === "contended") && !Object.hasOwn(raw, "value")) {
1712
1758
  return Object.freeze({ status: raw.status });
1713
1759
  }
1760
+ if (kind === "claim" && raw.status === "expiry_maintenance_required" && !Object.hasOwn(raw, "value")) {
1761
+ return Object.freeze({ status: raw.status });
1762
+ }
1714
1763
  return invalid(code);
1715
1764
  }
1716
1765
  function readRetryPolicy(input, code = REQUEST) {
@@ -2227,24 +2276,22 @@ var serviceAdmissions = /* @__PURE__ */ new WeakMap();
2227
2276
  function findServiceAdmission(service) {
2228
2277
  return serviceAdmissions.get(service);
2229
2278
  }
2279
+ function createEmailRelay(options) {
2280
+ const raw = readRecord(options, ["scope", "store"], ["retry", "retention", "smtpCapacity"], CONFIG);
2281
+ const { enqueuePrepared } = createAdmissionCore(raw, systemEmailClock);
2282
+ return Object.freeze({ enqueuePrepared });
2283
+ }
2230
2284
  function createEmailService(options) {
2231
2285
  return createEmailServiceWithClock(options, systemEmailClock);
2232
2286
  }
2233
2287
  function createEmailServiceWithClock(options, clock) {
2234
2288
  const raw = readRecord(options, ["scope", "store", "registry"], ["retry", "retention", "smtpCapacity"], CONFIG);
2235
- const capacity = readCapacityOption(raw);
2236
- assertPortCapacity(raw.store, capacity);
2289
+ const { scope, capacity, enqueuePrepared, admitParsed, inOperation, withAdmission } = createAdmissionCore(raw, clock);
2237
2290
  assertPortCapacity(raw.registry, capacity);
2238
- const scope = scopeToken(raw.scope, CONFIG);
2239
- const retry = readRetryPolicy(readPolicy(raw.retry, DEFAULT_RETRY_POLICY), CONFIG);
2240
- const retention = readRetentionPolicy(readPolicy(raw.retention, DEFAULT_RETENTION_POLICY), CONFIG);
2241
- const find = bindMethod(raw.store, "findAdmission");
2242
- const insert = bindMethod(raw.store, "insert");
2243
2291
  if (typeof raw.registry !== "object" || raw.registry === null || import_node_util7.types.isProxy(raw.registry)) invalid(CONFIG);
2244
2292
  const registry = raw.registry;
2245
2293
  const prepare = bindMethod(registry, "prepare");
2246
2294
  const internalPrepare = findRegistryPreparation(registry);
2247
- let admissions = 0;
2248
2295
  async function prepareMiss(parsed, parent) {
2249
2296
  const { identity, command } = parsed;
2250
2297
  const accept = (value) => {
@@ -2304,6 +2351,27 @@ function createEmailServiceWithClock(options, clock) {
2304
2351
  slot.close();
2305
2352
  }
2306
2353
  }
2354
+ const enqueueParsed = (parsed, budget) => admitParsed(parsed, budget, prepareMiss);
2355
+ const service = Object.freeze({
2356
+ scope,
2357
+ ...capacityTag(capacity),
2358
+ enqueue(command, call = {}) {
2359
+ return inOperation(call, (budget) => enqueueParsed(parseCommandIdentity(scope, command, capacity), budget));
2360
+ },
2361
+ enqueuePrepared
2362
+ });
2363
+ serviceAdmissions.set(service, (parsed, budget) => withAdmission(() => enqueueParsed(parsed, budget)));
2364
+ return service;
2365
+ }
2366
+ function createAdmissionCore(raw, clock) {
2367
+ const capacity = readCapacityOption(raw);
2368
+ assertPortCapacity(raw.store, capacity);
2369
+ const scope = scopeToken(raw.scope, CONFIG);
2370
+ const retry = readRetryPolicy(readPolicy(raw.retry, DEFAULT_RETRY_POLICY), CONFIG);
2371
+ const retention = readRetentionPolicy(readPolicy(raw.retention, DEFAULT_RETENTION_POLICY), CONFIG);
2372
+ const find = bindMethod(raw.store, "findAdmission");
2373
+ const insert = bindMethod(raw.store, "insert");
2374
+ let admissions = 0;
2307
2375
  function findWinner(key, budget) {
2308
2376
  return runStoreCall(clock, budget, {
2309
2377
  maxMs: STORE_PRIMITIVE_TIMEOUT_MS,
@@ -2327,6 +2395,7 @@ function createEmailServiceWithClock(options, clock) {
2327
2395
  }
2328
2396
  async function insertOrConfirm(command, identity, budget) {
2329
2397
  budget.check();
2398
+ if (command.snapshot.kind === "smtp") assertSmtpAttachmentTypes(command.snapshot.attachments);
2330
2399
  const admission = Object.freeze({ command, jobId: (0, import_node_crypto2.randomUUID)(), retry, retention });
2331
2400
  try {
2332
2401
  const job = await runStoreCall(clock, budget, {
@@ -2359,7 +2428,7 @@ function createEmailServiceWithClock(options, clock) {
2359
2428
  }
2360
2429
  return invalid("write_unconfirmed");
2361
2430
  }
2362
- async function enqueueParsed(parsed, budget) {
2431
+ async function admitParsed(parsed, budget, prepareMiss) {
2363
2432
  if (parsed.identity.scope !== scope) invalid("invalid_command");
2364
2433
  const winner = await findWinner(parsed.identity.key, budget);
2365
2434
  if (winner) return replay(winner, parsed.identity);
@@ -2387,31 +2456,23 @@ function createEmailServiceWithClock(options, clock) {
2387
2456
  }
2388
2457
  });
2389
2458
  }
2390
- const service = Object.freeze({
2391
- scope,
2392
- ...capacityTag(capacity),
2393
- enqueue(command, call = {}) {
2394
- return inOperation(call, (budget) => enqueueParsed(parseCommandIdentity(scope, command, capacity), budget));
2395
- },
2396
- enqueuePrepared(input, call = {}) {
2397
- return inOperation(call, async (budget) => {
2398
- const command = validatePreparedCommand(scope, input, capacity);
2399
- const identity = {
2400
- scope,
2401
- key: command.key,
2402
- templateKey: command.snapshot.template.key,
2403
- provider: command.snapshot.provider,
2404
- scheduleAt: command.scheduleAt,
2405
- intentHash: command.intentHash,
2406
- fingerprint: command.fingerprint
2407
- };
2408
- const winner = await findWinner(identity.key, budget);
2409
- return winner ? replay(winner, identity) : insertOrConfirm(command, identity, budget);
2410
- });
2411
- }
2412
- });
2413
- serviceAdmissions.set(service, (parsed, budget) => withAdmission(() => enqueueParsed(parsed, budget)));
2414
- return service;
2459
+ function enqueuePrepared(input, call = {}) {
2460
+ return inOperation(call, async (budget) => {
2461
+ const command = validatePreparedCommand(scope, input, capacity);
2462
+ const identity = {
2463
+ scope,
2464
+ key: command.key,
2465
+ templateKey: command.snapshot.template.key,
2466
+ provider: command.snapshot.provider,
2467
+ scheduleAt: command.scheduleAt,
2468
+ intentHash: command.intentHash,
2469
+ fingerprint: command.fingerprint
2470
+ };
2471
+ const winner = await findWinner(identity.key, budget);
2472
+ return winner ? replay(winner, identity) : insertOrConfirm(command, identity, budget);
2473
+ });
2474
+ }
2475
+ return { scope, capacity, enqueuePrepared, admitParsed, inOperation, withAdmission };
2415
2476
  }
2416
2477
  function readPolicy(input, defaults) {
2417
2478
  const result = { ...defaults };
@@ -2464,7 +2525,7 @@ function readProfiles(input, capacity) {
2464
2525
  if (profiles.has(ref.key)) invalid(CONFIG2);
2465
2526
  profiles.set(ref.key, Object.freeze({ ref, prepare: bindMethod(provider, "prepare") }));
2466
2527
  });
2467
- if (capacity && profiles.size === 0) invalid(CONFIG2);
2528
+ if (profiles.size === 0) invalid(CONFIG2);
2468
2529
  return profiles;
2469
2530
  }
2470
2531
  function readResolvers(input) {
@@ -2949,7 +3010,7 @@ async function launch(run, owner, mark, submit, preflight) {
2949
3010
  mark.dispatchedAt + (expiresAt - mark.grant.handoffAt) - CLOCK_MARGIN_MS
2950
3011
  );
2951
3012
  const stage = provider.kind === "smtp" ? "data" : "http";
2952
- const unknown = (reason) => Object.freeze({ outcome: "unknown", retry: "never", stage, reason });
3013
+ const unknown = (reason) => Object.freeze(uncertainProviderResult(stage, reason));
2953
3014
  let io;
2954
3015
  try {
2955
3016
  run.checkLaunch();
@@ -3181,10 +3242,14 @@ function claimNext(run) {
3181
3242
  dispatchedAt = start;
3182
3243
  return store.claimNext(scope, request, call);
3183
3244
  },
3184
- accept: (value) => readStoreNext(value, (raw) => {
3185
- const claim = readClaimed(raw, scope, request, capacity);
3186
- return { claim, dispatchedAt, confirmedAt: monotonicNow(clock) };
3187
- })
3245
+ accept: (value) => readStoreNext(
3246
+ value,
3247
+ (raw) => {
3248
+ const claim = readClaimed(raw, scope, request, capacity);
3249
+ return { claim, dispatchedAt, confirmedAt: monotonicNow(clock) };
3250
+ },
3251
+ "claim"
3252
+ )
3188
3253
  });
3189
3254
  }
3190
3255
  async function drainClaims(run, options, items, slots) {
@@ -3220,7 +3285,7 @@ async function drainClaims(run, options, items, slots) {
3220
3285
  }
3221
3286
  if (next.status !== "applied") {
3222
3287
  slot.close();
3223
- stop = next.status === "contended" ? "contended" : "idle";
3288
+ stop = next.status === "none" ? "idle" : next.status;
3224
3289
  break;
3225
3290
  }
3226
3291
  const { claim } = next.value;
@@ -3297,7 +3362,8 @@ async function runQueue(run, options, slots, shutdown) {
3297
3362
  else if (allowedErrorCode(run.budget.signal.reason, ["deadline"])) stop = "deadline";
3298
3363
  else if (run.persistenceFailures) stop = "store_error";
3299
3364
  else if (run.budget.signal.aborted) return invalid("invalid_config");
3300
- else if (queueStop !== "contended" && slots.size === run.config.limits.maxConcurrency) stop = "callback_capacity";
3365
+ else if (queueStop === "contended" || queueStop === "expiry_maintenance_required") stop = queueStop;
3366
+ else if (slots.size === run.config.limits.maxConcurrency) stop = "callback_capacity";
3301
3367
  else if (queueStop === "idle" && timeLeft < 1)
3302
3368
  stop = "deadline";
3303
3369
  else stop = queueStop;
@@ -3413,10 +3479,17 @@ function readAdmissionResult(input, identity, capacity) {
3413
3479
  if (!matchesAdmissionJob(job, identity, status)) invalid(code);
3414
3480
  return { status, job };
3415
3481
  }
3416
- function createEmailBatchService(options) {
3417
- return createEmailBatchServiceWithClock(options, systemEmailClock);
3482
+ function createEmailBatchAdmission(options) {
3483
+ return createEmailBatchAdmissionWithClock(options, systemEmailClock);
3484
+ }
3485
+ function createEmailBatchAdmissionWithClock(options, clock) {
3486
+ const raw = readRecord(options, ["service"], ["smtpCapacity"], "invalid_config");
3487
+ const { service } = raw;
3488
+ const capacity = readCapacityOption(raw);
3489
+ assertPortCapacity(service, capacity);
3490
+ return createBatchAdmission(service, boundScope(service), capacity, clock);
3418
3491
  }
3419
- function createEmailBatchServiceWithClock(options, clock) {
3492
+ function createEmailBatchService(options) {
3420
3493
  const raw = readRecord(options, ["service", "worker"], ["smtpCapacity"], "invalid_config");
3421
3494
  const { service, worker } = raw;
3422
3495
  const capacity = readCapacityOption(raw);
@@ -3425,6 +3498,18 @@ function createEmailBatchServiceWithClock(options, clock) {
3425
3498
  const scope = boundScope(service);
3426
3499
  if (scope !== boundScope(worker)) invalid("invalid_config");
3427
3500
  const run = bindMethod(worker, "run");
3501
+ const { enqueueBatch } = createBatchAdmission(service, scope, capacity, systemEmailClock);
3502
+ const batch = {
3503
+ enqueueBatch,
3504
+ async run(options2) {
3505
+ if (boundScope(worker) !== scope) invalid("invalid_config");
3506
+ assertPortCapacity(worker, capacity);
3507
+ return run(options2);
3508
+ }
3509
+ };
3510
+ return Object.freeze(batch);
3511
+ }
3512
+ function createBatchAdmission(service, scope, capacity, clock) {
3428
3513
  const enqueue = bindMethod(service, "enqueue");
3429
3514
  const admit = findServiceAdmission(service) ?? (async ({ command, identity }, budget) => {
3430
3515
  if (boundScope(service) !== scope) invalid("invalid_config");
@@ -3432,10 +3517,10 @@ function createEmailBatchServiceWithClock(options, clock) {
3432
3517
  const bounds = CALL_BUDGETS.admissionOrAdmin;
3433
3518
  const timeoutMs = Math.max(bounds.min, Math.min(bounds.max, Math.floor(budget.remainingMs())));
3434
3519
  budget.check();
3435
- let raw2;
3520
+ let raw;
3436
3521
  try {
3437
3522
  const pending = enqueue(command, Object.freeze({ signal: budget.signal, timeoutMs }));
3438
- raw2 = import_node_util9.types.isPromise(pending) ? await pending : pending;
3523
+ raw = import_node_util9.types.isPromise(pending) ? await pending : pending;
3439
3524
  } catch (error) {
3440
3525
  if (allowedErrorCode(error, ["aborted"]) && allowedErrorCode(budget.signal.reason, ["deadline"])) {
3441
3526
  invalid("deadline");
@@ -3443,7 +3528,7 @@ function createEmailBatchServiceWithClock(options, clock) {
3443
3528
  throw error;
3444
3529
  }
3445
3530
  try {
3446
- return readAdmissionResult(raw2, identity, capacity);
3531
+ return readAdmissionResult(raw, identity, capacity);
3447
3532
  } catch {
3448
3533
  return invalid("write_unconfirmed");
3449
3534
  }
@@ -3481,11 +3566,6 @@ function createEmailBatchServiceWithClock(options, clock) {
3481
3566
  admitting = false;
3482
3567
  budget.close();
3483
3568
  }
3484
- },
3485
- async run(options2) {
3486
- if (boundScope(worker) !== scope) invalid("invalid_config");
3487
- assertPortCapacity(worker, capacity);
3488
- return run(options2);
3489
3569
  }
3490
3570
  };
3491
3571
  return Object.freeze(batch);
@@ -3850,6 +3930,7 @@ function newJob(admission, time, capacity) {
3850
3930
  if (snapshot.preparedAt - now > MAX_PREPARED_AT_SKEW_MS) invalid("invalid_snapshot");
3851
3931
  const nextAt = Math.max(now, scheduleAt ?? now);
3852
3932
  if (nextAt >= snapshot.expiresAt) invalid("expired");
3933
+ if (snapshot.kind === "smtp") assertSmtpAttachmentTypes(snapshot.attachments);
3853
3934
  return Object.freeze({
3854
3935
  version: EMAIL_FORMAT_VERSION,
3855
3936
  ...capacityTag(capacity),
@@ -3892,9 +3973,13 @@ function liveLease(job, fence, phase, now) {
3892
3973
  }
3893
3974
  return lease;
3894
3975
  }
3976
+ function claimEligibility(job, now) {
3977
+ if (job.state.state !== "queued" || job.state.nextAt > now) return "not_due";
3978
+ return now >= job.expiresAt ? "expired" : "eligible";
3979
+ }
3895
3980
  function claimJob(job, claim, time, capacity) {
3896
3981
  const { now } = time;
3897
- if (job.state.state !== "queued" || job.state.nextAt > now || now >= job.expiresAt) return null;
3982
+ if (claimEligibility(job, now) !== "eligible") return null;
3898
3983
  const manual = hasRedrive(job);
3899
3984
  const ordinal = job.attempts.length + 1;
3900
3985
  if (ordinal > MAX_ATTEMPT_LEDGER || !manual && ordinal > job.retry.maxAttempts) invalid("store_incompatible");
@@ -3922,6 +4007,20 @@ function claimJob(job, claim, time, capacity) {
3922
4007
  Math.min(job.expiresAt, lease.leaseEndsAt)
3923
4008
  );
3924
4009
  }
4010
+ var EXPIRY_MAINTENANCE_REQUIRED = Object.freeze({ status: "expiry_maintenance_required" });
4011
+ function claimWindow(claim, candidateLimit, capacity) {
4012
+ let expired = 0;
4013
+ return {
4014
+ decide(job, time) {
4015
+ const decision = claimJob(job, claim, time, capacity);
4016
+ if (decision === null && claimEligibility(job, time.now) === "expired") expired++;
4017
+ return decision;
4018
+ },
4019
+ result(next) {
4020
+ return next.status !== "applied" && expired === candidateLimit ? EXPIRY_MAINTENANCE_REQUIRED : next;
4021
+ }
4022
+ };
4023
+ }
3925
4024
  function renewJob(job, fence, leaseMs, time) {
3926
4025
  const lease = liveLease(job, fence, "pre_handoff", time.now);
3927
4026
  if (!lease || time.now >= job.expiresAt) return null;
@@ -4410,8 +4509,8 @@ function createMemoryEmailStore(options = {}) {
4410
4509
  },
4411
4510
  async claimNext(scope, claim, call) {
4412
4511
  return primitive(call, true, (check) => {
4413
- const safe = readClaim(claim);
4414
- return next(scope, "nextAt", check, (row, time) => claimJob(row, safe, time, capacity));
4512
+ const window = claimWindow(readClaim(claim), MAX_STORE_CANDIDATES, capacity);
4513
+ return window.result(next(scope, "nextAt", check, window.decide));
4415
4514
  });
4416
4515
  },
4417
4516
  async renew(scope, fence, leaseMs, call) {
@@ -4512,11 +4611,14 @@ function createMemoryEmailStore(options = {}) {
4512
4611
  0 && (module.exports = {
4513
4612
  EmailError,
4514
4613
  createEmailAdmin,
4614
+ createEmailBatchAdmission,
4515
4615
  createEmailBatchService,
4616
+ createEmailRelay,
4516
4617
  createEmailService,
4517
4618
  createEmailTemplateRegistry,
4518
4619
  createEmailWorker,
4519
4620
  createMemoryEmailStore,
4621
+ createSmtpAcceptanceResult,
4520
4622
  defineLocalTemplate,
4521
4623
  defineSendGridTemplate
4522
4624
  });