hammerkit 2.1.0-next.9 → 2.2.0-next.1

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 (70) hide show
  1. package/dist/dashboard/assets/{graph-canvas-BFnEN5i0.js → graph-canvas-D6GMgkoe.js} +1 -1
  2. package/dist/dashboard/assets/index-BNq9j5Jo.js +23 -0
  3. package/dist/dashboard/assets/{index-Dt3ITvRO.css → index-DP3_hKOe.css} +1 -1
  4. package/dist/dashboard/index.html +2 -2
  5. package/dist/executer/archive-task-entry.js +1 -1
  6. package/dist/executer/deadline.js +63 -10
  7. package/dist/executer/event-cache.js +5 -1
  8. package/dist/executer/execute-work-task.js +15 -3
  9. package/dist/executer/runner-commands.js +36 -0
  10. package/dist/file/get-file-context.js +4 -7
  11. package/dist/harness/connect.js +12 -8
  12. package/dist/harness/reconnect.js +141 -0
  13. package/dist/harness/sandbox-client.js +242 -33
  14. package/dist/harness/service-tools.js +36 -3
  15. package/dist/kubernetes/cluster-state.js +48 -14
  16. package/dist/kubernetes/ensure-persistent-data.js +15 -4
  17. package/dist/kubernetes/follow-pod-logs.js +8 -5
  18. package/dist/kubernetes/kept-claims.js +26 -5
  19. package/dist/kubernetes/resources.js +5 -1
  20. package/dist/kubernetes/sandbox-runner.js +526 -156
  21. package/dist/kubernetes/store-kubernetes-data.js +18 -3
  22. package/dist/kubernetes/sync-changes.js +463 -0
  23. package/dist/kubernetes/volumes.js +23 -1
  24. package/dist/optimizer/get-work-cache-stats.js +7 -0
  25. package/dist/planner/work-item-status.js +12 -2
  26. package/dist/planner/work-runtime-aggregate.js +1 -0
  27. package/dist/planner/work-runtime-docker.js +9 -5
  28. package/dist/planner/work-runtime-kubernetes.js +277 -55
  29. package/dist/planner/work-runtime-local.js +8 -4
  30. package/dist/remote/annotations.js +29 -3
  31. package/dist/remote/bundle.js +6 -8
  32. package/dist/remote/collect-bundle.js +3 -2
  33. package/dist/remote/device-login.js +4 -1
  34. package/dist/remote/remote-commands.js +16 -7
  35. package/dist/remote/remote-work-commands.js +265 -72
  36. package/dist/remote/server-client.js +38 -40
  37. package/dist/server/artifacts-api.js +56 -0
  38. package/dist/server/definitions-api.js +62 -8
  39. package/dist/server/endpoints.js +52 -32
  40. package/dist/server/executor.js +117 -30
  41. package/dist/server/http.js +4 -1
  42. package/dist/server/keep-artifacts.js +230 -0
  43. package/dist/server/kubernetes-backend.js +186 -59
  44. package/dist/server/kubernetes-sandbox-storage.js +83 -22
  45. package/dist/server/overview.js +67 -9
  46. package/dist/server/paging.js +167 -0
  47. package/dist/server/plan.js +8 -1
  48. package/dist/server/public-paths.js +52 -0
  49. package/dist/server/run-access.js +24 -0
  50. package/dist/server/run-artifacts.js +171 -0
  51. package/dist/server/run-logs.js +25 -1
  52. package/dist/server/run-request.js +63 -1
  53. package/dist/server/run-retry.js +6 -0
  54. package/dist/server/run-worker.js +267 -33
  55. package/dist/server/runs.js +527 -99
  56. package/dist/server/sandbox-files.js +9 -8
  57. package/dist/server/sandbox-follow.js +54 -0
  58. package/dist/server/sandbox-storage.js +38 -1
  59. package/dist/server/sandbox-sync.js +392 -0
  60. package/dist/server/sandboxes-api.js +54 -8
  61. package/dist/server/sandboxes.js +19 -0
  62. package/dist/server/server-config.js +14 -0
  63. package/dist/server/server.js +189 -46
  64. package/dist/server/service-runs.js +41 -8
  65. package/dist/server/task-order.js +56 -0
  66. package/dist/utils/project-path.js +20 -0
  67. package/dist/utils/tar-files.js +52 -0
  68. package/dist/utils/tar.js +37 -1
  69. package/package.json +1 -1
  70. package/dist/dashboard/assets/index-CE5PSB3y.js +0 -23
