@capybara-hq/kernel 0.1.0-rc.146 → 0.1.0-rc.147

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.
Files changed (168) hide show
  1. package/dist/admin/extensions.controller.d.ts +0 -11
  2. package/dist/admin/extensions.controller.js +0 -28
  3. package/dist/admin/health.service.d.ts +25 -1
  4. package/dist/admin/health.service.js +50 -18
  5. package/dist/audit/full-access.d.ts +78 -0
  6. package/dist/audit/full-access.js +283 -0
  7. package/dist/automations/automations.service.d.ts +1 -0
  8. package/dist/automations/automations.service.js +3 -1
  9. package/dist/automations/calendar.js +3 -1
  10. package/dist/automations/grant-rules.d.ts +2 -1
  11. package/dist/automations/grant-rules.js +8 -1
  12. package/dist/automations/unattended.d.ts +13 -1
  13. package/dist/automations/unattended.js +13 -1
  14. package/dist/catalog/admin-catalog.controller.d.ts +8 -0
  15. package/dist/catalog/admin-catalog.controller.js +8 -2
  16. package/dist/catalog/admin-catalog.schemas.d.ts +10 -0
  17. package/dist/catalog/admin-catalog.schemas.js +8 -1
  18. package/dist/catalog/catalog-content.d.ts +6 -0
  19. package/dist/catalog/catalog-scope.service.d.ts +22 -2
  20. package/dist/catalog/catalog-scope.service.js +27 -3
  21. package/dist/catalog/catalog.service.js +19 -2
  22. package/dist/catalog/marketplaces.service.d.ts +1 -1
  23. package/dist/catalog/org-catalog.service.d.ts +8 -1
  24. package/dist/catalog/org-catalog.service.js +36 -3
  25. package/dist/catalog/platform-components.js +3 -2
  26. package/dist/catalog/platform-import-update.d.ts +2 -0
  27. package/dist/catalog/platform-import-update.js +8 -1
  28. package/dist/catalog/plugin-connectors.d.ts +11 -0
  29. package/dist/catalog/plugin-connectors.js +33 -0
  30. package/dist/catalog/plugin-import.d.ts +35 -15
  31. package/dist/catalog/plugin-import.js +110 -35
  32. package/dist/catalog/plugin-install.js +6 -0
  33. package/dist/catalog/provenance.d.ts +2 -0
  34. package/dist/catalog/provenance.js +5 -1
  35. package/dist/config/auto-approve.d.ts +16 -0
  36. package/dist/config/auto-approve.js +24 -0
  37. package/dist/config/capacity-presets.d.ts +243 -0
  38. package/dist/config/capacity-presets.js +195 -0
  39. package/dist/config/env.d.ts +2 -1
  40. package/dist/config/env.js +6 -1
  41. package/dist/config/load.js +15 -0
  42. package/dist/config/schema.d.ts +46 -9
  43. package/dist/config/schema.js +154 -30
  44. package/dist/ctx/net.d.ts +5 -1
  45. package/dist/ctx/net.js +62 -12
  46. package/dist/db/kernel-schema.d.ts +31 -0
  47. package/dist/db/migrator.js +0 -36
  48. package/dist/dial-in/routes.js +1 -1
  49. package/dist/erasure/org-batches.js +1 -6
  50. package/dist/erasure/org-catalog.js +6 -2
  51. package/dist/erasure/org-rules.js +1 -0
  52. package/dist/erasure/org-worker.js +0 -13
  53. package/dist/errors.d.ts +6 -0
  54. package/dist/errors.js +6 -0
  55. package/dist/extensions/admin-ops.d.ts +14 -1
  56. package/dist/extensions/admin-ops.js +30 -3
  57. package/dist/extensions/admin-view.d.ts +21 -1
  58. package/dist/extensions/admin-view.js +43 -0
  59. package/dist/extensions/bootstrap-packages.d.ts +5 -0
  60. package/dist/extensions/bootstrap-packages.js +1 -1
  61. package/dist/extensions/bootstrap-review.d.ts +251 -0
  62. package/dist/extensions/bootstrap-review.js +676 -0
  63. package/dist/extensions/bootstrap.d.ts +21 -1
  64. package/dist/extensions/bootstrap.js +72 -2
  65. package/dist/extensions/cli.d.ts +6 -0
  66. package/dist/extensions/cli.js +4 -0
  67. package/dist/extensions/enabled.d.ts +3 -0
  68. package/dist/extensions/extensions.module.js +9 -0
  69. package/dist/extensions/full-access-disclosure.d.ts +15 -0
  70. package/dist/extensions/full-access-disclosure.js +57 -0
  71. package/dist/extensions/grant-epoch.d.ts +5 -0
  72. package/dist/extensions/grant-epoch.js +9 -0
  73. package/dist/extensions/host.d.ts +71 -2
  74. package/dist/extensions/host.js +293 -27
  75. package/dist/extensions/installs.d.ts +18 -0
  76. package/dist/extensions/installs.js +28 -0
  77. package/dist/extensions/isolated/admission.d.ts +17 -2
  78. package/dist/extensions/isolated/admission.js +15 -7
  79. package/dist/extensions/isolated/authorization.d.ts +8 -2
  80. package/dist/extensions/isolated/authorization.js +11 -3
  81. package/dist/extensions/isolated/broker.d.ts +3 -0
  82. package/dist/extensions/isolated/broker.js +50 -14
  83. package/dist/extensions/isolated/configured-package.d.ts +5 -0
  84. package/dist/extensions/isolated/configured-package.js +2 -0
  85. package/dist/extensions/isolated/lanes.d.ts +44 -3
  86. package/dist/extensions/isolated/lanes.js +263 -80
  87. package/dist/extensions/isolated/metrics.d.ts +146 -0
  88. package/dist/extensions/isolated/metrics.js +304 -0
  89. package/dist/extensions/isolated/revision.d.ts +7 -1
  90. package/dist/extensions/isolated/revision.js +26 -5
  91. package/dist/extensions/isolated/rpc.d.ts +5 -0
  92. package/dist/extensions/isolated/rpc.js +7 -2
  93. package/dist/extensions/isolated/sandbox.d.ts +23 -0
  94. package/dist/extensions/isolated/sandbox.js +50 -0
  95. package/dist/extensions/isolated/status.d.ts +79 -0
  96. package/dist/extensions/isolated/status.js +216 -0
  97. package/dist/extensions/isolated/tier.d.ts +127 -2
  98. package/dist/extensions/isolated/tier.js +266 -7
  99. package/dist/extensions/isolated/usage.d.ts +134 -0
  100. package/dist/extensions/isolated/usage.js +322 -0
  101. package/dist/extensions/lifecycle.d.ts +42 -2
  102. package/dist/extensions/lifecycle.js +100 -4
  103. package/dist/extensions/org-config.js +11 -0
  104. package/dist/extensions/package.d.ts +14 -0
  105. package/dist/extensions/package.js +23 -0
  106. package/dist/extensions/permissions.controller.d.ts +35 -0
  107. package/dist/extensions/permissions.controller.js +98 -0
  108. package/dist/extensions/permissions.schemas.d.ts +288 -0
  109. package/dist/extensions/permissions.schemas.js +96 -0
  110. package/dist/extensions/permissions.service.d.ts +116 -0
  111. package/dist/extensions/permissions.service.js +428 -0
  112. package/dist/extensions/realm-retirement.d.ts +65 -0
  113. package/dist/extensions/realm-retirement.js +150 -0
  114. package/dist/extensions/revision-approvals.d.ts +58 -3
  115. package/dist/extensions/revision-approvals.js +135 -14
  116. package/dist/extensions/revision-review.d.ts +144 -0
  117. package/dist/extensions/revision-review.js +297 -0
  118. package/dist/extensions/revocation.js +3 -0
  119. package/dist/extensions/state.module.js +12 -0
  120. package/dist/git/run-end.d.ts +35 -7
  121. package/dist/git/run-end.js +87 -38
  122. package/dist/http/api.module.js +2 -0
  123. package/dist/identity/audit.d.ts +2 -1
  124. package/dist/identity/audit.js +4 -17
  125. package/dist/index.d.ts +4 -0
  126. package/dist/index.js +4 -0
  127. package/dist/infra/config/kernel-config.service.d.ts +6 -0
  128. package/dist/infra/config/kernel-config.service.js +21 -0
  129. package/dist/infra/outbox/registry.d.ts +13 -0
  130. package/dist/infra/outbox/registry.js +8 -0
  131. package/dist/lifecycle/kernel-lifecycle.d.ts +25 -1
  132. package/dist/lifecycle/kernel-lifecycle.js +73 -18
  133. package/dist/net/private-endpoint-preflight.d.ts +159 -0
  134. package/dist/net/private-endpoint-preflight.js +417 -0
  135. package/dist/net/private-endpoints.d.ts +68 -0
  136. package/dist/net/private-endpoints.js +164 -0
  137. package/dist/net/public-address.d.ts +14 -0
  138. package/dist/net/public-address.js +15 -1
  139. package/dist/net/safe-fetch.d.ts +2 -1
  140. package/dist/net/safe-fetch.js +10 -3
  141. package/dist/overrides.d.ts +4 -0
  142. package/dist/overrides.js +2 -0
  143. package/dist/packages/official-publisher.d.ts +26 -1
  144. package/dist/packages/official-publisher.js +48 -1
  145. package/dist/packages/provenance.d.ts +11 -0
  146. package/dist/packages/provenance.js +24 -0
  147. package/dist/platform/exclusions.js +4 -4
  148. package/dist/platform/ops/automations.ops.js +1 -1
  149. package/dist/platform/ops/catalog-admin.ops.js +25 -4
  150. package/dist/platform/ops/extension-permissions.ops.d.ts +11 -0
  151. package/dist/platform/ops/extension-permissions.ops.js +159 -0
  152. package/dist/platform/platform-ops.module.d.ts +2 -1
  153. package/dist/platform/platform-ops.module.js +2 -0
  154. package/dist/platform/route-schemas.js +2 -0
  155. package/dist/retention/purge-batch.js +10 -14
  156. package/dist/runtime/maintenance.d.ts +4 -2
  157. package/dist/runtime/maintenance.js +16 -3
  158. package/dist/runtime/run-finish.d.ts +3 -3
  159. package/dist/runtime/run-finish.js +7 -3
  160. package/dist/sandbox/permission-availability.d.ts +17 -2
  161. package/dist/sandbox/permission-availability.js +22 -1
  162. package/dist/sandbox/permission-facts.js +7 -1
  163. package/dist/tools/builtins/sandbox/common.js +2 -0
  164. package/dist/tools/pipeline.d.ts +2 -1
  165. package/dist/tools/pipeline.js +7 -2
  166. package/package.json +4 -3
  167. package/src/migrations/0238_extension_usage.sql +40 -0
  168. package/src/migrations/0239_extension_replica_isolation.sql +28 -0
