@capybara-hq/kernel 0.1.0-rc.136 → 0.1.0-rc.138

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 (203) hide show
  1. package/dist/admin/audit-log.service.d.ts +96 -12
  2. package/dist/admin/audit-log.service.js +508 -44
  3. package/dist/admin/audit-targets.d.ts +17 -0
  4. package/dist/admin/audit-targets.js +84 -0
  5. package/dist/admin/audit.controller.d.ts +12 -9
  6. package/dist/admin/audit.controller.js +29 -8
  7. package/dist/admin/audit.schemas.d.ts +20 -4
  8. package/dist/admin/audit.schemas.js +42 -17
  9. package/dist/admin/extensions.controller.d.ts +5 -2
  10. package/dist/admin/extensions.controller.js +10 -1
  11. package/dist/admin/extensions.schemas.d.ts +4 -0
  12. package/dist/admin/extensions.schemas.js +9 -0
  13. package/dist/admin/health.service.d.ts +1 -1
  14. package/dist/admin/health.service.js +3 -3
  15. package/dist/agents/templates.js +3 -10
  16. package/dist/app.d.ts +3 -1
  17. package/dist/app.js +1 -0
  18. package/dist/automations/automations.service.js +4 -5
  19. package/dist/catalog/catalog-content.d.ts +6 -8
  20. package/dist/catalog/catalog-content.js +17 -22
  21. package/dist/catalog/catalog-items.d.ts +5 -10
  22. package/dist/catalog/catalog-items.js +27 -51
  23. package/dist/catalog/catalog-scope.service.d.ts +4 -2
  24. package/dist/catalog/catalog-scope.service.js +109 -145
  25. package/dist/catalog/catalog.module.js +7 -4
  26. package/dist/catalog/catalog.service.d.ts +10 -4
  27. package/dist/catalog/catalog.service.js +52 -10
  28. package/dist/catalog/cli.js +17 -0
  29. package/dist/catalog/component-promotion.js +8 -4
  30. package/dist/catalog/component-scope.service.d.ts +3 -1
  31. package/dist/catalog/component-scope.service.js +101 -140
  32. package/dist/catalog/component-state.d.ts +10 -8
  33. package/dist/catalog/component-state.js +42 -30
  34. package/dist/catalog/dependency-edges.d.ts +25 -0
  35. package/dist/catalog/dependency-edges.js +125 -0
  36. package/dist/catalog/effect-work.d.ts +27 -0
  37. package/dist/catalog/effect-work.js +151 -0
  38. package/dist/catalog/jobs.d.ts +4 -1
  39. package/dist/catalog/jobs.js +14 -4
  40. package/dist/catalog/org-catalog.service.d.ts +5 -1
  41. package/dist/catalog/org-catalog.service.js +101 -106
  42. package/dist/catalog/org-intent.d.ts +45 -0
  43. package/dist/catalog/org-intent.js +205 -0
  44. package/dist/catalog/owned-items.d.ts +6 -2
  45. package/dist/catalog/owned-items.js +27 -32
  46. package/dist/catalog/ownership.d.ts +2 -3
  47. package/dist/catalog/ownership.js +10 -28
  48. package/dist/catalog/platform-components.d.ts +3 -1
  49. package/dist/catalog/platform-components.js +9 -1
  50. package/dist/catalog/plugin-import.d.ts +4 -2
  51. package/dist/catalog/plugin-import.js +22 -21
  52. package/dist/catalog/plugin-install.d.ts +19 -54
  53. package/dist/catalog/plugin-install.js +221 -271
  54. package/dist/catalog/plugin-upgrade.d.ts +10 -5
  55. package/dist/catalog/plugin-upgrade.js +80 -67
  56. package/dist/catalog/request-rules.js +20 -8
  57. package/dist/catalog/scope-orgs.js +2 -7
  58. package/dist/catalog/scope-state.d.ts +6 -6
  59. package/dist/catalog/scope-state.js +24 -43
  60. package/dist/catalog/scope-sync-workers.d.ts +7 -11
  61. package/dist/catalog/scope-sync-workers.js +10 -26
  62. package/dist/catalog/scope-sync.d.ts +19 -116
  63. package/dist/catalog/scope-sync.js +228 -275
  64. package/dist/catalog/scope-writer.d.ts +87 -0
  65. package/dist/catalog/scope-writer.js +239 -0
  66. package/dist/catalog/template-connector-ensure.js +1 -1
  67. package/dist/catalog/unshare.js +9 -43
  68. package/dist/channels/connections.service.js +6 -6
  69. package/dist/channels/supervisor.js +3 -7
  70. package/dist/client/client-access.service.js +2 -12
  71. package/dist/config/schema.d.ts +6 -0
  72. package/dist/config/schema.js +32 -1
  73. package/dist/ctx/create-ctx.d.ts +2 -2
  74. package/dist/ctx/create-ctx.js +2 -60
  75. package/dist/ctx/guard-db.d.ts +6 -0
  76. package/dist/ctx/guard-db.js +55 -0
  77. package/dist/db/extension-handoff-schema.d.ts +1 -1
  78. package/dist/db/extension-handoff-schema.js +48 -10
  79. package/dist/db/extension-schema-transfer.js +5 -2
  80. package/dist/db/kernel-schema.d.ts +32 -6
  81. package/dist/device-access/host-services.d.ts +2 -2
  82. package/dist/device-access/host-services.js +5 -6
  83. package/dist/erasure/org-catalog.js +2 -2
  84. package/dist/erasure/org-rules.js +7 -0
  85. package/dist/extensions/admin-ops.d.ts +10 -6
  86. package/dist/extensions/admin-ops.js +53 -9
  87. package/dist/extensions/admin-view.d.ts +4 -1
  88. package/dist/extensions/admin-view.js +27 -14
  89. package/dist/extensions/bootstrap.d.ts +1 -1
  90. package/dist/extensions/bootstrap.js +6 -4
  91. package/dist/extensions/cli.js +1 -0
  92. package/dist/extensions/effective-config.js +1 -4
  93. package/dist/extensions/enabled.d.ts +183 -29
  94. package/dist/extensions/enabled.js +148 -62
  95. package/dist/extensions/host.d.ts +65 -45
  96. package/dist/extensions/host.js +446 -128
  97. package/dist/extensions/installs.d.ts +9 -0
  98. package/dist/extensions/installs.js +23 -0
  99. package/dist/extensions/isolated/admission.d.ts +10 -0
  100. package/dist/extensions/isolated/admission.js +206 -0
  101. package/dist/extensions/isolated/authorization.d.ts +45 -0
  102. package/dist/extensions/isolated/authorization.js +191 -0
  103. package/dist/extensions/isolated/broker.d.ts +15 -0
  104. package/dist/extensions/isolated/broker.js +471 -0
  105. package/dist/extensions/isolated/child-protocol.d.ts +84 -0
  106. package/dist/extensions/isolated/child-protocol.js +21 -0
  107. package/dist/extensions/isolated/child-registration.d.ts +22 -0
  108. package/dist/extensions/isolated/child-registration.js +152 -0
  109. package/dist/extensions/isolated/child-session.d.ts +6 -0
  110. package/dist/extensions/isolated/child-session.js +343 -0
  111. package/dist/extensions/isolated/child-streams.d.ts +4 -0
  112. package/dist/extensions/isolated/child-streams.js +142 -0
  113. package/dist/extensions/isolated/child.d.ts +1 -0
  114. package/dist/extensions/isolated/child.js +10 -0
  115. package/dist/extensions/isolated/configured-package.d.ts +15 -0
  116. package/dist/extensions/isolated/configured-package.js +73 -0
  117. package/dist/extensions/isolated/engine-binds.d.ts +9 -0
  118. package/dist/extensions/isolated/engine-binds.js +82 -0
  119. package/dist/extensions/isolated/engine-policy.d.ts +85 -0
  120. package/dist/extensions/isolated/engine-policy.js +75 -0
  121. package/dist/extensions/isolated/engine-proxy-main.d.ts +1 -0
  122. package/dist/extensions/isolated/engine-proxy-main.js +20 -0
  123. package/dist/extensions/isolated/engine-proxy.d.ts +7 -0
  124. package/dist/extensions/isolated/engine-proxy.js +408 -0
  125. package/dist/extensions/isolated/engine-vaults.d.ts +12 -0
  126. package/dist/extensions/isolated/engine-vaults.js +93 -0
  127. package/dist/extensions/isolated/lanes.d.ts +108 -0
  128. package/dist/extensions/isolated/lanes.js +726 -0
  129. package/dist/extensions/isolated/postgres-gate.d.ts +15 -0
  130. package/dist/extensions/isolated/postgres-gate.js +255 -0
  131. package/dist/extensions/isolated/revision.d.ts +32 -0
  132. package/dist/extensions/isolated/revision.js +359 -0
  133. package/dist/extensions/isolated/rpc-frame.d.ts +50 -0
  134. package/dist/extensions/isolated/rpc-frame.js +193 -0
  135. package/dist/extensions/isolated/rpc.d.ts +66 -0
  136. package/dist/extensions/isolated/rpc.js +314 -0
  137. package/dist/extensions/isolated/sandbox.d.ts +39 -0
  138. package/dist/extensions/isolated/sandbox.js +356 -0
  139. package/dist/extensions/isolated/tier.d.ts +6 -0
  140. package/dist/extensions/isolated/tier.js +45 -0
  141. package/dist/extensions/ledger.d.ts +1 -1
  142. package/dist/extensions/lifecycle-topics.d.ts +2 -0
  143. package/dist/extensions/lifecycle-topics.js +2 -0
  144. package/dist/extensions/lifecycle.d.ts +3 -1
  145. package/dist/extensions/lifecycle.js +53 -5
  146. package/dist/extensions/locks.d.ts +2 -0
  147. package/dist/extensions/locks.js +7 -0
  148. package/dist/extensions/org-config.d.ts +17 -27
  149. package/dist/extensions/org-config.js +114 -129
  150. package/dist/extensions/permission-view.d.ts +6 -1
  151. package/dist/extensions/plugin-guides.d.ts +5 -10
  152. package/dist/extensions/plugin-guides.js +18 -37
  153. package/dist/extensions/plugin-icons.d.ts +3 -21
  154. package/dist/extensions/plugin-icons.js +9 -44
  155. package/dist/extensions/plugin-items.d.ts +10 -30
  156. package/dist/extensions/plugin-items.js +32 -73
  157. package/dist/extensions/source-intent.d.ts +14 -0
  158. package/dist/extensions/source-intent.js +77 -0
  159. package/dist/inbox/platform-inbox.service.js +16 -27
  160. package/dist/index.d.ts +2 -1
  161. package/dist/index.js +2 -1
  162. package/dist/infra/database/database.module.js +6 -1
  163. package/dist/infra/database/kernel-db.d.ts +3 -1
  164. package/dist/infra/database/kernel-db.js +4 -0
  165. package/dist/infra/events/kernel-events.d.ts +4 -0
  166. package/dist/infra/outbox/registry.d.ts +3 -36
  167. package/dist/infra/outbox/registry.js +4 -49
  168. package/dist/infra/paging/paged-read.d.ts +56 -0
  169. package/dist/infra/paging/paged-read.js +78 -0
  170. package/dist/infra/queue/queue-names.d.ts +1 -1
  171. package/dist/infra/queue/queue-names.js +1 -1
  172. package/dist/kernel.d.ts +3 -2
  173. package/dist/kernel.js +21 -2
  174. package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
  175. package/dist/lifecycle/kernel-lifecycle.js +22 -12
  176. package/dist/lifecycle/tokens.d.ts +8 -0
  177. package/dist/lifecycle/tokens.js +2 -0
  178. package/dist/orgs/directory-sync.js +1 -4
  179. package/dist/orgs/org-lock.d.ts +3 -1
  180. package/dist/orgs/org-lock.js +3 -1
  181. package/dist/orgs/orgs.service.d.ts +3 -1
  182. package/dist/orgs/orgs.service.js +15 -8
  183. package/dist/overrides.d.ts +0 -3
  184. package/dist/overrides.js +0 -2
  185. package/dist/platform/ops/admin.ops.js +14 -3
  186. package/dist/platform/ops/extensions-admin.ops.js +20 -3
  187. package/dist/platform/ops/org-plugins.ops.js +5 -2
  188. package/dist/platform/ops/orgs.ops.js +13 -3
  189. package/dist/platform/ops/plugins.ops.js +11 -10
  190. package/dist/setup/setup-checks.service.js +3 -2
  191. package/dist/skills/usable.js +41 -30
  192. package/dist/themes/theme-state.js +3 -3
  193. package/dist/tools/registry.d.ts +2 -2
  194. package/dist/tools/registry.js +7 -3
  195. package/package.json +2 -2
  196. package/src/migrations/0228_extension_org_switches.sql +56 -0
  197. package/src/migrations/0229_catalog_dependency_edges.sql +17 -0
  198. package/src/migrations/0230_audit_filter_idx.sql +18 -0
  199. package/src/migrations/0231_plugin_effect_work.sql +171 -0
  200. package/dist/catalog/install-status.d.ts +0 -6
  201. package/dist/catalog/install-status.js +0 -6
  202. package/dist/catalog/scope-jobs.d.ts +0 -59
  203. package/dist/catalog/scope-jobs.js +0 -78
