hammerkit 1.27.0-next.9 → 2.0.0-next.10

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 (141) hide show
  1. package/build.schema.json +176 -6
  2. package/dist/cache/backends/local-cache-backend.js +6 -0
  3. package/dist/cache/backends/registry/registry-client.js +1 -0
  4. package/dist/cache/cache-sync.js +1 -1
  5. package/dist/cache/explain.js +23 -4
  6. package/dist/cli.js +2 -0
  7. package/dist/dashboard/assets/graph-canvas-DLioOiRN.css +1 -0
  8. package/dist/dashboard/assets/graph-canvas-HmkW_-XJ.js +8 -0
  9. package/dist/dashboard/assets/index-gIBDC_m8.css +2 -0
  10. package/dist/dashboard/assets/index-vE22S5E_.js +17 -0
  11. package/dist/dashboard/index.html +15 -0
  12. package/dist/dashboard/logo.png +0 -0
  13. package/dist/docker/item-network.js +13 -5
  14. package/dist/executer/archive-task-entry.js +4 -2
  15. package/dist/executer/deadline.js +17 -3
  16. package/dist/executer/deferred-restore.js +36 -0
  17. package/dist/executer/docker-service.js +30 -8
  18. package/dist/executer/docker-task.js +24 -1
  19. package/dist/executer/execute-work-service.js +2 -0
  20. package/dist/executer/execute-work-task.js +14 -5
  21. package/dist/executer/execution-steps.js +25 -4
  22. package/dist/executer/local-task.js +3 -0
  23. package/dist/executer/reset-work-tree.js +4 -0
  24. package/dist/executer/scheduler/enqueue-next.js +63 -7
  25. package/dist/executer/scheduler/state-key.js +89 -15
  26. package/dist/executer/watch-loop.js +22 -6
  27. package/dist/file/get-file-context.js +5 -1
  28. package/dist/harness/connect.js +20 -6
  29. package/dist/harness/mcp-command.js +22 -6
  30. package/dist/harness/mcp.js +63 -114
  31. package/dist/harness/opencode.js +158 -50
  32. package/dist/harness/pi.js +29 -0
  33. package/dist/harness/sandbox-client.js +194 -23
  34. package/dist/harness/service-tools.js +141 -0
  35. package/dist/harness/task-tools.js +221 -0
  36. package/dist/kubernetes/apply.js +49 -1
  37. package/dist/kubernetes/await-running-state.js +241 -18
  38. package/dist/kubernetes/claim-layout.js +10 -1
  39. package/dist/kubernetes/cluster-state.js +245 -0
  40. package/dist/kubernetes/ensure-kubernetes-deployment-exists.js +142 -9
  41. package/dist/kubernetes/ensure-kubernetes-service-exists.js +2 -0
  42. package/dist/kubernetes/ensure-persistent-data.js +305 -12
  43. package/dist/kubernetes/follow-pod-logs.js +281 -0
  44. package/dist/kubernetes/job-placement.js +36 -12
  45. package/dist/kubernetes/kept-claims.js +16 -1
  46. package/dist/kubernetes/kubernetes-instance.js +1 -0
  47. package/dist/kubernetes/network-policy.js +6 -5
  48. package/dist/kubernetes/quota-wait.js +97 -0
  49. package/dist/kubernetes/remove-stale-items.js +46 -0
  50. package/dist/kubernetes/restore-kubernetes-data.js +35 -8
  51. package/dist/kubernetes/sandbox-runner.js +628 -0
  52. package/dist/kubernetes/service-rollouts.js +74 -0
  53. package/dist/kubernetes/store-kubernetes-data.js +18 -4
  54. package/dist/kubernetes/volumes.js +124 -12
  55. package/dist/main.js +2 -0
  56. package/dist/optimizer/calculate-checksum.js +49 -5
  57. package/dist/optimizer/check-key.js +94 -0
  58. package/dist/optimizer/check-keys.js +66 -0
  59. package/dist/optimizer/get-work-cache-stats.js +53 -27
  60. package/dist/optimizer/work-task-cache-description.js +49 -1
  61. package/dist/parser/read-build-file.js +8 -3
  62. package/dist/planner/service-definition.js +9 -4
  63. package/dist/planner/utils/append-work-dependencies.js +5 -3
  64. package/dist/planner/utils/append-work-service.js +18 -1
  65. package/dist/planner/utils/append-work-task.js +13 -3
  66. package/dist/planner/utils/get-work-runtime.js +6 -1
  67. package/dist/planner/utils/normalize-path.js +19 -1
  68. package/dist/planner/utils/parse-work-mount.js +7 -1
  69. package/dist/planner/utils/parse-work-port.js +4 -1
  70. package/dist/planner/utils/template-value.js +20 -4
  71. package/dist/planner/validate.js +22 -0
  72. package/dist/planner/work-item-executions.js +27 -0
  73. package/dist/planner/work-network.js +3 -1
  74. package/dist/planner/work-runtime-aggregate.js +32 -0
  75. package/dist/planner/work-runtime-kubernetes.js +204 -53
  76. package/dist/planner/work-task.js +6 -1
  77. package/dist/program.js +27 -9
  78. package/dist/remote/device-login.js +7 -2
  79. package/dist/remote/host-config.js +69 -3
  80. package/dist/remote/remote-commands.js +33 -7
  81. package/dist/remote/remote-status.js +112 -0
  82. package/dist/remote/remote-work-commands.js +571 -45
  83. package/dist/remote/server-client.js +15 -2
  84. package/dist/remote/token-source.js +64 -26
  85. package/dist/run-program.js +9 -0
  86. package/dist/schema/build-file-base-task-schema.js +3 -3
  87. package/dist/schema/build-file-container-service-schema.js +10 -0
  88. package/dist/schema/build-file-container-task-schema.js +16 -1
  89. package/dist/schema/build-file-include-schema.js +18 -4
  90. package/dist/schema/build-file-kubernetes-service-schema.js +2 -0
  91. package/dist/schema/build-file-task-schema.js +5 -1
  92. package/dist/schema/capabilities-schema.js +56 -0
  93. package/dist/schema/reference-parser.js +119 -11
  94. package/dist/schema/removed-properties.js +20 -0
  95. package/dist/schema/schema-parser.js +140 -43
  96. package/dist/schema/work-scope-parser.js +33 -10
  97. package/dist/secrets/command-secret-provider.js +3 -1
  98. package/dist/secrets/github-app-token-command.js +3 -1
  99. package/dist/secrets/secret-catalog.js +43 -19
  100. package/dist/server/accounts-api.js +4 -1
  101. package/dist/server/approvals-api.js +1 -1
  102. package/dist/server/capacity-format.js +36 -0
  103. package/dist/server/capacity.js +330 -0
  104. package/dist/server/checks-api.js +83 -0
  105. package/dist/server/checks.js +116 -0
  106. package/dist/server/dashboard.js +214 -0
  107. package/dist/server/definitions-api.js +66 -3
  108. package/dist/server/endpoints.js +803 -0
  109. package/dist/server/executor.js +216 -30
  110. package/dist/server/kubernetes-backend.js +415 -48
  111. package/dist/server/kubernetes-sandbox-storage.js +60 -6
  112. package/dist/server/oauth.js +16 -1
  113. package/dist/server/overview.js +340 -0
  114. package/dist/server/plan.js +186 -124
  115. package/dist/server/policy.js +42 -4
  116. package/dist/server/proposals-api.js +17 -8
  117. package/dist/server/repo-access.js +5 -0
  118. package/dist/server/run-logs.js +4 -0
  119. package/dist/server/run-plan.js +38 -4
  120. package/dist/server/run-request.js +58 -3
  121. package/dist/server/run-worker.js +307 -17
  122. package/dist/server/runs.js +1036 -42
  123. package/dist/server/sandbox-files.js +107 -16
  124. package/dist/server/sandbox-patch.js +43 -17
  125. package/dist/server/sandbox-pod.js +28 -0
  126. package/dist/server/sandbox-storage.js +23 -0
  127. package/dist/server/sandboxes.js +65 -23
  128. package/dist/server/server-config.js +250 -11
  129. package/dist/server/server.js +465 -33
  130. package/dist/server/service-runs.js +89 -0
  131. package/dist/server/sources.js +68 -11
  132. package/dist/server/timings.js +152 -0
  133. package/dist/server/wait-reason.js +21 -0
  134. package/dist/utils/buffer-context.js +30 -20
  135. package/dist/utils/limit.js +30 -0
  136. package/dist/utils/read-lines.js +65 -0
  137. package/dist/utils/tar.js +28 -1
  138. package/dist/utils/terminal-prompt.js +53 -0
  139. package/dist/utils/units.js +36 -1
  140. package/dist/utils/web-links.js +34 -0
  141. package/package.json +8 -2