@@ -1,25 +1,11 @@
1
1
  import { randomUUID } from "node:crypto";
2
+ import { STANDARD_CAPACITY } from "../../config/capacity-presets.js";
2
3
  import { canonicalJson } from "../../tools/canonical-json.js";
3
4
  import { startPostgresGate } from "./postgres-gate.js";
4
5
  import { createRpcBudget, IsolatedRpcError, IsolatedRpcPeer, RpcByteChunk, } from "./rpc.js";
5
- import { ExtensionSandboxUnconfirmedCleanupError, startExtensionSandbox, } from "./sandbox.js";
6
- export const MAX_ISOLATED_LANES = 4;
7
- const IDLE_MS = 60_000;
8
- const ADMISSION_TIMEOUT_MS = 15_000;
9
- const CONTROL_WAIT_MS = 2_000;
10
- const MAX_WAITING_CONTROL = 4;
11
- const PROCESS_LIMITS = { serving: MAX_ISOLATED_LANES, control: 1 };
12
- const STARTS_PER_SECOND = { serving: 4, control: 2 };
13
- const INGRESS_LANES = PROCESS_LIMITS.serving + PROCESS_LIMITS.control;
14
- const LANE_FRAMES_PER_SECOND = Math.floor(512 / INGRESS_LANES);
15
- const LANE_BYTES_PER_SECOND = Math.floor((4 * 1024 * 1024) / INGRESS_LANES);
16
- const MAX_WAITING = 32;
17
- const MAX_WAITING_PER_LANE = 4;
18
- const MAX_CALLS_PER_LANE = 8;
19
- const MAX_CALLS = MAX_ISOLATED_LANES * MAX_CALLS_PER_LANE;
20
- const MAX_PREFLIGHTS_PER_ORG = 8;
21
- // Each serving callback can hold one concurrent broker request at full admission.
22
- const MAX_SERVICES_PER_LANE = { serving: MAX_CALLS_PER_LANE, control: 6 };
6
+ import { ExtensionSandboxCapacityError, ExtensionSandboxUnconfirmedCleanupError, startExtensionSandbox, } from "./sandbox.js";
7
+ /** Control lanes: each concurrent broker request of a registration or setup check. */
8
+ const CONTROL_SERVICES_PER_LANE = 6;
23
9
  const CANCELLATION_GRACE_MS = 250;