@@ -0,0 +1,726 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { canonicalJson } from "../../tools/canonical-json.js";
3
+ import { startPostgresGate } from "./postgres-gate.js";
4
+ 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 };
23
+ const CANCELLATION_GRACE_MS = 250;
24
+ const CRASH_HISTORY_MS = 120_000;
25
+ const CLEANUP_RETRY_MS = 250;
26
+ const MAX_CLEANUP_RETRY_MS = 15_000;
27
+ function admissionGroup(orgId, role) {
28
+ return orgId === undefined ? `deployment:${role ?? "api"}` : `org:${orgId}`;
29
+ }
30
+ function processIngress() {
31
+ return {
32
+ budget: createRpcBudget({
33
+ framesPerSecond: LANE_FRAMES_PER_SECOND,
34
+ bytesPerSecond: LANE_BYTES_PER_SECOND,
35
+ }),
36
+ requestBudget: createRpcBudget({
37
+ framesPerSecond: Math.floor(LANE_FRAMES_PER_SECOND / 2),
38
+ bytesPerSecond: Math.floor(LANE_BYTES_PER_SECOND / 2),
39
+ }),
40
+ };
41
+ }
42
+ export class IsolatedExtensionQuota {
43
+ processes = { serving: 0, control: 0 };
44
+ calls = 0;
45
+ services = { serving: 0, control: 0 };
46
+ 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
+ };
57
+ retryTimers = {};
58
+ available = new Set();
59
+ removals = new Set();
60
+ crashes = new Map();
61
+ watch(listener) {
62
+ this.available.add(listener);
63
+ for (const removal of this.removals)
64
+ this.scheduleRemoval(removal);
65
+ return () => {
66
+ this.available.delete(listener);
67
+ if (this.available.size !== 0)
68
+ return;
69
+ for (const removal of this.removals) {
70
+ clearTimeout(removal.timer);
71
+ removal.timer = undefined;
72
+ }
73
+ };
74
+ }
75
+ retryRemoval(remove, release) {
76
+ // Retain the process charge across revisions. Retry only while a live supervisor can use it.
77
+ const removal = { remove, release, delay: CLEANUP_RETRY_MS, running: false };
78
+ this.removals.add(removal);
79
+ this.scheduleRemoval(removal);
80
+ }
81
+ scheduleRemoval(removal) {
82
+ if (this.available.size === 0 || removal.running || removal.timer)
83
+ return;
84
+ removal.timer = setTimeout(() => {
85
+ removal.timer = undefined;
86
+ removal.running = true;
87
+ void Promise.resolve()
88
+ .then(removal.remove)
89
+ .then(() => {
90
+ this.removals.delete(removal);
91
+ removal.release();
92
+ }, () => {
93
+ removal.running = false;
94
+ removal.delay = Math.min(removal.delay * 2, MAX_CLEANUP_RETRY_MS);
95
+ this.scheduleRemoval(removal);
96
+ });
97
+ }, removal.delay);
98
+ removal.timer.unref();
99
+ }
100
+ atCapacity(kind) {
101
+ return this.processes[kind] >= PROCESS_LIMITS[kind];
102
+ }
103
+ process(kind) {
104
+ if (this.atCapacity(kind))
105
+ return;
106
+ if (!this.starts[kind].take(1)) {
107
+ if (!this.retryTimers[kind]) {
108
+ this.retryTimers[kind] = setTimeout(() => {
109
+ delete this.retryTimers[kind];
110
+ for (const listener of this.available)
111
+ listener();
112
+ }, 1_000 / STARTS_PER_SECOND[kind]);
113
+ this.retryTimers[kind].unref();
114
+ }
115
+ return;
116
+ }
117
+ this.processes[kind]++;
118
+ let released = false;
119
+ return {
120
+ ...processIngress(),
121
+ release: () => {
122
+ if (released)
123
+ return;
124
+ released = true;
125
+ this.processes[kind]--;
126
+ for (const listener of this.available)
127
+ listener();
128
+ },
129
+ };
130
+ }
131
+ call() {
132
+ if (this.calls >= MAX_CALLS)
133
+ throw new IsolatedRpcError("overloaded");
134
+ this.calls++;
135
+ let held = true;
136
+ return () => {
137
+ if (!held)
138
+ return;
139
+ held = false;
140
+ this.calls--;
141
+ };
142
+ }
143
+ admitPreflight(orgId, role, setupCheck = false) {
144
+ const key = setupCheck ? "control" : admissionGroup(orgId, role);
145
+ const count = this.preflights.get(key) ?? 0;
146
+ const limit = setupCheck ? MAX_WAITING_CONTROL + 1 : MAX_PREFLIGHTS_PER_ORG;
147
+ if (count >= limit)
148
+ throw new IsolatedRpcError("overloaded");
149
+ const release = setupCheck ? undefined : this.call();
150
+ this.preflights.set(key, count + 1);
151
+ let held = true;
152
+ return () => {
153
+ if (!held)
154
+ return;
155
+ held = false;
156
+ const remaining = (this.preflights.get(key) ?? 0) - 1;
157
+ if (remaining === 0)
158
+ this.preflights.delete(key);
159
+ else
160
+ this.preflights.set(key, remaining);
161
+ release?.();
162
+ };
163
+ }
164
+ service(kind) {
165
+ if (this.services[kind] >= PROCESS_LIMITS[kind] * MAX_SERVICES_PER_LANE[kind])
166
+ throw new IsolatedRpcError("overloaded");
167
+ this.services[kind]++;
168
+ return () => {
169
+ this.services[kind]--;
170
+ };
171
+ }
172
+ inBackoff(revision) {
173
+ return (this.crashes.get(revision)?.until ?? 0) > performance.now();
174
+ }
175
+ crashed(revision) {
176
+ const now = performance.now();
177
+ for (const [key, crash] of this.crashes) {
178
+ if (now - crash.at >= CRASH_HISTORY_MS)
179
+ this.crashes.delete(key);
180
+ }
181
+ const count = Math.min(7, (this.crashes.get(revision)?.count ?? 0) + 1);
182
+ const delay = Math.min(60_000, 1_000 * 2 ** (count - 1));
183
+ this.crashes.set(revision, { at: now, count, until: now + delay });
184
+ return delay;
185
+ }
186
+ }
187
+ function envelope(value) {
188
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
189
+ throw new IsolatedRpcError("invalid");
190
+ }
191
+ return value;
192
+ }
193
+ async function waitForLane(opening, signal) {
194
+ if (signal.aborted)
195
+ throw new IsolatedRpcError("cancelled");
196
+ let abort = () => { };
197
+ const interrupted = new Promise((_resolve, reject) => {
198
+ abort = () => reject(new IsolatedRpcError("cancelled"));
199
+ signal.addEventListener("abort", abort, { once: true });
200
+ });
201
+ try {
202
+ return await Promise.race([opening, interrupted]);
203
+ }
204
+ finally {
205
+ signal.removeEventListener("abort", abort);
206
+ }
207
+ }
208
+ /** Owns only this revision's authenticated pipes, lanes and live invocation handles. */
209
+ export class IsolatedLanes {
210
+ options;
211
+ shutdown = new AbortController();
212
+ lifetime;
213
+ lanes = new Map();
214
+ waiting = new Map();
215
+ waitingControl = [];
216
+ waitingCount = 0;
217
+ scheduled = false;
218
+ sequence = 0;
219
+ draining;
220
+ control;
221
+ expected;
222
+ constructor(options) {
223
+ this.options = options;
224
+ this.lifetime = AbortSignal.any([options.signal, this.shutdown.signal]);
225
+ if (!this.lifetime.aborted) {
226
+ const unwatch = options.quota.watch(() => this.schedule());
227
+ this.lifetime.addEventListener("abort", unwatch, { once: true });
228
+ }
229
+ }
230
+ async register() {
231
+ const lane = await this.openControl("registration");
232
+ try {
233
+ this.expected = canonicalJson(lane.ready);
234
+ return lane.ready;
235
+ }
236
+ finally {
237
+ await lane.close();
238
+ }
239
+ }
240
+ async invoke(callback, args, scope) {
241
+ if (this.lifetime.aborted || this.expected === undefined)
242
+ throw new IsolatedRpcError("closed");
243
+ if (scope.signal?.aborted)
244
+ throw new IsolatedRpcError("cancelled");
245
+ const release = scope.mode === "setupCheck" ? undefined : this.options.quota.call();
246
+ let serving;
247
+ let lane;
248
+ const invocation = randomUUID();
249
+ const controller = new AbortController();
250
+ const cleanup = new Set();
251
+ const callSignal = AbortSignal.any([
252
+ controller.signal,
253
+ this.lifetime,
254
+ AbortSignal.timeout(60_000),
255
+ ...(scope.signal ? [scope.signal] : []),
256
+ ]);
257
+ try {
258
+ if (scope.mode === "setupCheck") {
259
+ lane = await this.openControl(scope.mode, scope.orgId, callSignal);
260
+ }
261
+ else {
262
+ const { mode, orgId, role } = scope;
263
+ if ((role !== "api" && role !== "worker" && role !== "gateway") ||
264
+ (mode === "org" ? !orgId : orgId !== undefined)) {
265
+ throw new IsolatedRpcError("refused");
266
+ }
267
+ serving = await this.admit(mode, orgId, role, callSignal);
268
+ lane = await waitForLane(serving.opening, callSignal);
269
+ }
270
+ lane.invocations.set(invocation, { ...scope, signal: callSignal, cleanup });
271
+ return await lane.rpc.call("invoke", { callback, invocation, args, ...(scope.config !== undefined && { config: scope.config }) }, { signal: callSignal, cancelGraceMs: CANCELLATION_GRACE_MS });
272
+ }
273
+ finally {
274
+ controller.abort();
275
+ lane?.invocations.delete(invocation);
276
+ for (const dispose of cleanup)
277
+ void Promise.resolve()
278
+ .then(dispose)
279
+ .catch(() => { });
280
+ release?.();
281
+ if (serving) {
282
+ serving.calls--;
283
+ serving.lastUsed = ++this.sequence;
284
+ if (serving.calls === 0 && serving.lane && !serving.closing)
285
+ this.idle(serving);
286
+ this.schedule();
287
+ }
288
+ else if (lane) {
289
+ await lane.close();
290
+ }
291
+ }
292
+ }
293
+ admit(mode, orgId, role, signal) {
294
+ if (signal.aborted)
295
+ return Promise.reject(new IsolatedRpcError("cancelled"));
296
+ const key = JSON.stringify([role, mode, orgId]);
297
+ const warm = this.lanes.get(key);
298
+ if (this.waitingCount === 0 && warm?.lane && this.claim(warm))
299
+ return Promise.resolve(warm);
300
+ const group = admissionGroup(orgId, role);
301
+ 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"));
305
+ }
306
+ return new Promise((resolve, reject) => {
307
+ const remove = (code) => {
308
+ this.remove(admission);
309
+ reject(new IsolatedRpcError(code));
310
+ this.schedule();
311
+ };
312
+ const abort = () => remove("cancelled");
313
+ const timer = setTimeout(() => remove("overloaded"), ADMISSION_TIMEOUT_MS);
314
+ timer.unref();
315
+ const admission = {
316
+ group,
317
+ mode,
318
+ orgId,
319
+ key,
320
+ resolve,
321
+ reject,
322
+ cleanup: () => {
323
+ clearTimeout(timer);
324
+ signal.removeEventListener("abort", abort);
325
+ },
326
+ };
327
+ queue.push(admission);
328
+ this.waiting.set(group, queue);
329
+ this.waitingCount++;
330
+ signal.addEventListener("abort", abort, { once: true });
331
+ this.schedule();
332
+ });
333
+ }
334
+ remove(admission, rotate = false) {
335
+ const queue = this.waiting.get(admission.group);
336
+ const index = queue?.indexOf(admission) ?? -1;
337
+ if (!queue || index < 0)
338
+ return;
339
+ queue.splice(index, 1);
340
+ this.waitingCount--;
341
+ admission.cleanup();
342
+ if (this.draining?.forAdmission === admission)
343
+ this.draining = undefined;
344
+ if (queue.length === 0 || rotate)
345
+ this.waiting.delete(admission.group);
346
+ if (rotate && queue.length > 0)
347
+ this.waiting.set(admission.group, queue);
348
+ }
349
+ schedule() {
350
+ if (this.scheduled ||
351
+ (this.waitingCount === 0 && this.waitingControl.length === 0) ||
352
+ this.lifetime.aborted)
353
+ return;
354
+ this.scheduled = true;
355
+ queueMicrotask(() => {
356
+ this.scheduled = false;
357
+ this.admitControl();
358
+ while (!this.lifetime.aborted && this.admitNext()) {
359
+ // Each admission advances the round robin by one organization.
360
+ }
361
+ });
362
+ }
363
+ admitNext() {
364
+ for (const queue of this.waiting.values()) {
365
+ const roles = new Set();
366
+ for (const admission of queue) {
367
+ if (roles.has(admission.key))
368
+ continue;
369
+ roles.add(admission.key);
370
+ if (this.tryAdmission(admission))
371
+ return true;
372
+ }
373
+ }
374
+ return false;
375
+ }
376
+ tryAdmission(admission) {
377
+ let slot = this.lanes.get(admission.key);
378
+ if (!slot) {
379
+ if (this.options.quota.inBackoff(this.options.revision)) {
380
+ this.remove(admission, true);
381
+ admission.reject(new IsolatedRpcError("overloaded"));
382
+ return true;
383
+ }
384
+ const lease = this.lanes.size < MAX_ISOLATED_LANES ? this.options.quota.process("serving") : undefined;
385
+ if (lease) {
386
+ slot = this.openServing(admission, lease);
387
+ }
388
+ else if (this.options.quota.atCapacity("serving")) {
389
+ this.makeRoomFor(admission);
390
+ }
391
+ }
392
+ if (!slot || !this.claim(slot))
393
+ return false;
394
+ this.remove(admission, true);
395
+ admission.resolve(slot);
396
+ return true;
397
+ }
398
+ claim(slot) {
399
+ if (slot.closing || slot === this.draining?.slot || slot.calls >= MAX_CALLS_PER_LANE)
400
+ return false;
401
+ clearTimeout(slot.timer);
402
+ slot.calls++;
403
+ slot.lastUsed = ++this.sequence;
404
+ return true;
405
+ }
406
+ makeRoomFor(admission) {
407
+ const ordered = [...this.lanes.values()].sort((a, b) => a.lastUsed - b.lastUsed);
408
+ if (ordered.some((slot) => slot.closing))
409
+ return;
410
+ const idle = ordered.find((slot) => slot.calls === 0 && slot.lane);
411
+ if (idle) {
412
+ this.draining = undefined;
413
+ this.evict(idle);
414
+ }
415
+ else if (!this.draining && ordered[0]) {
416
+ // Keep this lane reserved for the same waiter as warm lanes renew their calls.
417
+ this.draining = { forAdmission: admission, slot: ordered[0] };
418
+ }
419
+ }
420
+ openServing(admission, lease) {
421
+ const stop = new AbortController();
422
+ const end = AbortSignal.any([this.lifetime, stop.signal]);
423
+ const opening = this.start(admission.mode, admission.orgId, end, end, () => this.retire(slot), () => {
424
+ this.lanes.delete(admission.key);
425
+ if (this.draining?.slot === slot)
426
+ this.draining = undefined;
427
+ this.schedule();
428
+ }, lease);
429
+ const slot = {
430
+ orgId: admission.orgId,
431
+ stop,
432
+ opening,
433
+ calls: 0,
434
+ lastUsed: ++this.sequence,
435
+ closing: false,
436
+ };
437
+ this.lanes.set(admission.key, slot);
438
+ void opening.then((lane) => {
439
+ slot.lane = lane;
440
+ if (slot.calls === 0 && !slot.closing) {
441
+ this.idle(slot);
442
+ this.schedule();
443
+ }
444
+ }, () => { });
445
+ return slot;
446
+ }
447
+ idle(slot) {
448
+ clearTimeout(slot.timer);
449
+ slot.timer = setTimeout(() => this.evict(slot), IDLE_MS);
450
+ slot.timer.unref();
451
+ }
452
+ retire(slot) {
453
+ slot.closing = true;
454
+ clearTimeout(slot.timer);
455
+ }
456
+ evict(slot) {
457
+ this.retire(slot);
458
+ void slot.lane?.close().catch(() => this.options.cleanupFault());
459
+ }
460
+ async openControl(mode, orgId, signal = this.lifetime) {
461
+ if (this.lifetime.aborted)
462
+ throw new IsolatedRpcError("closed");
463
+ if (signal.aborted)
464
+ throw new IsolatedRpcError("cancelled");
465
+ if (this.waitingControl.length >= MAX_WAITING_CONTROL)
466
+ throw new IsolatedRpcError("overloaded");
467
+ return new Promise((resolve, reject) => {
468
+ const stopWaiting = (code) => {
469
+ this.removeControl(admission);
470
+ reject(new IsolatedRpcError(code));
471
+ this.schedule();
472
+ };
473
+ const abort = () => stopWaiting("cancelled");
474
+ const timer = setTimeout(() => stopWaiting("overloaded"), CONTROL_WAIT_MS);
475
+ timer.unref();
476
+ const admission = {
477
+ mode,
478
+ orgId,
479
+ signal,
480
+ resolve,
481
+ reject,
482
+ cleanup: () => {
483
+ clearTimeout(timer);
484
+ signal.removeEventListener("abort", abort);
485
+ },
486
+ };
487
+ this.waitingControl.push(admission);
488
+ signal.addEventListener("abort", abort, { once: true });
489
+ this.schedule();
490
+ });
491
+ }
492
+ removeControl(admission) {
493
+ const index = this.waitingControl.indexOf(admission);
494
+ if (index < 0)
495
+ return;
496
+ this.waitingControl.splice(index, 1);
497
+ admission.cleanup();
498
+ }
499
+ admitControl() {
500
+ const admission = this.waitingControl[0];
501
+ if (!admission || this.lifetime.aborted)
502
+ return;
503
+ if (this.options.quota.inBackoff(this.options.revision)) {
504
+ for (const waiting of this.waitingControl.splice(0)) {
505
+ waiting.cleanup();
506
+ waiting.reject(new IsolatedRpcError("overloaded"));
507
+ }
508
+ return;
509
+ }
510
+ if (this.control)
511
+ return;
512
+ const lease = this.options.quota.process("control");
513
+ if (!lease)
514
+ return;
515
+ this.removeControl(admission);
516
+ const { mode, orgId, signal } = admission;
517
+ const stop = new AbortController();
518
+ const end = AbortSignal.any([this.lifetime, stop.signal]);
519
+ const opening = this.start(mode, orgId, end, AbortSignal.any([end, signal]), () => { }, () => {
520
+ this.control = undefined;
521
+ this.schedule();
522
+ }, lease);
523
+ this.control = { orgId, stop, opening };
524
+ admission.resolve(opening);
525
+ }
526
+ async start(mode, orgId, end, admission, retiring, removed, lease) {
527
+ const kind = mode === "registration" || mode === "setupCheck" ? "control" : "serving";
528
+ const nonce = randomUUID();
529
+ const invocations = new Map();
530
+ let close;
531
+ let gate;
532
+ let closing;
533
+ let crashed = false;
534
+ let initialized = false;
535
+ let services = 0;
536
+ const crash = () => {
537
+ if (crashed || closing || end.aborted || (!initialized && admission.aborted))
538
+ return;
539
+ crashed = true;
540
+ const delay = this.options.quota.crashed(this.options.revision);
541
+ try {
542
+ this.options.onCrash?.(delay);
543
+ }
544
+ catch {
545
+ // Diagnostics must leave lane teardown and backoff intact.
546
+ }
547
+ };
548
+ const tearDown = () => {
549
+ void close?.().catch(() => this.options.cleanupFault());
550
+ };
551
+ const unexpectedExit = () => {
552
+ crash();
553
+ tearDown();
554
+ };
555
+ try {
556
+ const { postgresSocket, ...sandboxOptions } = this.options.sandbox;
557
+ if (mode === "org") {
558
+ if (!postgresSocket)
559
+ throw new IsolatedRpcError("refused");
560
+ gate = await startPostgresGate({
561
+ directory: this.options.socketDir,
562
+ sandboxId: nonce,
563
+ upstreamSocket: postgresSocket,
564
+ login: this.options.credential.login,
565
+ database: this.options.credential.database,
566
+ signal: end,
567
+ });
568
+ }
569
+ const sandbox = await startExtensionSandbox({
570
+ ...sandboxOptions,
571
+ stagingDir: this.options.socketDir,
572
+ sandboxId: nonce,
573
+ ...(gate && { postgresSocket: gate.socket }),
574
+ signal: admission,
575
+ });
576
+ const rpc = new IsolatedRpcPeer(sandbox.output, sandbox.input, {
577
+ budget: lease.budget,
578
+ requestBudget: lease.requestBudget,
579
+ onClose: (_error, cause) => {
580
+ if (cause === "transport" || (!initialized && cause === "protocol"))
581
+ unexpectedExit();
582
+ else
583
+ tearDown();
584
+ },
585
+ handle: async (method, payload, requestSignal) => {
586
+ const binary = payload instanceof RpcByteChunk ? payload : undefined;
587
+ const frame = envelope(binary?.metadata ?? payload);
588
+ const scope = typeof frame.invocation === "string" && invocations.get(frame.invocation);
589
+ if (!scope ||
590
+ end.aborted ||
591
+ Object.keys(frame).length !== 2 ||
592
+ !Object.hasOwn(frame, "invocation") ||
593
+ !Object.hasOwn(frame, "args") ||
594
+ !Array.isArray(frame.args) ||
595
+ scope.signal?.aborted ||
596
+ (binary && method !== "broker.storage.write")) {
597
+ throw new IsolatedRpcError("refused");
598
+ }
599
+ if (services >= MAX_SERVICES_PER_LANE[kind])
600
+ throw new IsolatedRpcError("overloaded");
601
+ const releaseService = this.options.quota.service(kind);
602
+ services++;
603
+ try {
604
+ return await this.options.broker(method, binary ? [...frame.args, binary.bytes] : frame.args, scope, AbortSignal.any([requestSignal, end, ...(scope.signal ? [scope.signal] : [])]));
605
+ }
606
+ finally {
607
+ services--;
608
+ releaseService();
609
+ }
610
+ },
611
+ });
612
+ close = () => {
613
+ if (closing)
614
+ return closing;
615
+ retiring();
616
+ end.removeEventListener("abort", tearDown);
617
+ closing = Promise.resolve().then(async () => {
618
+ const closeGate = gate?.close().catch(() => this.options.cleanupFault());
619
+ try {
620
+ await sandbox.close();
621
+ await closeGate;
622
+ lease.release();
623
+ }
624
+ catch {
625
+ this.options.cleanupFault();
626
+ await closeGate;
627
+ this.options.quota.retryRemoval(() => sandbox.close(), lease.release);
628
+ }
629
+ removed();
630
+ });
631
+ invocations.clear();
632
+ rpc.close(new IsolatedRpcError(end.aborted ? "cancelled" : "closed"));
633
+ return closing;
634
+ };
635
+ end.addEventListener("abort", tearDown, { once: true });
636
+ sandbox.stderr.resume();
637
+ void sandbox.exited.then(unexpectedExit, unexpectedExit);
638
+ const response = envelope(await rpc.call("initialize", {
639
+ entry: this.options.entry,
640
+ nonce,
641
+ mode,
642
+ ...(orgId && { orgId }),
643
+ ...(mode === "org" && {
644
+ db: { login: this.options.credential.login, url: this.options.credential.url },
645
+ rls: this.options.rls,
646
+ }),
647
+ }, { signal: admission, timeoutMs: ADMISSION_TIMEOUT_MS }));
648
+ if (response.nonce !== nonce ||
649
+ canonicalJson(response.manifest) !== canonicalJson(this.options.manifest) ||
650
+ canonicalJson(response.configSchemas) !== canonicalJson(this.options.configSchemas) ||
651
+ !Array.isArray(response.callbacks)) {
652
+ throw new IsolatedRpcError("refused");
653
+ }
654
+ const ready = response.callbacks;
655
+ if (mode !== "registration" && canonicalJson(ready) !== this.expected) {
656
+ throw new IsolatedRpcError("refused");
657
+ }
658
+ initialized = true;
659
+ return { rpc, close, ready, invocations };
660
+ }
661
+ catch (error) {
662
+ crash();
663
+ if (close)
664
+ await close().catch(() => this.options.cleanupFault());
665
+ else {
666
+ retiring();
667
+ await gate?.close().catch(() => this.options.cleanupFault());
668
+ if (error instanceof ExtensionSandboxUnconfirmedCleanupError) {
669
+ this.options.cleanupFault();
670
+ this.options.quota.retryRemoval(error.retryRemove, lease.release);
671
+ }
672
+ else {
673
+ lease.release();
674
+ }
675
+ removed();
676
+ }
677
+ throw error;
678
+ }
679
+ }
680
+ /** Stop the admitted processes and PostgreSQL gates while their grant is revoked. */
681
+ revokeOrg(orgId) {
682
+ for (const queue of this.waiting.values()) {
683
+ for (const admission of [...queue]) {
684
+ if (orgId !== undefined && admission.orgId !== orgId)
685
+ continue;
686
+ this.remove(admission);
687
+ admission.reject(new IsolatedRpcError("refused"));
688
+ }
689
+ }
690
+ for (const admission of [...this.waitingControl]) {
691
+ if (orgId !== undefined && admission.orgId !== orgId)
692
+ continue;
693
+ this.removeControl(admission);
694
+ admission.reject(new IsolatedRpcError("refused"));
695
+ }
696
+ for (const slot of this.lanes.values()) {
697
+ if (orgId !== undefined && slot.orgId !== orgId)
698
+ continue;
699
+ this.retire(slot);
700
+ slot.stop.abort();
701
+ }
702
+ if (this.control && (orgId === undefined || this.control.orgId === orgId)) {
703
+ this.control.stop.abort();
704
+ }
705
+ this.schedule();
706
+ }
707
+ async close() {
708
+ this.shutdown.abort();
709
+ for (const queue of this.waiting.values()) {
710
+ for (const admission of queue) {
711
+ admission.cleanup();
712
+ admission.reject(new IsolatedRpcError("closed"));
713
+ }
714
+ }
715
+ this.waiting.clear();
716
+ this.waitingCount = 0;
717
+ for (const admission of this.waitingControl.splice(0)) {
718
+ admission.cleanup();
719
+ admission.reject(new IsolatedRpcError("closed"));
720
+ }
721
+ const openings = [...this.lanes.values()].map((slot) => slot.opening);
722
+ if (this.control)
723
+ openings.push(this.control.opening);
724
+ await Promise.allSettled(openings.map(async (opening) => (await opening).close()));
725
+ }
726
+ }