@@ -1,18 +1,23 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.startServer = exports.getDiscoveryDocument = exports.SERVER_PROTOCOL = exports.DISCOVERY_PATH = void 0;
3
+ exports.startServer = exports.runsTheSame = exports.refuseWake = exports.getDiscoveryDocument = exports.SERVER_PROTOCOL = exports.DISCOVERY_PATH = void 0;
4
4
  const http_1 = require("http");
5
5
  const https_1 = require("https");
6
+ const tls_1 = require("tls");
6
7
  const version_1 = require("../version");
7
8
  const server_config_1 = require("./server-config");
8
9
  const discovery_1 = require("./discovery");
9
10
  const oauth_1 = require("./oauth");
10
11
  const policy_1 = require("./policy");
12
+ const repo_1 = require("./repo");
11
13
  const run_store_1 = require("./run-store");
12
14
  const runs_1 = require("./runs");
13
15
  const git_checkout_1 = require("./git-checkout");
14
16
  const repo_access_1 = require("./repo-access");
15
17
  const executor_1 = require("./executor");
18
+ const capacity_1 = require("./capacity");
19
+ const execute_docker_1 = require("../executer/execute-docker");
20
+ const timings_1 = require("./timings");
16
21
  const kubernetes_backend_1 = require("./kubernetes-backend");
17
22
  const run_plan_1 = require("./run-plan");
18
23
  const work_network_1 = require("../planner/work-network");
@@ -32,10 +37,15 @@ const sandbox_storage_1 = require("./sandbox-storage");
32
37
  const kubernetes_sandbox_storage_1 = require("./kubernetes-sandbox-storage");
33
38
  const sandbox_docker_1 = require("./sandbox-docker");
34
39
  const sandboxes_api_1 = require("./sandboxes-api");
40
+ const endpoints_1 = require("./endpoints");
41
+ const service_runs_1 = require("./service-runs");
35
42
  const units_1 = require("../utils/units");
36
43
  const run_logs_1 = require("./run-logs");
37
44
  const get_cache_directory_1 = require("../optimizer/get-cache-directory");
38
45
  const path_1 = require("path");
46
+ const checks_1 = require("./checks");
47
+ const checks_api_1 = require("./checks-api");
48
+ const overview_1 = require("./overview");
39
49
  var discovery_2 = require("./discovery");
40
50
  Object.defineProperty(exports, "DISCOVERY_PATH", { enumerable: true, get: function () { return discovery_2.DISCOVERY_PATH; } });
41
51
  Object.defineProperty(exports, "SERVER_PROTOCOL", { enumerable: true, get: function () { return discovery_2.SERVER_PROTOCOL; } });
@@ -64,6 +74,8 @@ const HEARTBEAT_MS = 15000;
64
74
  // the longest `?wait=` of a run: below the 60 seconds after which a proxy in front of the
65
75
  // server (nginx by default) closes a connection that says nothing
66
76
  const MAX_WAIT_MS = 50000;
77
+ // how often checks older than `runs.checksKeep` are removed
78
+ const CHECK_SWEEP_MS = 6 * 60 * 60 * 1000;
67
79
  // Server-sent events: `id` is the sequence number, so a client that lost the
68
80
  // connection continues with Last-Event-ID (or ?after=) and misses nothing.
69
81
  function streamEvents(registry, config, principal, id, req, res, url) {
@@ -96,8 +108,8 @@ function streamEvents(registry, config, principal, id, req, res, url) {
96
108
  watch.stop();
97
109
  });
98
110
  }