@@ -2,6 +2,8 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.callServer = exports.getMe = exports.getDiscovery = exports.printableWhole = exports.printableLines = exports.printable = exports.ServerError = void 0;
4
4
  const discovery_1 = require("../server/discovery");
5
+ const reconnect_1 = require("../harness/reconnect");
6
+ const sandbox_client_1 = require("../harness/sandbox-client");
5
7
  const TIMEOUT_MS = 10000;
6
8
  const WRITE_TIMEOUT_MS = 30000;
7
9
  class ServerError extends Error {
@@ -12,6 +14,8 @@ class ServerError extends Error {
12
14
  }
13
15
  }
14
16
  exports.ServerError = ServerError;
17
+ // a reason from the network, such as a TLS or DNS error, can hold control characters
18
+ const failWith = (message) => new ServerError(printable(message));
15
19
  // Text from the server or the identity provider is shown to the user: no
16
20
  // control characters, so it can't rewrite the terminal, and format characters
17
21
  // (bidi overrides, zero-width) written out, so text reads in the order it runs.
@@ -39,58 +43,55 @@ function printableWhole(value) {
39
43
  .replace(/\p{Cf}/gu, (char) => `\\u{${char.codePointAt(0)?.toString(16)}}`);
40
44
  }
41
45
  exports.printableWhole = printableWhole;