24
10
  const CRASH_HISTORY_MS = 120_000;
25
11
  const CLEANUP_RETRY_MS = 250;
@@ -27,33 +13,55 @@ const MAX_CLEANUP_RETRY_MS = 15_000;
27
13
  function admissionGroup(orgId, role) {
28
14
  return orgId === undefined ? `deployment:${role ?? "api"}` : `org:${orgId}`;
29
15
  }
30
- function processIngress() {
16
+ /** The ingress budget of one new lane: the extension's per-replica total split across its lanes. */
17
+ function processIngress(limits) {
18
+ const lanes = limits.servingLanes + limits.controlLanes;
19
+ const frames = Math.max(2, Math.floor(limits.ingressFramesPerSecond / lanes));
20
+ const bytes = Math.max(2, Math.floor(limits.ingressBytesPerSecond / lanes));
31
21
  return {
32
- budget: createRpcBudget({
33
- framesPerSecond: LANE_FRAMES_PER_SECOND,
34
- bytesPerSecond: LANE_BYTES_PER_SECOND,
35
- }),
22
+ budget: createRpcBudget({ framesPerSecond: frames, bytesPerSecond: bytes }),
36
23
  requestBudget: createRpcBudget({
37
- framesPerSecond: Math.floor(LANE_FRAMES_PER_SECOND / 2),
38
- bytesPerSecond: Math.floor(LANE_BYTES_PER_SECOND / 2),
24
+ framesPerSecond: Math.floor(frames / 2),
25
+ bytesPerSecond: Math.floor(bytes / 2),
39
26
  }),
40
27
  };
41
28
  }
29
+ /** An `overloaded` refusal before the call reached a lane, with its reason for the metrics. */
30
+ export class IsolatedRejection extends IsolatedRpcError {
31
+ constructor(reason) {
32
+ super("overloaded");
33
+ // Not enumerable: the error still compares equal to a plain `overloaded` error.
34
+ Object.defineProperty(this, "reason", { value: reason });
35
+ }
36
+ }
37
+ function startBudget(rate) {
38
+ return { rate, budget: createRpcBudget({ framesPerSecond: rate, bytesPerSecond: rate }) };
39
+ }
42
40
  export class IsolatedExtensionQuota {
41
+ limits;
43
42
  processes = { serving: 0, control: 0 };
44
43
  calls = 0;
45
44
  services = { serving: 0, control: 0 };
46
45
  preflights = new Map();
47
- starts = {
48
- serving: createRpcBudget({
49
- framesPerSecond: STARTS_PER_SECOND.serving,
50
- bytesPerSecond: STARTS_PER_SECOND.serving,
51
- }),
52
- control: createRpcBudget({
53
- framesPerSecond: STARTS_PER_SECOND.control,
54
- bytesPerSecond: STARTS_PER_SECOND.control,
55
- }),
56
- };
46
+ starts;
47
+ /**
48
+ * `limits` is read at every admission and lane start (the hot capacity fields apply at once).
49
+ * Without it the quota uses the `standard` preset.
50
+ */
51
+ constructor(limits = () => STANDARD_CAPACITY) {
52
+ this.limits = limits;
53
+ const current = limits();
54
+ this.starts = {
55
+ serving: startBudget(current.startsPerSecond),
56
+ control: startBudget(current.controlStartsPerSecond),
57
+ };
58
+ }
59
+ processLimit(kind, limits = this.limits()) {
60
+ return kind === "serving" ? limits.servingLanes : limits.controlLanes;
61
+ }
62
+ startRate(kind, limits) {
63
+ return kind === "serving" ? limits.startsPerSecond : limits.controlStartsPerSecond;
64
+ }
57
65
  retryTimers = {};
58
66
  available = new Set();
59
67
  removals = new Set();
@@ -98,18 +106,22 @@ export class IsolatedExtensionQuota {
98
106
  removal.timer.unref();
99
107
  }
100
108
  atCapacity(kind) {
101
- return this.processes[kind] >= PROCESS_LIMITS[kind];
109
+ return this.processes[kind] >= this.processLimit(kind);
102
110
  }
103
111
  process(kind) {
104
- if (this.atCapacity(kind))
112
+ const limits = this.limits();
113
+ if (this.processes[kind] >= this.processLimit(kind, limits))
105
114
  return;
106
- if (!this.starts[kind].take(1)) {
115
+ const rate = this.startRate(kind, limits);
116
+ if (this.starts[kind].rate !== rate)
117
+ this.starts[kind] = startBudget(rate);
118
+ if (!this.starts[kind].budget.take(1)) {
107
119
  if (!this.retryTimers[kind]) {
108
120
  this.retryTimers[kind] = setTimeout(() => {
109
121
  delete this.retryTimers[kind];
110
122
  for (const listener of this.available)
111
123
  listener();
112
- }, 1_000 / STARTS_PER_SECOND[kind]);
124
+ }, 1_000 / rate);
113
125
  this.retryTimers[kind].unref();
114
126
  }
115
127
  return;
@@ -117,7 +129,7 @@ export class IsolatedExtensionQuota {
117
129
  this.processes[kind]++;
118
130
  let released = false;
119
131
  return {
120
- ...processIngress(),
132
+ ...processIngress(limits),
121
133
  release: () => {
122
134
  if (released)
123
135
  return;
@@ -129,8 +141,10 @@ export class IsolatedExtensionQuota {
129
141
  };
130
142
  }
131
143
  call() {
132
- if (this.calls >= MAX_CALLS)
133
- throw new IsolatedRpcError("overloaded");
144
+ const limits = this.limits();
145
+ if (this.calls >= limits.servingLanes * limits.callsPerLane) {
146
+ throw new IsolatedRejection("call_limit");
147
+ }
134
148
  this.calls++;
135
149
  let held = true;
136
150
  return () => {
@@ -143,9 +157,10 @@ export class IsolatedExtensionQuota {
143
157
  admitPreflight(orgId, role, setupCheck = false) {
144
158
  const key = setupCheck ? "control" : admissionGroup(orgId, role);
145
159
  const count = this.preflights.get(key) ?? 0;
146
- const limit = setupCheck ? MAX_WAITING_CONTROL + 1 : MAX_PREFLIGHTS_PER_ORG;
160
+ const limits = this.limits();
161
+ const limit = setupCheck ? limits.controlWaiters + 1 : limits.preflightsPerOrg;
147
162
  if (count >= limit)
148
- throw new IsolatedRpcError("overloaded");
163
+ throw new IsolatedRejection("preflight_limit");
149
164
  const release = setupCheck ? undefined : this.call();
150
165
  this.preflights.set(key, count + 1);
151
166
  let held = true;
@@ -161,8 +176,13 @@ export class IsolatedExtensionQuota {
161
176
  release?.();
162
177
  };
163
178
  }
179
+ /** Concurrent broker requests one lane may hold: each serving call can hold one. */
180
+ servicesPerLane(kind, limits = this.limits()) {
181
+ return kind === "serving" ? limits.callsPerLane : CONTROL_SERVICES_PER_LANE;
182
+ }
164
183
  service(kind) {
165
- if (this.services[kind] >= PROCESS_LIMITS[kind] * MAX_SERVICES_PER_LANE[kind])
184
+ const limits = this.limits();
185
+ if (this.services[kind] >= this.processLimit(kind, limits) * this.servicesPerLane(kind, limits))
166
186
  throw new IsolatedRpcError("overloaded");
167
187
  this.services[kind]++;
168
188
  return () => {
@@ -184,6 +204,22 @@ export class IsolatedExtensionQuota {
184
204
  return delay;
185
205
  }
186
206
  }
207
+ /** Why a lane start failed, for the start failure metric. */
208
+ function startFailure(error, admission) {
209
+ if (error instanceof ExtensionSandboxCapacityError)
210
+ return "engine_capacity";
211
+ if (admission.aborted)
212
+ return "cancelled";
213
+ if (error instanceof IsolatedRpcError) {
214
+ if (error.code === "deadline")
215
+ return "timeout";
216
+ if (error.code === "refused" || error.code === "invalid")
217
+ return "refused";
218
+ if (error.code === "closed")
219
+ return "exited";
220
+ }
221
+ return "error";
222
+ }
187
223
  function envelope(value) {
188
224
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
189
225
  throw new IsolatedRpcError("invalid");
@@ -219,12 +255,77 @@ export class IsolatedLanes {
219
255
  draining;
220
256
  control;
221
257
  expected;
258
+ /** Lane keys whose serving lane exited unexpectedly: the next start there replaces a crash. */
259
+ crashedKeys = new Set();
222
260
  constructor(options) {
223
261
  this.options = options;
224
262
  this.lifetime = AbortSignal.any([options.signal, this.shutdown.signal]);
225
263
  if (!this.lifetime.aborted) {
226
264
  const unwatch = options.quota.watch(() => this.schedule());
227
- this.lifetime.addEventListener("abort", unwatch, { once: true });
265
+ const observer = options.observer;
266
+ const unobserve = observer?.observeLanes(() => this.snapshot());
267
+ const uncheckpoint = observer?.onCheckpoint(() => this.checkpointBusy());
268
+ this.lifetime.addEventListener("abort", () => {
269
+ unwatch();
270
+ unobserve?.();
271
+ uncheckpoint?.();
272
+ }, { once: true });
273
+ }
274
+ }
275
+ get limits() {
276
+ return this.options.quota.limits();
277
+ }
278
+ /** The serving and control lanes as the gauges see them. */
279
+ *snapshot() {
280
+ const callsPerLane = this.limits.callsPerLane;
281
+ for (const slot of this.lanes.values()) {
282
+ yield {
283
+ laneClass: "standard",
284
+ mode: slot.mode,
285
+ role: slot.role,
286
+ orgId: slot.orgId,
287
+ state: slot.closing
288
+ ? "draining"
289
+ : !slot.lane
290
+ ? "starting"
291
+ : slot.calls > 0
292
+ ? "busy"
293
+ : "warm",
294
+ calls: slot.calls,
295
+ capacity: callsPerLane,
296
+ };
297
+ }
298
+ if (this.control) {
299
+ yield {
300
+ laneClass: "control",
301
+ mode: this.control.mode,
302
+ role: "none",
303
+ orgId: this.control.orgId,
304
+ state: this.control.started ? "busy" : "starting",
305
+ calls: this.control.started ? 1 : 0,
306
+ capacity: 1,
307
+ };
308
+ }
309
+ }
310
+ servingLabels(mode, role, orgId) {
311
+ return { laneClass: "standard", mode, role, orgId };
312
+ }
313
+ reject(labels, reason) {
314
+ this.options.observer?.rejected(labels, reason);
315
+ return new IsolatedRejection(reason);
316
+ }
317
+ /** Books the busy time of a lane whose calls just ended, or of every busy lane at a flush. */
318
+ bookBusy(slot, until = performance.now(), stillBusy = false) {
319
+ if (slot.busySince === undefined)
320
+ return;
321
+ this.options.observer?.busy(slot.orgId, until - slot.busySince);
322
+ slot.busySince = stillBusy ? until : undefined;
323
+ }
324
+ checkpointBusy() {
325
+ const now = performance.now();
326
+ for (const slot of this.lanes.values()) {
327
+ if (slot.calls > 0)
328
+ this.bookBusy(slot, now, true);
228
329
  }
229
330
  }
230
331
  async register() {
@@ -242,7 +343,19 @@ export class IsolatedLanes {
242
343
  throw new IsolatedRpcError("closed");
243
344
  if (scope.signal?.aborted)
244
345
  throw new IsolatedRpcError("cancelled");
245
- const release = scope.mode === "setupCheck" ? undefined : this.options.quota.call();
346
+ const observer = this.options.observer;
347
+ const labels = scope.mode === "setupCheck"
348
+ ? { laneClass: "control", mode: "setupCheck", role: "none", orgId: scope.orgId }
349
+ : this.servingLabels(scope.mode, scope.role ?? "none", scope.orgId);
350
+ let release;
351
+ try {
352
+ release = scope.mode === "setupCheck" ? undefined : this.options.quota.call();
353
+ }
354
+ catch (error) {
355
+ if (error instanceof IsolatedRejection)
356
+ observer?.rejected(labels, error.reason);
357
+ throw error;
358
+ }
246
359
  let serving;
247
360
  let lane;
248
361
  const invocation = randomUUID();
@@ -255,8 +368,12 @@ export class IsolatedLanes {
255
368
  ...(scope.signal ? [scope.signal] : []),
256
369
  ]);
257
370
  try {
371
+ let cold = scope.grantChecked === true;
258
372
  if (scope.mode === "setupCheck") {
259
373
  lane = await this.openControl(scope.mode, scope.orgId, callSignal);
374
+ // A setup check always runs in a process of its own.
375
+ observer?.coldWait(labels);
376
+ cold = true;
260
377
  }
261
378
  else {
262
379
  const { mode, orgId, role } = scope;
@@ -264,10 +381,20 @@ export class IsolatedLanes {
264
381
  (mode === "org" ? !orgId : orgId !== undefined)) {
265
382
  throw new IsolatedRpcError("refused");
266
383
  }
384
+ const queuedAt = performance.now();
267
385
  serving = await this.admit(mode, orgId, role, callSignal);
386
+ observer?.queued(labels, (performance.now() - queuedAt) / 1000);
387
+ if (!serving.lane) {
388
+ observer?.coldWait(labels);
389
+ cold = true;
390
+ }
268
391
  lane = await waitForLane(serving.opening, callSignal);
269
392
  }
270
393
  lane.invocations.set(invocation, { ...scope, signal: callSignal, cleanup });
394
+ if (scope.receivedAt !== undefined) {
395
+ observer?.overhead(labels, (performance.now() - scope.receivedAt) / 1000, cold);
396
+ }
397
+ observer?.invoked(scope.orgId);
271
398
  return await lane.rpc.call("invoke", { callback, invocation, args, ...(scope.config !== undefined && { config: scope.config }) }, { signal: callSignal, cancelGraceMs: CANCELLATION_GRACE_MS });
272
399
  }
273
400
  finally {
@@ -281,6 +408,8 @@ export class IsolatedLanes {
281
408
  if (serving) {
282
409
  serving.calls--;
283
410
  serving.lastUsed = ++this.sequence;
411
+ if (serving.calls === 0)
412
+ this.bookBusy(serving);
284
413
  if (serving.calls === 0 && serving.lane && !serving.closing)
285
414
  this.idle(serving);
286
415
  this.schedule();
@@ -299,22 +428,25 @@ export class IsolatedLanes {
299
428
  return Promise.resolve(warm);
300
429
  const group = admissionGroup(orgId, role);
301
430
  const queue = this.waiting.get(group) ?? [];
302
- if (this.waitingCount >= MAX_WAITING ||
303
- queue.filter((entry) => entry.key === key).length >= MAX_WAITING_PER_LANE) {
304
- return Promise.reject(new IsolatedRpcError("overloaded"));
431
+ const limits = this.limits;
432
+ const labels = this.servingLabels(mode, role, orgId);
433
+ if (this.waitingCount >= limits.maxQueued ||
434
+ queue.filter((entry) => entry.key === key).length >= limits.maxQueuedPerLane) {
435
+ return Promise.reject(this.reject(labels, "queue_full"));
305
436
  }
306
437
  return new Promise((resolve, reject) => {
307
- const remove = (code) => {
438
+ const remove = (error) => {
308
439
  this.remove(admission);
309
- reject(new IsolatedRpcError(code));
440
+ reject(error);
310
441
  this.schedule();
311
442
  };
312
- const abort = () => remove("cancelled");
313
- const timer = setTimeout(() => remove("overloaded"), ADMISSION_TIMEOUT_MS);
443
+ const abort = () => remove(new IsolatedRpcError("cancelled"));
444
+ const timer = setTimeout(() => remove(this.reject(labels, "deadline")), limits.maxQueueWaitMs);
314
445
  timer.unref();
315
446
  const admission = {
316
447
  group,
317
448
  mode,
449
+ role,
318
450
  orgId,
319
451
  key,
320
452
  resolve,
@@ -378,10 +510,12 @@ export class IsolatedLanes {
378
510
  if (!slot) {
379
511
  if (this.options.quota.inBackoff(this.options.revision)) {
380
512
  this.remove(admission, true);
381
- admission.reject(new IsolatedRpcError("overloaded"));
513
+ admission.reject(this.reject(this.servingLabels(admission.mode, admission.role, admission.orgId), "crash_backoff"));
382
514
  return true;
383
515
  }
384
- const lease = this.lanes.size < MAX_ISOLATED_LANES ? this.options.quota.process("serving") : undefined;
516
+ const lease = this.lanes.size < this.limits.servingLanes
517
+ ? this.options.quota.process("serving")
518
+ : undefined;
385
519
  if (lease) {
386
520
  slot = this.openServing(admission, lease);
387
521
  }
@@ -396,9 +530,11 @@ export class IsolatedLanes {
396
530
  return true;
397
531
  }
398
532
  claim(slot) {
399
- if (slot.closing || slot === this.draining?.slot || slot.calls >= MAX_CALLS_PER_LANE)
533
+ if (slot.closing || slot === this.draining?.slot || slot.calls >= this.limits.callsPerLane)
400
534
  return false;
401
535
  clearTimeout(slot.timer);
536
+ if (slot.calls === 0)
537
+ slot.busySince = performance.now();
402
538
  slot.calls++;
403
539
  slot.lastUsed = ++this.sequence;
404
540
  return true;
@@ -420,7 +556,13 @@ export class IsolatedLanes {
420
556
  openServing(admission, lease) {
421
557
  const stop = new AbortController();
422
558
  const end = AbortSignal.any([this.lifetime, stop.signal]);
423
- const opening = this.start(admission.mode, admission.orgId, end, end, () => this.retire(slot), () => {
559
+ // Only the start that replaces the lane that crashed is a `crash` start.
560
+ const reason = this.crashedKeys.delete(admission.key) ? "crash" : "demand";
561
+ const opening = this.start(admission.mode, admission.orgId, {
562
+ reason,
563
+ role: admission.role,
564
+ onUnexpectedExit: () => this.crashedKeys.add(admission.key),
565
+ }, end, end, () => this.retire(slot), () => {
424
566
  this.lanes.delete(admission.key);
425
567
  if (this.draining?.slot === slot)
426
568
  this.draining = undefined;
@@ -428,6 +570,8 @@ export class IsolatedLanes {
428
570
  }, lease);
429
571
  const slot = {
430
572
  orgId: admission.orgId,
573
+ mode: admission.mode,
574
+ role: admission.role,
431
575
  stop,
432
576
  opening,
433
577
  calls: 0,
@@ -446,32 +590,34 @@ export class IsolatedLanes {
446
590
  }
447
591
  idle(slot) {
448
592
  clearTimeout(slot.timer);
449
- slot.timer = setTimeout(() => this.evict(slot), IDLE_MS);
593
+ slot.timer = setTimeout(() => this.evict(slot, "idle_reap"), this.limits.idleReapMs);
450
594
  slot.timer.unref();
451
595
  }
452
596
  retire(slot) {
453
597
  slot.closing = true;
454
598
  clearTimeout(slot.timer);
455
599
  }
456
- evict(slot) {
600
+ evict(slot, reason = "normal") {
457
601
  this.retire(slot);
458
- void slot.lane?.close().catch(() => this.options.cleanupFault());
602
+ void slot.lane?.close(reason).catch(() => this.options.cleanupFault());
459
603
  }
460
604
  async openControl(mode, orgId, signal = this.lifetime) {
461
605
  if (this.lifetime.aborted)
462
606
  throw new IsolatedRpcError("closed");
463
607
  if (signal.aborted)
464
608
  throw new IsolatedRpcError("cancelled");
465
- if (this.waitingControl.length >= MAX_WAITING_CONTROL)
466
- throw new IsolatedRpcError("overloaded");
609
+ const limits = this.limits;
610
+ const labels = { laneClass: "control", mode, role: "none", orgId };
611
+ if (this.waitingControl.length >= limits.controlWaiters)
612
+ throw this.reject(labels, "queue_full");
467
613
  return new Promise((resolve, reject) => {
468
- const stopWaiting = (code) => {
614
+ const stopWaiting = (error) => {
469
615
  this.removeControl(admission);
470
- reject(new IsolatedRpcError(code));
616
+ reject(error);
471
617
  this.schedule();
472
618
  };
473
- const abort = () => stopWaiting("cancelled");
474
- const timer = setTimeout(() => stopWaiting("overloaded"), CONTROL_WAIT_MS);
619
+ const abort = () => stopWaiting(new IsolatedRpcError("cancelled"));
620
+ const timer = setTimeout(() => stopWaiting(this.reject(labels, "deadline")), limits.controlWaitMs);
475
621
  timer.unref();
476
622
  const admission = {
477
623
  mode,
@@ -503,7 +649,7 @@ export class IsolatedLanes {
503
649
  if (this.options.quota.inBackoff(this.options.revision)) {
504
650
  for (const waiting of this.waitingControl.splice(0)) {
505
651
  waiting.cleanup();
506
- waiting.reject(new IsolatedRpcError("overloaded"));
652
+ waiting.reject(this.reject({ laneClass: "control", mode: waiting.mode, role: "none", orgId: waiting.orgId }, "crash_backoff"));
507
653
  }
508
654
  return;
509
655
  }
@@ -516,30 +662,44 @@ export class IsolatedLanes {
516
662
  const { mode, orgId, signal } = admission;
517
663
  const stop = new AbortController();
518
664
  const end = AbortSignal.any([this.lifetime, stop.signal]);
519
- const opening = this.start(mode, orgId, end, AbortSignal.any([end, signal]), () => { }, () => {
665
+ const opening = this.start(mode, orgId, { reason: mode === "registration" ? "registration" : "setup_check", role: "none" }, end, AbortSignal.any([end, signal]), () => { }, () => {
520
666
  this.control = undefined;
521
667
  this.schedule();
522
668
  }, lease);
523
- this.control = { orgId, stop, opening };
669
+ const control = { orgId, mode, stop, opening, started: false };
670
+ this.control = control;
671
+ void opening.then(() => {
672
+ control.started = true;
673
+ }, () => { });
524
674
  admission.resolve(opening);
525
675
  }
526
- async start(mode, orgId, end, admission, retiring, removed, lease) {
676
+ async start(mode, orgId, measure, end, admission, retiring, removed, lease) {
527
677
  const kind = mode === "registration" || mode === "setupCheck" ? "control" : "serving";
678
+ const startedAt = performance.now();
679
+ const labels = {
680
+ laneClass: kind === "control" ? "control" : "standard",
681
+ mode,
682
+ role: measure.role,
683
+ orgId,
684
+ };
528
685
  const nonce = randomUUID();
529
686
  const invocations = new Map();
530
687
  let close;
531
688
  let gate;
532
689
  let closing;
690
+ let exitReason;
533
691
  let crashed = false;
534
692
  let initialized = false;
535
693
  let services = 0;
536
- const crash = () => {
694
+ const crash = (cause) => {
537
695
  if (crashed || closing || end.aborted || (!initialized && admission.aborted))
538
696
  return;
539
697
  crashed = true;
698
+ if (initialized)
699
+ measure.onUnexpectedExit?.();
540
700
  const delay = this.options.quota.crashed(this.options.revision);
541
701
  try {
542
- this.options.onCrash?.(delay);
702
+ this.options.onCrash?.(delay, cause);
543
703
  }
544
704
  catch {
545
705
  // Diagnostics must leave lane teardown and backoff intact.
@@ -549,9 +709,13 @@ export class IsolatedLanes {
549
709
  void close?.().catch(() => this.options.cleanupFault());
550
710
  };
551
711
  const unexpectedExit = () => {
552
- crash();
712
+ crash(initialized ? "exited" : "start_failed");
553
713
  tearDown();
554
714
  };
715
+ /** Why an initialized lane ended, once its sandbox is gone. */
716
+ const exited = () => crashed
717
+ ? "crash"
718
+ : (exitReason ?? (end.aborted && !this.lifetime.aborted ? "killed" : "normal"));
555
719
  try {
556
720
  const { postgresSocket, ...sandboxOptions } = this.options.sandbox;
557
721
  if (mode === "org") {
@@ -576,6 +740,7 @@ export class IsolatedLanes {
576
740
  const rpc = new IsolatedRpcPeer(sandbox.output, sandbox.input, {
577
741
  budget: lease.budget,
578
742
  requestBudget: lease.requestBudget,
743
+ onOverloaded: (cause) => this.options.observer?.rejected(labels, cause === "budget" ? "callback_budget" : "callback_limit"),
579
744
  onClose: (_error, cause) => {
580
745
  if (cause === "transport" || (!initialized && cause === "protocol"))
581
746
  unexpectedExit();
@@ -596,9 +761,19 @@ export class IsolatedLanes {
596
761
  (binary && method !== "broker.storage.write")) {
597
762
  throw new IsolatedRpcError("refused");
598
763
  }
599
- if (services >= MAX_SERVICES_PER_LANE[kind])
600
- throw new IsolatedRpcError("overloaded");
601
- const releaseService = this.options.quota.service(kind);
764
+ let releaseService;
765
+ try {
766
+ if (services >= this.options.quota.servicesPerLane(kind)) {
767
+ throw new IsolatedRpcError("overloaded");
768
+ }
769
+ releaseService = this.options.quota.service(kind);
770
+ }
771
+ catch (error) {
772
+ this.options.observer?.rejected(labels, "callback_limit");
773
+ throw error;
774
+ }
775
+ // Counted only once admitted, like the RPC layer's refusals.
776
+ this.options.observer?.callback(scope.orgId, method);
602
777
  services++;
603
778
  try {
604
779
  return await this.options.broker(method, binary ? [...frame.args, binary.bytes] : frame.args, scope, AbortSignal.any([requestSignal, end, ...(scope.signal ? [scope.signal] : [])]));
@@ -609,9 +784,10 @@ export class IsolatedLanes {
609
784
  }
610
785
  },
611
786
  });
612
- close = () => {
787
+ close = (reason) => {
613
788
  if (closing)
614
789
  return closing;
790
+ exitReason = reason;
615
791
  retiring();
616
792
  end.removeEventListener("abort", tearDown);
617
793
  closing = Promise.resolve().then(async () => {
@@ -626,6 +802,8 @@ export class IsolatedLanes {
626
802
  await closeGate;
627
803
  this.options.quota.retryRemoval(() => sandbox.close(), lease.release);
628
804
  }
805
+ if (initialized)
806
+ this.options.observer?.laneExited(labels, exited());
629
807
  removed();
630
808
  });
631
809
  invocations.clear();
@@ -644,7 +822,7 @@ export class IsolatedLanes {
644
822
  db: { login: this.options.credential.login, url: this.options.credential.url },
645
823
  rls: this.options.rls,
646
824
  }),
647
- }, { signal: admission, timeoutMs: ADMISSION_TIMEOUT_MS }));
825
+ }, { signal: admission, timeoutMs: this.limits.maxQueueWaitMs }));
648
826
  if (response.nonce !== nonce ||
649
827
  canonicalJson(response.manifest) !== canonicalJson(this.options.manifest) ||
650
828
  canonicalJson(response.configSchemas) !== canonicalJson(this.options.configSchemas) ||
@@ -656,10 +834,15 @@ export class IsolatedLanes {
656
834
  throw new IsolatedRpcError("refused");
657
835
  }
658
836
  initialized = true;
837
+ this.options.observer?.laneStarted(labels, measure.reason, (performance.now() - startedAt) / 1000);
659
838
  return { rpc, close, ready, invocations };
660
839
  }
661
840
  catch (error) {
662
- crash();
841
+ const failure = startFailure(error, admission);
842
+ this.options.observer?.laneStartFailed(labels, failure);
843
+ // The guard refusing a launch for lack of capacity is not a crash: no backoff.
844
+ if (failure !== "engine_capacity")
845
+ crash("start_failed");
663
846
  if (close)
664
847
  await close().catch(() => this.options.cleanupFault());
665
848
  else {