99
- async function handleRuns(config, registry, definitions, sources, sandboxes, planning, repos, log, principal, req, res, url) {
100
- const match = /^\/v1\/runs(?:\/([^/]+)(?:\/(cancel|events|logs))?)?$/.exec(url.pathname);
111
+ async function handleRuns(config, registry, definitions, sources, sandboxes, planning, repos, endpointUrl, log, principal, req, res, url) {
112
+ const match = /^\/v1\/runs(?:\/([^/]+)(?:\/(cancel|events|logs|extend|wake))?)?$/.exec(url.pathname);
101
113
  if (!match) {
102
114
  return false;
103
115
  }
@@ -106,16 +118,22 @@ async function handleRuns(config, registry, definitions, sources, sandboxes, pla
106
118
  if (!id) {
107
119
  if (method === 'GET') {
108
120
  // the results of each task are read one run at a time
121
+ const viewer = (0, overview_1.getViewer)(config, principal);
122
+ let filter;
123
+ try {
124
+ filter = (0, overview_1.parseRunFilter)(url.searchParams, viewer.grant);
125
+ }
126
+ catch (e) {
127
+ (0, http_2.send)(res, e instanceof overview_1.FilterRefused ? 403 : 400, { error: e instanceof Error ? e.message : String(e) });
128
+ return true;
129
+ }
130
+ const runs = filter.scope === 'mine' ? registry.list(principal) : registry.all();
109
131
  (0, http_2.send)(res, 200, {
110
- runs: registry.list(principal).map((run) => {
111
- const { results, ...listed } = toRunResponse(run);
112
- void results;
113
- return listed;
114
- }),
132
+ runs: (0, overview_1.filterRuns)(runs, viewer, filter).map((run) => listRun(registry, definitions, viewer, run)),
115
133
  });
116
134
  }
117
135
  else if (method === 'POST') {
118
- await submitRun(config, registry, definitions, sources, sandboxes, planning, repos, log, principal, req, res);
136
+ await submitRun(config, registry, definitions, sources, sandboxes, planning, repos, endpointUrl, log, principal, req, res);
119
137
  }
120
138
  else {
121
139
  (0, http_2.send)(res, 405, { error: 'method not allowed' }, { allow: 'GET, POST' });
@@ -130,10 +148,40 @@ async function handleRuns(config, registry, definitions, sources, sandboxes, pla
130
148
  (0, http_2.send)(res, 405, { error: 'method not allowed' }, { allow: 'POST' });
131
149
  return true;
132
150
  }
133
- const run = registry.cancel(principal, id, accountsOf(config, principal));
151
+ const grant = (0, policy_1.getGrant)(config.entitlements, principal);
152
+ const run = registry.cancel(principal, id, accountsOf(config, principal), (up) => (0, service_runs_1.mayPublishEndpoints)(grant, up));
134
153
  log(`cancel iss=${principal.iss} sub=${principal.sub} run=${id} found=${Boolean(run)}`);
135
154
  run ? (0, http_2.send)(res, 200, toRunResponse(run)) : (0, http_2.send)(res, 404, { error: 'not found' });
136
155
  }
156
+ else if (action === 'extend') {
157
+ if (method !== 'POST') {
158
+ (0, http_2.send)(res, 405, { error: 'method not allowed' }, { allow: 'POST' });
159
+ return true;
160
+ }
161
+ await extendRun(config, registry, log, principal, id, req, res);
162
+ }
163
+ else if (action === 'wake') {
164
+ if (method !== 'POST') {
165
+ (0, http_2.send)(res, 405, { error: 'method not allowed' }, { allow: 'POST' });
166
+ return true;
167
+ }
168
+ // as a request to one of its endpoints would, with the same check of its owner
169
+ const grant = (0, policy_1.getGrant)(config.entitlements, principal);
170
+ const result = registry.wake(principal, id, (run) => (0, service_runs_1.mayOpenEndpoints)(grant, run), (run) => refuseWake(config, repos, run));
171
+ log(`wake iss=${principal.iss} sub=${principal.sub} run=${id} result=${result.status}`);
172
+ if (result.status === 'not-found') {
173
+ (0, http_2.send)(res, 404, { error: 'not found' });
174
+ }
175
+ else if (result.status === 'not-asleep') {
176
+ (0, http_2.send)(res, 409, { error: `the run is ${result.state}, only a service run that sleeps wakes` });
177
+ }
178
+ else if (result.status === 'refused') {
179
+ (0, http_2.send)(res, 409, { error: result.reason });
180
+ }
181
+ else {
182
+ (0, http_2.send)(res, 200, toRunResponse(result.run));
183
+ }
184
+ }
137
185
  else if (method !== 'GET') {
138
186
  (0, http_2.send)(res, 405, { error: 'method not allowed' }, { allow: 'GET' });
139
187
  }
@@ -149,9 +197,12 @@ async function handleRuns(config, registry, definitions, sources, sandboxes, pla
149
197
  (0, http_2.send)(res, 400, { error: e instanceof Error ? e.message : String(e) });
150
198
  return true;
151
199
  }
152
- const logs = registry.logs(principal, id, accountsOf(config, principal));
200
+ // an entitlement with `observe` reads the log of every run
201
+ const logs = registry.logs(principal, id, accountsOf(config, principal)) ??
202
+ ((0, policy_1.getGrant)(config.entitlements, principal).observe ? registry.logsOf(id) : undefined);
203
+ // with the tasks, services and the server's own lines (`hammerkit`) the log has
153
204
  logs
154
- ? (0, http_2.send)(res, 200, (0, run_logs_1.readLogs)(logs.events, logs.index, query, logs.truncated))
205
+ ? (0, http_2.send)(res, 200, { ...(0, run_logs_1.readLogs)(logs.events, logs.index, query, logs.truncated), names: logs.index.names() })
155
206
  : (0, http_2.send)(res, 404, { error: 'not found' });
156
207
  }
157
208
  else {
@@ -169,9 +220,18 @@ async function handleRuns(config, registry, definitions, sources, sandboxes, pla
169
220
  // a caller that hangs up stops waiting
170
221
  const gone = new AbortController();
171
222
  res.on('close', () => gone.abort());
172
- const run = await registry.wait(principal, id, wait, accountsOf(config, principal), gone.signal);
223
+ const viewer = (0, overview_1.getViewer)(config, principal);
224
+ // an entitlement with `observe` reads every run as it is, without waiting
225
+ const run = (await registry.wait(principal, id, wait, accountsOf(config, principal), gone.signal)) ??
226
+ (viewer.grant.observe ? registry.peek(id) : undefined);
173
227
  if (!gone.signal.aborted) {
174
- run ? (0, http_2.send)(res, 200, toRunResponse(run)) : (0, http_2.send)(res, 404, { error: 'not found' });
228
+ const may = run && (0, overview_1.runActions)(viewer, run);
229
+ run
230
+ ? (0, http_2.send)(res, 200, {
231
+ ...toRunResponse(run, (0, overview_1.queuePlace)(registry, viewer, run), !(0, overview_1.owns)(viewer, run), viewer.nameOf),
232
+ ...(may ? { may } : {}),
233
+ })
234
+ : (0, http_2.send)(res, 404, { error: 'not found' });
175
235
  }
176
236
  }
177
237
  return true;
@@ -181,12 +241,103 @@ function accountsOf(config, principal) {
181
241
  const grant = (0, policy_1.getGrant)(config.entitlements, principal);
182
242
  return (account) => (0, policy_1.canUse)(grant, account);
183
243
  }
184
- function toRunResponse(run) {
244
+ async function extendRun(config, registry, log, principal, id, req, res) {
245
+ const body = (await (0, http_2.readJson)(req));
246
+ let ttl;
247
+ try {
248
+ if (typeof body !== 'object' || body === null || typeof body.ttl !== 'string') {
249
+ throw new Error();
250
+ }
251
+ ttl = (0, units_1.parseDuration)(body.ttl);
252
+ if (!(ttl > 0)) {
253
+ throw new Error();
254
+ }
255
+ }
256
+ catch {
257
+ (0, http_2.send)(res, 400, { error: 'ttl: expected a duration like 30m, 8h or 1d' });
258
+ return;
259
+ }
260
+ const grant = (0, policy_1.getGrant)(config.entitlements, principal);
261
+ const result = registry.extend(principal, id, ttl, (run) => (0, service_runs_1.mayOpenEndpoints)(grant, run));
262
+ log(`extend iss=${principal.iss} sub=${principal.sub} run=${id} result=${result.status}`);
263
+ if (result.status === 'not-found') {
264
+ (0, http_2.send)(res, 404, { error: 'not found' });
265
+ }
266
+ else if (result.status === 'not-up') {
267
+ (0, http_2.send)(res, 409, { error: `the run is ${result.state}, only a service run that is up can be extended` });
268
+ }
269
+ else {
270
+ (0, http_2.send)(res, 200, toRunResponse(result.run));
271
+ }
272
+ }
273
+ // Why the owner of a service run that sleeps may no longer run it, with the entitlements of
274
+ // the moment: a wake is started by who opens an endpoint, but runs as the owner, as a new
275
+ // run of theirs would.
276
+ function refuseWake(config, repos, run) {
277
+ if (run.source.type !== 'ref') {
278
+ return 'a run from a sandbox does not wake';
279
+ }
280
+ const grant = (0, policy_1.getGrant)(config.entitlements, {
281
+ iss: run.owner.iss,
282
+ sub: run.owner.sub,
283
+ groups: run.owner.groups ?? [],
284
+ claims: run.owner.claims ?? {},
285
+ });
286
+ const decision = (0, policy_1.decideRun)({
287
+ grant,
288
+ accounts: run.accounts,
289
+ catalog: config.accounts,
290
+ source: { type: 'ref', repo: run.source.repo, ref: run.source.ref },
291
+ // an account it may only request is refused, the wake has nobody to approve it
292
+ approvable: () => true,
293
+ readable: (repo) => repos.readable(repo),
294
+ });
295
+ if (decision.type === 'refuse') {
296
+ return `its owner ${run.owner.sub} may no longer run it: ${decision.error.replace(/^you /, 'they ')}`;
297
+ }
298
+ if (decision.type === 'approval') {
299
+ return `its owner ${run.owner.sub} may only request ${decision.accounts.join(', ')} now, start it again`;
300
+ }
301
+ if (run.up?.endpoints.length && (0, policy_1.endpointLevel)(grant, run.source.repo) !== 'publish') {
302
+ return `its owner ${run.owner.sub} may no longer publish endpoints of ${run.source.repo}`;
303
+ }
304
+ return undefined;
305
+ }
306
+ exports.refuseWake = refuseWake;
307
+ // Whether a service run that is not over runs what a new one would, but for its commit: then
308
+ // the new one moves it there (RunRegistry.move)
309
+ function runsTheSame(run, next) {
310
+ const sorted = (values) => JSON.stringify([...values].sort());
311
+ const options = (value) => JSON.stringify(value ?? {}, Object.keys(value ?? {}).sort());
312
+ const endpoints = (spec) => JSON.stringify(spec.endpoints.map((endpoint) => [endpoint.service, endpoint.port, endpoint.host]));
313
+ return (!!run.up &&
314
+ run.source.type === 'ref' &&
315
+ run.source.repo === next.source.repo &&
316
+ run.definition === next.definition &&
317
+ sorted(run.accounts) === sorted(next.accounts) &&
318
+ sorted(run.up.services) === sorted(next.up.services) &&
319
+ endpoints(run.up) === endpoints(next.up) &&
320
+ (run.up.sleepTtl ?? null) === (next.up.sleepTtl ?? null) &&
321
+ options(run.options) === options(next.request.options));
322
+ }
323
+ exports.runsTheSame = runsTheSame;
324
+ // A run whole, for its owner and who may read it; who is not its owner is told whose it is.
325
+ function toRunResponse(run, queue, named = false, nameOf) {
185
326
  const { owner, ...visible } = run;
186
- void owner;
187
- return { ...visible, results: run.results ?? {} };
327
+ const name = owner.name ?? nameOf?.(owner);
328
+ return {
329
+ ...visible,
330
+ ...(named ? { owner: { iss: owner.iss, sub: owner.sub, ...(name ? { name } : {}) } } : {}),
331
+ results: run.results ?? {},
332
+ ...(queue ? { queue } : {}),
333
+ };
334
+ }
335
+ function listRun(registry, definitions, viewer, run) {
336
+ return (0, overview_1.toListedRun)(viewer, run, (0, overview_1.queuePlace)(registry, viewer, run), entryOf(definitions));
188
337
  }
189
- async function submitRun(config, registry, definitions, sources, sandboxes, planning, repos, log, principal, req, res) {
338
+ // where in its repository the build file of a version is
339
+ const entryOf = (definitions) => (definition) => definitions.find(definition)?.entry;
340
+ async function submitRun(config, registry, definitions, sources, sandboxes, planning, repos, endpointUrl, log, principal, req, res) {
190
341
  const parsed = run_request_1.runRequestSchema.safeParse(await (0, http_2.readJson)(req));
191
342
  if (!parsed.success) {
192
343
  const issue = parsed.error.issues[0];
@@ -218,6 +369,27 @@ async function submitRun(config, registry, definitions, sources, sandboxes, plan
218
369
  (0, http_2.send)(res, 400, { error: `${version.hash} has no task ${unknown.map(oauth_1.quote).join(', ')}` });
219
370
  return;
220
371
  }
372
+ const notServices = request.services.filter((service) => !version.services.includes(service));
373
+ if (notServices.length > 0) {
374
+ (0, http_2.send)(res, 400, { error: `${version.hash} has no service ${notServices.map(oauth_1.quote).join(', ')}` });
375
+ return;
376
+ }
377
+ if (request.endpoints.length > 0 && !config.endpoints) {
378
+ (0, http_2.send)(res, 400, { error: 'this server publishes no endpoints (endpoints is not configured)' });
379
+ return;
380
+ }
381
+ const ttl = request.services.length > 0 ? (0, units_1.parseDuration)(request.ttl ?? config.runs.up.ttl) : 0;
382
+ if (ttl > (0, units_1.parseDuration)(config.runs.up.maxTtl)) {
383
+ (0, http_2.send)(res, 400, { error: `ttl: at most ${config.runs.up.maxTtl} on this server (runs.up.maxTtl)` });
384
+ return;
385
+ }
386
+ // the files of a sandbox change under a run that sleeps, it would wake to others
387
+ if (request.sleepTtl !== undefined && request.source.type === 'sandbox') {
388
+ (0, http_2.send)(res, 400, { error: 'sleepTtl: a service run from a sandbox does not sleep, start it from a branch' });
389
+ return;
390
+ }
391
+ const sleepTtlText = request.source.type === 'ref' ? request.sleepTtl ?? config.runs.up.sleepTtl : undefined;
392
+ const sleepTtl = request.services.length > 0 && sleepTtlText ? (0, units_1.parseDuration)(sleepTtlText) : undefined;
221
393
  const argued = (request.options.args ?? []).length > 0 ? request.tasks[0] : undefined;
222
394
  if (argued !== undefined && version.services.includes(argued)) {
223
395
  (0, http_2.send)(res, 400, { error: `${argued} is a service, arguments go to a task` });
@@ -239,6 +411,12 @@ async function submitRun(config, registry, definitions, sources, sandboxes, plan
239
411
  return;
240
412
  }
241
413
  }
414
+ if (request.services.length > 0 && request.source.type === 'sandbox' && config.backend.type === 'kubernetes') {
415
+ (0, http_2.send)(res, 400, {
416
+ error: 'on a cluster a service run starts from a branch, push the sandbox and start it from there',
417
+ });
418
+ return;
419
+ }
242
420
  const sandbox = request.source.type === 'sandbox' ? sandboxes.registry.get(principal, request.source.id) : undefined;
243
421
  if (request.source.type === 'sandbox') {
244
422
  if (!sandbox) {
@@ -257,6 +435,24 @@ async function submitRun(config, registry, definitions, sources, sandboxes, plan
257
435
  (0, http_2.send)(res, 413, { error: over });
258
436
  return;
259
437
  }
438
+ // a check counts like a run from a commit of the repository, and leaves what it made in
439
+ // the repository's cache, which runs from main restore from: the caller must be allowed
440
+ // to start runs from it, and to push a branch of it, which with a run from that branch
441
+ // leaves the same
442
+ if (request.source.check && !(0, repo_1.matchesAnyRepo)(grant.repos, sandbox.repo)) {
443
+ log(`refuse run iss=${principal.iss} sub=${principal.sub}: check on ${sandbox.repo} without the repository`);
444
+ (0, http_2.send)(res, 403, {
445
+ error: `a check counts like a run from ${sandbox.repo}, which no entitlement of yours lists in repos`,
446
+ });
447
+ return;
448
+ }
449
+ if (request.source.check && (0, policy_1.sandboxPushBranches)(grant, sandbox.repo).length === 0) {
450
+ log(`refuse run iss=${principal.iss} sub=${principal.sub}: check on ${sandbox.repo} without a branch to push`);
451
+ (0, http_2.send)(res, 403, {
452
+ error: `a check counts like a run from a branch you pushed, and you may push no branch of ${sandbox.repo}`,
453
+ });
454
+ return;
455
+ }
260
456
  }
261
457
  // the accounts of a run are read from the files it is pinned to, with the engine
262
458
  const bundle = version.plan ? await definitions.files(version) : undefined;
@@ -275,12 +471,20 @@ async function submitRun(config, registry, definitions, sources, sandboxes, plan
275
471
  (0, http_2.send)(res, 400, { error: `the run does not load: ${e instanceof Error ? e.message : String(e)}` });
276
472
  return;
277
473
  }
278
- const refused = (0, run_plan_1.refuseArguments)(request, planned.plan, sandbox ? sandboxes.policy : planning.policy);
474
+ const refused = (0, run_plan_1.refuseArguments)(request, planned.plan, sandbox ? sandboxes.policy : planning.policy) ??
475
+ (0, service_runs_1.refuseEndpoints)(request, planned.plan, config.runs.secretNetwork === 'open');
279
476
  if (refused) {
280
477
  log(`refuse run iss=${principal.iss} sub=${principal.sub}: ${refused}`);
281
478
  (0, http_2.send)(res, 400, { error: refused });
282
479
  return;
283
480
  }
481
+ const runRepo = request.source.type === 'ref' ? request.source.repo : sandbox?.repo;
482
+ if (request.endpoints.length > 0 && (!runRepo || (0, policy_1.endpointLevel)(grant, runRepo) !== 'publish')) {
483
+ const error = `you may not publish endpoints of ${runRepo ?? 'this source'}, an entitlement needs endpoints with level publish for it`;
484
+ log(`refuse run iss=${principal.iss} sub=${principal.sub}: ${error}`);
485
+ (0, http_2.send)(res, 403, { error });
486
+ return;
487
+ }
284
488
  const decision = (0, policy_1.decideRun)({
285
489
  grant,
286
490
  accounts: planned.accounts,
@@ -324,13 +528,57 @@ async function submitRun(config, registry, definitions, sources, sandboxes, plan
324
528
  else if (request.source.type === 'upload') {
325
529
  source = request.source;
326
530
  }
327
- const submit = (runSource) => registry.submit(principal, {
531
+ // a service run is named after its branch unless it says, and its endpoints after that
532
+ const serviceName = request.services.length > 0
533
+ ? request.name ??
534
+ (0, service_runs_1.getServiceRunName)(request.source.type === 'ref' ? request.source.ref : sandbox?.ref)
535
+ : '';
536
+ const up = request.services.length > 0
537
+ ? {
538
+ services: request.services,
539
+ ttl,
540
+ ...(sleepTtl ? { sleepTtl } : {}),
541
+ name: serviceName,
542
+ endpoints: (0, service_runs_1.toRunEndpoints)(request.endpoints, (0, service_runs_1.getEndpointHosts)(serviceName, principal, request.endpoints), endpointUrl),
543
+ }
544
+ : undefined;
545
+ // a run that may sleep keeps what its owner is entitled by, for the check of a wake
546
+ const claimNames = new Set(config.entitlements.flatMap((entitlement) => Object.keys(entitlement.claims?.match ?? {})));
547
+ const name = (0, oauth_1.displayName)(principal);
548
+ const owner = {
549
+ ...principal,
550
+ // how the pages name them, which the claims kept no longer tell
551
+ ...(name ? { name } : {}),
552
+ claims: Object.fromEntries(Object.entries(principal.claims).filter(([name]) => claimNames.has(name))),
553
+ };
554
+ // A service run of the caller of this name that runs the same build file, services and
555
+ // endpoints moves to the commit, in place of a new run that would replace it: it keeps its
556
+ // id, its addresses and its volumes. A run that needs an approval is new as before.
557
+ if (up && source?.type === 'ref' && approvals.length === 0) {
558
+ const named = registry.named(principal, up.name);
559
+ if (named && runsTheSame(named, { definition: version.hash, accounts: planned.accounts, request, source, up })) {
560
+ const from = (registry.logs(principal, named.id)?.index.size ?? 0) + 1;
561
+ const moved = registry.move(principal, named.id, {
562
+ source,
563
+ plan: planned.plan,
564
+ owner,
565
+ ...(request.ttl ? { ttl } : {}),
566
+ });
567
+ if (moved) {
568
+ log(`move run ${moved.id} iss=${principal.iss} sub=${principal.sub} name=${up.name} to ${source.commit} (${moved.state})`);
569
+ (0, http_2.send)(res, 202, { ...toRunResponse(moved), moved: { logFrom: from } });
570
+ return;
571
+ }
572
+ }
573
+ }
574
+ const submit = (runSource) => registry.submit(owner, {
328
575
  definition: version.hash,
329
576
  tasks: request.tasks,
330
577
  accounts: planned.accounts,
331
578
  plan: planned.plan,
332
579
  source: runSource,
333
580
  options: request.options,
581
+ ...(up ? { up } : {}),
334
582
  }, approvals);
335
583
  try {
336
584
  // a sandbox is read and the run submitted while nothing else changes it: the run
@@ -346,10 +594,13 @@ async function submitRun(config, registry, definitions, sources, sandboxes, plan
346
594
  commit: state.commit,
347
595
  tree: state.tree,
348
596
  clean: state.clean,
597
+ ...(request.source.type === 'sandbox' && request.source.check ? { check: true } : {}),
349
598
  });
350
599
  });
351
- log(`run ${run.id} iss=${principal.iss} sub=${principal.sub} accounts=[${planned.accounts.join(',')}] source=${run.source.type}${run.source.type === 'sandbox' ? ` sandbox=${run.source.id}` : ''} tasks=${run.tasks.length}${approvals.length > 0 ? ` approval=[${approvals.join(',')}]` : ''}`);
352
- (0, http_2.send)(res, 202, toRunResponse(run));
600
+ log(`run ${run.id} iss=${principal.iss} sub=${principal.sub} accounts=[${planned.accounts.join(',')}] source=${run.source.type}${run.source.type === 'sandbox' ? ` sandbox=${run.source.id}${run.source.check ? ' check' : ''}` : ''} tasks=${run.tasks.length}${run.up
601
+ ? ` services=[${run.up.services.join(',')}] name=${run.up.name} endpoints=${run.up.endpoints.length}`
602
+ : ''}${approvals.length > 0 ? ` approval=[${approvals.join(',')}]` : ''}`);
603
+ (0, http_2.send)(res, 202, toRunResponse(run, (0, overview_1.queuePlace)(registry, (0, overview_1.getViewer)(config, principal), run)));
353
604
  }
354
605
  catch (e) {
355
606
  if (e instanceof runs_1.RunError) {
@@ -385,7 +636,14 @@ async function authenticate(verifier, log, req, res) {
385
636
  return null;
386
637
  }
387
638
  }
388
- async function handle(config, registry, definitions, proposals, sources, sandboxes, planning, repos, verifier, log, req, res) {
639
+ async function handle(api, verifier, req, res) {
640
+ const { config, gateway, log } = api;
641
+ // the hosts of endpoints are the apps of service runs, not the API
642
+ const label = gateway?.hostOf(req);
643
+ if (gateway && label) {
644
+ await gateway.handle(label, req, res);
645
+ return;
646
+ }
389
647
  const url = new URL(req.url ?? '/', 'http://localhost');
390
648
  const path = url.pathname;
391
649
  if (path === discovery_1.DISCOVERY_PATH || path === '/healthz') {
@@ -393,13 +651,30 @@ async function handle(config, registry, definitions, proposals, sources, sandbox
393
651
  (0, http_2.send)(res, 405, { error: 'method not allowed' }, { allow: 'GET, HEAD' });
394
652
  return;
395
653
  }
396
- (0, http_2.send)(res, 200, path === '/healthz' ? { status: 'ok' } : getDiscoveryDocument(config));
654
+ const dashboard = gateway?.dashboardUrl();
655
+ (0, http_2.send)(res, 200, path === '/healthz' ? { status: 'ok' } : { ...getDiscoveryDocument(config), ...(dashboard ? { dashboard } : {}) });
656
+ return;
657
+ }
658
+ // a person who opens the address of the server in a browser goes to the dashboard
659
+ const dashboard = gateway?.dashboardUrl();
660
+ if (path === '/' && req.method === 'GET' && dashboard && (req.headers.accept ?? '').includes('text/html')) {
661
+ res.writeHead(302, { location: dashboard, 'cache-control': 'no-store' });
662
+ res.end();
397
663
  return;
398
664
  }
399
665
  const principal = await authenticate(verifier, log, req, res);
400
666
  if (!principal) {
401
667
  return;
402
668
  }
669
+ await handleApi(api, principal, req, res, url);
670
+ }
671
+ /**
672
+ * The API for a caller who is known: by their token here, or by the sign-in of the
673
+ * dashboard, which asks the same API for what its pages show (dashboard.ts).
674
+ */
675
+ async function handleApi(api, principal, req, res, url) {
676
+ const { config, registry, gateway, definitions, proposals, sources, sandboxes, planning, repos, checks, capacity, log, } = api;
677
+ const path = url.pathname;
403
678
  if (await (0, accounts_api_1.handleAccounts)(config, log, principal, req, res, url)) {
404
679
  return;
405
680
  }
@@ -412,7 +687,57 @@ async function handle(config, registry, definitions, proposals, sources, sandbox
412
687
  if (await (0, sandboxes_api_1.handleSandboxes)(config, sandboxes.registry, repos, log, principal, req, res, url)) {
413
688
  return;
414
689
  }
415
- if (await handleRuns(config, registry, definitions, sources, sandboxes, planning, repos, log, principal, req, res, url)) {
690
+ if (await handleRuns(config, registry, definitions, sources, sandboxes, planning, repos, (host) => gateway?.url(host) ?? host, log, principal, req, res, url)) {
691
+ return;
692
+ }
693
+ if (path === '/v1/overview') {
694
+ if (req.method !== 'GET') {
695
+ (0, http_2.send)(res, 405, { error: 'method not allowed' }, { allow: 'GET' });
696
+ return;
697
+ }
698
+ const viewer = (0, overview_1.getViewer)(config, principal);
699
+ if (viewer.grant.matched.length === 0) {
700
+ (0, http_2.send)(res, 403, { error: 'you are not entitled to anything on this server' });
701
+ return;
702
+ }
703
+ (0, http_2.send)(res, 200, (0, overview_1.getOverview)(registry.snapshot(), registry.usage(principal), viewer, entryOf(definitions)));
704
+ return;
705
+ }
706
+ if (path === '/v1/capacity' || path === '/v1/tasks') {
707
+ if (req.method !== 'GET') {
708
+ (0, http_2.send)(res, 405, { error: 'method not allowed' }, { allow: 'GET' });
709
+ return;
710
+ }
711
+ const viewer = (0, overview_1.getViewer)(config, principal);
712
+ if (viewer.grant.matched.length === 0) {
713
+ (0, http_2.send)(res, 403, { error: 'you are not entitled to anything on this server' });
714
+ return;
715
+ }
716
+ if (path === '/v1/capacity') {
717
+ (0, http_2.send)(res, 200, (0, overview_1.visibleCapacity)(await capacity.read(registry.all()), viewer));
718
+ return;
719
+ }
720
+ // of every run the caller may see, unless they ask for their own
721
+ const params = new URLSearchParams(url.searchParams);
722
+ if (!params.has('scope')) {
723
+ params.set('scope', 'visible');
724
+ }
725
+ let filter;
726
+ try {
727
+ filter = (0, overview_1.parseRunFilter)(params, viewer.grant);
728
+ }
729
+ catch (e) {
730
+ (0, http_2.send)(res, e instanceof overview_1.FilterRefused ? 403 : 400, { error: e instanceof Error ? e.message : String(e) });
731
+ return;
732
+ }
733
+ const runs = (0, overview_1.filterRuns)(registry.all(), viewer, filter).map((run) => (0, overview_1.toListedRun)(viewer, run));
734
+ const oldest = (0, timings_1.getOldestCounted)(runs);
735
+ // where in the repository the build file of the last run is, as its version says
736
+ const tasks = (0, timings_1.getTaskStats)(runs, Date.now()).map((stats) => {
737
+ const entry = stats.last.definition ? api.definitions.find(stats.last.definition)?.entry : undefined;
738
+ return entry ? { ...stats, last: { ...stats.last, entry } } : stats;
739
+ });
740
+ (0, http_2.send)(res, 200, { tasks, ...(oldest ? { oldest } : {}) });
416
741
  return;
417
742
  }
418
743
  if (await (0, approvals_api_1.handleApprovals)(config, registry, log, principal, req, res, url)) {
@@ -421,6 +746,9 @@ async function handle(config, registry, definitions, proposals, sources, sandbox
421
746
  if (await (0, proposals_api_1.handleProposals)(config, definitions, proposals, log, principal, req, res, url)) {
422
747
  return;
423
748
  }
749
+ if (await (0, checks_api_1.handleChecks)(config, checks, definitions, log, principal, req, res, url)) {
750
+ return;
751
+ }
424
752
  (0, http_2.send)(res, 404, { error: 'not found' });
425
753
  }
426
754
  async function startServer(config, environment, options = {}) {
@@ -447,12 +775,13 @@ async function startServer(config, environment, options = {}) {
447
775
  },
448
776
  policy: {
449
777
  envs: config.runs.env.allow,
450
- reserved: (0, server_config_1.getSourceAccounts)(config),
778
+ reserved: (0, server_config_1.getServerAccounts)(config),
451
779
  runtimes: config.runtimes,
452
780
  backend: config.backend.type,
453
781
  network: (0, work_network_1.parseWorkNetwork)(config.runs.network),
454
782
  secretNetwork: (0, work_network_1.parseWorkNetwork)(config.runs.secretNetwork),
455
783
  args: config.runs.args,
784
+ capabilities: config.backend.capabilities?.allow ?? [],
456
785
  proxiedProviders: config.backend.type === 'kubernetes'
457
786
  ? Object.entries(config.backend.providers)
458
787
  .filter(([, provider]) => provider.allow)
@@ -493,6 +822,8 @@ async function startServer(config, environment, options = {}) {
493
822
  envs: config.sandboxes.env.allow,
494
823
  envsFrom: 'sandboxes.env.allow',
495
824
  runtimes: sandboxRuntimes,
825
+ capabilities: config.sandboxes.capabilities,
826
+ capabilitiesFrom: 'sandboxes.capabilities',
496
827
  },
497
828
  };
498
829
  if (sandboxRuntimes.length === 0 && config.entitlements.some((entitlement) => entitlement.sandboxes?.length)) {
@@ -512,6 +843,9 @@ async function startServer(config, environment, options = {}) {
512
843
  cache: (0, path_1.join)(storage, 'cache'),
513
844
  worker: options.worker,
514
845
  sandboxes: { ...sandboxes, network: config.sandboxes.network },
846
+ ...(config.backend.type === 'host' && config.backend.capabilities
847
+ ? { capabilityRuntime: config.backend.capabilities.runtime }
848
+ : {}),
515
849
  log,
516
850
  };
517
851
  const backend = config.backend;
@@ -519,7 +853,16 @@ async function startServer(config, environment, options = {}) {
519
853
  (backend.type === 'kubernetes'
520
854
  ? new kubernetes_backend_1.KubernetesExecutor({ ...config, backend }, environment.processEnvs, executorOptions)
521
855
  : new executor_1.HostExecutor(executorOptions));
856
+ const capacity = (0, capacity_1.cachedCapacity)(options.capacity ??
857
+ (executor instanceof kubernetes_backend_1.KubernetesExecutor
858
+ ? executor.capacity()
859
+ : new capacity_1.HostCapacity((0, execute_docker_1.createDockerClient)(undefined), !environment.processEnvs.DOCKER_HOST)));
522
860
  const sources = new sources_1.SourceStore((0, path_1.join)(storage, 'sources'));
861
+ const checks = new checks_1.CheckStore((0, path_1.join)(storage, 'checks'), { keep: (0, units_1.parseDuration)(config.runs.checksKeep) });
862
+ const sweepChecks = () => checks.sweep().catch((e) => log(`the old checks could not be removed: ${e instanceof Error ? e.message : e}`));
863
+ void sweepChecks();
864
+ const sweeping = setInterval(sweepChecks, CHECK_SWEEP_MS);
865
+ sweeping.unref();
523
866
  const registry = new runs_1.RunRegistry({
524
867
  executor,
525
868
  maxConcurrent: config.runs.maxConcurrent,
@@ -529,21 +872,74 @@ async function startServer(config, environment, options = {}) {
529
872
  limits: config.runs.limits,
530
873
  maxDuration: (0, units_1.parseDuration)(config.runs.maxDuration),
531
874
  maxLogBytes: config.runs.maxLogBytes,
875
+ up: {
876
+ maxTtl: (0, units_1.parseDuration)(config.runs.up.maxTtl),
877
+ perCaller: config.runs.up.limits.up,
878
+ asleep: config.runs.up.limits.asleep,
879
+ total: config.runs.up.total,
880
+ keepVolumes: config.runs.up.keepVolumes,
881
+ },
532
882
  store: new run_store_1.FileRunStore((0, path_1.join)(storage, 'records')),
883
+ // what a check run passed, for `remote verify` to find
884
+ onFinished: (run, keys) => {
885
+ const passed = (0, checks_1.getCheckRecords)(run, keys);
886
+ if (passed.length > 0) {
887
+ checks
888
+ .save(passed)
889
+ .then(() => log(`checks run=${run.id} passed=[${passed.map((record) => record.task).join(',')}]`))
890
+ .catch((e) => log(`the checks of run ${run.id} were not kept: ${e instanceof Error ? e.message : e}`));
891
+ }
892
+ },
533
893
  log,
534
894
  });
895
+ // the executor hears which service runs sleep with their volumes kept, and removes what it
896
+ // kept for any other (RunExecutor.restored)
535
897
  await registry.restore();
536
- sandboxes.registry.useRuns({
537
- holder: (id) => registry.holder(id),
538
- stop: (id) => registry.stopSandbox(id, 'the sandbox was deleted'),
539
- });
540
898
  const proposals = new proposals_1.ProposalRegistry({
541
899
  maxWaiting: config.approvals.maxWaiting,
542
900
  timeout: (0, units_1.parseDuration)(config.approvals.timeout),
543
901
  cooldown: (0, units_1.parseDuration)(config.approvals.cooldown),
544
902
  });
903
+ const login = config.endpoints?.login;
904
+ const gateway = config.endpoints
905
+ ? new endpoints_1.EndpointGateway(config, registry, {
906
+ keyFile: (0, path_1.join)(storage, 'endpoints', 'session.key'),
907
+ verifier,
908
+ ...(login?.clientSecret
909
+ ? { clientSecret: () => repos.serverSecret(login.clientSecret) }
910
+ : {}),
911
+ log,
912
+ ...(options.fetch ? { fetch: options.fetch } : {}),
913
+ ...(options.now ? { now: options.now } : {}),
914
+ mayWake: (run) => refuseWake(config, repos, run),
915
+ // the pages of the dashboard read and do what they show through the API
916
+ dashboard: {
917
+ api: (principal, req, res, url) => handleApi(api, principal, req, res, url),
918
+ ...(options.dashboardAssets ? { assets: options.dashboardAssets } : {}),
919
+ },
920
+ })
921
+ : undefined;
922
+ const api = {
923
+ config,
924
+ registry,
925
+ gateway,
926
+ definitions,
927
+ proposals,
928
+ sources,
929
+ sandboxes,
930
+ planning,
931
+ repos,
932
+ checks,
933
+ capacity,
934
+ log,
935
+ };
936
+ await gateway?.load();
937
+ sandboxes.registry.useRuns({
938
+ holder: (id) => registry.holder(id),
939
+ stop: (id) => registry.stopSandbox(id, 'the sandbox was deleted'),
940
+ });
545
941
  const listener = (req, res) => {
546
- handle(config, registry, definitions, proposals, sources, sandboxes, planning, repos, verifier, log, req, res).catch((e) => {
942
+ handle(api, verifier, req, res).catch((e) => {
547
943
  if (e instanceof http_2.HttpError) {
548
944
  (0, http_2.send)(res, e.status, { error: e.message });
549
945
  return;
@@ -563,11 +959,44 @@ async function startServer(config, environment, options = {}) {
563
959
  environment.file.read(config.tls.cert),
564
960
  environment.file.read(config.tls.key),
565
961
  ]);
566
- server = (0, https_1.createServer)({ cert, key }, listener);
962
+ // the hosts of endpoints have a wildcard certificate of their own
963
+ const endpointsTls = config.endpoints?.tls;
964
+ const endpointContext = endpointsTls
965
+ ? (0, tls_1.createSecureContext)({
966
+ cert: await environment.file.read(endpointsTls.cert),
967
+ key: await environment.file.read(endpointsTls.key),
968
+ })
969
+ : undefined;
970
+ const domain = config.endpoints?.domain;
971
+ server = (0, https_1.createServer)({
972
+ cert,
973
+ key,
974
+ ...(endpointContext && domain
975
+ ? {
976
+ SNICallback: (servername, done) => done(null, servername.toLowerCase().endsWith(`.${domain}`) ? endpointContext : undefined),
977
+ }
978
+ : {}),
979
+ }, listener);
567
980
  }
568
981
  else {
569
982
  server = (0, http_1.createServer)(listener);
570
983
  }
984
+ // WebSockets of the apps behind endpoints; the API has none. An upgraded connection is
985
+ // no longer the HTTP server's, it goes when the server closes.
986
+ const upgraded = new Set();
987
+ server.on('upgrade', (req, socket, head) => {
988
+ upgraded.add(socket);
989
+ socket.once('close', () => upgraded.delete(socket));
990
+ const label = gateway?.hostOf(req);
991
+ if (!gateway || !label) {
992
+ socket.end('HTTP/1.1 404 Not Found\r\nconnection: close\r\ncontent-length: 0\r\n\r\n');
993
+ return;
994
+ }
995
+ gateway.upgrade(label, req, socket, head).catch((e) => {
996
+ log(`error upgrade ${label}: ${e instanceof Error ? e.message : String(e)}`);
997
+ socket.destroy();
998
+ });
999
+ });
571
1000
  await new Promise((resolve, reject) => {
572
1001
  server.once('error', reject);
573
1002
  server.listen(config.listen.port, config.listen.host, () => {
@@ -576,11 +1005,12 @@ async function startServer(config, environment, options = {}) {
576
1005
  });
577
1006
  });
578
1007
  const address = server.address();
1008
+ gateway?.listening(address.port, Boolean(config.tls));
579
1009
  const host = address.family === 'IPv6' ? `[${address.address}]` : address.address;
580
1010
  return {
581
1011
  url: `${config.tls ? 'https' : 'http'}://${host}:${address.port}`,
582
1012
  reload: (next) => {
583
- const readers = (0, server_config_1.getSourceAccounts)(config);
1013
+ const readers = (0, server_config_1.getServerAccounts)(config);
584
1014
  next.entitlements.forEach((entitlement, index) => {
585
1015
  const iss = (entitlement.subject ?? entitlement.group ?? entitlement.claims)?.iss;
586
1016
  if (iss && !config.issuers.some((issuer) => issuer.issuer === iss)) {
@@ -600,11 +1030,13 @@ async function startServer(config, environment, options = {}) {
600
1030
  return { restart };
601
1031
  },
602
1032
  close: async () => {
1033
+ clearInterval(sweeping);
603
1034
  proposals.close();
604
1035
  await registry.close();
605
1036
  await new Promise((resolve, reject) => {
606
1037
  server.close((err) => (err ? reject(err) : resolve()));
607
1038
  server.closeAllConnections();
1039
+ upgraded.forEach((socket) => socket.destroy());
608
1040
  });
609
1041
  },
610
1042
  };