@web-ts-toolkit/email-service 0.72.0 → 0.73.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.mjs CHANGED
@@ -257,6 +257,12 @@ function scopeToken(value, code = "invalid_command") {
257
257
  function identifier(value, code) {
258
258
  return opaqueToken(value, MESSAGE_LIMITS.identifierBytes, code);
259
259
  }
260
+ function uuidV4(value, code) {
261
+ 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)) {
262
+ invalid(code);
263
+ }
264
+ return value;
265
+ }
260
266
  function hashToken(value, code) {
261
267
  if (typeof value !== "string" || value.length !== 64 || !/^[0-9a-f]{64}$/.test(value)) invalid(code);
262
268
  return value;
@@ -578,9 +584,9 @@ function syncStage(budget, code, run) {
578
584
  // src/internal/canonical-json.ts
579
585
  import { createHash } from "crypto";
580
586
  var treeLimits = { depth: MESSAGE_LIMITS.jsonDepth, values: MESSAGE_LIMITS.jsonValues };
581
- function canonicalJson(input, maxBytes, code = "invalid_snapshot", limits = treeLimits) {
587
+ function canonicalJson(input, maxBytes, code = "invalid_snapshot", limits2 = treeLimits) {
582
588
  let bytesLeft = maxBytes;
583
- let valuesLeft = limits.values;
589
+ let valuesLeft = limits2.values;
584
590
  const chunks = [];
585
591
  const ancestors = /* @__PURE__ */ new Set();
586
592
  function append(text, bytes = text.length) {
@@ -599,7 +605,7 @@ function canonicalJson(input, maxBytes, code = "invalid_snapshot", limits = tree
599
605
  append(JSON.stringify(text), bytes);
600
606
  }
601
607
  function visit(value2, depth) {
602
- if (depth > limits.depth || --valuesLeft < 0 || bytesLeft < 1) invalid(code);
608
+ if (depth > limits2.depth || --valuesLeft < 0 || bytesLeft < 1) invalid(code);
603
609
  switch (typeof value2) {
604
610
  case "string":
605
611
  appendString(value2);
@@ -623,7 +629,7 @@ function canonicalJson(input, maxBytes, code = "invalid_snapshot", limits = tree
623
629
  if (ancestors.has(value2)) invalid(code);
624
630
  ancestors.add(value2);
625
631
  try {
626
- const maxChildren = depth === limits.depth ? 0 : valuesLeft;
632
+ const maxChildren = depth === limits2.depth ? 0 : valuesLeft;
627
633
  if (isArray(value2, code)) {
628
634
  const length = denseArrayLength(value2, maxChildren, code);
629
635
  if (length && 2 * length + 1 > bytesLeft) invalid(code);
@@ -666,10 +672,83 @@ function sha256(input) {
666
672
  function hashJson(input, maxBytes, code = "invalid_snapshot") {
667
673
  return sha256(canonicalJson(input, maxBytes, code).encoded);
668
674
  }
675
+ function encodeEvidence(input, code, capacity) {
676
+ return canonicalJson(input, capacity?.limits.evidenceBytes ?? 8192, code, capacity?.limits.evidenceTree).encoded;
677
+ }
669
678
 
670
679
  // src/internal/message-codecs.ts
671
680
  import { isIP } from "net";
672
681
  import { types as types4 } from "util";
682
+
683
+ // src/internal/smtp-capacity.ts
684
+ var MIN_RECIPIENTS = MESSAGE_LIMITS.recipients + 1;
685
+ var MAX_RECIPIENTS = 1e3;
686
+ var KIB = 1024;
687
+ var limits = Object.freeze({
688
+ snapshotBytes: 2 * KIB * KIB,
689
+ snapshotTree: Object.freeze({ depth: 4, values: 4096 }),
690
+ evidenceBytes: 64 * KIB,
691
+ evidenceTree: Object.freeze({ depth: 5, values: 4096 }),
692
+ jobBsonBytes: 4 * KIB * KIB,
693
+ activityBsonBytes: 128 * KIB,
694
+ registryCache: Object.freeze({ min: 0, default: 8, max: 16 }),
695
+ registryPending: Object.freeze({ min: 1, default: 2, max: 4 }),
696
+ servicePending: 4,
697
+ workerProfiles: 16,
698
+ workerConcurrency: Object.freeze({ min: 1, default: 1, max: 2 }),
699
+ runClaims: Object.freeze({ min: 1, default: 4, max: 16 }),
700
+ runMaintenance: Object.freeze({ min: 0, default: 4, max: 16 }),
701
+ adminMaintenance: Object.freeze({ min: 1, default: 4, max: 16 }),
702
+ page: Object.freeze({ min: 1, default: 8, max: 16 }),
703
+ memoryJobs: Object.freeze({ min: 1, default: 8, max: 16 }),
704
+ mongoInFlight: 4,
705
+ dueCandidates: 4
706
+ });
707
+ function readBinding(input, code) {
708
+ const { format, namespace, maxRecipients } = readRecord(input, ["format", "namespace", "maxRecipients"], [], code);
709
+ if (format !== "smtp-v2") invalid(code);
710
+ return Object.freeze({
711
+ format,
712
+ namespace: uuidV4(namespace, code),
713
+ maxRecipients: integer(maxRecipients, MIN_RECIPIENTS, MAX_RECIPIENTS, code)
714
+ });
715
+ }
716
+ function readCapacityOption(raw) {
717
+ if (!Object.hasOwn(raw, "smtpCapacity")) return;
718
+ return Object.freeze({ binding: readBinding(raw.smtpCapacity, "invalid_config"), limits });
719
+ }
720
+ function capacityTag(capacity) {
721
+ return capacity ? { smtpCapacity: capacity.binding } : {};
722
+ }
723
+ function recipientLimit(capacity) {
724
+ return capacity?.binding.maxRecipients ?? MESSAGE_LIMITS.recipients;
725
+ }
726
+ function matchesBinding(input, capacity, code) {
727
+ const binding = readBinding(input, code);
728
+ if (binding.namespace !== capacity.binding.namespace || binding.maxRecipients !== capacity.binding.maxRecipients) {
729
+ invalid(code);
730
+ }
731
+ }
732
+ function assertCapacityTag(raw, capacity, code) {
733
+ const tagged = Object.hasOwn(raw, "smtpCapacity");
734
+ if (capacity) {
735
+ if (!tagged) invalid(code);
736
+ matchesBinding(raw.smtpCapacity, capacity, code);
737
+ } else if (tagged) {
738
+ invalid(code);
739
+ }
740
+ }
741
+ function assertPortCapacity(port, capacity) {
742
+ const code = "invalid_config";
743
+ const binding = readPortMember(port, "smtpCapacity");
744
+ if (capacity) matchesBinding(binding, capacity, code);
745
+ else if (binding !== void 0) invalid(code);
746
+ }
747
+ function assertCapacityProvider(provider, capacity, code) {
748
+ if (capacity && provider.kind !== "smtp") invalid(code);
749
+ }
750
+
751
+ // src/internal/message-codecs.ts
673
752
  var L = MESSAGE_LIMITS;
674
753
  var SNAPSHOT = "invalid_snapshot";
675
754
  var DOT_ATOM = /^[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*$/;
@@ -706,7 +785,8 @@ function validateMailbox(input, code = SNAPSHOT) {
706
785
  ...Object.hasOwn(mailbox, "name") ? { name: headerString(mailbox.name, L.displayNameBytes, code) } : {}
707
786
  });
708
787
  }
709
- function validateEnvelope(input, kind, code = SNAPSHOT) {
788
+ function validateEnvelope(input, kind, code = SNAPSHOT, capacity) {
789
+ const limit = recipientLimit(capacity);
710
790
  const envelope = readRecord(input, ["from", "to", "cc", "bcc"], ["replyTo"], code);
711
791
  const seen = /* @__PURE__ */ new Set();
712
792
  const recipient = (raw) => {
@@ -717,9 +797,9 @@ function validateEnvelope(input, kind, code = SNAPSHOT) {
717
797
  return mailbox;
718
798
  };
719
799
  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);
800
+ const to = readArray(envelope.to, limit, code, recipient);
801
+ const cc = readArray(envelope.cc, limit - to.length, code, recipient);
802
+ const bcc = readArray(envelope.bcc, limit - to.length - cc.length, code, recipient);
723
803
  if (seen.size === 0 || kind === "sendgrid" && to.length === 0) invalid(code);
724
804
  return Object.freeze({
725
805
  from,
@@ -807,12 +887,17 @@ function validateExpiry(input, preparedAt, scheduleAt, code = SNAPSHOT) {
807
887
  }
808
888
  return expiresAt;
809
889
  }
810
- function hashSnapshot(snapshot) {
890
+ function hashSnapshot(snapshot, capacity) {
811
891
  return sha256(
812
- canonicalJson(snapshot, L.snapshotBytes, SNAPSHOT, { depth: L.jsonDepth + 1, values: L.jsonValues + 256 }).encoded
892
+ canonicalJson(
893
+ snapshot,
894
+ capacity?.limits.snapshotBytes ?? L.snapshotBytes,
895
+ SNAPSHOT,
896
+ capacity?.limits.snapshotTree ?? { depth: L.jsonDepth + 1, values: L.jsonValues + 256 }
897
+ ).encoded
813
898
  );
814
899
  }
815
- function readSnapshot(input) {
900
+ function readSnapshot(input, capacity) {
816
901
  const dto = readRecord(
817
902
  input,
818
903
  [
@@ -827,17 +912,19 @@ function readSnapshot(input) {
827
912
  "attachments",
828
913
  "correlation"
829
914
  ],
830
- ["subject", "html", "text", "templateId", "data"],
915
+ ["subject", "html", "text", "templateId", "data", "smtpCapacity"],
831
916
  SNAPSHOT
832
917
  );
833
918
  if (dto.version !== EMAIL_FORMAT_VERSION || dto.kind !== "smtp" && dto.kind !== "sendgrid") invalid(SNAPSHOT);
919
+ assertCapacityTag(dto, capacity, SNAPSHOT);
834
920
  const provider = validateProviderRef(dto.provider);
835
921
  if (provider.kind !== dto.kind) invalid("provider_mismatch");
922
+ assertCapacityProvider(provider, capacity, "provider_mismatch");
836
923
  const preparedAt = unixMs(dto.preparedAt, SNAPSHOT);
837
924
  const common = {
838
925
  version: EMAIL_FORMAT_VERSION,
839
926
  template: validateTemplateIdentity(dto.template),
840
- envelope: validateEnvelope(dto.envelope, provider.kind),
927
+ envelope: validateEnvelope(dto.envelope, provider.kind, SNAPSHOT, capacity),
841
928
  preparedAt,
842
929
  expiresAt: validateExpiry(dto.expiresAt, preparedAt, null),
843
930
  priority: integer(dto.priority, PRIORITY.min, PRIORITY.max, SNAPSHOT),
@@ -851,7 +938,7 @@ function readSnapshot(input) {
851
938
  ...Object.hasOwn(dto, "html") ? { html: dto.html } : {},
852
939
  ...Object.hasOwn(dto, "text") ? { text: dto.text } : {}
853
940
  });
854
- return Object.freeze({ ...common, kind: provider.kind, provider, ...content });
941
+ return Object.freeze({ ...common, kind: provider.kind, provider, ...capacityTag(capacity), ...content });
855
942
  }
856
943
  if (Object.hasOwn(dto, "subject") || Object.hasOwn(dto, "html") || Object.hasOwn(dto, "text")) invalid(SNAPSHOT);
857
944
  return Object.freeze({
@@ -862,9 +949,9 @@ function readSnapshot(input) {
862
949
  data: copyJsonObject(dto.data, L.dataBytes, SNAPSHOT)
863
950
  });
864
951
  }
865
- function validateSnapshot(input) {
866
- const snapshot = readSnapshot(input);
867
- return { snapshot, snapshotHash: hashSnapshot(snapshot) };
952
+ function validateSnapshot(input, capacity) {
953
+ const snapshot = readSnapshot(input, capacity);
954
+ return { snapshot, snapshotHash: hashSnapshot(snapshot, capacity) };
868
955
  }
869
956
 
870
957
  // src/internal/command-codecs.ts
@@ -888,25 +975,35 @@ function encodeAdmissionKey(key) {
888
975
  function sameCommandMetadata(key, templateKey, provider, scheduleAt, expected) {
889
976
  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
977
  }
891
- function fingerprintFor(identity) {
978
+ function fingerprintFor(identity, capacity) {
892
979
  const { scope, key, templateKey, provider, scheduleAt, intentHash } = identity;
893
980
  return hashJson(
894
- [EMAIL_FORMAT_VERSION, scope, key, templateKey, provider, scheduleAt, intentHash],
981
+ [
982
+ ...capacity ? ["smtp-v2-admission", capacity.binding] : [],
983
+ EMAIL_FORMAT_VERSION,
984
+ scope,
985
+ key,
986
+ templateKey,
987
+ provider,
988
+ scheduleAt,
989
+ intentHash
990
+ ],
895
991
  MESSAGE_LIMITS.intentBytes
896
992
  );
897
993
  }
898
- function parseCommandIdentity(scope, command) {
994
+ function parseCommandIdentity(scope, command, capacity) {
899
995
  const code = "invalid_command";
900
996
  const parsedScope = scopeToken(scope, code);
901
997
  const raw = readRecord(command, ["key", "templateKey", "input", "provider", "intent"], ["scheduleAt"], code);
902
998
  const key = validateAdmissionKey(raw.key, code);
903
999
  const templateKey = identifier(raw.templateKey, code);
904
1000
  const provider = validateProviderRef(raw.provider, code);
1001
+ assertCapacityProvider(provider, capacity, "provider_mismatch");
905
1002
  const scheduleAt = raw.scheduleAt === void 0 ? null : unixMs(raw.scheduleAt, code);
906
1003
  const intent = canonicalJson(raw.intent, MESSAGE_LIMITS.intentBytes, code);
907
1004
  const identity = { scope: parsedScope, key, templateKey, provider, scheduleAt, intentHash: sha256(intent.encoded) };
908
1005
  return Object.freeze({
909
- identity: Object.freeze({ ...identity, fingerprint: fingerprintFor(identity) }),
1006
+ identity: Object.freeze({ ...identity, fingerprint: fingerprintFor(identity, capacity) }),
910
1007
  command: Object.freeze({
911
1008
  key,
912
1009
  templateKey,
@@ -917,35 +1014,40 @@ function parseCommandIdentity(scope, command) {
917
1014
  })
918
1015
  });
919
1016
  }
920
- function validatePreparedCommand(scope, input) {
1017
+ function validatePreparedCommand(scope, input, capacity) {
921
1018
  const expectedScope = scopeToken(scope);
922
1019
  const code = "invalid_snapshot";
923
1020
  const dto = readRecord(
924
1021
  input,
925
1022
  ["version", "scope", "key", "scheduleAt", "intentHash", "fingerprint", "snapshotHash", "snapshot"],
926
- [],
1023
+ ["smtpCapacity"],
927
1024
  code
928
1025
  );
929
1026
  if (dto.version !== EMAIL_FORMAT_VERSION || scopeToken(dto.scope, code) !== expectedScope) invalid(code);
1027
+ assertCapacityTag(dto, capacity, code);
930
1028
  const key = validateAdmissionKey(dto.key, code);
931
1029
  const scheduleAt = dto.scheduleAt === null ? null : unixMs(dto.scheduleAt, code);
932
1030
  const intentHash = hashToken(dto.intentHash, code);
933
1031
  const fingerprint = hashToken(dto.fingerprint, code);
934
1032
  const storedSnapshotHash = hashToken(dto.snapshotHash, code);
935
- const { snapshot, snapshotHash } = validateSnapshot(dto.snapshot);
1033
+ const { snapshot, snapshotHash } = validateSnapshot(dto.snapshot, capacity);
936
1034
  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
- })) {
1035
+ if (snapshotHash !== storedSnapshotHash || fingerprint !== fingerprintFor(
1036
+ {
1037
+ scope: expectedScope,
1038
+ key,
1039
+ templateKey: snapshot.template.key,
1040
+ provider: snapshot.provider,
1041
+ scheduleAt,
1042
+ intentHash
1043
+ },
1044
+ capacity
1045
+ )) {
945
1046
  invalid(code);
946
1047
  }
947
1048
  return Object.freeze({
948
1049
  version: EMAIL_FORMAT_VERSION,
1050
+ ...capacityTag(capacity),
949
1051
  scope: expectedScope,
950
1052
  key,
951
1053
  scheduleAt,
@@ -1179,7 +1281,7 @@ function readDefinition(value) {
1179
1281
  }
1180
1282
  return invalid(code);
1181
1283
  }
1182
- function captureFields(raw, definition, context, scheduleAt, budget, slot) {
1284
+ function captureFields(raw, definition, context, scheduleAt, budget, slot, capacity) {
1183
1285
  const code = "invalid_snapshot";
1184
1286
  const fields = readRecord(
1185
1287
  raw,
@@ -1197,7 +1299,9 @@ function captureFields(raw, definition, context, scheduleAt, budget, slot) {
1197
1299
  bcc: fields.bcc === void 0 ? [] : fields.bcc,
1198
1300
  ...replyTo === void 0 ? {} : { replyTo }
1199
1301
  },
1200
- context.provider.kind
1302
+ context.provider.kind,
1303
+ code,
1304
+ capacity
1201
1305
  );
1202
1306
  const expiresAt = validateExpiry(
1203
1307
  fields.expiresAt === void 0 ? context.now + DEFAULT_EXPIRY_MS : fields.expiresAt,
@@ -1220,18 +1324,25 @@ function findRegistryPreparation(registry) {
1220
1324
  }
1221
1325
  function createEmailTemplateRegistry(definitions, options = {}) {
1222
1326
  const code = "invalid_config";
1223
- const config = readRecord(options, [], ["clock", "cacheEntries", "maxPending", "helpers"], code);
1327
+ const config = readRecord(options, [], ["clock", "cacheEntries", "maxPending", "helpers", "smtpCapacity"], code);
1328
+ const capacity = readCapacityOption(config);
1224
1329
  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);
1330
+ const maxPending = boundedOption(config.maxPending, capacity?.limits.registryPending ?? TEMPLATE_MAX_PENDING);
1331
+ const renderer = createLocalRenderer(
1332
+ boundedOption(config.cacheEntries, capacity?.limits.registryCache ?? TEMPLATE_CACHE_ENTRIES),
1333
+ config.helpers
1334
+ );
1227
1335
  const registered = /* @__PURE__ */ new Map();
1228
1336
  for (const key of plainKeys(definitions, Infinity, code)) {
1229
- registered.set(identifier(key, code), readDefinition(ownData(definitions, key, code)));
1337
+ const definition = readDefinition(ownData(definitions, key, code));
1338
+ if (capacity && definition.kind !== "handlebars") invalid(code);
1339
+ registered.set(identifier(key, code), definition);
1230
1340
  }
1231
1341
  let pending = 0;
1232
1342
  async function prepareParsed({ identity, command: safe }, budget) {
1233
1343
  budget.check();
1234
1344
  const { templateKey, provider, key, scheduleAt } = identity;
1345
+ assertCapacityProvider(provider, capacity, "provider_mismatch");
1235
1346
  const definition = registered.get(templateKey);
1236
1347
  if (!definition) invalid("template_not_found");
1237
1348
  if ((definition.kind === "handlebars" ? "smtp" : "sendgrid") !== provider.kind) invalid("provider_mismatch");
@@ -1255,7 +1366,7 @@ function createEmailTemplateRegistry(definitions, options = {}) {
1255
1366
  slot,
1256
1367
  "preparation_failed",
1257
1368
  () => prepare(input, context),
1258
- (raw) => captureFields(raw, definition, context, scheduleAt, budget, slot)
1369
+ (raw) => captureFields(raw, definition, context, scheduleAt, budget, slot, capacity)
1259
1370
  );
1260
1371
  budget.check();
1261
1372
  const base = {
@@ -1267,17 +1378,18 @@ function createEmailTemplateRegistry(definitions, options = {}) {
1267
1378
  let snapshot;
1268
1379
  if (provider.kind === "smtp" && definition.kind === "handlebars") {
1269
1380
  const content = await renderer.render(templateKey, definition, data, budget, slot);
1270
- snapshot = Object.freeze({ ...base, kind: provider.kind, provider, ...content });
1381
+ snapshot = Object.freeze({ ...base, kind: provider.kind, provider, ...capacityTag(capacity), ...content });
1271
1382
  } else if (provider.kind === "sendgrid" && definition.kind === "sendgrid") {
1272
1383
  snapshot = Object.freeze({ ...base, kind: provider.kind, provider, templateId: definition.templateId, data });
1273
1384
  } else {
1274
1385
  return invalid("provider_mismatch");
1275
1386
  }
1276
1387
  budget.check();
1277
- const snapshotHash = hashSnapshot(snapshot);
1388
+ const snapshotHash = hashSnapshot(snapshot, capacity);
1278
1389
  budget.check();
1279
1390
  return Object.freeze({
1280
1391
  version: EMAIL_FORMAT_VERSION,
1392
+ ...capacityTag(capacity),
1281
1393
  scope: identity.scope,
1282
1394
  key,
1283
1395
  scheduleAt,
@@ -1291,6 +1403,7 @@ function createEmailTemplateRegistry(definitions, options = {}) {
1291
1403
  }
1292
1404
  }
1293
1405
  const registry = Object.freeze({
1406
+ ...capacityTag(capacity),
1294
1407
  invalidate(key) {
1295
1408
  if (key !== void 0) identifier(key, code);
1296
1409
  renderer.invalidate(key);
@@ -1300,7 +1413,7 @@ function createEmailTemplateRegistry(definitions, options = {}) {
1300
1413
  const budget = createBudget(clock, call.timeoutMs, call.signal);
1301
1414
  try {
1302
1415
  budget.check();
1303
- return await prepareParsed(parseCommandIdentity(scope, command), budget);
1416
+ return await prepareParsed(parseCommandIdentity(scope, command, capacity), budget);
1304
1417
  } finally {
1305
1418
  budget.close();
1306
1419
  }
@@ -1368,9 +1481,19 @@ function attemptOutcome(reason) {
1368
1481
  function isSafeTransient(reason) {
1369
1482
  return evidence[reason][1] === "safe_transient";
1370
1483
  }
1484
+ var recipientGroups = ["to", "cc", "bcc"];
1371
1485
  function recipientCounts(envelope) {
1372
1486
  return Object.freeze({ to: envelope.to.length, cc: envelope.cc.length, bcc: envelope.bcc.length });
1373
1487
  }
1488
+ function readRecipientCounts(input, code, capacity) {
1489
+ const limit = recipientLimit(capacity);
1490
+ const counts = readRecord(input, recipientGroups, [], code);
1491
+ const to = integer(counts.to, 0, limit, code);
1492
+ const cc = integer(counts.cc, 0, limit - to, code);
1493
+ const bcc = integer(counts.bcc, 0, limit - to - cc, code);
1494
+ if (to + cc + bcc === 0) invalid(code);
1495
+ return Object.freeze({ to, cc, bcc });
1496
+ }
1374
1497
  function smtpMessageId(attemptId) {
1375
1498
  return `<${attemptId}@email.invalid>`;
1376
1499
  }
@@ -1387,7 +1510,7 @@ function readHint(input, reason, code) {
1387
1510
  ...hasFloor ? { notBefore: unixMs(raw.notBefore, code) } : {}
1388
1511
  });
1389
1512
  }
1390
- function readAttemptResult(input, code = "invalid_command", projected = false) {
1513
+ function readAttemptResult(input, code = "invalid_command", projected = false, capacity) {
1391
1514
  const raw = readRecord(
1392
1515
  input,
1393
1516
  ["outcome", "retry", "stage", "reason"],
@@ -1398,6 +1521,7 @@ function readAttemptResult(input, code = "invalid_command", projected = false) {
1398
1521
  const [outcome, retry, stages2, origin] = evidence[reason];
1399
1522
  const stage = stages2.find((value) => value === raw.stage);
1400
1523
  if (raw.outcome !== outcome || raw.retry !== retry || !stage) invalid(code);
1524
+ if (capacity && (origin === "sendgrid" || stage === "http")) invalid(code);
1401
1525
  const hasHint = Object.hasOwn(raw, "retryHint");
1402
1526
  if (projected && hasHint || !projected && reason === "rate_deferred" && !hasHint) invalid(code);
1403
1527
  const smtpSuccess = reason === "smtp_accepted" || reason === "smtp_partial";
@@ -1407,14 +1531,22 @@ function readAttemptResult(input, code = "invalid_command", projected = false) {
1407
1531
  if (hasRecipients) {
1408
1532
  if (origin !== "smtp" && origin !== "provider" || stage !== "envelope" && stage !== "data") invalid(code);
1409
1533
  const seen = /* @__PURE__ */ new Set();
1410
- recipients = readArray(raw.recipients, MESSAGE_LIMITS.recipients, code, (value) => {
1534
+ const limit = recipientLimit(capacity);
1535
+ let previous = -1;
1536
+ recipients = readArray(raw.recipients, limit, code, (value) => {
1411
1537
  const { group, index: rawIndex, status } = readRecord(value, ["group", "index", "status"], [], code);
1412
1538
  if (group !== "to" && group !== "cc" && group !== "bcc") invalid(code);
1413
1539
  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);
1540
+ const index = integer(rawIndex, 0, limit - 1, code);
1541
+ if (capacity) {
1542
+ const position = recipientGroups.indexOf(group) * limit + index;
1543
+ if (position <= previous) invalid(code);
1544
+ previous = position;
1545
+ } else {
1546
+ const key = `${group}:${index}`;
1547
+ if (seen.has(key)) invalid(code);
1548
+ seen.add(key);
1549
+ }
1418
1550
  return Object.freeze({ group, index, status });
1419
1551
  });
1420
1552
  const accepted = recipients.filter(({ status }) => status === "accepted").length;
@@ -1429,7 +1561,7 @@ function readAttemptResult(input, code = "invalid_command", projected = false) {
1429
1561
  if (hasProviderId && (reason !== "sendgrid_accepted" || typeof providerMessageId !== "string" || providerMessageId.length > 128 || !/^[A-Za-z0-9][A-Za-z0-9._=-]{0,127}$/.test(providerMessageId))) {
1430
1562
  invalid(code);
1431
1563
  }
1432
- return Object.freeze({
1564
+ const result = Object.freeze({
1433
1565
  outcome,
1434
1566
  retry,
1435
1567
  stage,
@@ -1439,6 +1571,8 @@ function readAttemptResult(input, code = "invalid_command", projected = false) {
1439
1571
  ...typeof messageId === "string" ? { messageId } : {},
1440
1572
  ...typeof providerMessageId === "string" ? { providerMessageId } : {}
1441
1573
  });
1574
+ if (capacity && !projected) encodeEvidence(result, code, capacity);
1575
+ return result;
1442
1576
  }
1443
1577
  function assertEvidencePhase(reason, phase, source, code) {
1444
1578
  const origin = evidence[reason][3];
@@ -1464,9 +1598,9 @@ function assertEvidenceContext(result, provider, attemptId, counts, code) {
1464
1598
  }
1465
1599
  }
1466
1600
  }
1467
- function readProviderResult(input, provider, attemptId, envelope) {
1601
+ function readProviderResult(input, provider, attemptId, envelope, capacity) {
1468
1602
  const code = "invalid_command";
1469
- const result = readAttemptResult(input, code);
1603
+ const result = readAttemptResult(input, code, false, capacity);
1470
1604
  const origin = evidence[result.reason][3];
1471
1605
  if (origin !== "smtp" && origin !== "sendgrid" && origin !== "provider") invalid(code);
1472
1606
  assertEvidenceContext(result, provider, attemptId, recipientCounts(envelope), code);
@@ -1497,10 +1631,7 @@ function attemptEffect(result, attemptId, ordinal, manual, policy, expiresAt, no
1497
1631
  var REQUEST = "invalid_command";
1498
1632
  var LEASE = WORKER_LIMIT_BOUNDS.leaseMs;
1499
1633
  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;
1634
+ return uuidV4(value, code);
1504
1635
  }
1505
1636
  function readLeaseToken(value, code = REQUEST) {
1506
1637
  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)) {
@@ -1514,14 +1645,18 @@ function readLeaseMs(value) {
1514
1645
  function timeAfter(start, delayMs) {
1515
1646
  return delayMs <= MAX_UNIX_MS - start ? start + delayMs : void 0;
1516
1647
  }
1517
- function readStoreCall(input, worker = false) {
1648
+ function readStoreCall(input, worker = false, capacity) {
1518
1649
  const code = "invalid_config";
1519
- const raw = readRecord(input, ["signal", "timeoutMs"], [], code);
1650
+ const { smtpCapacity, ...raw } = readRecord(input, ["signal", "timeoutMs"], capacity ? ["smtpCapacity"] : [], code);
1651
+ if (capacity) assertCapacityTag({ smtpCapacity }, capacity, "store_incompatible");
1520
1652
  const max = worker ? WORKER_LIMIT_BOUNDS.storeTimeoutMs.max : CALL_BUDGETS.admissionOrAdmin.max;
1521
1653
  const timeoutMs = integer(raw.timeoutMs, 1, max, code);
1522
1654
  const call = readCallOptions(raw, { default: STORE_PRIMITIVE_TIMEOUT_MS, min: 1, max });
1523
1655
  if (!call.signal) invalid(code);
1524
- return { signal: call.signal, timeoutMs: worker ? timeoutMs : Math.min(timeoutMs, STORE_PRIMITIVE_TIMEOUT_MS) };
1656
+ return {
1657
+ signal: call.signal,
1658
+ timeoutMs: worker && !capacity ? timeoutMs : Math.min(timeoutMs, STORE_PRIMITIVE_TIMEOUT_MS)
1659
+ };
1525
1660
  }
1526
1661
  function readStoreNext(value, read) {
1527
1662
  const code = "store_incompatible";
@@ -1558,9 +1693,9 @@ function readRetentionPolicy(input, code = REQUEST) {
1558
1693
  idempotencyMs: integer(idempotencyMs, bounds.idempotencyMs.min, bounds.idempotencyMs.max, code)
1559
1694
  });
1560
1695
  }
1561
- function readStoreAdmission(scope, input) {
1696
+ function readStoreAdmission(scope, input, capacity) {
1562
1697
  const raw = readRecord(input, ["command", "jobId", "retry", "retention"], [], REQUEST);
1563
- const command = validatePreparedCommand(scope, raw.command);
1698
+ const command = validatePreparedCommand(scope, raw.command, capacity);
1564
1699
  return Object.freeze({
1565
1700
  command,
1566
1701
  admissionKey: encodeAdmissionKey(command.key),
@@ -1581,7 +1716,7 @@ function readClaim(input) {
1581
1716
  leaseMs: readLeaseMs(leaseMs)
1582
1717
  });
1583
1718
  }
1584
- function readFinish(input) {
1719
+ function readFinish(input, capacity) {
1585
1720
  const { fence, phase, operationId, result } = readRecord(
1586
1721
  input,
1587
1722
  ["fence", "phase", "operationId", "result"],
@@ -1589,7 +1724,7 @@ function readFinish(input) {
1589
1724
  REQUEST
1590
1725
  );
1591
1726
  if (phase !== "pre_handoff" && phase !== "handed_off") invalid(REQUEST);
1592
- const evidence2 = readAttemptResult(result);
1727
+ const evidence2 = readAttemptResult(result, REQUEST, false, capacity);
1593
1728
  assertEvidencePhase(evidence2.reason, phase, "owner", REQUEST);
1594
1729
  return Object.freeze({ fence: readFence(fence), phase, operationId: readStoreId(operationId), result: evidence2 });
1595
1730
  }
@@ -1606,7 +1741,6 @@ function readResolution(input) {
1606
1741
  }
1607
1742
 
1608
1743
  // src/internal/activity-codecs.ts
1609
- var ACTIVITY_BYTES = 8192;
1610
1744
  var dispositions = [
1611
1745
  "accepted",
1612
1746
  "partially_accepted",
@@ -1633,7 +1767,7 @@ function assertActivityDisposition(result, disposition, code) {
1633
1767
  invalid(code);
1634
1768
  }
1635
1769
  }
1636
- function readActivity(scope, input, code = "store_incompatible") {
1770
+ function captureActivity(scope, input, code, capacity) {
1637
1771
  const raw = readRecord(
1638
1772
  input,
1639
1773
  [
@@ -1650,26 +1784,32 @@ function readActivity(scope, input, code = "store_incompatible") {
1650
1784
  "result",
1651
1785
  "disposition"
1652
1786
  ],
1653
- ["handedOffAt"],
1787
+ ["handedOffAt", "smtpCapacity", "recipientCounts"],
1654
1788
  code
1655
1789
  );
1656
1790
  if (raw.version !== EMAIL_FORMAT_VERSION || scopeToken(raw.scope, code) !== scope) invalid(code);
1791
+ assertCapacityTag(raw, capacity, code);
1792
+ if (!capacity && Object.hasOwn(raw, "recipientCounts")) invalid(code);
1793
+ const counts = capacity ? readRecipientCounts(raw.recipientCounts, code, capacity) : void 0;
1657
1794
  const jobId = readStoreId(raw.jobId, code);
1658
1795
  const attemptId = readStoreId(raw.attemptId, code);
1659
1796
  const provider = validateProviderRef(raw.provider, code);
1797
+ assertCapacityProvider(provider, capacity, code);
1660
1798
  const startedAt = unixMs(raw.startedAt, code);
1661
1799
  const finishedAt = unixMs(raw.finishedAt, code);
1662
1800
  const handedOffAt = Object.hasOwn(raw, "handedOffAt") ? unixMs(raw.handedOffAt, code) : void 0;
1663
1801
  if (finishedAt < startedAt || handedOffAt !== void 0 && (handedOffAt < startedAt || handedOffAt > finishedAt)) {
1664
1802
  invalid(code);
1665
1803
  }
1666
- const result = readAttemptResult(raw.result, code, true);
1804
+ const result = readAttemptResult(raw.result, code, true, capacity);
1667
1805
  assertEvidencePhase(result.reason, handedOffAt === void 0 ? "pre_handoff" : "handed_off", "ledger", code);
1668
- assertEvidenceContext(result, provider, attemptId, void 0, code);
1806
+ assertEvidenceContext(result, provider, attemptId, counts, code);
1669
1807
  const disposition = readDisposition(raw.disposition, code);
1670
1808
  assertActivityDisposition(result, disposition, code);
1671
1809
  return Object.freeze({
1672
1810
  version: EMAIL_FORMAT_VERSION,
1811
+ ...capacityTag(capacity),
1812
+ ...counts ? { recipientCounts: counts } : {},
1673
1813
  scope,
1674
1814
  jobId,
1675
1815
  attemptId,
@@ -1684,50 +1824,62 @@ function readActivity(scope, input, code = "store_incompatible") {
1684
1824
  disposition
1685
1825
  });
1686
1826
  }
1687
- function activityFor(job, commit) {
1827
+ function readActivity(scope, input, code = "store_incompatible", capacity) {
1828
+ const activity = captureActivity(scope, input, code, capacity);
1829
+ if (capacity) encodeEvidence(activity, code, capacity);
1830
+ return activity;
1831
+ }
1832
+ function activityFor(job, commit, capacity) {
1688
1833
  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
- });
1834
+ return captureActivity(
1835
+ job.scope,
1836
+ {
1837
+ version: EMAIL_FORMAT_VERSION,
1838
+ ...capacityTag(capacity),
1839
+ ...capacity ? { recipientCounts: job.recipientCounts } : {},
1840
+ scope: job.scope,
1841
+ jobId: job.jobId,
1842
+ attemptId: commit.attemptId,
1843
+ ordinal: commit.ordinal,
1844
+ provider: job.provider,
1845
+ template: job.template,
1846
+ correlation: job.correlation,
1847
+ startedAt: commit.startedAt,
1848
+ ...commit.handedOffAt === void 0 ? {} : { handedOffAt: commit.handedOffAt },
1849
+ finishedAt: commit.finishedAt,
1850
+ disposition: commit.disposition,
1851
+ result: {
1852
+ outcome,
1853
+ retry,
1854
+ stage,
1855
+ reason,
1856
+ ...recipients === void 0 ? {} : { recipients },
1857
+ ...messageId === void 0 ? {} : { messageId },
1858
+ ...providerMessageId === void 0 ? {} : { providerMessageId }
1859
+ }
1860
+ },
1861
+ "store_incompatible",
1862
+ capacity
1863
+ );
1712
1864
  }
1713
- function activityDigest(activity) {
1714
- return hashJson(activity, ACTIVITY_BYTES, "store_incompatible");
1865
+ function activityDigest(activity, capacity) {
1866
+ return sha256(encodeEvidence(activity, "store_incompatible", capacity));
1715
1867
  }
1716
- function readStoredActivity(scope, input, code = "store_incompatible") {
1868
+ function readStoredActivity(scope, input, code = "store_incompatible", capacity) {
1717
1869
  const raw = readRecord(input, ["activity", "digest"], [], code);
1718
- const activity = readActivity(scope, raw.activity, code);
1870
+ const activity = captureActivity(scope, raw.activity, code, capacity);
1719
1871
  const digest = hashToken(raw.digest, code);
1720
- if (activityDigest(activity) !== digest) invalid(code);
1872
+ if (activityDigest(activity, capacity) !== digest) invalid(code);
1721
1873
  return Object.freeze({ activity, digest });
1722
1874
  }
1723
- function readProjectionPermit(scope, input) {
1875
+ function readProjectionPermit(scope, input, capacity) {
1724
1876
  const code = "invalid_command";
1725
1877
  const {
1726
1878
  activity,
1727
1879
  digest,
1728
1880
  permitUntil: rawUntil
1729
1881
  } = readRecord(input, ["activity", "digest", "permitUntil"], [], code);
1730
- const stored = readStoredActivity(scope, { activity, digest }, code);
1882
+ const stored = readStoredActivity(scope, { activity, digest }, code, capacity);
1731
1883
  const permitUntil = unixMs(rawUntil, code);
1732
1884
  if (permitUntil - stored.activity.finishedAt < PROJECTION_PERMIT_MS) invalid(code);
1733
1885
  return Object.freeze({ ...stored, permitUntil });
@@ -1739,13 +1891,15 @@ function compareActivity(a, b) {
1739
1891
  return b.finishedAt - a.finishedAt || compareAscii(a.jobId, b.jobId) || compareAscii(a.attemptId, b.attemptId);
1740
1892
  }
1741
1893
  function cursorPayload(criteria, position) {
1894
+ const binding = criteria.capacity?.binding;
1742
1895
  return {
1743
1896
  v: EMAIL_FORMAT_VERSION,
1744
1897
  s: criteria.scope,
1745
1898
  j: criteria.jobId,
1746
1899
  f: criteria.from,
1747
1900
  b: criteria.before,
1748
- p: [position.finishedAt, position.jobId, position.attemptId]
1901
+ p: [position.finishedAt, position.jobId, position.attemptId],
1902
+ ...binding ? { c: [binding.format, binding.namespace, binding.maxRecipients] } : {}
1749
1903
  };
1750
1904
  }
1751
1905
  function encodeCursor(criteria, position) {
@@ -1766,7 +1920,7 @@ function decodeCursor(criteria, cursor) {
1766
1920
  } catch {
1767
1921
  invalid(code);
1768
1922
  }
1769
- const { p } = readRecord(input, ["v", "s", "j", "f", "b", "p"], [], code);
1923
+ const { p } = readRecord(input, ["v", "s", "j", "f", "b", "p"], criteria.capacity ? ["c"] : [], code);
1770
1924
  const tuple = readArray(p, 3, code, (entry) => entry);
1771
1925
  const position = Object.freeze({
1772
1926
  finishedAt: unixMs(tuple[0], code),
@@ -1778,15 +1932,16 @@ function decodeCursor(criteria, cursor) {
1778
1932
  }
1779
1933
  return position;
1780
1934
  }
1781
- function readActivityCriteria(scope, input) {
1935
+ function readActivityCriteria(scope, input, capacity) {
1782
1936
  const code = "invalid_command";
1783
1937
  const raw = readRecord(input, [], ["jobId", "from", "before", "limit", "cursor"], code);
1784
1938
  const jobId = Object.hasOwn(raw, "jobId") ? readStoreId(raw.jobId, code) : null;
1785
1939
  const from = Object.hasOwn(raw, "from") ? unixMs(raw.from, code) : null;
1786
1940
  const before = Object.hasOwn(raw, "before") ? unixMs(raw.before, code) : null;
1787
1941
  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 };
1942
+ const page = capacity?.limits.page ?? ACTIVITY_PAGE_LIMIT;
1943
+ const limit = Object.hasOwn(raw, "limit") ? integer(raw.limit, page.min, page.max, code) : page.default;
1944
+ const criteria = { scope, jobId, from, before, limit, ...capacity ? { capacity } : {} };
1790
1945
  return Object.freeze({
1791
1946
  ...criteria,
1792
1947
  ...Object.hasOwn(raw, "cursor") ? { after: decodeCursor(criteria, raw.cursor) } : {}
@@ -1806,7 +1961,7 @@ function readOrderedActivities(criteria, input, maxRows) {
1806
1961
  const code = "store_incompatible";
1807
1962
  let previous = criteria.after;
1808
1963
  return readArray(input, maxRows, code, (row) => {
1809
- const activity = readActivity(criteria.scope, row);
1964
+ const activity = readActivity(criteria.scope, row, code, criteria.capacity);
1810
1965
  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
1966
  invalid(code);
1812
1967
  }
@@ -1856,14 +2011,18 @@ function readUnknownResolution(input) {
1856
2011
  if (action !== "dismiss" && action !== "redrive") invalid(STORED);
1857
2012
  return Object.freeze({ attemptId: readStoreId(attemptId, STORED), at: unixMs(at, STORED), action });
1858
2013
  }
1859
- function readJobSummary(scope, input) {
2014
+ function readJobSummary(scope, input, capacity) {
1860
2015
  const raw = readRecord(
1861
2016
  input,
1862
2017
  COMMON,
1863
- ["latestAttempt", "nextAt", "phase", "disposition", "terminalReason", "terminalAt"],
2018
+ ["latestAttempt", "nextAt", "phase", "disposition", "terminalReason", "terminalAt", "smtpCapacity"],
1864
2019
  STORED
1865
2020
  );
1866
2021
  if (raw.version !== EMAIL_FORMAT_VERSION || scopeToken(raw.scope, STORED) !== scope) invalid(STORED);
2022
+ assertCapacityTag(raw, capacity, STORED);
2023
+ const optional = capacity ? ["latestAttempt", "smtpCapacity"] : ["latestAttempt"];
2024
+ const provider = validateProviderRef(raw.provider, STORED);
2025
+ assertCapacityProvider(provider, capacity, STORED);
1867
2026
  const createdAt = unixMs(raw.createdAt, STORED);
1868
2027
  const updatedAt = unixMs(raw.updatedAt, STORED);
1869
2028
  const expiresAt = unixMs(raw.expiresAt, STORED);
@@ -1872,16 +2031,16 @@ function readJobSummary(scope, input) {
1872
2031
  if (updatedAt < createdAt || firstDue >= expiresAt) invalid(STORED);
1873
2032
  let state;
1874
2033
  if (raw.state === "queued") {
1875
- readRecord(raw, [...COMMON, "nextAt"], ["latestAttempt"], STORED);
2034
+ readRecord(raw, [...COMMON, "nextAt"], optional, STORED);
1876
2035
  const nextAt = unixMs(raw.nextAt, STORED);
1877
2036
  if (nextAt < firstDue || nextAt >= expiresAt) invalid(STORED);
1878
2037
  state = { state: raw.state, nextAt };
1879
2038
  } else if (raw.state === "leased") {
1880
- readRecord(raw, [...COMMON, "phase"], ["latestAttempt"], STORED);
2039
+ readRecord(raw, [...COMMON, "phase"], optional, STORED);
1881
2040
  if (raw.phase !== "pre_handoff" && raw.phase !== "handed_off") invalid(STORED);
1882
2041
  state = { state: raw.state, phase: raw.phase };
1883
2042
  } else if (raw.state === "terminal") {
1884
- readRecord(raw, [...COMMON, "disposition", "terminalAt", "terminalReason"], ["latestAttempt"], STORED);
2043
+ readRecord(raw, [...COMMON, "disposition", "terminalAt", "terminalReason"], optional, STORED);
1885
2044
  const terminalAt = unixMs(raw.terminalAt, STORED);
1886
2045
  const disposition = readDisposition(raw.disposition, STORED);
1887
2046
  if (terminalAt < createdAt || terminalAt > updatedAt || disposition === "retry_scheduled") invalid(STORED);
@@ -1906,10 +2065,11 @@ function readJobSummary(scope, input) {
1906
2065
  const resolutions = readArray(raw.resolutions, Math.min(2, attemptCount - active), STORED, readUnknownResolution);
1907
2066
  return Object.freeze({
1908
2067
  version: EMAIL_FORMAT_VERSION,
2068
+ ...capacityTag(capacity),
1909
2069
  scope,
1910
2070
  jobId: readStoreId(raw.jobId, STORED),
1911
2071
  key: validateAdmissionKey(raw.key, STORED),
1912
- provider: validateProviderRef(raw.provider, STORED),
2072
+ provider,
1913
2073
  template: validateTemplateIdentity(raw.template, STORED),
1914
2074
  correlation: validateCorrelation(raw.correlation, STORED),
1915
2075
  scheduleAt,
@@ -1961,7 +2121,7 @@ async function runStoreCall(clock, parent, options) {
1961
2121
  budget.check();
1962
2122
  invalid("deadline");
1963
2123
  }
1964
- const call = Object.freeze({ timeoutMs, signal: budget.signal });
2124
+ const call = Object.freeze({ timeoutMs, signal: budget.signal, ...capacityTag(options.capacity) });
1965
2125
  let raw;
1966
2126
  try {
1967
2127
  const pending = options.invoke(call, dispatchedAt);
@@ -2027,7 +2187,10 @@ function createEmailService(options) {
2027
2187
  return createEmailServiceWithClock(options, systemEmailClock);
2028
2188
  }
2029
2189
  function createEmailServiceWithClock(options, clock) {
2030
- const raw = readRecord(options, ["scope", "store", "registry"], ["retry", "retention"], CONFIG);
2190
+ const raw = readRecord(options, ["scope", "store", "registry"], ["retry", "retention", "smtpCapacity"], CONFIG);
2191
+ const capacity = readCapacityOption(raw);
2192
+ assertPortCapacity(raw.store, capacity);
2193
+ assertPortCapacity(raw.registry, capacity);
2031
2194
  const scope = scopeToken(raw.scope, CONFIG);
2032
2195
  const retry = readRetryPolicy(readPolicy(raw.retry, DEFAULT_RETRY_POLICY), CONFIG);
2033
2196
  const retention = readRetentionPolicy(readPolicy(raw.retention, DEFAULT_RETENTION_POLICY), CONFIG);
@@ -2037,10 +2200,11 @@ function createEmailServiceWithClock(options, clock) {
2037
2200
  const registry = raw.registry;
2038
2201
  const prepare = bindMethod(registry, "prepare");
2039
2202
  const internalPrepare = findRegistryPreparation(registry);
2203
+ let admissions = 0;
2040
2204
  async function prepareMiss(parsed, parent) {
2041
2205
  const { identity, command } = parsed;
2042
2206
  const accept = (value) => {
2043
- const staged = validatePreparedCommand(scope, value);
2207
+ const staged = validatePreparedCommand(scope, value, capacity);
2044
2208
  if (!sameCommandMetadata(
2045
2209
  staged.key,
2046
2210
  staged.snapshot.template.key,
@@ -2069,7 +2233,7 @@ function createEmailServiceWithClock(options, clock) {
2069
2233
  slots = { pending: 0 };
2070
2234
  injectedRegistrySlots.set(registry, slots);
2071
2235
  }
2072
- if (slots.pending >= TEMPLATE_MAX_PENDING.default) invalid("busy");
2236
+ if (slots.pending >= (capacity?.limits.registryPending.default ?? TEMPLATE_MAX_PENDING.default)) invalid("busy");
2073
2237
  const budget = createChildBudget(clock, parent, CALL_BUDGETS.prepare.default);
2074
2238
  const occupied = slots;
2075
2239
  slots.pending++;
@@ -2099,12 +2263,13 @@ function createEmailServiceWithClock(options, clock) {
2099
2263
  function findWinner(key, budget) {
2100
2264
  return runStoreCall(clock, budget, {
2101
2265
  maxMs: STORE_PRIMITIVE_TIMEOUT_MS,
2266
+ capacity,
2102
2267
  effect: "read",
2103
2268
  invoke: (call) => find(scope, key, call),
2104
2269
  accept(value) {
2105
2270
  if (value === null) return null;
2106
2271
  const raw2 = readRecord(value, ["job", "fingerprint"], [], STORED2);
2107
- const job = readJobSummary(scope, raw2.job);
2272
+ const job = readJobSummary(scope, raw2.job, capacity);
2108
2273
  if (encodeAdmissionKey(job.key) !== encodeAdmissionKey(key)) invalid(STORED2);
2109
2274
  return { job, fingerprint: hashToken(raw2.fingerprint, STORED2) };
2110
2275
  }
@@ -2122,6 +2287,7 @@ function createEmailServiceWithClock(options, clock) {
2122
2287
  try {
2123
2288
  const job = await runStoreCall(clock, budget, {
2124
2289
  maxMs: STORE_PRIMITIVE_TIMEOUT_MS,
2290
+ capacity,
2125
2291
  effect: "mutation",
2126
2292
  definite: INSERT_REJECTIONS,
2127
2293
  invoke: (call) => insert(scope, admission, call),
@@ -2129,7 +2295,7 @@ function createEmailServiceWithClock(options, clock) {
2129
2295
  const raw2 = readRecord(value, ["status"], ["job"], STORED2);
2130
2296
  if (raw2.status === "duplicate" && !Object.hasOwn(raw2, "job")) return null;
2131
2297
  if (raw2.status !== "inserted") invalid(STORED2);
2132
- const job2 = readJobSummary(scope, raw2.job);
2298
+ const job2 = readJobSummary(scope, raw2.job, capacity);
2133
2299
  const { snapshot } = command;
2134
2300
  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
2301
  invalid(STORED2);
@@ -2155,24 +2321,37 @@ function createEmailServiceWithClock(options, clock) {
2155
2321
  if (winner) return replay(winner, parsed.identity);
2156
2322
  return insertOrConfirm(await prepareMiss(parsed, budget), parsed.identity, budget);
2157
2323
  }
2158
- async function inOperation(call, run) {
2159
- const { timeoutMs, signal } = readCallOptions(call, CALL_BUDGETS.admissionOrAdmin);
2160
- const budget = createBudget(clock, timeoutMs, signal);
2324
+ async function withAdmission(run) {
2325
+ if (!capacity) return run();
2326
+ if (admissions >= capacity.limits.servicePending) invalid("busy");
2327
+ admissions++;
2161
2328
  try {
2162
- budget.check();
2163
- return await run(budget);
2329
+ return await run();
2164
2330
  } finally {
2165
- budget.close();
2331
+ admissions--;
2166
2332
  }
2167
2333
  }
2334
+ function inOperation(call, run) {
2335
+ return withAdmission(async () => {
2336
+ const { timeoutMs, signal } = readCallOptions(call, CALL_BUDGETS.admissionOrAdmin);
2337
+ const budget = createBudget(clock, timeoutMs, signal);
2338
+ try {
2339
+ budget.check();
2340
+ return await run(budget);
2341
+ } finally {
2342
+ budget.close();
2343
+ }
2344
+ });
2345
+ }
2168
2346
  const service = Object.freeze({
2169
2347
  scope,
2348
+ ...capacityTag(capacity),
2170
2349
  enqueue(command, call = {}) {
2171
- return inOperation(call, (budget) => enqueueParsed(parseCommandIdentity(scope, command), budget));
2350
+ return inOperation(call, (budget) => enqueueParsed(parseCommandIdentity(scope, command, capacity), budget));
2172
2351
  },
2173
2352
  enqueuePrepared(input, call = {}) {
2174
2353
  return inOperation(call, async (budget) => {
2175
- const command = validatePreparedCommand(scope, input);
2354
+ const command = validatePreparedCommand(scope, input, capacity);
2176
2355
  const identity = {
2177
2356
  scope,
2178
2357
  key: command.key,
@@ -2187,7 +2366,7 @@ function createEmailServiceWithClock(options, clock) {
2187
2366
  });
2188
2367
  }
2189
2368
  });
2190
- serviceAdmissions.set(service, enqueueParsed);
2369
+ serviceAdmissions.set(service, (parsed, budget) => withAdmission(() => enqueueParsed(parsed, budget)));
2191
2370
  return service;
2192
2371
  }
2193
2372
  function readPolicy(input, defaults) {
@@ -2212,30 +2391,36 @@ import { types as types7 } from "util";
2212
2391
 
2213
2392
  // src/internal/worker-config.ts
2214
2393
  var CONFIG2 = "invalid_config";
2215
- function readLimits(input) {
2394
+ function readLimits(input, capacity) {
2216
2395
  const keys = Object.keys(WORKER_LIMIT_BOUNDS);
2217
2396
  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;
2397
+ const limits2 = {};
2398
+ for (const key of keys) {
2399
+ const bounds = key === "maxConcurrency" ? capacity?.limits.workerConcurrency : void 0;
2400
+ limits2[key] = boundedOption(raw[key], bounds ?? WORKER_LIMIT_BOUNDS[key]);
2401
+ }
2402
+ const { leaseMs, storeTimeoutMs, providerTimeoutMs, finalizeGraceMs } = limits2;
2221
2403
  if (leaseMs < Math.max(
2222
2404
  3 * storeTimeoutMs + CLOCK_MARGIN_MS,
2223
2405
  storeTimeoutMs + providerTimeoutMs + finalizeGraceMs + CLOCK_MARGIN_MS
2224
2406
  )) {
2225
2407
  invalid(CONFIG2);
2226
2408
  }
2227
- return Object.freeze(limits);
2409
+ return Object.freeze(limits2);
2228
2410
  }
2229
2411
  function sameProvider(a, b) {
2230
2412
  return a.kind === b.kind && a.key === b.key && a.mode === b.mode;
2231
2413
  }
2232
- function readProfiles(input) {
2414
+ function readProfiles(input, capacity) {
2233
2415
  const profiles = /* @__PURE__ */ new Map();
2234
- readArray(input, Number.MAX_SAFE_INTEGER, CONFIG2, (provider) => {
2416
+ readArray(input, capacity?.limits.workerProfiles ?? Number.MAX_SAFE_INTEGER, CONFIG2, (provider) => {
2235
2417
  const ref = validateProviderRef(readPortMember(provider, "ref"), CONFIG2);
2418
+ assertPortCapacity(provider, capacity);
2419
+ assertCapacityProvider(ref, capacity, CONFIG2);
2236
2420
  if (profiles.has(ref.key)) invalid(CONFIG2);
2237
2421
  profiles.set(ref.key, Object.freeze({ ref, prepare: bindMethod(provider, "prepare") }));
2238
2422
  });
2423
+ if (capacity && profiles.size === 0) invalid(CONFIG2);
2239
2424
  return profiles;
2240
2425
  }
2241
2426
  function readResolvers(input) {
@@ -2273,15 +2458,18 @@ function readWorkerConfig(input) {
2273
2458
  const raw = readRecord(
2274
2459
  input,
2275
2460
  ["scope", "store", "providers"],
2276
- ["attachmentResolvers", "rateLimiter", "clock", "limits"],
2461
+ ["attachmentResolvers", "rateLimiter", "clock", "limits", "smtpCapacity"],
2277
2462
  CONFIG2
2278
2463
  );
2279
2464
  const { store } = raw;
2465
+ const capacity = readCapacityOption(raw);
2466
+ assertPortCapacity(store, capacity);
2280
2467
  return Object.freeze({
2468
+ capacity,
2281
2469
  scope: scopeToken(raw.scope, CONFIG2),
2282
- limits: readLimits(raw.limits),
2470
+ limits: readLimits(raw.limits, capacity),
2283
2471
  clock: readWorkerClock(raw.clock),
2284
- profiles: readProfiles(raw.providers),
2472
+ profiles: readProfiles(raw.providers, capacity),
2285
2473
  resolvers: readResolvers(raw.attachmentResolvers),
2286
2474
  limiter: readLimiter(raw.rateLimiter),
2287
2475
  store: Object.freeze({
@@ -2295,7 +2483,7 @@ function readWorkerConfig(input) {
2295
2483
  })
2296
2484
  });
2297
2485
  }
2298
- function readRunOptions(input, limits) {
2486
+ function readRunOptions(input, limits2, capacity) {
2299
2487
  const { limit, concurrency, maintenanceLimit, ...call } = readRecord(
2300
2488
  input,
2301
2489
  [],
@@ -2304,9 +2492,9 @@ function readRunOptions(input, limits) {
2304
2492
  );
2305
2493
  return Object.freeze({
2306
2494
  ...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)
2495
+ limit: boundedOption(limit, capacity?.limits.runClaims ?? RUN_CLAIM_LIMIT),
2496
+ concurrency: boundedOption(concurrency, { min: 1, max: limits2.maxConcurrency, default: limits2.maxConcurrency }),
2497
+ maintenanceLimit: boundedOption(maintenanceLimit, capacity?.limits.runMaintenance ?? RUN_MAINTENANCE_LIMIT)
2310
2498
  });
2311
2499
  }
2312
2500
  function readShutdownOptions(input) {
@@ -2322,10 +2510,10 @@ function readGrant(times, leaseMs) {
2322
2510
  if (leaseEndsAt - grantedAt !== leaseMs) invalid(STORED3);
2323
2511
  return Object.freeze({ grantedAt, leaseEndsAt });
2324
2512
  }
2325
- function readClaimed(value, scope, expected) {
2513
+ function readClaimed(value, scope, expected, capacity) {
2326
2514
  const raw = readRecord(value, ["job", "snapshot", "fence", "lease", "ordinal", "manual"], [], STORED3);
2327
- const job = readJobSummary(scope, raw.job);
2328
- const { snapshot } = validateSnapshot(raw.snapshot);
2515
+ const job = readJobSummary(scope, raw.job, capacity);
2516
+ const { snapshot } = validateSnapshot(raw.snapshot, capacity);
2329
2517
  const fence = readFence(raw.fence);
2330
2518
  const lease = readGrant(readRecord(raw.lease, ["grantedAt", "leaseEndsAt"], [], STORED3), expected.leaseMs);
2331
2519
  const ordinal = integer(raw.ordinal, 1, MAX_ATTEMPT_LEDGER, STORED3);
@@ -2360,7 +2548,7 @@ function readHandoff(value, last, claim, leaseMs, times) {
2360
2548
  assertLaterGrant(grant, last, claim.job.expiresAt, times);
2361
2549
  return Object.freeze({ ...grant, handoffAt });
2362
2550
  }
2363
- function readCommit(value) {
2551
+ function readCommit(value, capacity) {
2364
2552
  const raw = readRecord(
2365
2553
  value,
2366
2554
  ["jobId", "attemptId", "ordinal", "operationId", "startedAt", "finishedAt", "result", "disposition", "reason"],
@@ -2371,7 +2559,7 @@ function readCommit(value) {
2371
2559
  const finishedAt = unixMs(raw.finishedAt, STORED3);
2372
2560
  const handedOffAt = Object.hasOwn(raw, "handedOffAt") ? unixMs(raw.handedOffAt, STORED3) : void 0;
2373
2561
  const retryAt = Object.hasOwn(raw, "retryAt") ? unixMs(raw.retryAt, STORED3) : void 0;
2374
- const result = readAttemptResult(raw.result, STORED3);
2562
+ const result = readAttemptResult(raw.result, STORED3, false, capacity);
2375
2563
  const disposition = readDisposition(raw.disposition, STORED3);
2376
2564
  const reason = raw.reason === "attempts_exhausted" ? raw.reason : readAttemptReason(raw.reason, STORED3);
2377
2565
  assertEvidencePhase(result.reason, handedOffAt === void 0 ? "pre_handoff" : "handed_off", "ledger", STORED3);
@@ -2394,23 +2582,23 @@ function readCommit(value) {
2394
2582
  ...retryAt === void 0 ? {} : { retryAt }
2395
2583
  });
2396
2584
  }
2397
- function readRecovery(value) {
2398
- const commit = readCommit(value);
2585
+ function readRecovery(value, capacity) {
2586
+ const commit = readCommit(value, capacity);
2399
2587
  const { result, startedAt, handedOffAt, finishedAt } = commit;
2400
2588
  if (result.reason !== "pre_handoff_lease_expired" && result.reason !== "post_handoff_lease_expired" || finishedAt - (handedOffAt ?? startedAt) < WORKER_LIMIT_BOUNDS.leaseMs.min) {
2401
2589
  invalid(STORED3);
2402
2590
  }
2403
2591
  return commit;
2404
2592
  }
2405
- function readQueuedExpiry(value, scope) {
2406
- const job = readJobSummary(scope, value);
2593
+ function readQueuedExpiry(value, scope, capacity) {
2594
+ const job = readJobSummary(scope, value, capacity);
2407
2595
  if (job.state !== "terminal" || job.disposition !== "expired" || job.terminalReason !== "expired" || job.terminalAt < job.expiresAt || job.updatedAt !== job.terminalAt) {
2408
2596
  invalid(STORED3);
2409
2597
  }
2410
2598
  return job;
2411
2599
  }
2412
- function readOwnedCommit(value, { claim, lease, handoff }, request, providerInvoked, direct) {
2413
- const commit = readCommit(value);
2600
+ function readOwnedCommit(value, { claim, lease, handoff }, request, providerInvoked, direct, capacity) {
2601
+ const commit = readCommit(value, capacity);
2414
2602
  const { attemptId, startedAt, handedOffAt, finishedAt, result, disposition, retryAt } = commit;
2415
2603
  const { job, snapshot, fence, ordinal, manual } = claim;
2416
2604
  const { expiresAt } = job;
@@ -2423,7 +2611,7 @@ function readOwnedCommit(value, { claim, lease, handoff }, request, providerInvo
2423
2611
  assertEvidenceContext(result, snapshot.provider, attemptId, recipientCounts(snapshot.envelope), STORED3);
2424
2612
  if (request && commit.operationId === request.operationId) {
2425
2613
  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) {
2614
+ if (phase !== request.phase || finishedAt >= last.leaseEndsAt || encodeEvidence(result, STORED3, capacity) !== encodeEvidence(request.result, STORED3, capacity)) {
2427
2615
  invalid(STORED3);
2428
2616
  }
2429
2617
  } else if (direct) {
@@ -2435,7 +2623,7 @@ function readOwnedCommit(value, { claim, lease, handoff }, request, providerInvo
2435
2623
  // src/internal/worker-finish.ts
2436
2624
  import { randomUUID as randomUUID2 } from "crypto";
2437
2625
  async function finishAttempt(run, evidence2, providerInvoked, result) {
2438
- const { clock, store, scope, limits } = run.config;
2626
+ const { clock, store, scope, limits: limits2, capacity } = run.config;
2439
2627
  const {
2440
2628
  claim: { fence },
2441
2629
  handoff,
@@ -2444,13 +2632,13 @@ async function finishAttempt(run, evidence2, providerInvoked, result) {
2444
2632
  const now = monotonicNow(clock);
2445
2633
  const request = result && handoff !== "unconfirmed" ? Object.freeze({ fence, phase: handoff ? "handed_off" : "pre_handoff", operationId: randomUUID2(), result }) : void 0;
2446
2634
  const leaseEnd = safeLeaseEnd(handoff && handoff !== "unconfirmed" ? handoff : lease);
2447
- const grace = createBudgetUntil(clock, Math.min(now, run.budget.deadline) + limits.finalizeGraceMs);
2635
+ const grace = createBudgetUntil(clock, Math.min(now, run.budget.deadline) + limits2.finalizeGraceMs);
2448
2636
  async function confirm() {
2449
2637
  try {
2450
2638
  return await run.callStore(grace, {
2451
2639
  effect: "read",
2452
2640
  invoke: (call) => store.findAttempt(scope, fence.jobId, fence.attemptId, call),
2453
- accept: (value) => value === null ? null : readOwnedCommit(value, evidence2, request, providerInvoked, false)
2641
+ accept: (value) => value === null ? null : readOwnedCommit(value, evidence2, request, providerInvoked, false, capacity)
2454
2642
  });
2455
2643
  } catch {
2456
2644
  return null;
@@ -2461,7 +2649,7 @@ async function finishAttempt(run, evidence2, providerInvoked, result) {
2461
2649
  effect: "mutation",
2462
2650
  deadline: leaseEnd,
2463
2651
  invoke: (call) => store.finish(scope, exact, call),
2464
- accept: (value) => value === null ? null : readOwnedCommit(value, evidence2, exact, providerInvoked, true)
2652
+ accept: (value) => value === null ? null : readOwnedCommit(value, evidence2, exact, providerInvoked, true, capacity)
2465
2653
  });
2466
2654
  }
2467
2655
  try {
@@ -2638,8 +2826,8 @@ var AttemptOwner = class {
2638
2826
  }
2639
2827
  }
2640
2828
  async renewWhile(budget, stopped) {
2641
- const { clock, limits } = this.run.config;
2642
- const cadence = Math.floor(limits.leaseMs / 3);
2829
+ const { clock, limits: limits2 } = this.run.config;
2830
+ const cadence = Math.floor(limits2.leaseMs / 3);
2643
2831
  const waitSignal = AbortSignal.any([stopped, this.run.noLaunch]);
2644
2832
  while (!waitSignal.aborted) {
2645
2833
  try {
@@ -2709,7 +2897,7 @@ var AttemptOwner = class {
2709
2897
  }
2710
2898
  };
2711
2899
  async function launch(run, owner, mark, submit, preflight) {
2712
- const { clock, limits } = run.config;
2900
+ const { clock, limits: limits2, capacity } = run.config;
2713
2901
  const { provider, envelope, expiresAt } = owner.claim.snapshot;
2714
2902
  const { attemptId } = owner.claim.fence;
2715
2903
  const launchEnd = Math.min(
@@ -2727,7 +2915,7 @@ async function launch(run, owner, mark, submit, preflight) {
2727
2915
  io = createChildBudgetUntil(
2728
2916
  clock,
2729
2917
  run.budget,
2730
- Math.min(now + limits.providerTimeoutMs, safeLeaseEnd(mark) - limits.finalizeGraceMs)
2918
+ Math.min(now + limits2.providerTimeoutMs, safeLeaseEnd(mark) - limits2.finalizeGraceMs)
2731
2919
  );
2732
2920
  run.checkLaunch();
2733
2921
  io.check();
@@ -2743,7 +2931,7 @@ async function launch(run, owner, mark, submit, preflight) {
2743
2931
  if (!types7.isPromise(returned)) return unknown("transport_uncertain");
2744
2932
  let result;
2745
2933
  try {
2746
- result = readProviderResult(raw, provider, attemptId, envelope);
2934
+ result = readProviderResult(raw, provider, attemptId, envelope, capacity);
2747
2935
  } catch {
2748
2936
  return unknown("transport_uncertain");
2749
2937
  }
@@ -2767,8 +2955,8 @@ async function launch(run, owner, mark, submit, preflight) {
2767
2955
  }
2768
2956
  async function processOwned(owner, slot) {
2769
2957
  const { run, claim, lease } = owner;
2770
- const { clock, limits } = run.config;
2771
- const deadline = lease.dispatchedAt + limits.preHandoffTimeoutMs;
2958
+ const { clock, limits: limits2 } = run.config;
2959
+ const deadline = lease.dispatchedAt + limits2.preHandoffTimeoutMs;
2772
2960
  let budget;
2773
2961
  try {
2774
2962
  budget = createChildBudgetUntil(clock, run.budget, deadline);
@@ -2847,11 +3035,16 @@ var WorkerRun = class {
2847
3035
  if (this.noLaunch.aborted) invalid("aborted");
2848
3036
  }
2849
3037
  callStore(budget, operation) {
2850
- const { clock, limits } = this.config;
3038
+ const { clock, limits: limits2, capacity } = this.config;
2851
3039
  let invoked = false;
2852
3040
  return runStoreCall(clock, budget, {
2853
3041
  ...operation,
2854
- maxMs: Math.min(operation.maxMs ?? limits.storeTimeoutMs, limits.storeTimeoutMs),
3042
+ capacity,
3043
+ maxMs: Math.min(
3044
+ operation.maxMs ?? limits2.storeTimeoutMs,
3045
+ limits2.storeTimeoutMs,
3046
+ capacity ? STORE_PRIMITIVE_TIMEOUT_MS : Infinity
3047
+ ),
2855
3048
  beforeInvoke: () => {
2856
3049
  if (operation.authorize) this.checkLaunch();
2857
3050
  operation.beforeInvoke?.();
@@ -2929,23 +3122,23 @@ async function sweep(run, limit, items, invoke, read, entry) {
2929
3122
  return false;
2930
3123
  }
2931
3124
  function claimNext(run) {
2932
- const { clock, scope, store, limits } = run.config;
3125
+ const { clock, scope, store, limits: limits2, capacity } = run.config;
2933
3126
  const request = Object.freeze({
2934
3127
  attemptId: randomUUID3(),
2935
3128
  token: randomBytes(16).toString("base64url"),
2936
- leaseMs: limits.leaseMs
3129
+ leaseMs: limits2.leaseMs
2937
3130
  });
2938
3131
  let dispatchedAt;
2939
3132
  return run.callStore(run.budget, {
2940
3133
  effect: "mutation",
2941
3134
  authorize: true,
2942
- maxMs: limits.preHandoffTimeoutMs,
3135
+ maxMs: limits2.preHandoffTimeoutMs,
2943
3136
  invoke(call, start) {
2944
3137
  dispatchedAt = start;
2945
3138
  return store.claimNext(scope, request, call);
2946
3139
  },
2947
3140
  accept: (value) => readStoreNext(value, (raw) => {
2948
- const claim = readClaimed(raw, scope, request);
3141
+ const claim = readClaimed(raw, scope, request, capacity);
2949
3142
  return { claim, dispatchedAt, confirmedAt: monotonicNow(clock) };
2950
3143
  })
2951
3144
  });
@@ -3023,13 +3216,13 @@ async function drainClaims(run, options, items, slots) {
3023
3216
  }
3024
3217
  async function runQueue(run, options, slots, shutdown) {
3025
3218
  const items = [];
3026
- const { scope, store } = run.config;
3219
+ const { scope, store, capacity } = run.config;
3027
3220
  const contended = await sweep(
3028
3221
  run,
3029
3222
  options.maintenanceLimit,
3030
3223
  items,
3031
3224
  (call) => store.recoverNext(scope, call),
3032
- readRecovery,
3225
+ (value) => readRecovery(value, capacity),
3033
3226
  (commit) => ({
3034
3227
  operation: "recover",
3035
3228
  jobId: commit.jobId,
@@ -3043,7 +3236,7 @@ async function runQueue(run, options, slots, shutdown) {
3043
3236
  options.maintenanceLimit,
3044
3237
  items,
3045
3238
  (call) => store.expireNext(scope, call),
3046
- (value) => readQueuedExpiry(value, scope),
3239
+ (value) => readQueuedExpiry(value, scope, capacity),
3047
3240
  (job) => ({
3048
3241
  operation: "expire",
3049
3242
  jobId: job.jobId,
@@ -3068,16 +3261,17 @@ async function runQueue(run, options, slots, shutdown) {
3068
3261
  }
3069
3262
  function createEmailWorker(options) {
3070
3263
  const config = readWorkerConfig(options);
3071
- const { clock, scope, limits } = config;
3264
+ const { clock, scope, limits: limits2, capacity } = config;
3072
3265
  const shutdown = new AbortController();
3073
3266
  const slots = /* @__PURE__ */ new Set();
3074
3267
  let active;
3075
3268
  const worker = {
3076
3269
  scope,
3270
+ ...capacityTag(capacity),
3077
3271
  async run(options2 = {}) {
3078
3272
  if (shutdown.signal.aborted) invalid("closed");
3079
3273
  if (active) invalid("busy");
3080
- const settings = readRunOptions(options2, limits);
3274
+ const settings = readRunOptions(options2, limits2, capacity);
3081
3275
  const done = new AbortController();
3082
3276
  active = done;
3083
3277
  try {
@@ -3144,7 +3338,7 @@ var ADMISSION_ERRORS = [
3144
3338
  function boundScope(port) {
3145
3339
  return scopeToken(readPortMember(port, "scope"), "invalid_config");
3146
3340
  }
3147
- function readBatch(scope, input) {
3341
+ function readBatch(scope, input, capacity) {
3148
3342
  const code = "invalid_command";
3149
3343
  const raw = readRecord(input, ["batchId", "items"], [], code);
3150
3344
  const batchId = identifier(raw.batchId, code);
@@ -3155,7 +3349,10 @@ function readBatch(scope, input) {
3155
3349
  if (seen.has(itemId)) invalid(code);
3156
3350
  seen.add(itemId);
3157
3351
  const command = readRecord(item.command, ["templateKey", "input", "provider", "intent"], ["scheduleAt"], code);
3158
- return { itemId, parsed: parseCommandIdentity(scope, { ...command, key: { kind: "batch", batchId, itemId } }) };
3352
+ return {
3353
+ itemId,
3354
+ parsed: parseCommandIdentity(scope, { ...command, key: { kind: "batch", batchId, itemId } }, capacity)
3355
+ };
3159
3356
  });
3160
3357
  if (!items.length) invalid(code);
3161
3358
  return { batchId, items };
@@ -3164,11 +3361,11 @@ function stopReason(budget) {
3164
3361
  if (budget.remainingMs() > 0) return;
3165
3362
  return allowedErrorCode(budget.signal.reason, STOP_ERRORS2) ?? invalid("invalid_config");
3166
3363
  }
3167
- function readAdmissionResult(input, identity) {
3364
+ function readAdmissionResult(input, identity, capacity) {
3168
3365
  const code = "write_unconfirmed";
3169
3366
  const { status, job: raw } = readRecord(input, ["status", "job"], [], code);
3170
3367
  if (status !== "enqueued" && status !== "replayed") invalid(code);
3171
- const job = readJobSummary(identity.scope, raw);
3368
+ const job = readJobSummary(identity.scope, raw, capacity);
3172
3369
  if (!matchesAdmissionJob(job, identity, status)) invalid(code);
3173
3370
  return { status, job };
3174
3371
  }
@@ -3176,20 +3373,25 @@ function createEmailBatchService(options) {
3176
3373
  return createEmailBatchServiceWithClock(options, systemEmailClock);
3177
3374
  }
3178
3375
  function createEmailBatchServiceWithClock(options, clock) {
3179
- const { service, worker } = readRecord(options, ["service", "worker"], [], "invalid_config");
3376
+ const raw = readRecord(options, ["service", "worker"], ["smtpCapacity"], "invalid_config");
3377
+ const { service, worker } = raw;
3378
+ const capacity = readCapacityOption(raw);
3379
+ assertPortCapacity(service, capacity);
3380
+ assertPortCapacity(worker, capacity);
3180
3381
  const scope = boundScope(service);
3181
3382
  if (scope !== boundScope(worker)) invalid("invalid_config");
3182
3383
  const run = bindMethod(worker, "run");
3183
3384
  const enqueue = bindMethod(service, "enqueue");
3184
3385
  const admit = findServiceAdmission(service) ?? (async ({ command, identity }, budget) => {
3185
3386
  if (boundScope(service) !== scope) invalid("invalid_config");
3387
+ assertPortCapacity(service, capacity);
3186
3388
  const bounds = CALL_BUDGETS.admissionOrAdmin;
3187
3389
  const timeoutMs = Math.max(bounds.min, Math.min(bounds.max, Math.floor(budget.remainingMs())));
3188
3390
  budget.check();
3189
- let raw;
3391
+ let raw2;
3190
3392
  try {
3191
3393
  const pending = enqueue(command, Object.freeze({ signal: budget.signal, timeoutMs }));
3192
- raw = types8.isPromise(pending) ? await pending : pending;
3394
+ raw2 = types8.isPromise(pending) ? await pending : pending;
3193
3395
  } catch (error) {
3194
3396
  if (allowedErrorCode(error, ["aborted"]) && allowedErrorCode(budget.signal.reason, ["deadline"])) {
3195
3397
  invalid("deadline");
@@ -3197,17 +3399,20 @@ function createEmailBatchServiceWithClock(options, clock) {
3197
3399
  throw error;
3198
3400
  }
3199
3401
  try {
3200
- return readAdmissionResult(raw, identity);
3402
+ return readAdmissionResult(raw2, identity, capacity);
3201
3403
  } catch {
3202
3404
  return invalid("write_unconfirmed");
3203
3405
  }
3204
3406
  });
3407
+ let admitting = false;
3205
3408
  const batch = {
3206
3409
  async enqueueBatch(input, call = {}) {
3410
+ if (capacity && admitting) invalid("busy");
3207
3411
  const { signal, timeoutMs } = readCallOptions(call, CALL_BUDGETS.batchOrRun);
3208
3412
  const budget = createBudget(clock, timeoutMs, signal);
3413
+ admitting = true;
3209
3414
  try {
3210
- const { batchId, items: commands } = readBatch(scope, input);
3415
+ const { batchId, items: commands } = readBatch(scope, input, capacity);
3211
3416
  const items = [];
3212
3417
  const counts = { enqueued: 0, replayed: 0, failed: 0, notStarted: 0, persistenceFailures: 0 };
3213
3418
  for (const { itemId, parsed } of commands) {
@@ -3229,11 +3434,13 @@ function createEmailBatchServiceWithClock(options, clock) {
3229
3434
  }
3230
3435
  return Object.freeze({ batchId, items: Object.freeze(items), counts: Object.freeze(counts) });
3231
3436
  } finally {
3437
+ admitting = false;
3232
3438
  budget.close();
3233
3439
  }
3234
3440
  },
3235
3441
  async run(options2) {
3236
3442
  if (boundScope(worker) !== scope) invalid("invalid_config");
3443
+ assertPortCapacity(worker, capacity);
3237
3444
  return run(options2);
3238
3445
  }
3239
3446
  };
@@ -3254,7 +3461,10 @@ function createEmailAdmin(options) {
3254
3461
  return createEmailAdminWithClock(options, systemEmailClock);
3255
3462
  }
3256
3463
  function createEmailAdminWithClock(options, clock) {
3257
- const { scope: input, store, onActivity: callback } = readRecord(options, ["scope", "store"], ["onActivity"], CONFIG3);
3464
+ const raw = readRecord(options, ["scope", "store"], ["onActivity", "smtpCapacity"], CONFIG3);
3465
+ const { scope: input, store, onActivity: callback } = raw;
3466
+ const capacity = readCapacityOption(raw);
3467
+ assertPortCapacity(store, capacity);
3258
3468
  const scope = scopeToken(input, CONFIG3);
3259
3469
  const findJob = bindMethod(store, "findJob");
3260
3470
  const cancel = bindMethod(store, "cancel");
@@ -3266,6 +3476,7 @@ function createEmailAdminWithClock(options, clock) {
3266
3476
  const cleanupNext = bindMethod(store, "cleanupNext");
3267
3477
  const onActivity = callback === void 0 ? void 0 : requireCallback(callback);
3268
3478
  let observers = 0;
3479
+ let active = false;
3269
3480
  function observe(activity, counts) {
3270
3481
  if (!onActivity) return;
3271
3482
  if (observers >= MAX_OBSERVER_PENDING) {
@@ -3284,29 +3495,35 @@ function createEmailAdminWithClock(options, clock) {
3284
3495
  }
3285
3496
  }
3286
3497
  function readJob(jobId, value) {
3287
- const job = readJobSummary(scope, value);
3498
+ const job = readJobSummary(scope, value, capacity);
3288
3499
  if (job.jobId !== jobId) invalid(STORED4);
3289
3500
  return job;
3290
3501
  }
3291
3502
  function callStore(budget, operation) {
3292
- return runStoreCall(clock, budget, { ...operation, maxMs: STORE_PRIMITIVE_TIMEOUT_MS });
3503
+ return runStoreCall(clock, budget, { ...operation, maxMs: STORE_PRIMITIVE_TIMEOUT_MS, capacity });
3293
3504
  }
3294
3505
  function write(budget, invoke, accept) {
3295
3506
  return callStore(budget, { effect: "mutation", invoke, accept });
3296
3507
  }
3297
3508
  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);
3509
+ if (capacity && active) invalid("busy");
3510
+ active = true;
3301
3511
  try {
3302
- return await run(budget, signal);
3512
+ const { timeoutMs, signal: source } = readCallOptions(options2, CALL_BUDGETS.admissionOrAdmin);
3513
+ const signal = source && AbortSignal.any([source]);
3514
+ const budget = createBudget(clock, timeoutMs, signal);
3515
+ try {
3516
+ return await run(budget, signal);
3517
+ } finally {
3518
+ budget.close();
3519
+ }
3303
3520
  } finally {
3304
- budget.close();
3521
+ active = false;
3305
3522
  }
3306
3523
  }
3307
3524
  async function maintain(options2, step) {
3308
3525
  const { limit: input2, ...call } = readRecord(options2, [], ["limit", "signal", "timeoutMs"], CONFIG3);
3309
- const limit = boundedOption(input2, ADMIN_MAINTENANCE_LIMIT);
3526
+ const limit = boundedOption(input2, capacity?.limits.adminMaintenance ?? ADMIN_MAINTENANCE_LIMIT);
3310
3527
  return inOperation(call, async (budget, signal) => {
3311
3528
  let stop = "limit";
3312
3529
  for (let i = 0; i < limit; i++) {
@@ -3349,11 +3566,11 @@ function createEmailAdminWithClock(options, clock) {
3349
3566
  budget,
3350
3567
  (call) => cancel(scope, id, call),
3351
3568
  (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 });
3569
+ const raw2 = readRecord(value, ["status"], ["job"], STORED4);
3570
+ const { status } = raw2;
3571
+ if (status === "not_found" && !Object.hasOwn(raw2, "job")) return Object.freeze({ status });
3355
3572
  if (status !== "cancelled" && status !== "too_late") invalid(STORED4);
3356
- const job = readJob(id, raw.job);
3573
+ const job = readJob(id, raw2.job);
3357
3574
  if (status === "cancelled" !== (job.state === "terminal" && job.disposition === "cancelled")) {
3358
3575
  invalid(STORED4);
3359
3576
  }
@@ -3370,8 +3587,8 @@ function createEmailAdminWithClock(options, clock) {
3370
3587
  definite: RESOLUTION_REJECTIONS,
3371
3588
  invoke: (call) => resolveUnknown(scope, request, call),
3372
3589
  accept(value) {
3373
- const { status, job: raw } = readRecord(value, ["status", "job"], [], STORED4);
3374
- const job = readJob(request.jobId, raw);
3590
+ const { status, job: raw2 } = readRecord(value, ["status", "job"], [], STORED4);
3591
+ const job = readJob(request.jobId, raw2);
3375
3592
  const decision = job.resolutions.find(({ attemptId }) => attemptId === request.attemptId);
3376
3593
  if (decision?.action !== request.action || status !== "resolved" && status !== "replayed") {
3377
3594
  invalid(STORED4);
@@ -3386,7 +3603,7 @@ function createEmailAdminWithClock(options, clock) {
3386
3603
  },
3387
3604
  listActivities(query = {}, options2 = {}) {
3388
3605
  return inOperation(options2, (budget) => {
3389
- const criteria = readActivityCriteria(scope, query);
3606
+ const criteria = readActivityCriteria(scope, query, capacity);
3390
3607
  const request = activityQuery(criteria);
3391
3608
  return callStore(budget, {
3392
3609
  effect: "read",
@@ -3401,7 +3618,7 @@ function createEmailAdminWithClock(options, clock) {
3401
3618
  const next = await write(
3402
3619
  budget,
3403
3620
  (call) => reserve(scope, call),
3404
- (value) => readStoreNext(value, (permit2) => readProjectionPermit(scope, permit2))
3621
+ (value) => readStoreNext(value, (permit2) => readProjectionPermit(scope, permit2, capacity))
3405
3622
  );
3406
3623
  if (next.status !== "applied") return next.status === "none" ? "idle" : "contended";
3407
3624
  counts.reserved++;
@@ -3516,6 +3733,7 @@ function jobSummary(job) {
3516
3733
  const latest = job.attempts.at(-1)?.commit;
3517
3734
  return Object.freeze({
3518
3735
  version: EMAIL_FORMAT_VERSION,
3736
+ ...job.smtpCapacity ? { smtpCapacity: job.smtpCapacity } : {},
3519
3737
  scope: job.scope,
3520
3738
  jobId: job.jobId,
3521
3739
  key: Object.freeze({ ...job.key }),
@@ -3540,13 +3758,13 @@ function jobSummary(job) {
3540
3758
  ...summaryState
3541
3759
  });
3542
3760
  }
3543
- function copyCommit(commit) {
3544
- return Object.freeze({ ...commit, result: readAttemptResult(commit.result, STORED5) });
3761
+ function copyCommit(commit, capacity) {
3762
+ return Object.freeze({ ...commit, result: readAttemptResult(commit.result, STORED5, false, capacity) });
3545
3763
  }
3546
- function readStoredSnapshot(job, input) {
3764
+ function readStoredSnapshot(job, input, capacity) {
3547
3765
  let validated;
3548
3766
  try {
3549
- validated = validateSnapshot(input);
3767
+ validated = validateSnapshot(input, capacity);
3550
3768
  } catch {
3551
3769
  return invalid(STORED5);
3552
3770
  }
@@ -3581,7 +3799,7 @@ function replace(job, time, patch, value, before, pendingAck) {
3581
3799
  write: { kind: "replace", guard: pendingAck ? { ...expect, pendingAck } : expect, next }
3582
3800
  };
3583
3801
  }
3584
- function newJob(admission, time) {
3802
+ function newJob(admission, time, capacity) {
3585
3803
  const { command, jobId, retry, retention, admissionKey } = admission;
3586
3804
  const { scope, key, scheduleAt, fingerprint, snapshotHash, snapshot } = command;
3587
3805
  const now = unixMs(time.now, "store_unavailable");
@@ -3590,6 +3808,8 @@ function newJob(admission, time) {
3590
3808
  if (nextAt >= snapshot.expiresAt) invalid("expired");
3591
3809
  return Object.freeze({
3592
3810
  version: EMAIL_FORMAT_VERSION,
3811
+ ...capacityTag(capacity),
3812
+ ...capacity ? { intentHash: command.intentHash } : {},
3593
3813
  scope,
3594
3814
  jobId,
3595
3815
  key,
@@ -3628,14 +3848,14 @@ function liveLease(job, fence, phase, now) {
3628
3848
  }
3629
3849
  return lease;
3630
3850
  }
3631
- function claimJob(job, claim, time) {
3851
+ function claimJob(job, claim, time, capacity) {
3632
3852
  const { now } = time;
3633
3853
  if (job.state.state !== "queued" || job.state.nextAt > now || now >= job.expiresAt) return null;
3634
3854
  const manual = hasRedrive(job);
3635
3855
  const ordinal = job.attempts.length + 1;
3636
3856
  if (ordinal > MAX_ATTEMPT_LEDGER || !manual && ordinal > job.retry.maxAttempts) invalid("store_incompatible");
3637
3857
  if (job.attempts.some(({ commit }) => commit.attemptId === claim.attemptId)) invalid("invalid_command");
3638
- const snapshot = readStoredSnapshot(job, job.snapshot);
3858
+ const snapshot = readStoredSnapshot(job, job.snapshot, capacity);
3639
3859
  const lease = Object.freeze({
3640
3860
  attemptId: claim.attemptId,
3641
3861
  token: claim.token,
@@ -3695,7 +3915,7 @@ function markJob(job, fence, leaseMs, time) {
3695
3915
  Math.min(job.expiresAt, lease.leaseEndsAt, grant.leaseEndsAt)
3696
3916
  );
3697
3917
  }
3698
- function finalize(job, lease, operationId, result, time, owner) {
3918
+ function finalize(job, lease, operationId, result, time, owner, capacity) {
3699
3919
  const { now } = time;
3700
3920
  const { attemptId, startedAt, handedOffAt } = lease;
3701
3921
  const ordinal = job.attempts.length + 1;
@@ -3713,7 +3933,7 @@ function finalize(job, lease, operationId, result, time, owner) {
3713
3933
  });
3714
3934
  const entry = Object.freeze({
3715
3935
  commit,
3716
- digest: activityDigest(activityFor(job, commit)),
3936
+ digest: activityDigest(activityFor(job, commit, capacity), capacity),
3717
3937
  ...owner ? { ownerDigest: sha256(lease.token) } : {}
3718
3938
  });
3719
3939
  const state = effect.disposition === "retry_scheduled" ? Object.freeze({ state: "queued", nextAt: effect.retryAt }) : terminalState(effect.disposition, effect.reason, now);
@@ -3725,11 +3945,11 @@ function finalize(job, lease, operationId, result, time, owner) {
3725
3945
  job,
3726
3946
  time,
3727
3947
  { ...job, state, attempts: Object.freeze([...job.attempts, entry]) },
3728
- () => copyCommit(commit),
3948
+ () => copyCommit(commit, capacity),
3729
3949
  before
3730
3950
  );
3731
3951
  }
3732
- function finishJob(job, request, time) {
3952
+ function finishJob(job, request, time, capacity) {
3733
3953
  const { fence, phase, operationId, result } = request;
3734
3954
  if (job.jobId !== fence.jobId) return null;
3735
3955
  assertEvidencePhase(result.reason, phase, "owner", "invalid_command");
@@ -3740,28 +3960,28 @@ function finishJob(job, request, time) {
3740
3960
  if (previous.ownerDigest !== sha256(fence.token) || commit.operationId !== operationId || previousPhase !== phase) {
3741
3961
  return null;
3742
3962
  }
3743
- if (hashJson(result, 8192, "invalid_command") !== hashJson(commit.result, 8192, "store_incompatible")) {
3963
+ if (sha256(encodeEvidence(result, "invalid_command", capacity)) !== sha256(encodeEvidence(commit.result, "store_incompatible", capacity))) {
3744
3964
  invalid("invalid_command");
3745
3965
  }
3746
- return { value: copyCommit(commit) };
3966
+ return { value: copyCommit(commit, capacity) };
3747
3967
  }
3748
3968
  const lease = liveLease(job, fence, phase, time.now);
3749
3969
  if (!lease) return null;
3750
3970
  if (result.reason === "expired" && time.now < job.expiresAt) invalid("invalid_command");
3751
3971
  assertEvidenceContext(result, job.provider, fence.attemptId, job.recipientCounts, "invalid_command");
3752
- return finalize(job, lease, operationId, result, time, true);
3972
+ return finalize(job, lease, operationId, result, time, true, capacity);
3753
3973
  }
3754
- function recoverJob(job, operationId, time) {
3974
+ function recoverJob(job, operationId, time, capacity) {
3755
3975
  if (job.state.state !== "leased" || time.now < job.state.lease.leaseEndsAt) return null;
3756
3976
  const { lease } = job.state;
3757
3977
  const reason = lease.handedOffAt === void 0 ? "pre_handoff_lease_expired" : "post_handoff_lease_expired";
3758
- return finalize(job, lease, operationId, lifecycleEvidence(reason), time, false);
3978
+ return finalize(job, lease, operationId, lifecycleEvidence(reason), time, false, capacity);
3759
3979
  }
3760
3980
  function expireJob(job, time) {
3761
3981
  if (job.state.state !== "queued" || time.now < job.expiresAt) return null;
3762
3982
  return replace(job, time, { ...job, state: terminalState("expired", "expired", time.now) }, jobSummary);
3763
3983
  }
3764
- function cancelJob(job, operationId, time) {
3984
+ function cancelJob(job, operationId, time, capacity) {
3765
3985
  const { state } = job;
3766
3986
  if (state.state === "terminal") {
3767
3987
  return {
@@ -3775,7 +3995,7 @@ function cancelJob(job, operationId, time) {
3775
3995
  return { value: Object.freeze({ status: "too_late", job: jobSummary(job) }) };
3776
3996
  }
3777
3997
  if (state.state === "leased") {
3778
- const decision = finalize(job, state.lease, operationId, lifecycleEvidence("cancelled"), time, false);
3998
+ const decision = finalize(job, state.lease, operationId, lifecycleEvidence("cancelled"), time, false, capacity);
3779
3999
  const { write } = decision;
3780
4000
  if (write?.kind !== "replace") invalid("store_incompatible");
3781
4001
  return { write, value: Object.freeze({ status: "cancelled", job: jobSummary(write.next) }) };
@@ -3820,11 +4040,11 @@ function resolveJob(job, request, time) {
3820
4040
  function replaceAttempt(job, previous, entry) {
3821
4041
  return Object.freeze(job.attempts.map((attempt) => attempt === previous ? Object.freeze(entry) : attempt));
3822
4042
  }
3823
- function reserveJobProjection(job, time) {
4043
+ function reserveJobProjection(job, time, capacity) {
3824
4044
  const entry = pendingAttempt(job);
3825
4045
  if (job.retiring || !entry || entry.commit.finishedAt > time.now) return null;
3826
4046
  const permitUntil = timeAfter(time.now, PROJECTION_PERMIT_MS) ?? invalid("store_unavailable");
3827
- const activity = activityFor(job, entry.commit);
4047
+ const activity = activityFor(job, entry.commit, capacity);
3828
4048
  const permit = Object.freeze({ activity, digest: entry.digest, permitUntil });
3829
4049
  const attempts = replaceAttempt(job, entry, { ...entry, permitUntil });
3830
4050
  return replace(
@@ -3968,12 +4188,14 @@ var TIME_MISS = /* @__PURE__ */ Symbol("time_miss");
3968
4188
  var NONE = Object.freeze({ status: "none" });
3969
4189
  var CONTENDED = Object.freeze({ status: "contended" });
3970
4190
  function createMemoryEmailStore(options = {}) {
3971
- const config = readRecord(options, [], ["clock", "maxJobs"], "invalid_config");
4191
+ const config = readRecord(options, [], ["clock", "maxJobs", "smtpCapacity"], "invalid_config");
4192
+ const capacity = readCapacityOption(config);
3972
4193
  const clock = readClock(config.clock);
3973
- const maxJobs = boundedOption(config.maxJobs, MEMORY_MAX_JOBS);
4194
+ const maxJobs = boundedOption(config.maxJobs, capacity?.limits.memoryJobs ?? MEMORY_MAX_JOBS);
3974
4195
  const scopes = /* @__PURE__ */ new Map();
3975
4196
  let count = 0;
3976
4197
  let active = false;
4198
+ let ready = false;
3977
4199
  let lastWall = 0;
3978
4200
  function wallNow() {
3979
4201
  let now;
@@ -4014,8 +4236,13 @@ function createMemoryEmailStore(options = {}) {
4014
4236
  active = false;
4015
4237
  }
4016
4238
  }
4239
+ function primitive(call, worker, run) {
4240
+ const safe = readStoreCall(call, worker, capacity);
4241
+ if (capacity && !ready) invalid("store_unavailable");
4242
+ return atomic(safe, run);
4243
+ }
4017
4244
  function read(call, worker, get) {
4018
- return atomic(readStoreCall(call, worker), (check) => {
4245
+ return primitive(call, worker, (check) => {
4019
4246
  const value = get();
4020
4247
  check();
4021
4248
  return value;
@@ -4080,12 +4307,14 @@ function createMemoryEmailStore(options = {}) {
4080
4307
  return misses ? CONTENDED : NONE;
4081
4308
  }
4082
4309
  const store = {
4310
+ ...capacityTag(capacity),
4083
4311
  async ready(options2 = {}) {
4084
4312
  const call = readCallOptions(options2, CALL_BUDGETS.admissionOrAdmin);
4085
4313
  atomic({ ...call, timeoutMs: Math.min(call.timeoutMs, STORE_PRIMITIVE_TIMEOUT_MS) }, (check) => {
4086
4314
  wallNow();
4087
4315
  check();
4088
4316
  });
4317
+ ready = true;
4089
4318
  },
4090
4319
  async findAdmission(scope, key, call) {
4091
4320
  return read(call, false, () => {
@@ -4097,15 +4326,15 @@ function createMemoryEmailStore(options = {}) {
4097
4326
  });
4098
4327
  },
4099
4328
  async insert(scope, admission, call) {
4100
- return atomic(readStoreCall(call), (check) => {
4101
- const parsed = readStoreAdmission(scope, admission);
4329
+ return primitive(call, false, (check) => {
4330
+ const parsed = readStoreAdmission(scope, admission, capacity);
4102
4331
  const rows = scopes.get(parsed.command.scope);
4103
4332
  if (rows?.identities.has(parsed.admissionKey)) {
4104
4333
  check();
4105
4334
  return Object.freeze({ status: "duplicate" });
4106
4335
  }
4107
4336
  if (rows?.jobs.has(parsed.jobId)) invalid("invalid_command");
4108
- const row = newJob(parsed, { now: wallNow(), revision: randomUUID4() });
4337
+ const row = newJob(parsed, { now: wallNow(), revision: randomUUID4() }, capacity);
4109
4338
  if (count >= maxJobs) invalid("store_capacity");
4110
4339
  const result = Object.freeze({ status: "inserted", job: jobSummary(row) });
4111
4340
  check();
@@ -4132,62 +4361,66 @@ function createMemoryEmailStore(options = {}) {
4132
4361
  const job = readStoreId(jobId);
4133
4362
  const id = readStoreId(attemptId);
4134
4363
  const entry = rows?.jobs.get(job)?.attempts.find(({ commit }) => commit.attemptId === id);
4135
- return entry ? copyCommit(entry.commit) : null;
4364
+ return entry ? copyCommit(entry.commit, capacity) : null;
4136
4365
  });
4137
4366
  },
4138
4367
  async claimNext(scope, claim, call) {
4139
- return atomic(readStoreCall(call, true), (check) => {
4368
+ return primitive(call, true, (check) => {
4140
4369
  const safe = readClaim(claim);
4141
- return next(scope, "nextAt", check, (row, time) => claimJob(row, safe, time));
4370
+ return next(scope, "nextAt", check, (row, time) => claimJob(row, safe, time, capacity));
4142
4371
  });
4143
4372
  },
4144
4373
  async renew(scope, fence, leaseMs, call) {
4145
- return atomic(readStoreCall(call, true), (check) => {
4374
+ return primitive(call, true, (check) => {
4146
4375
  const safe = readFence(fence);
4147
4376
  const duration = readLeaseMs(leaseMs);
4148
4377
  return point(scope, safe.jobId, check, (row, time) => renewJob(row, safe, duration, time));
4149
4378
  });
4150
4379
  },
4151
4380
  async markHandoff(scope, fence, leaseMs, call) {
4152
- return atomic(readStoreCall(call, true), (check) => {
4381
+ return primitive(call, true, (check) => {
4153
4382
  const safe = readFence(fence);
4154
4383
  const duration = readLeaseMs(leaseMs);
4155
4384
  return point(scope, safe.jobId, check, (row, time) => markJob(row, safe, duration, time));
4156
4385
  });
4157
4386
  },
4158
4387
  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));
4388
+ return primitive(call, true, (check) => {
4389
+ const safe = readFinish(finish, capacity);
4390
+ return point(scope, safe.fence.jobId, check, (row, time) => finishJob(row, safe, time, capacity));
4162
4391
  });
4163
4392
  },
4164
4393
  async recoverNext(scope, call) {
4165
- return atomic(readStoreCall(call, true), (check) => {
4394
+ return primitive(call, true, (check) => {
4166
4395
  const operationId = randomUUID4();
4167
- return next(scope, "leaseEndsAt", check, (row, time) => recoverJob(row, operationId, time));
4396
+ return next(scope, "leaseEndsAt", check, (row, time) => recoverJob(row, operationId, time, capacity));
4168
4397
  });
4169
4398
  },
4170
4399
  async expireNext(scope, call) {
4171
- return atomic(readStoreCall(call, true), (check) => next(scope, "queuedExpiresAt", check, expireJob));
4400
+ return primitive(call, true, (check) => next(scope, "queuedExpiresAt", check, expireJob));
4172
4401
  },
4173
4402
  async cancel(scope, jobId, call) {
4174
- return atomic(readStoreCall(call), (check) => {
4403
+ return primitive(call, false, (check) => {
4175
4404
  const operationId = randomUUID4();
4176
- return point(scope, readStoreId(jobId), check, (row, time) => cancelJob(row, operationId, time)) ?? Object.freeze({ status: "not_found" });
4405
+ return point(scope, readStoreId(jobId), check, (row, time) => cancelJob(row, operationId, time, capacity)) ?? Object.freeze({ status: "not_found" });
4177
4406
  });
4178
4407
  },
4179
4408
  async resolveUnknown(scope, command, call) {
4180
- return atomic(readStoreCall(call), (check) => {
4409
+ return primitive(call, false, (check) => {
4181
4410
  const safe = readResolution(command);
4182
4411
  return point(scope, safe.jobId, check, (row, time) => resolveJob(row, safe, time)) ?? invalid("not_found");
4183
4412
  });
4184
4413
  },
4185
4414
  async reserveProjection(scope, call) {
4186
- return atomic(readStoreCall(call), (check) => next(scope, "pendingAt", check, reserveJobProjection));
4415
+ return primitive(
4416
+ call,
4417
+ false,
4418
+ (check) => next(scope, "pendingAt", check, (row, time) => reserveJobProjection(row, time, capacity))
4419
+ );
4187
4420
  },
4188
4421
  async putActivity(scope, permit, call) {
4189
- return atomic(readStoreCall(call), (check) => {
4190
- const safe = readProjectionPermit(scopeToken(scope), permit);
4422
+ return primitive(call, false, (check) => {
4423
+ const safe = readProjectionPermit(scopeToken(scope), permit, capacity);
4191
4424
  const rows = scopes.get(scope);
4192
4425
  const { jobId, attemptId } = safe.activity;
4193
4426
  const existing = rows?.byJob.get(jobId)?.byId.get(attemptId);
@@ -4203,8 +4436,8 @@ function createMemoryEmailStore(options = {}) {
4203
4436
  });
4204
4437
  },
4205
4438
  async ackProjection(scope, permit, call) {
4206
- return atomic(readStoreCall(call), (check) => {
4207
- const safe = readProjectionPermit(scopeToken(scope), permit);
4439
+ return primitive(call, false, (check) => {
4440
+ const safe = readProjectionPermit(scopeToken(scope), permit, capacity);
4208
4441
  const { jobId, attemptId } = safe.activity;
4209
4442
  const proof = scopes.get(scope)?.byJob.get(jobId)?.byId.get(attemptId);
4210
4443
  return point(scope, jobId, check, (row, time) => acknowledgeJobProjection(row, safe, proof, time)) ?? "stale";
@@ -4212,7 +4445,7 @@ function createMemoryEmailStore(options = {}) {
4212
4445
  },
4213
4446
  async listActivities(scope, query, call) {
4214
4447
  return read(call, false, () => {
4215
- const criteria = readActivityCriteria(scopeToken(scope), query);
4448
+ const criteria = readActivityCriteria(scopeToken(scope), query, capacity);
4216
4449
  const rows = scopes.get(scope);
4217
4450
  const { jobId, before, from, after, limit } = criteria;
4218
4451
  const index = (jobId === null ? rows?.activities : rows?.byJob.get(jobId)?.ordered) ?? [];
@@ -4226,7 +4459,7 @@ function createMemoryEmailStore(options = {}) {
4226
4459
  });
4227
4460
  },
4228
4461
  async cleanupNext(scope, call) {
4229
- return atomic(readStoreCall(call), (check) => next(scope, "nextCleanupAt", check, cleanupJob));
4462
+ return primitive(call, false, (check) => next(scope, "nextCleanupAt", check, cleanupJob));
4230
4463
  }
4231
4464
  };
4232
4465
  return Object.freeze(store);