hammerkit 2.1.0-next.9 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/build.schema.json +28 -126
  2. package/dist/cli.js +0 -5
  3. package/dist/dashboard/assets/graph-canvas-DtJSpova.js +8 -0
  4. package/dist/dashboard/assets/index-BndChMep.css +2 -0
  5. package/dist/dashboard/assets/{index-CE5PSB3y.js → index-DRSwIRXd.js} +9 -15
  6. package/dist/dashboard/index.html +2 -2
  7. package/dist/docker/item-network.js +5 -6
  8. package/dist/docker/remove-orphaned-containers.js +4 -5
  9. package/dist/environment/replace-env-variables.js +5 -8
  10. package/dist/environment/run-source-envs.js +1 -2
  11. package/dist/executer/check-readiness.js +4 -8
  12. package/dist/executer/deadline.js +63 -10
  13. package/dist/executer/docker-service.js +15 -21
  14. package/dist/executer/execute-work-task.js +15 -3
  15. package/dist/harness/sandbox-client.js +1 -0
  16. package/dist/harness/service-tools.js +25 -1
  17. package/dist/kubernetes/cluster-state.js +48 -14
  18. package/dist/kubernetes/ensure-kubernetes-deployment-exists.js +14 -62
  19. package/dist/kubernetes/ensure-persistent-data.js +14 -3
  20. package/dist/kubernetes/kept-claims.js +9 -12
  21. package/dist/kubernetes/resources.js +5 -1
  22. package/dist/optimizer/work-task-cache-description.js +3 -5
  23. package/dist/planner/image-build.js +0 -5
  24. package/dist/planner/service-definition.js +1 -2
  25. package/dist/planner/utils/append-work-service.js +4 -12
  26. package/dist/planner/utils/dependency-outputs.js +6 -7
  27. package/dist/planner/validate.js +0 -41
  28. package/dist/planner/work-healthcheck.js +2 -23
  29. package/dist/planner/work-runtime-docker.js +1 -24
  30. package/dist/planner/work-runtime-kubernetes.js +16 -37
  31. package/dist/planner/work-secret.js +11 -33
  32. package/dist/planner/work-service-id.js +6 -30
  33. package/dist/planner/work-service.js +2 -2
  34. package/dist/program.js +1 -19
  35. package/dist/remote/annotations.js +31 -11
  36. package/dist/remote/collect-bundle.js +3 -2
  37. package/dist/remote/remote-status.js +1 -1
  38. package/dist/remote/remote-work-commands.js +53 -12
  39. package/dist/schema/build-file-base-task-schema.js +1 -16
  40. package/dist/schema/build-file-image-build-schema.js +8 -5
  41. package/dist/schema/build-file-service-container-healthcheck.js +7 -25
  42. package/dist/schema/reference-parser.js +43 -108
  43. package/dist/schema/work-scope-parser.js +0 -8
  44. package/dist/secrets/prefetch-secrets.js +1 -20
  45. package/dist/server/capacity.js +6 -18
  46. package/dist/server/endpoints.js +52 -32
  47. package/dist/server/kubernetes-backend.js +28 -114
  48. package/dist/server/kubernetes-sandbox-storage.js +2 -3
  49. package/dist/server/overview.js +1 -7
  50. package/dist/server/plan.js +0 -8
  51. package/dist/server/public-paths.js +52 -0
  52. package/dist/server/run-request.js +52 -1
  53. package/dist/server/run-retry.js +6 -0
  54. package/dist/server/run-source-environment.js +1 -1
  55. package/dist/server/runs.js +6 -4
  56. package/dist/server/sandbox-files-api.js +12 -27
  57. package/dist/server/sandbox-files.js +2 -3
  58. package/dist/server/sandbox-pod.js +1 -1
  59. package/dist/server/sandboxes-api.js +14 -65
  60. package/dist/server/sandboxes.js +3 -19
  61. package/dist/server/server-config.js +2 -59
  62. package/dist/server/server.js +20 -8
  63. package/dist/server/service-runs.js +41 -8
  64. package/package.json +1 -1
  65. package/dist/dashboard/assets/graph-canvas-BFnEN5i0.js +0 -8
  66. package/dist/dashboard/assets/index-Dt3ITvRO.css +0 -2
  67. package/dist/executer/docker-healthcheck.js +0 -73
  68. package/dist/network/healthcheck-request.js +0 -38
  69. package/dist/server/borrowed-quota.js +0 -216