42
- async function getJson(url, token) {
43
- let response;
44
- try {
45
- response = await fetch(url, {
46
- headers: token ? { authorization: `Bearer ${token}` } : {},
47
- signal: AbortSignal.timeout(TIMEOUT_MS),
48
- });
49
- }
50
- catch (e) {
51
- throw new ServerError(`unable to reach ${url}: ${e instanceof Error ? e.message : String(e)}`);
52
- }
46
+ // A document of the server, read as the connection reads it: a 401 carries its status, as
47
+ // the caller tells a token the server refused from a server that is not there.
48
+ async function getJson(connection, path) {
49
+ const url = `${(0, reconnect_1.showUrl)(connection.url)}${path}`;
50
+ const response = await (0, sandbox_client_1.request)(connection, 'GET', path, { timeoutMs: TIMEOUT_MS, fail: failWith });
53
51
  if (response.status === 401) {
54
- throw new ServerError(`${url} did not accept the token`);
52
+ throw new ServerError(`${url} did not accept the token`, 401);
55
53
  }
56
54
  if (!response.ok) {
57
- throw new ServerError(`${url} answered ${response.status}`);
55
+ throw new ServerError(`${url} answered ${response.status}`, response.status);
58
56
  }
59
57
  return response.json();
60
58
  }
61
59
  // What the server says it is. The issuer registered with `remote add` has to be
62
60
  // one it accepts, otherwise a login would send the user to an identity provider
63
- // the server does not trust.
64
- async function getDiscovery(server) {
65
- const document = (await getJson(`${server.url}${discovery_1.DISCOVERY_PATH}`));
61
+ // the server does not trust. No token is sent: the document is for anybody.
62
+ async function getDiscovery(server, options = {}) {
63
+ const connection = { url: server.url, say: options.say, signal: options.signal };
64
+ const document = (await getJson(connection, discovery_1.DISCOVERY_PATH));
66
65
  if (document?.name !== 'hammerkit' || !Array.isArray(document.issuers)) {
67
66
  throw new ServerError(`${server.url} is not a hammerkit server`);
68
67
  }
69
68
  return document;
70
69
  }
71
70
  exports.getDiscovery = getDiscovery;
72
- async function getMe(server, token) {
73
- return (await getJson(`${server.url}/v1/me`, token));
71
+ async function getMe(connection) {
72
+ return (await getJson(connection, '/v1/me'));
74
73
  }
75
74
  exports.getMe = getMe;
76
- // A call that changes something, or whose answer the caller tells apart by status.
77
- // Anything but 2xx is an error carrying what the server said about it.
78
- async function callServer(server, token, method, path, body) {
79
- const url = `${server.url}${path}`;
80
- let response;
81
- try {
82
- response = await fetch(url, {
83
- method,
84
- headers: {
85
- authorization: `Bearer ${token}`,
86
- ...(body !== undefined ? { 'content-type': 'application/json' } : {}),
87
- },
88
- body: body === undefined ? undefined : JSON.stringify(body),
89
- signal: AbortSignal.timeout(method === 'GET' ? TIMEOUT_MS : WRITE_TIMEOUT_MS),
90
- });
91
- }
92
- catch (e) {
93
- throw new ServerError(`unable to reach ${url}: ${printable(e instanceof Error ? e.message : e)}`);
75
+ /**
76
+ * A call of the server: its answer, or an error that says what the server answered. The call
77
+ * is made the way the sandbox calls are (`request`): a server that is away is waited for within
78
+ * the window of the connection (`reconnectMs` shortens it, 0 is no wait), and the call is sent
79
+ * again only as `repeat` allows. A read, or a call that ends the same however often the server
80
+ * takes it, is `always`; by default a POST is `unsent`, sent again only when the server certainly
81
+ * did not take it. A call that times out counts as lost, so an `always` call that is slow is
82
+ * sent again too, for up to the window.
83
+ */
84
+ async function callServer(connection, method, path, options = {}) {
85
+ const response = await (0, sandbox_client_1.request)(connection, method, path, {
86
+ body: options.body,
87
+ repeat: options.repeat,
88
+ reconnectMs: options.reconnectMs,
89
+ timeoutMs: method === 'GET' ? TIMEOUT_MS : WRITE_TIMEOUT_MS,
90
+ fail: failWith,
91
+ });
92
+ const shown = (0, reconnect_1.showUrl)(connection.url);
93
+ if (response.status === 401) {
94
+ throw new ServerError(`${shown} did not accept the token`, 401);
94
95
  }
95
96
  let answer;
96
97
  try {
@@ -99,14 +100,11 @@ async function callServer(server, token, method, path, body) {
99
100
  catch {
100
101
  answer = undefined;
101
102
  }
102
- if (response.status === 401) {
103
- throw new ServerError(`${server.url} did not accept the token`);
104
- }
105
103
  if (!response.ok) {
106
104
  const lines = answer && typeof answer.error === 'string' ? printableLines(answer.error) : [];
107
105
  // a refused publish says every problem, each on a line of its own
108
106
  const said = lines.length > 1 ? `:\n${lines.map((line) => ` ${line}`).join('\n')}` : lines.length === 1 ? `: ${lines[0]}` : '';
109
- throw new ServerError(`${server.url} answered ${response.status}${said}`, response.status);
107
+ throw new ServerError(`${shown} answered ${response.status}${said}`, response.status);
110
108
  }
111
109
  return { status: response.status, body: answer };
112
110
  }
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.handleArtifacts = void 0;
4
+ const promises_1 = require("stream/promises");
5
+ const http_1 = require("./http");
6
+ const run_access_1 = require("./run-access");
7
+ const runs_1 = require("./runs");
8
+ /**
9
+ * The outputs a run's tasks exported, kept by the server once the run ended (ArtifactStore):
10
+ *
11
+ * GET /v1/runs/<id>/artifacts what it kept, by number, until when, or why it kept none
12
+ * GET /v1/runs/<id>/artifacts/<n> one of them, a gzipped tar of its paths in the project
13
+ *
14
+ * Who may read the run's log may read them (its owner, who decided about it, `observe`): a
15
+ * task could print what it writes there into its log all the same. What a credential can
16
+ * reach is never kept (refuseArtifacts).
17
+ */
18
+ async function handleArtifacts(config, registry, artifacts, log, principal, req, res, url, now) {
19
+ const match = /^\/v1\/runs\/([^/]+)\/artifacts(?:\/([^/]+))?$/.exec(url.pathname);
20
+ if (!match) {
21
+ return false;
22
+ }
23
+ const [, id, output] = match;
24
+ if (req.method !== 'GET') {
25
+ (0, http_1.send)(res, 405, { error: 'method not allowed' }, { allow: 'GET' });
26
+ return true;
27
+ }
28
+ const run = (0, run_access_1.findReadableRun)(config, registry, principal, id);
29
+ if (!run || (output !== undefined && !/^\d{1,6}$/.test(output))) {
30
+ (0, http_1.send)(res, 404, { error: 'not found' });
31
+ return true;
32
+ }
33
+ if (!(0, runs_1.isFinal)(run.state)) {
34
+ (0, http_1.send)(res, 409, { error: `the run is ${run.state}, what it keeps is there once it ended` });
35
+ return true;
36
+ }
37
+ if (output === undefined) {
38
+ (0, http_1.send)(res, 200, await artifacts.read(run, now()));
39
+ return true;
40
+ }
41
+ const opened = await artifacts.open(run, Number(output), now());
42
+ if (!opened) {
43
+ (0, http_1.send)(res, 404, { error: 'not found' });
44
+ return true;
45
+ }
46
+ log(`artifacts iss=${principal.iss} sub=${principal.sub} run=${run.id} output=${output}`);
47
+ res.writeHead(200, {
48
+ 'content-type': 'application/gzip',
49
+ 'content-length': String(opened.bytes),
50
+ 'cache-control': 'no-store',
51
+ });
52
+ await (0, promises_1.pipeline)(opened.stream(), res).catch(() => res.destroy());
53
+ return true;
54
+ }
55
+ exports.handleArtifacts = handleArtifacts;
56
+ //# sourceMappingURL=artifacts-api.js.map
@@ -9,6 +9,7 @@ const run_plan_1 = require("./run-plan");
9
9
  const oauth_1 = require("./oauth");
10
10
  const policy_1 = require("./policy");
11
11
  const proposals_1 = require("./proposals");
12
+ const paging_1 = require("./paging");
12
13
  // A bundle is JSON text with escapes, so the body may be somewhat larger than the files.
13
14
  const MAX_PUBLISH_BYTES = bundle_1.MAX_BUNDLE_BYTES * 2;
14
15
  /**
@@ -19,7 +20,11 @@ const MAX_PUBLISH_BYTES = bundle_1.MAX_BUNDLE_BYTES * 2;
19
20
  * Beside entry and files the body may carry
20
21
  * `annotations`, which are not part of the hash
21
22
  * GET /v1/definitions the versions, newest first; `?<key>=<value>`
22
- * keeps the ones with those annotations
23
+ * keeps the ones with those annotations (a key
24
+ * repeated, with any of its values), `q` the ones
25
+ * with the text; `limit` and `cursor` page them,
26
+ * `values=<key>` answers the values of an
27
+ * annotation (paging.ts)
23
28
  * GET /v1/definitions/<hash> one version, with `arguments`: per task null when
24
29
  * a run of it may pass arguments, else why not
25
30
  * GET /v1/definitions/<hash>/files its files
@@ -67,13 +72,15 @@ async function handleDefinitions(config, store, proposals, log, principal, req,
67
72
  return true;
68
73
  }
69
74
  if (hash === undefined) {
70
- const wanted = [...url.searchParams.entries()];
71
- (0, http_1.send)(res, 200, {
72
- definitions: store
73
- .list()
74
- .filter((version) => wanted.every(([key, value]) => version.annotations?.[key] === value))
75
- .map(toSummary),
76
- });
75
+ try {
76
+ listDefinitions(store, url.searchParams, res);
77
+ }
78
+ catch (e) {
79
+ if (!(e instanceof paging_1.ListParamError)) {
80
+ throw e;
81
+ }
82
+ (0, http_1.send)(res, 400, { error: e.message });
83
+ }
77
84
  return true;
78
85
  }
79
86
  const found = store.find(hash);
@@ -91,6 +98,53 @@ async function handleDefinitions(config, store, proposals, log, principal, req,
91
98
  return true;
92
99
  }
93
100
  exports.handleDefinitions = handleDefinitions;
101
+ // the parameters of the list that are not annotations to filter by
102
+ const LIST_PARAMS = ['q', 'limit', 'cursor', 'values', 'search'];
103
+ // GET /v1/definitions: the versions with the annotations and the text asked for, a page of
104
+ // them, or the values of an annotation.
105
+ function listDefinitions(store, params, res) {
106
+ const wanted = new Map();
107
+ for (const [key, value] of params) {
108
+ if (!LIST_PARAMS.includes(key)) {
109
+ wanted.set(key, [...(wanted.get(key) ?? []), value]);
110
+ }
111
+ }
112
+ const text = (0, paging_1.readText)(params);
113
+ // any annotation has values, those of a key no version has are none
114
+ const asked = params.get('values');
115
+ if (asked !== null && !bundle_1.ANNOTATION_KEY_PATTERN.test(asked)) {
116
+ throw new paging_1.ListParamError('values: the key of an annotation');
117
+ }
118
+ const values = asked !== null ? (0, paging_1.parseValues)(params, [asked]) : undefined;
119
+ const page = values ? undefined : (0, paging_1.parsePage)(params);
120
+ const found = (except) => store
121
+ .list()
122
+ .filter((version) => [...wanted].every(([key, accepted]) => key === except || accepted.includes(version.annotations?.[key] ?? '\0')) &&
123
+ (!text ||
124
+ (0, paging_1.hasText)([
125
+ version.hash,
126
+ version.entry,
127
+ version.publishedBy.sub,
128
+ ...Object.values(version.annotations ?? {}),
129
+ ...version.tasks,
130
+ ...version.services,
131
+ ], text)));
132
+ if (values) {
133
+ // the values an annotation has, counted over the versions the other filters let through
134
+ const key = values.field;
135
+ const counted = (0, paging_1.countValues)(found(key), (version) => (version.annotations?.[key] !== undefined ? [version.annotations[key]] : []), values);
136
+ (0, http_1.send)(res, 200, (0, paging_1.answerPage)('values', counted));
137
+ return;
138
+ }
139
+ const listed = found();
140
+ if (!page) {
141
+ (0, http_1.send)(res, 200, { definitions: listed.map(toSummary) });
142
+ return;
143
+ }
144
+ const key = (version) => [version.publishedAt, version.hash];
145
+ const answered = (0, paging_1.pageByKey)((0, paging_1.newestFirst)(listed, key), page, key);
146
+ (0, http_1.send)(res, 200, (0, paging_1.answerPage)('definitions', { ...answered, items: answered.items.map(toSummary) }));
147
+ }
94
148
  // What the list shows of a version: who published it and when, and what it runs as.
95
149
  function toSummary(version) {
96
150
  const { hash, entry, publishedAt, publishedBy, approvedBy, annotations, tasks, services, accounts, yanked } = version;
@@ -8,6 +8,7 @@ const net_1 = require("net");
8
8
  const path_1 = require("path");
9
9
  const oauth_1 = require("./oauth");
10
10
  const policy_1 = require("./policy");
11
+ const public_paths_1 = require("./public-paths");
11
12
  const service_runs_1 = require("./service-runs");
12
13
  const units_1 = require("../utils/units");
13
14
  const dashboard_1 = require("./dashboard");
@@ -149,25 +150,30 @@ class EndpointGateway {
149
150
  return page(res, 404, 'Not found', '<p>There is no endpoint at this address.</p>');
150
151
  }
151
152
  const principal = await this.caller(label, req);
152
- if (!principal) {
153
- return this.signIn(label, req, res, url);
154
- }
155
- if (!this.mayOpen(principal, found.run)) {
153
+ // A public path of the endpoint is for anybody: a caller who may not open the run is
154
+ // treated as no caller there. Any other path needs a caller who may open the run.
155
+ const publicPath = (0, public_paths_1.isPublicPath)(found.endpoint.publicPaths, req.url ?? '');
156
+ const visitor = principal && this.mayOpen(principal, found.run) ? principal : null;
157
+ if (!visitor && !publicPath) {
158
+ if (!principal) {
159
+ return this.signIn(label, req, res, url);
160
+ }
156
161
  this.options.log(`deny endpoint ${label} iss=${principal.iss} sub=${principal.sub}`);
157
162
  return page(res, 403, 'Not allowed', `<p>You are signed in as <code>${escape(principal.sub)}</code> of <code>${escape(principal.iss)}</code>, which may not open this endpoint.</p><p><a href="${OWN_PATH}logout">Sign out</a></p>`);
158
163
  }
159
- if (url.pathname === `${OWN_PATH}status` || url.pathname === `${OWN_PATH}extend`) {
160
- return this.status(label, found.run, found.endpoint, principal, req, res, url);
164
+ if (visitor && (url.pathname === `${OWN_PATH}status` || url.pathname === `${OWN_PATH}extend`)) {
165
+ return this.status(label, found.run, found.endpoint, visitor, req, res, url);
161
166
  }
162
167
  if (url.pathname.startsWith(OWN_PATH)) {
163
168
  return page(res, 404, 'Not found', '<p>There is no such page.</p>');
164
169
  }
165
- // a request keeps the services up, or wakes them
166
- const refused = this.registry.visit(found.run.id, this.options.mayWake);
170
+ // Only a signed-in visit keeps the services up or wakes them: a request without a caller
171
+ // of a public path does neither, so anybody can not keep a run awake or wake it
172
+ const refused = visitor ? this.registry.visit(found.run.id, this.options.mayWake) : undefined;
167
173
  if (!found.target) {
168
- return this.notUp(res, this.registry.endpoint(label)?.run ?? found.run, refused);
174
+ return this.notUp(res, this.registry.endpoint(label)?.run ?? found.run, refused, !!visitor);
169
175
  }
170
- this.forward(found.target, principal, req, res);
176
+ this.forward(found.target, visitor, req, res);
171
177
  }
172
178
  // A WebSocket (or any upgrade) to an endpoint, after the same checks as a request.
173
179
  async upgrade(label, req, socket, head) {
@@ -338,7 +344,8 @@ class EndpointGateway {
338
344
  res.on('close', () => upstream.destroy());
339
345
  req.pipe(upstream);
340
346
  }
341
- // What reaches the app: the request without the server's cookie and headers, with who asked.
347
+ // What reaches the app: the request without the server's cookie and headers, with who asked
348
+ // when a caller is known; a request let through without one carries no such header.
342
349
  forwardedHeaders(req, principal) {
343
350
  const headers = {};
344
351
  for (const [name, value] of Object.entries(req.headers)) {
@@ -359,29 +366,42 @@ class EndpointGateway {
359
366
  headers['x-forwarded-proto'] = this.base.scheme;
360
367
  headers['x-forwarded-host'] = req.headers.host ?? '';
361
368
  headers['x-forwarded-for'] = req.socket.remoteAddress ?? '';
362
- headers['x-hammerkit-caller'] = `${principal.iss} ${principal.sub}`;
369
+ if (principal) {
370
+ headers['x-hammerkit-caller'] = `${principal.iss} ${principal.sub}`;
371
+ }
363
372
  return headers;
364
373
  }
365
- notUp(res, run, refused) {
366
- if (run.state === 'queued' || run.state === 'running' || run.state === 'awaiting-approval') {
367
- res.setHeader('refresh', '5');
368
- res.setHeader('retry-after', '5');
369
- return page(res, 503, 'Starting', `<p>The services of this endpoint are ${run.wakes ? `waking up${run.volumesKept ? ' with the volumes they kept' : ''}` : 'starting'} (${escape(run.state)}), this page reloads until they are up.</p>`);
370
- }
371
- if (run.state === 'asleep') {
372
- // it may wake on a later request, once there is a place for it
373
- res.setHeader('refresh', '30');
374
- res.setHeader('retry-after', '30');
375
- return page(res, 503, 'Asleep', `<p>The services of this endpoint sleep and can not wake now: ${escape(refused ?? 'try again')}.</p>`);
376
- }
377
- const why = run.stoppedBy === 'ttl'
378
- ? 'its time ran out'
379
- : run.stoppedBy === 'replaced'
380
- ? 'a newer run of the same name replaced it'
381
- : run.stoppedBy
382
- ? `${escape(run.stoppedBy.sub)} stopped it`
383
- : escape(run.error ?? run.state);
384
- return page(res, 410, 'Ended', `<p>This endpoint ended${run.finishedAt ? ` at ${escape(run.finishedAt)}` : ''}: ${why}.</p><p>Ask <code>${escape(run.owner.sub)}</code> to start it again.</p>`);
374
+ // What a request is told when the run is not up: the status and headers of its state, here
375
+ // once. Only a signed-in caller hears why it is not up (its owner, who stopped it, its error);
376
+ // anybody else hears the state alone.
377
+ notUp(res, run, refused, signedIn) {
378
+ const starting = run.state === 'queued' || run.state === 'running' || run.state === 'awaiting-approval';
379
+ const asleep = run.state === 'asleep';
380
+ if (!starting && !asleep) {
381
+ if (!signedIn) {
382
+ return page(res, 410, 'Ended', '<p>This endpoint ended.</p>');
383
+ }
384
+ const why = run.stoppedBy === 'ttl'
385
+ ? 'its time ran out'
386
+ : run.stoppedBy === 'replaced'
387
+ ? 'a newer run of the same name replaced it'
388
+ : run.stoppedBy
389
+ ? `${escape(run.stoppedBy.sub)} stopped it`
390
+ : escape(run.error ?? run.state);
391
+ return page(res, 410, 'Ended', `<p>This endpoint ended${run.finishedAt ? ` at ${escape(run.finishedAt)}` : ''}: ${why}.</p><p>Ask <code>${escape(run.owner.sub)}</code> to start it again.</p>`);
392
+ }
393
+ // a page reloads until the services are up, and a sleeping run is asked again once there is a place for it
394
+ const seconds = asleep ? '30' : '5';
395
+ res.setHeader('refresh', seconds);
396
+ res.setHeader('retry-after', seconds);
397
+ const text = !signedIn
398
+ ? asleep
399
+ ? 'The services of this endpoint sleep, a signed-in visit wakes them.'
400
+ : 'The services of this endpoint are not up yet, this page reloads until they are.'
401
+ : asleep
402
+ ? `The services of this endpoint sleep and can not wake now: ${escape(refused ?? 'try again')}.`
403
+ : `The services of this endpoint are ${run.wakes ? `waking up${run.volumesKept ? ' with the volumes they kept' : ''}` : 'starting'} (${escape(run.state)}), this page reloads until they are up.`;
404
+ return page(res, 503, asleep ? 'Asleep' : 'Starting', `<p>${text}</p>`);
385
405
  }
386
406
  async status(label, run, endpoint, principal, req, res, url) {
387
407
  const csrf = this.sign(`csrf\0${label}\0${principal.iss}\0${principal.sub}`);