@crvouga/mockingbird-runtime 0.3.2 → 0.5.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.
@@ -49,7 +49,7 @@ import {
49
49
  toHex,
50
50
  upstreamRequest,
51
51
  upstreamState
52
- } from "./chunk-M4HUKBLC.js";
52
+ } from "./chunk-GAIPLMRY.js";
53
53
  import {
54
54
  Timeline,
55
55
  forwardMountContext,
@@ -4272,6 +4272,8 @@ var awsXml = (value, listTag = "member") => {
4272
4272
  var WriteJournal = class {
4273
4273
  records = /* @__PURE__ */ new Map();
4274
4274
  sequences = /* @__PURE__ */ new Map();
4275
+ /** The first write in this scope refused for the record cap, if one was. */
4276
+ limitHit = void 0;
4275
4277
  restore(sqlite, namespace) {
4276
4278
  sqlite.transaction(() => {
4277
4279
  const remove = sqlite.prepare("DELETE FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?");
@@ -4322,6 +4324,41 @@ var closeJournal = (sqlite, namespace, journal) => {
4322
4324
  };
4323
4325
 
4324
4326
  // ../service/core/dist/collection.js
4327
+ var RECORD_LIMITS = /* @__PURE__ */ new WeakMap();
4328
+ var limitFor = (sqlite, namespace) => {
4329
+ const limits = RECORD_LIMITS.get(sqlite);
4330
+ if (!limits)
4331
+ return void 0;
4332
+ let owner;
4333
+ for (const service of limits.keys())
4334
+ if ((namespace === service || namespace.startsWith(`${service}:`)) && (owner === void 0 || service.length > owner.length))
4335
+ owner = service;
4336
+ return owner === void 0 ? void 0 : limits.get(owner);
4337
+ };
4338
+ var RecordLimitError = class extends RangeError {
4339
+ limit;
4340
+ constructor(limit) {
4341
+ super(`this namespace already holds ${limit} records, the most maxRecords allows; reset or delete the namespace to free them`);
4342
+ this.limit = limit;
4343
+ this.name = "RecordLimitError";
4344
+ }
4345
+ };
4346
+ var recordLimitResponse = (error) => new Response(JSON.stringify({ error: { type: "mockingbird_admin", message: error.message } }), {
4347
+ status: 507,
4348
+ headers: { "content-type": "application/json; charset=utf-8" }
4349
+ });
4350
+ var setRecordLimit = (sqlite, service, limit) => {
4351
+ let limits = RECORD_LIMITS.get(sqlite);
4352
+ if (limit === void 0) {
4353
+ limits?.delete(service);
4354
+ return;
4355
+ }
4356
+ if (!limits) {
4357
+ limits = /* @__PURE__ */ new Map();
4358
+ RECORD_LIMITS.set(sqlite, limits);
4359
+ }
4360
+ limits.set(service, limit);
4361
+ };
4325
4362
  var Collection = class {
4326
4363
  sqlite;
4327
4364
  namespace;
@@ -4384,9 +4421,22 @@ var Collection = class {
4384
4421
  const row = this.prepare("SELECT 1 AS ok FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?").get(this.namespace, this.collectionName, id);
4385
4422
  return row !== void 0;
4386
4423
  }
4424
+ assertRoom(id) {
4425
+ const limit = limitFor(this.sqlite, this.namespace);
4426
+ if (limit === void 0 || this.has(id))
4427
+ return;
4428
+ const row = this.prepare("SELECT COUNT(*) AS n FROM mockingbird_records WHERE namespace = ?").get(this.namespace);
4429
+ if (Number(row?.n ?? 0) < limit)
4430
+ return;
4431
+ const error = new RecordLimitError(limit);
4432
+ for (const journal of openJournals(this.sqlite, this.namespace) ?? [])
4433
+ journal.limitHit ??= error;
4434
+ throw error;
4435
+ }
4387
4436
  /** Insert a new record, assigning it the next sequence number. */
4388
4437
  insert(id, value) {
4389
4438
  return this.sqlite.transaction(() => {
4439
+ this.assertRoom(id);
4390
4440
  this.journalRecord(id);
4391
4441
  const seq = this.bumpCollectionSeq();
4392
4442
  const stored = { seq, value };
@@ -4709,7 +4759,7 @@ var createService = (options) => {
4709
4759
  const now = options.now ?? (() => Date.now());
4710
4760
  const app = new Hono();
4711
4761
  app.notFound((c) => options.notFound(c.req.raw));
4712
- app.onError((error, c) => options.onError(error, c.req.raw));
4762
+ app.onError((error, c) => error instanceof RecordLimitError ? recordLimitResponse(error) : options.onError(error, c.req.raw));
4713
4763
  const operations = [...listOperations(options.document)].sort(routeOrder);
4714
4764
  for (const operation of operations) {
4715
4765
  const path = operationPath(operation);
@@ -5849,8 +5899,8 @@ var stateAdminRoutes = (routes) => {
5849
5899
  };
5850
5900
 
5851
5901
  // ../service/core/dist/version.js
5852
- var UNRELEASED_VERSION = "0.3.2";
5853
- var PACKAGE_VERSION = true ? "0.3.2" : UNRELEASED_VERSION;
5902
+ var UNRELEASED_VERSION = "0.5.0";
5903
+ var PACKAGE_VERSION = true ? "0.5.0" : UNRELEASED_VERSION;
5854
5904
 
5855
5905
  // ../service/core/dist/webhooks.js
5856
5906
  var signers = {
@@ -6052,6 +6102,22 @@ var createWebhookHub = (options) => {
6052
6102
  else
6053
6103
  notify(delivery);
6054
6104
  }
6105
+ forgetFinished(message.namespace);
6106
+ };
6107
+ const forgetFinished = (namespace) => {
6108
+ let total = 0;
6109
+ const finished = [];
6110
+ for (const [deliveryId, delivery] of deliveries) {
6111
+ if (delivery.namespace !== namespace)
6112
+ continue;
6113
+ total++;
6114
+ if (delivery.state !== "pending" && !activeDeliveries.has(deliveryId))
6115
+ finished.push(deliveryId);
6116
+ }
6117
+ for (const deliveryId of finished.slice(0, Math.max(0, total - keep))) {
6118
+ deliveries.delete(deliveryId);
6119
+ payloads.delete(deliveryId);
6120
+ }
6055
6121
  };
6056
6122
  const takeFault = (namespace) => {
6057
6123
  const queue = faults.get(namespace);
@@ -6080,11 +6146,16 @@ var createWebhookHub = (options) => {
6080
6146
  transport = policy;
6081
6147
  },
6082
6148
  pending(namespace) {
6083
- const ids = new Set([...deliveries.values()].filter((d) => d.namespace === namespace && d.state === "pending").map((d) => d.id));
6149
+ const inScope = (name) => namespace === void 0 || name === namespace;
6150
+ const ids = new Set([...deliveries.values()].filter((d) => inScope(d.namespace) && d.state === "pending").map((d) => d.id));
6084
6151
  for (const [id2, active] of activeDeliveries)
6085
- if (active.namespace === namespace)
6152
+ if (inScope(active.namespace))
6086
6153
  ids.add(id2);
6087
- return ids.size + (held.get(namespace)?.length ?? 0);
6154
+ let waiting = 0;
6155
+ for (const [name, messages2] of held)
6156
+ if (inScope(name))
6157
+ waiting += messages2.length;
6158
+ return ids.size + waiting;
6088
6159
  },
6089
6160
  snapshot(namespace) {
6090
6161
  if (hub.pending(namespace) > 0)
@@ -6441,6 +6512,15 @@ var realSleep = (ms, signal) => new Promise((resolve, reject) => {
6441
6512
  }, ms);
6442
6513
  signal?.addEventListener("abort", abort, { once: true });
6443
6514
  });
6515
+ var hostHeapUsed = () => {
6516
+ const host = globalThis;
6517
+ return host.process?.memoryUsage?.().heapUsed;
6518
+ };
6519
+ var optionalCount = (value, label, least) => {
6520
+ if (value !== void 0 && !(Number.isSafeInteger(value) && value >= least))
6521
+ throw new RangeError(`${label} must be an integer of at least ${least} (got ${value})`);
6522
+ return value;
6523
+ };
6444
6524
  var NULL_BODY_STATUS = /* @__PURE__ */ new Set([101, 204, 205, 304]);
6445
6525
  var truncateResponse = (response, bytes) => {
6446
6526
  if (NULL_BODY_STATUS.has(response.status))
@@ -6518,6 +6598,25 @@ var createRuntime = (options) => {
6518
6598
  const wallNow = options.io?.wallNow ?? Date.now;
6519
6599
  const monotonicNow = options.io?.monotonicNow ?? (() => performance.now());
6520
6600
  const sleep = options.io?.sleep ?? realSleep;
6601
+ const heapUsedBytes = options.io?.heapUsedBytes ?? hostHeapUsed;
6602
+ const idleMs = optionalCount(options.namespaceIdleMs, "namespaceIdleMs", 0) ?? 0;
6603
+ const maxSnapshots = optionalCount(options.maxSnapshots, "maxSnapshots", 1);
6604
+ const maxRecords = optionalCount(options.maxRecords, "maxRecords", 1);
6605
+ if (maxRecords !== void 0)
6606
+ setRecordLimit(sqlite, options.name, maxRecords);
6607
+ const lastSeen = /* @__PURE__ */ new Map();
6608
+ const touch = (name) => {
6609
+ if (idleMs > 0 && name !== DEFAULT_NAMESPACE)
6610
+ lastSeen.set(name, wallNow());
6611
+ };
6612
+ const inFlight2 = /* @__PURE__ */ new Map();
6613
+ const expiring = /* @__PURE__ */ new Map();
6614
+ const cleanup = {
6615
+ namespacesExpired: 0,
6616
+ idleExpiryFailures: 0,
6617
+ recordLimitRefusals: 0,
6618
+ snapshotLimitRefusals: 0
6619
+ };
6521
6620
  const metrics = createMetrics();
6522
6621
  const upstreamModes = /* @__PURE__ */ new Map();
6523
6622
  const bootUpstream = options.upstream ? upstreamState({
@@ -6551,6 +6650,7 @@ var createRuntime = (options) => {
6551
6650
  const operationIdFor = options.document ? operationMatcher(options.document) : () => void 0;
6552
6651
  const controls = createNamespaceControls({
6553
6652
  seed,
6653
+ onStart: (namespace) => touch(namespace),
6554
6654
  clock: namespaceClock,
6555
6655
  boot,
6556
6656
  ...options.presets ? { presets: options.presets } : {},
@@ -6606,11 +6706,16 @@ var createRuntime = (options) => {
6606
6706
  instances.set(key, created);
6607
6707
  namespaceForStorage.set(key, publicNamespace);
6608
6708
  publicNamespaces.add(publicNamespace);
6709
+ touch(publicNamespace);
6609
6710
  if (key === publicNamespace)
6610
6711
  controls.ensure(key);
6611
6712
  return created;
6612
6713
  };
6613
- const instance = (name = DEFAULT_NAMESPACE) => instanceFor(name);
6714
+ const instance = (name = DEFAULT_NAMESPACE) => {
6715
+ const found = instanceFor(name);
6716
+ touch(name);
6717
+ return found;
6718
+ };
6614
6719
  const clockOf = (namespace) => {
6615
6720
  const own = namespaceClock(namespace);
6616
6721
  return Object.freeze({ ...own.state(), pinned: own.pinned() });
@@ -6804,7 +6909,46 @@ var createRuntime = (options) => {
6804
6909
  rngs.delete(name);
6805
6910
  namespaceClocks.delete(name);
6806
6911
  controls.forget(name);
6912
+ lastSeen.delete(name);
6913
+ };
6914
+ const expire = async (name, seen) => {
6915
+ try {
6916
+ await dropNamespace(name);
6917
+ cleanup.namespacesExpired++;
6918
+ } catch {
6919
+ cleanup.idleExpiryFailures++;
6920
+ if (publicNamespaces.has(name) && !lastSeen.has(name))
6921
+ lastSeen.set(name, seen);
6922
+ }
6923
+ };
6924
+ const forgetIdle = async (current) => {
6925
+ if (idleMs === 0)
6926
+ return;
6927
+ const now = wallNow();
6928
+ for (const [name, seen] of [...lastSeen]) {
6929
+ if (name === current || now - seen <= idleMs || expiring.has(name))
6930
+ continue;
6931
+ if ((inFlight2.get(name) ?? 0) > 0)
6932
+ continue;
6933
+ if ((options.webhooks?.pending(name) ?? 0) > 0)
6934
+ continue;
6935
+ lastSeen.delete(name);
6936
+ const dropping = expire(name, seen).finally(() => expiring.delete(name));
6937
+ expiring.set(name, dropping);
6938
+ await dropping;
6939
+ }
6807
6940
  };
6941
+ const storagePrefix = `${options.name}:`;
6942
+ const countRecords = sqlite.prepare("SELECT COUNT(*) AS n FROM mockingbird_records WHERE namespace = ? OR (namespace >= ? AND namespace < ?)");
6943
+ const resources = () => ({
6944
+ namespaces: publicNamespaces.size,
6945
+ records: Number(countRecords.get(options.name, storagePrefix, `${options.name};`)?.n ?? 0),
6946
+ journalEntries: journal.count(),
6947
+ snapshots: [...kept.values()].reduce((total, each) => total + each.size, 0),
6948
+ webhooksPending: options.webhooks?.pending() ?? 0,
6949
+ heapUsedBytes: heapUsedBytes() ?? null,
6950
+ ...cleanup
6951
+ });
6808
6952
  const captureAll = (namespace) => {
6809
6953
  instance(namespace);
6810
6954
  const state = capture(namespace);
@@ -6959,6 +7103,15 @@ var createRuntime = (options) => {
6959
7103
  };
6960
7104
  const kept = /* @__PURE__ */ new Map();
6961
7105
  const snapshotCounters = /* @__PURE__ */ new Map();
7106
+ const assertSnapshotRoom = (namespace, id) => {
7107
+ const store = kept.get(namespace);
7108
+ if (maxSnapshots === void 0 || !store || store.size < maxSnapshots)
7109
+ return;
7110
+ if (id !== void 0 && store.has(id))
7111
+ return;
7112
+ cleanup.snapshotLimitRefusals++;
7113
+ throw new ControlError(`namespace ${namespace} already holds ${maxSnapshots} snapshots, the most maxSnapshots allows; delete one or reuse its name`);
7114
+ };
6962
7115
  const keep = (namespace, given, point) => {
6963
7116
  let store = kept.get(namespace);
6964
7117
  if (!store) {
@@ -6984,14 +7137,20 @@ var createRuntime = (options) => {
6984
7137
  return info;
6985
7138
  };
6986
7139
  const snapshotStore = {
6987
- create: (namespace, id) => keep(namespace, id, captureAll(namespace)),
7140
+ create(namespace, id) {
7141
+ assertSnapshotRoom(namespace, id);
7142
+ return keep(namespace, id, captureAll(namespace));
7143
+ },
6988
7144
  list: (namespace) => [...kept.get(namespace)?.values() ?? []].map((each) => each.info),
6989
7145
  get: (namespace, id) => kept.get(namespace)?.get(id)?.info,
6990
7146
  export(namespace, id) {
6991
7147
  const found = kept.get(namespace)?.get(id);
6992
7148
  return found ? toDocument(found) : void 0;
6993
7149
  },
6994
- import: (namespace, id, document) => keep(namespace, id, fromDocument(namespace, document)),
7150
+ import(namespace, id, document) {
7151
+ assertSnapshotRoom(namespace, id);
7152
+ return keep(namespace, id, fromDocument(namespace, document));
7153
+ },
6995
7154
  restore(namespace, id) {
6996
7155
  const found = kept.get(namespace)?.get(id);
6997
7156
  if (!found)
@@ -7112,6 +7271,7 @@ var createRuntime = (options) => {
7112
7271
  namespaces: () => [...publicNamespaces].sort(),
7113
7272
  reset,
7114
7273
  dropNamespace,
7274
+ resources,
7115
7275
  controls: (namespace = DEFAULT_NAMESPACE) => describeControls(namespace),
7116
7276
  configure(document, namespace = DEFAULT_NAMESPACE) {
7117
7277
  applyControls(namespace, normalizeControls(document));
@@ -7145,14 +7305,14 @@ var createRuntime = (options) => {
7145
7305
  let request = incoming;
7146
7306
  const prefixed = matchNamespacePath(new URL(request.url).pathname, adminPrefix);
7147
7307
  if (prefixed) {
7148
- const url2 = new URL(request.url);
7149
- url2.pathname = prefixed[2] ?? "/";
7308
+ const url = new URL(request.url);
7309
+ url.pathname = prefixed[2] ?? "/";
7150
7310
  const headers = new Headers(request.headers);
7151
7311
  if (!headers.has(NAMESPACE_HEADER)) {
7152
7312
  headers.set(NAMESPACE_HEADER, decodeURIComponent(prefixed[1]));
7153
7313
  }
7154
7314
  const hasBody = request.method !== "GET" && request.method !== "HEAD";
7155
- request = forwardRequestContext(request, new Request(url2, {
7315
+ request = forwardRequestContext(request, new Request(url, {
7156
7316
  method: request.method,
7157
7317
  headers,
7158
7318
  ...hasBody ? { body: await request.arrayBuffer() } : {},
@@ -7174,274 +7334,303 @@ var createRuntime = (options) => {
7174
7334
  if (mapped !== void 0)
7175
7335
  namespace = mapped;
7176
7336
  }
7177
- const selectedBranch = request.headers.get(BRANCH_HEADER) ?? "main";
7178
- const at = request.headers.get(AT_HEADER) ?? void 0;
7179
- const stamp = (response2) => {
7180
- const value = KEY_PATTERN.test(namespace) ? `${options.name}@${version}; ns=${namespace}` : `${options.name}@${version}`;
7337
+ for (let dropping = expiring.get(namespace); dropping; dropping = expiring.get(namespace))
7338
+ await dropping;
7339
+ inFlight2.set(namespace, (inFlight2.get(namespace) ?? 0) + 1);
7340
+ if (publicNamespaces.has(namespace))
7341
+ touch(namespace);
7342
+ try {
7343
+ await forgetIdle(namespace);
7344
+ const selectedBranch = request.headers.get(BRANCH_HEADER) ?? "main";
7345
+ const at = request.headers.get(AT_HEADER) ?? void 0;
7346
+ const stamp = (response2) => {
7347
+ const value = KEY_PATTERN.test(namespace) ? `${options.name}@${version}; ns=${namespace}` : `${options.name}@${version}`;
7348
+ try {
7349
+ response2.headers.set(MOCKINGBIRD_HEADER, value);
7350
+ return response2;
7351
+ } catch {
7352
+ const copy = new Response(response2.body, response2);
7353
+ copy.headers.set(MOCKINGBIRD_HEADER, value);
7354
+ return copy;
7355
+ }
7356
+ };
7357
+ if (obsoleteInternalPath)
7358
+ return stamp(adminFail(404, "internal transport is only available under adminPrefix"));
7359
+ const handled = internal ? void 0 : await control.handle(request);
7360
+ if (handled)
7361
+ return stamp(handled);
7362
+ const started = monotonicNow();
7363
+ const url = new URL(request.url);
7364
+ const operationId = operationIdFor(request, url.pathname);
7365
+ let forwarded = false;
7366
+ let accepted;
7367
+ let acceptedNotes;
7368
+ let waitedMs = 0;
7369
+ let virtualTime = false;
7370
+ let requestClock = clock;
7371
+ const contentLength = request.headers.get("content-length");
7372
+ const received = {
7373
+ contentType: request.headers.get("content-type"),
7374
+ bodyBytes: contentLength !== null && /^\d+$/.test(contentLength) ? Number(contentLength) : null,
7375
+ transferEncoding: request.headers.get("transfer-encoding")
7376
+ };
7377
+ const log = (status, faultId, response2) => {
7378
+ const noted = { ...acceptedNotes, ...response2 ? responseNotes(response2) : {} };
7379
+ const rejected = status >= 400 && faultId === void 0;
7380
+ const entry = {
7381
+ service: options.name,
7382
+ ...forwarded ? { upstream: true } : {},
7383
+ namespace,
7384
+ operationId,
7385
+ method: request.method,
7386
+ path: url.pathname,
7387
+ status,
7388
+ durationMs: virtualTime ? waitedMs : Math.round((monotonicNow() - started) * 100) / 100,
7389
+ unmatched: options.document !== void 0 && operationId === void 0,
7390
+ ...faultId !== void 0 ? { faultId } : {},
7391
+ ...waitedMs > 0 ? { delayMs: waitedMs } : {},
7392
+ ...noted?.ids && Object.keys(noted.ids).length > 0 ? { ids: noted.ids } : {},
7393
+ ...noted?.adopted ? { adopted: true } : {},
7394
+ ...accepted ? { accepted: true, checkpoint: accepted.id } : {},
7395
+ ...rejected ? { request: { ...received } } : {},
7396
+ ...rejected && noted?.issues && noted.issues.length > 0 ? { issues: noted.issues.map((issue) => ({ ...issue })) } : {}
7397
+ };
7398
+ metrics.record(entry);
7399
+ journal.record({ ...entry, at: new Date(requestClock.now()).toISOString() });
7400
+ options.onLog?.(entry);
7401
+ };
7402
+ if (!KEY_PATTERN.test(namespace)) {
7403
+ log(400);
7404
+ return stamp(new Response(JSON.stringify({
7405
+ error: {
7406
+ type: "mockingbird_admin",
7407
+ message: `${NAMESPACE_HEADER} must match ${KEY_PATTERN}`
7408
+ }
7409
+ }), { status: 400, headers: { "content-type": "application/json; charset=utf-8" } }));
7410
+ }
7411
+ if (!KEY_PATTERN.test(selectedBranch)) {
7412
+ log(400);
7413
+ return stamp(adminFail(400, `${BRANCH_HEADER} must match ${KEY_PATTERN}`));
7414
+ }
7415
+ requestClock = namespaceClock(namespace);
7416
+ const refuse = (status, message) => {
7417
+ log(status);
7418
+ return stamp(adminFail(status, message));
7419
+ };
7420
+ let requested;
7421
+ let scripted = [];
7181
7422
  try {
7182
- response2.headers.set(MOCKINGBIRD_HEADER, value);
7183
- return response2;
7184
- } catch {
7185
- const copy = new Response(response2.body, response2);
7186
- copy.headers.set(MOCKINGBIRD_HEADER, value);
7187
- return copy;
7423
+ requested = parseControlHeaders(request.headers);
7424
+ if (requested)
7425
+ scripted = controls.scriptFaults(namespace, {
7426
+ ...requested.fault ? { fault: requested.fault } : {},
7427
+ ...requested.timeout !== void 0 ? { timeoutMs: requested.timeout } : {}
7428
+ });
7429
+ const lost = requested?.restore !== void 0 ? CONTROL_HEADERS.restore : at && AT_HEADER;
7430
+ if (requested?.snapshot !== void 0 && !requested.reset)
7431
+ assertSnapshotRoom(namespace, requested.snapshot);
7432
+ if (requested?.reset && lost)
7433
+ throw new ControlError(`${CONTROL_HEADERS.reset}: a reset discards snapshots and history, so ${lost} cannot follow it`);
7434
+ } catch (error) {
7435
+ if (error instanceof ControlError)
7436
+ return refuse(400, error.message);
7437
+ throw error;
7188
7438
  }
7189
- };
7190
- if (obsoleteInternalPath)
7191
- return stamp(adminFail(404, "internal transport is only available under adminPrefix"));
7192
- const handled = internal ? void 0 : await control.handle(request);
7193
- if (handled)
7194
- return stamp(handled);
7195
- const started = monotonicNow();
7196
- const url = new URL(request.url);
7197
- const operationId = operationIdFor(request, url.pathname);
7198
- let forwarded = false;
7199
- let accepted;
7200
- let acceptedNotes;
7201
- let waitedMs = 0;
7202
- let virtualTime = false;
7203
- let requestClock = clock;
7204
- const contentLength = request.headers.get("content-length");
7205
- const received = {
7206
- contentType: request.headers.get("content-type"),
7207
- bodyBytes: contentLength !== null && /^\d+$/.test(contentLength) ? Number(contentLength) : null,
7208
- transferEncoding: request.headers.get("transfer-encoding")
7209
- };
7210
- const log = (status, faultId, response2) => {
7211
- const noted = { ...acceptedNotes, ...response2 ? responseNotes(response2) : {} };
7212
- const rejected = status >= 400 && faultId === void 0;
7213
- const entry = {
7214
- service: options.name,
7215
- ...forwarded ? { upstream: true } : {},
7216
- namespace,
7439
+ const rewinds = at !== void 0 && selectedBranch === "main" && MUTATING_METHODS.has(request.method);
7440
+ if ((requested || rewinds) && options.adminKey !== void 0 && !hasAdminKey(request.headers, options.adminKey))
7441
+ return refuse(401, `control headers need ${ADMIN_KEY_HEADER}`);
7442
+ controls.ensure(namespace);
7443
+ if (requested?.restore !== void 0 && !snapshotStore.get(namespace, requested.restore))
7444
+ return refuse(404, `no snapshot ${requested.restore} in namespace ${namespace}`);
7445
+ if (at !== void 0) {
7446
+ try {
7447
+ timeline(namespace).get(at);
7448
+ } catch (error) {
7449
+ return refuse(409, error instanceof Error ? error.message : String(error));
7450
+ }
7451
+ }
7452
+ if (requested) {
7453
+ if (requested.reset)
7454
+ await reset(namespace);
7455
+ if (requested.restore !== void 0)
7456
+ snapshotStore.restore(namespace, requested.restore);
7457
+ if (requested.seed !== void 0)
7458
+ controls.reseed(namespace, requested.seed);
7459
+ if (requested.time !== void 0)
7460
+ controls.changeClock(namespace, { frozen: true, now: requested.time });
7461
+ if (requested.advance !== void 0)
7462
+ controls.changeClock(namespace, { advanceMs: requested.advance });
7463
+ if (requested.virtualTime !== void 0)
7464
+ controls.apply(namespace, { virtualTime: requested.virtualTime });
7465
+ }
7466
+ let storage;
7467
+ try {
7468
+ if (at !== void 0 && selectedBranch === "main" && !MUTATING_METHODS.has(request.method)) {
7469
+ const point = timeline(namespace).get(at);
7470
+ storage = physicalBranch(namespace, `at_${at}`);
7471
+ let viewRng = rngs.get(storage);
7472
+ if (!viewRng) {
7473
+ viewRng = createRng(seedOf(namespace));
7474
+ instanceFor(storage, namespace, viewRng);
7475
+ }
7476
+ viewRng.setState(point.value.rngState);
7477
+ restoreStorage(storage, point.value.snapshot);
7478
+ captured.set(storage, point.value.snapshot);
7479
+ } else {
7480
+ storage = ensureBranch(namespace, selectedBranch, at);
7481
+ }
7482
+ } catch (error) {
7483
+ log(409);
7484
+ return stamp(adminFail(409, error instanceof Error ? error.message : String(error)));
7485
+ }
7486
+ const settings = controls.settings(namespace);
7487
+ virtualTime = settings.virtualTime;
7488
+ if (settings.autoAdvanceMs > 0)
7489
+ requestClock.advance(settings.autoAdvanceMs);
7490
+ const wait = async (ms) => {
7491
+ if (!(ms > 0))
7492
+ return;
7493
+ waitedMs += ms;
7494
+ if (virtualTime)
7495
+ requestClock.advance(ms);
7496
+ else
7497
+ await sleepUnlessAborted(ms, request.signal);
7498
+ };
7499
+ const candidate = {
7217
7500
  operationId,
7218
7501
  method: request.method,
7219
7502
  path: url.pathname,
7220
- status,
7221
- durationMs: virtualTime ? waitedMs : Math.round((monotonicNow() - started) * 100) / 100,
7222
- unmatched: options.document !== void 0 && operationId === void 0,
7223
- ...faultId !== void 0 ? { faultId } : {},
7224
- ...waitedMs > 0 ? { delayMs: waitedMs } : {},
7225
- ...noted?.ids && Object.keys(noted.ids).length > 0 ? { ids: noted.ids } : {},
7226
- ...noted?.adopted ? { adopted: true } : {},
7227
- ...accepted ? { accepted: true, checkpoint: accepted.id } : {},
7228
- ...rejected ? { request: { ...received } } : {},
7229
- ...rejected && noted?.issues && noted.issues.length > 0 ? { issues: noted.issues.map((issue) => ({ ...issue })) } : {}
7503
+ namespace,
7504
+ headers: request.headers,
7505
+ query: url.searchParams,
7506
+ // Read from a copy, so the service still gets the body. Not JSON: nothing to match.
7507
+ readJson: async () => {
7508
+ try {
7509
+ return JSON.parse(await request.clone().text());
7510
+ } catch {
7511
+ return void 0;
7512
+ }
7513
+ },
7514
+ wait
7230
7515
  };
7231
- metrics.record(entry);
7232
- journal.record({ ...entry, at: new Date(requestClock.now()).toISOString() });
7233
- options.onLog?.(entry);
7234
- };
7235
- if (!KEY_PATTERN.test(namespace)) {
7236
- log(400);
7237
- return stamp(new Response(JSON.stringify({
7238
- error: {
7239
- type: "mockingbird_admin",
7240
- message: `${NAMESPACE_HEADER} must match ${KEY_PATTERN}`
7241
- }
7242
- }), { status: 400, headers: { "content-type": "application/json; charset=utf-8" } }));
7243
- }
7244
- if (!KEY_PATTERN.test(selectedBranch)) {
7245
- log(400);
7246
- return stamp(adminFail(400, `${BRANCH_HEADER} must match ${KEY_PATTERN}`));
7247
- }
7248
- requestClock = namespaceClock(namespace);
7249
- const refuse = (status, message) => {
7250
- log(status);
7251
- return stamp(adminFail(status, message));
7252
- };
7253
- let requested;
7254
- let scripted = [];
7255
- try {
7256
- requested = parseControlHeaders(request.headers);
7257
- if (requested)
7258
- scripted = controls.scriptFaults(namespace, {
7259
- ...requested.fault ? { fault: requested.fault } : {},
7260
- ...requested.timeout !== void 0 ? { timeoutMs: requested.timeout } : {}
7261
- });
7262
- const lost = requested?.restore !== void 0 ? CONTROL_HEADERS.restore : at && AT_HEADER;
7263
- if (requested?.reset && lost)
7264
- throw new ControlError(`${CONTROL_HEADERS.reset}: a reset discards snapshots and history, so ${lost} cannot follow it`);
7265
- } catch (error) {
7266
- if (error instanceof ControlError)
7267
- return refuse(400, error.message);
7268
- throw error;
7269
- }
7270
- const rewinds = at !== void 0 && selectedBranch === "main" && MUTATING_METHODS.has(request.method);
7271
- if ((requested || rewinds) && options.adminKey !== void 0 && !hasAdminKey(request.headers, options.adminKey))
7272
- return refuse(401, `control headers need ${ADMIN_KEY_HEADER}`);
7273
- controls.ensure(namespace);
7274
- if (requested?.restore !== void 0 && !snapshotStore.get(namespace, requested.restore))
7275
- return refuse(404, `no snapshot ${requested.restore} in namespace ${namespace}`);
7276
- if (at !== void 0) {
7516
+ let hits;
7277
7517
  try {
7278
- timeline(namespace).get(at);
7518
+ await wait(latency.take(namespace, operationId) + (requested?.delay ?? 0));
7519
+ hits = scripted.length > 0 ? await faults.fire(scripted, candidate) : [];
7520
+ if (!hits.some((hit) => hit.drop || hit.response))
7521
+ hits.push(...await faults.take({ ...candidate, now: requestClock.now() }));
7279
7522
  } catch (error) {
7280
- return refuse(409, error instanceof Error ? error.message : String(error));
7523
+ log(0);
7524
+ throw error;
7281
7525
  }
7282
- }
7283
- if (requested) {
7284
- if (requested.reset)
7285
- await reset(namespace);
7286
- if (requested.restore !== void 0)
7287
- snapshotStore.restore(namespace, requested.restore);
7288
- if (requested.seed !== void 0)
7289
- controls.reseed(namespace, requested.seed);
7290
- if (requested.time !== void 0)
7291
- controls.changeClock(namespace, { frozen: true, now: requested.time });
7292
- if (requested.advance !== void 0)
7293
- controls.changeClock(namespace, { advanceMs: requested.advance });
7294
- if (requested.virtualTime !== void 0)
7295
- controls.apply(namespace, { virtualTime: requested.virtualTime });
7296
- }
7297
- let storage;
7298
- try {
7299
- if (at !== void 0 && selectedBranch === "main" && !MUTATING_METHODS.has(request.method)) {
7300
- const point = timeline(namespace).get(at);
7301
- storage = physicalBranch(namespace, `at_${at}`);
7302
- let viewRng = rngs.get(storage);
7303
- if (!viewRng) {
7304
- viewRng = createRng(seedOf(namespace));
7305
- instanceFor(storage, namespace, viewRng);
7526
+ const final = hits.find((hit) => hit.drop || hit.response);
7527
+ const finish = (response2) => {
7528
+ let out = response2;
7529
+ const truncate = hits.find((hit) => hit.truncate !== void 0)?.truncate;
7530
+ if (truncate !== void 0)
7531
+ out = truncateResponse(out, truncate);
7532
+ const shaped = final ?? hits[0];
7533
+ if (shaped) {
7534
+ out = mutableResponse(out);
7535
+ out.headers.set(FAULT_HEADER, shaped.id);
7306
7536
  }
7307
- viewRng.setState(point.value.rngState);
7308
- restoreStorage(storage, point.value.snapshot);
7309
- captured.set(storage, point.value.snapshot);
7310
- } else {
7311
- storage = ensureBranch(namespace, selectedBranch, at);
7537
+ if (requested?.snapshot !== void 0) {
7538
+ out = mutableResponse(out);
7539
+ out.headers.set(SNAPSHOT_HEADER, snapshotStore.create(namespace, requested.snapshot).id);
7540
+ }
7541
+ return stamp(out);
7542
+ };
7543
+ if (final?.drop) {
7544
+ log(0, final.id);
7545
+ throw new DroppedConnectionError(final.timeout ? "timeout" : "drop");
7312
7546
  }
7313
- } catch (error) {
7314
- log(409);
7315
- return stamp(adminFail(409, error instanceof Error ? error.message : String(error)));
7316
- }
7317
- const settings = controls.settings(namespace);
7318
- virtualTime = settings.virtualTime;
7319
- if (settings.autoAdvanceMs > 0)
7320
- requestClock.advance(settings.autoAdvanceMs);
7321
- const wait = async (ms) => {
7322
- if (!(ms > 0))
7323
- return;
7324
- waitedMs += ms;
7325
- if (virtualTime)
7326
- requestClock.advance(ms);
7327
- else
7328
- await sleepUnlessAborted(ms, request.signal);
7329
- };
7330
- const candidate = {
7331
- operationId,
7332
- method: request.method,
7333
- path: url.pathname,
7334
- namespace,
7335
- headers: request.headers,
7336
- query: url.searchParams,
7337
- // Read from a copy, so the service still gets the body. Not JSON: nothing to match.
7338
- readJson: async () => {
7547
+ if (final?.response) {
7548
+ log(final.response.status, final.id);
7549
+ return finish(final.response);
7550
+ }
7551
+ const upstream = getUpstream(namespace);
7552
+ const wantsForward = (requested?.upstream ?? upstream?.mode) === "forward";
7553
+ if (wantsForward) {
7554
+ if (!options.upstream || !upstream)
7555
+ return refuse(409, "an upstream fetch and baseUrl are required");
7556
+ if (options.canForward && !options.canForward(request))
7557
+ return refuse(501, "forwarding this operation is not supported");
7558
+ const captureRequest = options.onForwardResponse ? request.clone() : void 0;
7559
+ forwarded = true;
7560
+ let response2;
7339
7561
  try {
7340
- return JSON.parse(await request.clone().text());
7562
+ let outgoing = (options.upstreamRequest ?? upstreamRequest)(request, upstream.baseUrl);
7563
+ if (options.upstream.rewriteAuth)
7564
+ outgoing = await options.upstream.rewriteAuth(outgoing);
7565
+ response2 = await options.upstream.fetch(outgoing);
7341
7566
  } catch {
7342
- return void 0;
7567
+ log(0, hits[0]?.id);
7568
+ throw new DroppedConnectionError("drop");
7343
7569
  }
7344
- },
7345
- wait
7346
- };
7347
- let hits;
7348
- try {
7349
- await wait(latency.take(namespace, operationId) + (requested?.delay ?? 0));
7350
- hits = scripted.length > 0 ? await faults.fire(scripted, candidate) : [];
7351
- if (!hits.some((hit) => hit.drop || hit.response))
7352
- hits.push(...await faults.take({ ...candidate, now: requestClock.now() }));
7353
- } catch (error) {
7354
- log(0);
7355
- throw error;
7356
- }
7357
- const final = hits.find((hit) => hit.drop || hit.response);
7358
- const finish = (response2) => {
7359
- let out = response2;
7360
- const truncate = hits.find((hit) => hit.truncate !== void 0)?.truncate;
7361
- if (truncate !== void 0)
7362
- out = truncateResponse(out, truncate);
7363
- const shaped = final ?? hits[0];
7364
- if (shaped) {
7365
- out = mutableResponse(out);
7366
- out.headers.set(FAULT_HEADER, shaped.id);
7367
- }
7368
- if (requested?.snapshot !== void 0) {
7369
- out = mutableResponse(out);
7370
- out.headers.set(SNAPSHOT_HEADER, snapshotStore.create(namespace, requested.snapshot).id);
7570
+ if (captureRequest && response2.ok && options.onForwardResponse) {
7571
+ await options.onForwardResponse(instanceFor(storage, namespace), captureRequest, response2.clone());
7572
+ }
7573
+ log(response2.status, hits[0]?.id, response2);
7574
+ return finish(response2);
7371
7575
  }
7372
- return stamp(out);
7373
- };
7374
- if (final?.drop) {
7375
- log(0, final.id);
7376
- throw new DroppedConnectionError(final.timeout ? "timeout" : "drop");
7377
- }
7378
- if (final?.response) {
7379
- log(final.response.status, final.id);
7380
- return finish(final.response);
7381
- }
7382
- const upstream = getUpstream(namespace);
7383
- const wantsForward = (requested?.upstream ?? upstream?.mode) === "forward";
7384
- if (wantsForward) {
7385
- if (!options.upstream || !upstream)
7386
- return refuse(409, "an upstream fetch and baseUrl are required");
7387
- if (options.canForward && !options.canForward(request))
7388
- return refuse(501, "forwarding this operation is not supported");
7389
- const captureRequest = options.onForwardResponse ? request.clone() : void 0;
7390
- forwarded = true;
7391
- let response2;
7576
+ const fired = hits.filter((hit) => hit.effect !== void 0);
7577
+ if (fired.length > 0)
7578
+ effects.set(request, fired.map((hit) => hit.effect));
7579
+ let active = true;
7580
+ acceptance.set(request, (notes) => {
7581
+ if (!checkpointMutations || !active || accepted || !MUTATING_METHODS.has(request.method))
7582
+ return;
7583
+ accepted = timeline(namespace).commit(capture(storage), { branch: selectedBranch });
7584
+ acceptedNotes = notes;
7585
+ });
7586
+ let response;
7587
+ const writes = maxRecords !== void 0 ? openJournal(sqlite, storageNamespace(storage)) : void 0;
7588
+ const refuseAtCap = (error) => {
7589
+ writes?.restore(sqlite, storageNamespace(storage));
7590
+ cleanup.recordLimitRefusals++;
7591
+ log(507, hits[0]?.id);
7592
+ return finish(recordLimitResponse(error));
7593
+ };
7392
7594
  try {
7393
- let outgoing = (options.upstreamRequest ?? upstreamRequest)(request, upstream.baseUrl);
7394
- if (options.upstream.rewriteAuth)
7395
- outgoing = await options.upstream.rewriteAuth(outgoing);
7396
- response2 = await options.upstream.fetch(outgoing);
7397
- } catch {
7398
- log(0, hits[0]?.id);
7399
- throw new DroppedConnectionError("drop");
7595
+ response = await instanceFor(storage, namespace).fetch(request);
7596
+ } catch (error) {
7597
+ if (error instanceof RecordLimitError)
7598
+ return refuseAtCap(error);
7599
+ log(error instanceof DroppedConnectionError ? 0 : 500, hits[0]?.id);
7600
+ throw error;
7601
+ } finally {
7602
+ active = false;
7603
+ acceptance.delete(request);
7604
+ if (writes)
7605
+ closeJournal(sqlite, storageNamespace(storage), writes);
7400
7606
  }
7401
- if (captureRequest && response2.ok && options.onForwardResponse) {
7402
- await options.onForwardResponse(instanceFor(storage, namespace), captureRequest, response2.clone());
7607
+ if (writes?.limitHit instanceof RecordLimitError)
7608
+ return refuseAtCap(writes.limitHit);
7609
+ const wireStatus = responseNotes(response)?.wireStatus ?? response.status;
7610
+ if (checkpointMutations && MUTATING_METHODS.has(request.method) && wireStatus >= 200 && wireStatus < 400) {
7611
+ const current = capture(storage);
7612
+ const unchanged = accepted && timeline(namespace).head(selectedBranch)?.id === accepted.id && current.snapshot.records === accepted.value.snapshot.records && current.snapshot.sequences === accepted.value.snapshot.sequences && current.rngState === accepted.value.rngState;
7613
+ const point = unchanged && accepted ? accepted : timeline(namespace).commit(current, { branch: selectedBranch });
7614
+ response = mutableResponse(response);
7615
+ response.headers.set(CHECKPOINT_HEADER, point.id);
7403
7616
  }
7404
- log(response2.status, hits[0]?.id, response2);
7405
- return finish(response2);
7406
- }
7407
- const fired = hits.filter((hit) => hit.effect !== void 0);
7408
- if (fired.length > 0)
7409
- effects.set(request, fired.map((hit) => hit.effect));
7410
- let active = true;
7411
- acceptance.set(request, (notes) => {
7412
- if (!checkpointMutations || !active || accepted || !MUTATING_METHODS.has(request.method))
7413
- return;
7414
- accepted = timeline(namespace).commit(capture(storage), { branch: selectedBranch });
7415
- acceptedNotes = notes;
7416
- });
7417
- let response;
7418
- try {
7419
- response = await instanceFor(storage, namespace).fetch(request);
7420
- } catch (error) {
7421
- log(error instanceof DroppedConnectionError ? 0 : 500, hits[0]?.id);
7422
- throw error;
7617
+ if (selectedBranch !== "main") {
7618
+ response = mutableResponse(response);
7619
+ response.headers.set(BRANCH_HEADER, selectedBranch);
7620
+ }
7621
+ if (at !== void 0) {
7622
+ response = mutableResponse(response);
7623
+ response.headers.set(AT_HEADER, at);
7624
+ }
7625
+ log(wireStatus, hits[0]?.id, response);
7626
+ return finish(response);
7423
7627
  } finally {
7424
- active = false;
7425
- acceptance.delete(request);
7426
- }
7427
- const wireStatus = responseNotes(response)?.wireStatus ?? response.status;
7428
- if (checkpointMutations && MUTATING_METHODS.has(request.method) && wireStatus >= 200 && wireStatus < 400) {
7429
- const current = capture(storage);
7430
- const unchanged = accepted && timeline(namespace).head(selectedBranch)?.id === accepted.id && current.snapshot.records === accepted.value.snapshot.records && current.snapshot.sequences === accepted.value.snapshot.sequences && current.rngState === accepted.value.rngState;
7431
- const point = unchanged && accepted ? accepted : timeline(namespace).commit(current, { branch: selectedBranch });
7432
- response = mutableResponse(response);
7433
- response.headers.set(CHECKPOINT_HEADER, point.id);
7434
- }
7435
- if (selectedBranch !== "main") {
7436
- response = mutableResponse(response);
7437
- response.headers.set(BRANCH_HEADER, selectedBranch);
7438
- }
7439
- if (at !== void 0) {
7440
- response = mutableResponse(response);
7441
- response.headers.set(AT_HEADER, at);
7628
+ const left = (inFlight2.get(namespace) ?? 1) - 1;
7629
+ if (left > 0)
7630
+ inFlight2.set(namespace, left);
7631
+ else
7632
+ inFlight2.delete(namespace);
7442
7633
  }
7443
- log(wireStatus, hits[0]?.id, response);
7444
- return finish(response);
7445
7634
  }
7446
7635
  };
7447
7636
  const sleepUnlessAborted = async (ms, signal) => {
@@ -7475,6 +7664,7 @@ var createRuntime = (options) => {
7475
7664
  namespaces: runtime.namespaces,
7476
7665
  reset,
7477
7666
  dropNamespace,
7667
+ resources,
7478
7668
  controls,
7479
7669
  snapshots: snapshotStore,
7480
7670
  applyControls,
@@ -7680,6 +7870,8 @@ export {
7680
7870
  awsParseXml,
7681
7871
  awsXmlEscape,
7682
7872
  awsXml,
7873
+ RecordLimitError,
7874
+ setRecordLimit,
7683
7875
  Collection,
7684
7876
  opaqueToken,
7685
7877
  normalizeIdBase,
@@ -7743,4 +7935,4 @@ export {
7743
7935
  signV4,
7744
7936
  putObject
7745
7937
  };
7746
- //# sourceMappingURL=chunk-KD6FHYQP.js.map
7938
+ //# sourceMappingURL=chunk-BK5KDNUE.js.map