@@ -29,15 +29,8 @@ class UnpublishedError extends Error {
29
29
  this.reason = reason;
30
30
  }
31
31
  }
32
- // What a task or service names that is a base (`abstract: true`), which only `extend` names
33
- class AbstractError extends Error {
34
- constructor(name) {
35
- super(`${name} is abstract`);
36
- this.name = name;
37
- }
38
- }
39
- // The task or service `user` names another one by, which a server left out or which is a base:
40
- // the error says which one names it, as an error elsewhere is left as it is
32
+ // The task or service `user` names another one by, which a server left out: the error says
33
+ // which published one still needs it, as an error elsewhere is left as it is
41
34
  function findPublished(user, verb, find) {
42
35
  try {
43
36
  return find();
@@ -46,9 +39,6 @@ function findPublished(user, verb, find) {
46
39
  if (e instanceof UnpublishedError) {
47
40
  throw new Error(`${user} ${verb} ${e.name}, which is not published (${e.reason})`);
48
41
  }
49
- if (e instanceof AbstractError) {
50
- throw new Error(`${user} ${verb} ${e.name}, which is abstract: a base that only extend names, it doesn't run`);
51
- }
52
42
  throw e;
53
43
  }
54
44
  }
@@ -77,7 +67,6 @@ async function parseReferences(ctx, mainScope, environment) {
77
67
  const reference = {
78
68
  files: {},
79
69
  tasks: {},
80
- bases: {},
81
70
  services: {},
82
71
  envFiles: {},
83
72
  environments: {},
@@ -120,8 +109,7 @@ async function parseReferences(ctx, mainScope, environment) {
120
109
  if (isLeftOut(file, relativeName, task)) {
121
110
  continue;
122
111
  }
123
- const tasks = task.abstract ? reference.bases : reference.tasks;
124
- tasks[relativeName] = {
112
+ reference.tasks[relativeName] = {
125
113
  type: 'task',
126
114
  schema: task,
127
115
  cwd: file.cwd,
@@ -171,8 +159,7 @@ async function parseReferences(ctx, mainScope, environment) {
171
159
  }
172
160
  }
173
161
  }
174
- // a base is checked as a task is, though only the tasks extending it run
175
- for (const task of [...Object.values(reference.tasks), ...Object.values(reference.bases)]) {
162
+ for (const task of Object.values(reference.tasks)) {
176
163
  applySchemaExtension(reference, task);
177
164
  resolveDeps(reference, task, task.scope, task.schema);
178
165
  resolveNeeds(reference, task, task.scope, task.schema);
@@ -201,67 +188,57 @@ function applySchemaExtension(reference, task) {
201
188
  task.extension = 'applying';
202
189
  task.depBases = [];
203
190
  task.needBases = [];
204
- // every property of every kind of task, as a task may take its kind from its base
205
- const schema = task.schema;
206
- const reset = new Set(schema.reset ?? []);
207
- if (!schema.extend) {
191
+ // a task that builds an image extends nothing (its schema has no `extend`)
192
+ if ((0, build_file_task_schema_1.isBuildFileImageBuildTaskSchema)(task.schema)) {
193
+ task.extension = 'applied';
194
+ return;
195
+ }
196
+ const reset = new Set(task.schema.reset ?? []);
197
+ if (!task.schema.extend) {
208
198
  if (reset.size > 0) {
209
199
  throw new Error(`task ${task.relativeName} sets reset without extend`);
210
200
  }
211
201
  task.extension = 'applied';
212
202
  return;
213
203
  }
214
- const name = schema.extend;
215
- const extend = findPublished(task.relativeName, 'extends', () => findBase(reference, task, name));
216
- applySchemaExtension(reference, extend);
217
- const base = extend.schema;
218
- // only a value the base has: `image` and `build` in a schema decide the kind of task
219
- for (const key of ['shell', 'cache', 'timeout', 'runner', 'network', 'args', 'image']) {
220
- if (schema[key] === undefined && base[key] !== undefined) {
221
- Object.assign(schema, { [key]: base[key] });
222
- }
204
+ const name = task.schema.extend;
205
+ const extend = findPublished(task.relativeName, 'extends', () => findTask(reference, task.scope, name, null)).task;
206
+ // hammerkit makes the commands of a task that builds an image (see image-build.ts)
207
+ if ((0, build_file_task_schema_1.isBuildFileImageBuildTaskSchema)(extend.schema)) {
208
+ throw new Error(`task ${task.relativeName} extends ${name}, which builds an image: such a task can't be extended`);
223
209
  }
210
+ applySchemaExtension(reference, extend);
211
+ task.schema.shell = task.schema.shell ?? extend.schema.shell;
212
+ task.schema.cache = task.schema.cache ?? extend.schema.cache;
213
+ task.schema.timeout = task.schema.timeout ?? extend.schema.timeout;
214
+ task.schema.runner = task.schema.runner ?? extend.schema.runner;
215
+ task.schema.network = task.schema.network ?? extend.schema.network;
216
+ task.schema.args = task.schema.args ?? extend.schema.args;
224
217
  if (!reset.has('cmds'))
225
- schema.cmds = extendArray(schema.cmds, base.cmds);
218
+ task.schema.cmds = extendArray(task.schema.cmds, extend.schema.cmds);
226
219
  if (!reset.has('src'))
227
- schema.src = extendArray(schema.src, base.src);
220
+ task.schema.src = extendArray(task.schema.src, extend.schema.src);
228
221
  if (!reset.has('generates'))
229
- schema.generates = extendArray(schema.generates, base.generates);
230
- if (!reset.has('mounts'))
231
- schema.mounts = extendArray(schema.mounts, base.mounts);
232
- // key by key, the task's own value winning, as envs and labels: a base sets push and login
233
- // for the tasks that set their own tags
234
- if (!reset.has('build') && base.build)
235
- schema.build = { ...base.build, ...schema.build };
236
- // what is a task's own, for its own run, a base that only is extended declares for the tasks
237
- // extending it: its credentials, limits and claim
238
- if (base.abstract) {
239
- for (const key of ['account', 'resources', 'volumeSize', 'platform']) {
240
- if (schema[key] === undefined && base[key] !== undefined) {
241
- Object.assign(schema, { [key]: base[key] });
242
- }
243
- }
244
- if (!reset.has('secrets'))
245
- schema.secrets = extendArray(schema.secrets, base.secrets);
246
- if (!reset.has('capAdd'))
247
- schema.capAdd = extendArray(schema.capAdd, base.capAdd);
248
- }
222
+ task.schema.generates = extendArray(task.schema.generates, extend.schema.generates);
249
223
  if (!reset.has('labels'))
250
- schema.labels = extendObject(schema.labels, base.labels);
251
- // the labels a task is filtered by: those of its build file with its own, now with its base's
252
- task.labels = (0, label_values_1.mergeLabels)(task.scope.schema.labels, schema.labels);
224
+ task.schema.labels = extendObject(task.schema.labels, extend.schema.labels);
253
225
  // the base's resolved envs: its own plus the top-level envs of its build file
254
226
  // (and the inputs an include passed), which carry the defaults it relies on
255
227
  if (!reset.has('envs'))
256
228
  task.envs = (0, merge_environment_variables_1.mergeEnvironmentVariables)(task.envs, extend.envs);
229
+ if ((0, build_file_task_schema_1.isBuildFileContainerTaskSchema)(extend.schema)) {
230
+ const taskSchema = task.schema;
231
+ taskSchema.image = taskSchema.image ?? extend.schema.image;
232
+ if (!reset.has('mounts'))
233
+ taskSchema.mounts = extendArray(taskSchema.mounts, extend.schema.mounts);
234
+ }
257
235
  rejectContainerPropertiesWithoutImage(task);
258
- rejectCommandsOfImageBuild(task);
259
236
  // deps and needs resolve in the file that declares them, so every base up the
260
237
  // chain contributes its own, not only the nearest; what a task resets is not
261
238
  // passed on to the tasks extending it either
262
- const declared = { scope: extend.scope, schema: extend.schema };
263
- task.needBases = reset.has('needs') ? [] : [...(extend.needBases ?? []), declared];
264
- task.depBases = reset.has('deps') ? [] : [...(extend.depBases ?? []), declared];
239
+ const base = { scope: extend.scope, schema: extend.schema };
240
+ task.needBases = reset.has('needs') ? [] : [...(extend.needBases ?? []), base];
241
+ task.depBases = reset.has('deps') ? [] : [...(extend.depBases ?? []), base];
265
242
  for (const needBase of task.needBases) {
266
243
  resolveNeeds(reference, task, needBase.scope, needBase.schema);
267
244
  }
@@ -270,20 +247,6 @@ function applySchemaExtension(reference, task) {
270
247
  }
271
248
  task.extension = 'applied';
272
249
  }
273
- // The task `extend` names, a base or a task, with what a build file is missing when there is none
274
- function findBase(reference, task, name) {
275
- try {
276
- return findTask(reference, task.scope, name, null, true).task;
277
- }
278
- catch (e) {
279
- if (!(e instanceof NotFoundError)) {
280
- throw e;
281
- }
282
- const prefix = (0, split_name_1.splitName)(e.name).prefix;
283
- const missing = prefix && !e.scope.references[prefix] ? `include or reference ${prefix}` : `task ${(0, split_name_1.splitName)(e.name).name}`;
284
- throw new Error(`task ${task.relativeName} extends ${name}, but ${e.scope.fileName} has no ${missing}`);
285
- }
286
- }
287
250
  function rejectContainerPropertiesWithoutImage(task) {
288
251
  if ((0, build_file_task_schema_1.isBuildFileContainerTaskSchema)(task.schema) || (0, build_file_task_schema_1.isBuildFileImageBuildTaskSchema)(task.schema)) {
289
252
  return;
@@ -294,22 +257,6 @@ function rejectContainerPropertiesWithoutImage(task) {
294
257
  throw new Error(`task ${task.relativeName} sets ${property}, but neither it nor its base has an image`);
295
258
  }
296
259
  }
297
- // hammerkit makes the image and the command of a task that builds one (see image-build.ts)
298
- const IMAGE_BUILD_EXCLUDED = ['image', 'cmds', 'shell', 'args', 'mounts', 'capAdd', 'platform'];
299
- function rejectCommandsOfImageBuild(task) {
300
- const schema = task.schema;
301
- if (!schema.build) {
302
- return;
303
- }
304
- const property = IMAGE_BUILD_EXCLUDED.find((key) => {
305
- const value = schema[key];
306
- return value !== undefined && !(Array.isArray(value) && value.length === 0);
307
- });
308
- if (property) {
309
- throw new Error(`task ${task.relativeName} has build and ${property}, from it or the task it extends: ` +
310
- `a task that builds an image takes no ${property}`);
311
- }
312
- }
313
260
  function extendArray(base, extend) {
314
261
  if (!extend) {
315
262
  return base;
@@ -378,30 +325,21 @@ function resolveNeeds(reference, taskOrService, scope, schema) {
378
325
  throw new Error(`${taskOrService.relativeName} needs two services as ${twice}, give one another name with name:`);
379
326
  }
380
327
  }
381
- // A name no task of a build file has
382
- class NotFoundError extends Error {
383
- constructor(scope, name) {
384
- super('unable to find ' + name);
385
- this.scope = scope;
386
- this.name = name;
387
- }
388
- }
389
- // The task a name stands for in a build file; a base (`abstract`) only for `extend`
390
- function findTask(ctx, scope, name, type, base = false) {
328
+ function findTask(ctx, scope, name, type) {
391
329
  refuseNotFetched(scope, name);
392
330
  const ref = (0, split_name_1.splitName)(name);
393
331
  if (ref.prefix) {
394
332
  if (scope.references[ref.prefix]) {
395
- return findTask(ctx, scope.references[ref.prefix].scope, ref.name, scope.references[ref.prefix].type, base);
333
+ return findTask(ctx, scope.references[ref.prefix].scope, ref.name, scope.references[ref.prefix].type);
396
334
  }
397
335
  else if (scope.schema.tasks && scope.schema.tasks[name]) {
398
- return resolveTask(ctx, scope, name, type ?? 'build-file', base);
336
+ return resolveTask(ctx, scope, name, type ?? 'build-file');
399
337
  }
400
338
  }
401
339
  else if (scope.schema.tasks && scope.schema.tasks[ref.name]) {
402
- return resolveTask(ctx, scope, ref.name, type ?? 'build-file', base);
340
+ return resolveTask(ctx, scope, ref.name, type ?? 'build-file');
403
341
  }
404
- throw new NotFoundError(scope, name);
342
+ throw new Error('unable to find ' + name); // TODO improve
405
343
  }
406
344
  exports.findTask = findTask;
407
345
  // A name in a git source a server did not fetch, since it is left out
@@ -410,12 +348,9 @@ function refuseNotFetched(scope, name) {
410
348
  throw new UnpublishedError(combinePath(scope.namePrefix, name), 'its build file is included with publish: false');
411
349
  }
412
350
  }
413
- function resolveTask(ctx, scope, name, type, base) {
351
+ function resolveTask(ctx, scope, name, type) {
414
352
  const fullName = combinePath(scope.namePrefix, name);
415
- if (!base && ctx.bases[fullName]) {
416
- throw new AbstractError(fullName);
417
- }
418
- const buildFileTask = ctx.tasks[fullName] ?? (base ? ctx.bases[fullName] : undefined);
353
+ const buildFileTask = ctx.tasks[fullName];
419
354
  if (!buildFileTask && ctx.unpublished?.[fullName]) {
420
355
  throw new UnpublishedError(fullName, ctx.unpublished[fullName]);
421
356
  }
@@ -48,7 +48,6 @@ function getWorkContext(context, scope, environment) {
48
48
  // its init task's need on it, which narrowing follows
49
49
  const tasks = Object.values(context.tasks).map((task) => (0, append_work_task_1.appendWorkTask)(workTree, task.cwd, task, environment, context));
50
50
  const services = Object.values(context.services).map((service) => (0, append_work_service_1.appendWorkService)(workTree, service, environment, context));
51
- refuseBases(context, (0, work_scope_1.isContextTaskFilter)(scope) ? [scope.taskName] : [...(scope.names ?? []), ...(scope.taskNames ?? [])]);
52
51
  const apply = { servicesAlone: !(0, work_scope_1.isContextTaskFilter)(scope) && !!scope.names && !!scope.stop };
53
52
  const selectedTasks = [];
54
53
  const selectedServices = [];
@@ -87,13 +86,6 @@ function getWorkContext(context, scope, environment) {
87
86
  return filteredWorkTree;
88
87
  }
89
88
  exports.getWorkContext = getWorkContext;
90
- // A base (`abstract: true`) is not run by its name, as it is not listed
91
- function refuseBases(context, names) {
92
- const base = names.find((name) => name in context.bases);
93
- if (base) {
94
- throw new Error(`${base} is abstract, a base for extend that doesn't run: run a task that extends it`);
95
- }
96
- }
97
89
  // The whole build file is planned first, so a shared service lists every task
98
90
  // and service that needs it. Those outside this run never start or end, and a
99
91
  // service waiting for them to finish would keep the run open forever.
@@ -1,34 +1,15 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.prefetchSecrets = exports.requireReadableSecrets = void 0;
3
+ exports.prefetchSecrets = void 0;
4
4
  const plan_work_tasks_1 = require("../planner/utils/plan-work-tasks");
5
5
  const work_secret_1 = require("../planner/work-secret");
6
6
  const provider_values_1 = require("./provider-values");
7
- function secretsOf(workTree) {
8
- return [
9
- ...[...(0, plan_work_tasks_1.iterateWorkServices)(workTree)].flatMap((service) => ('secrets' in service.data ? service.data.secrets : [])),
10
- ...[...(0, plan_work_tasks_1.iterateWorkTasks)(workTree)].flatMap((task) => task.data.secrets),
11
- ];
12
- }
13
- // A secret of a provider that this machine does not declare fails a command only when the
14
- // command needs it: a run needs every secret of the tasks and services it holds, the other
15
- // commands the `cache: true` ones, for task ids. A task elsewhere in the build file that reads
16
- // it does not stop them (ADR 0008).
17
- function requireReadableSecrets(workTree, needed = () => true) {
18
- for (const secret of secretsOf(workTree)) {
19
- if (secret.source.type === 'unavailable' && needed(secret)) {
20
- throw new Error(secret.source.error);
21
- }
22
- }
23
- }
24
- exports.requireReadableSecrets = requireReadableSecrets;
25
7
  // Fetches the values a task id needs; a run drops the ones of the previous run
26
8
  // first (`newRun`), any other command reuses what the run already fetched. A task id is computed synchronously and holds the
27
9
  // digest of each `cache: true` secret, so those values must be in memory before
28
10
  // anything asks for an id. Secrets that don't affect the id are read when their
29
11
  // task starts, and a plan without provider secrets calls no provider.
30
12
  async function prefetchSecrets(workTree, environment, newRun = false) {
31
- requireReadableSecrets(workTree, (secret) => secret.cache);
32
13
  if (newRun) {
33
14
  (0, provider_values_1.beginSecretRun)(environment);
34
15
  }
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.formatMemory = exports.formatCpu = exports.HostCapacity = exports.KubernetesCapacity = exports.getQuotaResources = exports.cachedCapacity = exports.parseQuantity = void 0;
3
+ exports.formatMemory = exports.formatCpu = exports.HostCapacity = exports.KubernetesCapacity = exports.cachedCapacity = exports.parseQuantity = void 0;
4
4
  const os_1 = require("os");
5
5
  const log_1 = require("../log");
6
6
  const apply_1 = require("../kubernetes/apply");
@@ -71,16 +71,6 @@ function briefly(e, what) {
71
71
  }
72
72
  return what === 'nodes' ? 'nodes not readable' : 'metrics not readable';
73
73
  }
74
- // The CPU and memory pods may request under a quota, if it limits them
75
- function getQuotaResources(hard) {
76
- const cpu = (0, units_1.parseQuantity)(hard['requests.cpu'] ?? hard.cpu);
77
- const memory = (0, units_1.parseQuantity)(hard['requests.memory'] ?? hard.memory);
78
- if (cpu === undefined && memory === undefined) {
79
- return undefined;
80
- }
81
- return { ...(cpu !== undefined ? { cpu } : {}), ...(memory !== undefined ? { memory } : {}) };
82
- }
83
- exports.getQuotaResources = getQuotaResources;
84
74
  const ENDED = ['Succeeded', 'Failed'];
85
75
  // On Kubernetes: per namespace of the server, its pods' requests, its quota and its usage.
86
76
  class KubernetesCapacity {
@@ -172,13 +162,11 @@ class KubernetesCapacity {
172
162
  name: this.options.quotaName,
173
163
  namespace,
174
164
  });
175
- const resources = getQuotaResources(quota.spec?.hard ?? {});
176
- if (resources) {
177
- group.quota = resources;
178
- const share = this.options.share;
179
- if (kind === 'caller' && share && (share.cpu !== resources.cpu || share.memory !== resources.memory)) {
180
- group.share = share;
181
- }
165
+ const hard = quota.spec?.hard ?? {};
166
+ const cpu = (0, units_1.parseQuantity)(hard['requests.cpu'] ?? hard.cpu);
167
+ const memory = (0, units_1.parseQuantity)(hard['requests.memory'] ?? hard.memory);
168
+ if (cpu !== undefined || memory !== undefined) {
169
+ group.quota = { ...(cpu !== undefined ? { cpu } : {}), ...(memory !== undefined ? { memory } : {}) };
182
170
  }
183
171
  }
184
172
  catch (e) {
@@ -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}`);