hammerkit 2.0.0-next.8 → 2.0.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 (99) hide show
  1. package/build.schema.json +228 -63
  2. package/dist/cache/backends/registry/registry-client.js +8 -2
  3. package/dist/cache/explain.js +5 -0
  4. package/dist/cache/last-resolved.js +11 -0
  5. package/dist/cli.js +4 -1
  6. package/dist/dashboard/assets/{graph-canvas-HmkW_-XJ.js → graph-canvas-DtJSpova.js} +1 -1
  7. package/dist/dashboard/assets/index-BndChMep.css +2 -0
  8. package/dist/dashboard/assets/{index-vE22S5E_.js → index-DRSwIRXd.js} +9 -9
  9. package/dist/dashboard/index.html +2 -2
  10. package/dist/docker/item-network.js +51 -18
  11. package/dist/docker/package.js +85 -76
  12. package/dist/docker/server-tools.js +96 -0
  13. package/dist/docker/stream.js +15 -7
  14. package/dist/environment/replace-env-variables.js +1 -1
  15. package/dist/environment/run-source-envs.js +18 -0
  16. package/dist/executer/check-container-binds.js +158 -0
  17. package/dist/executer/docker-service.js +42 -3
  18. package/dist/executer/docker-task.js +33 -6
  19. package/dist/executer/execute-command.js +9 -15
  20. package/dist/executer/execute-work-task.js +11 -1
  21. package/dist/executer/execute-work-tree.js +2 -1
  22. package/dist/executer/execution-steps.js +6 -2
  23. package/dist/executer/get-container-binds.js +2 -0
  24. package/dist/executer/print-container-options.js +10 -10
  25. package/dist/executer/process-manager.js +84 -5
  26. package/dist/executer/scheduler/state-key.js +19 -1
  27. package/dist/executer/task-priority.js +131 -0
  28. package/dist/file/stat-beneath.js +66 -0
  29. package/dist/file/within-root.js +13 -4
  30. package/dist/harness/connect.js +1 -6
  31. package/dist/harness/mcp-command.js +1 -1
  32. package/dist/harness/sandbox-client.js +39 -4
  33. package/dist/harness/service-tools.js +2 -2
  34. package/dist/kubernetes/await-running-state.js +42 -26
  35. package/dist/kubernetes/ensure-persistent-data.js +22 -7
  36. package/dist/kubernetes/follow-pod-logs.js +5 -3
  37. package/dist/kubernetes/network-gate.js +74 -11
  38. package/dist/kubernetes/network-policy.js +32 -10
  39. package/dist/kubernetes/remove-stale-items.js +15 -2
  40. package/dist/kubernetes/restore-kubernetes-data.js +3 -2
  41. package/dist/kubernetes/sandbox-runner.js +3 -4
  42. package/dist/kubernetes/store-kubernetes-data.js +3 -2
  43. package/dist/kubernetes/transfer-tools.js +66 -0
  44. package/dist/kubernetes/volumes.js +52 -10
  45. package/dist/optimizer/check-key.js +7 -0
  46. package/dist/optimizer/check-keys.js +19 -5
  47. package/dist/optimizer/get-work-cache-stats.js +19 -7
  48. package/dist/optimizer/work-task-cache-description.js +42 -8
  49. package/dist/parser/read-build-file.js +8 -3
  50. package/dist/planner/image-build.js +172 -0
  51. package/dist/planner/utils/append-work-dependencies.js +14 -1
  52. package/dist/planner/utils/append-work-service.js +1 -1
  53. package/dist/planner/utils/append-work-task.js +51 -1
  54. package/dist/planner/utils/assert-item-paths.js +6 -7
  55. package/dist/planner/utils/dependency-outputs.js +18 -0
  56. package/dist/planner/utils/template-value.js +20 -4
  57. package/dist/planner/work-runtime-docker.js +48 -50
  58. package/dist/planner/work-runtime-kubernetes.js +1 -0
  59. package/dist/planner/work-runtime-local.js +3 -7
  60. package/dist/planner/work-secret.js +135 -13
  61. package/dist/planner/work-tree.js +10 -0
  62. package/dist/remote/collect-bundle.js +9 -1
  63. package/dist/remote/host-config.js +49 -3
  64. package/dist/remote/location.js +5 -5
  65. package/dist/remote/remote-commands.js +12 -14
  66. package/dist/remote/remote-work-commands.js +20 -8
  67. package/dist/schema/build-file-image-build-schema.js +77 -0
  68. package/dist/schema/build-file-task-schema.js +9 -2
  69. package/dist/schema/reference-parser.js +10 -1
  70. package/dist/schema/schema-parser.js +46 -2
  71. package/dist/schema/work-scope-parser.js +16 -1
  72. package/dist/secrets/secret-catalog.js +8 -1
  73. package/dist/server/dashboard.js +8 -5
  74. package/dist/server/executor.js +58 -35
  75. package/dist/server/kubernetes-backend.js +29 -4
  76. package/dist/server/kubernetes-sandbox-storage.js +14 -4
  77. package/dist/server/overview.js +20 -2
  78. package/dist/server/plan.js +31 -3
  79. package/dist/server/policy.js +14 -7
  80. package/dist/server/repo-access.js +4 -3
  81. package/dist/server/run-environment.js +5 -2
  82. package/dist/server/run-plan.js +18 -6
  83. package/dist/server/run-retry.js +57 -0
  84. package/dist/server/run-source-environment.js +39 -0
  85. package/dist/server/run-worker.js +38 -9
  86. package/dist/server/runs.js +59 -1
  87. package/dist/server/sandbox-files.js +339 -55
  88. package/dist/server/sandbox-patch.js +43 -17
  89. package/dist/server/sandboxes.js +57 -23
  90. package/dist/server/server-config.js +24 -4
  91. package/dist/server/server.js +107 -12
  92. package/dist/server/service-runs.js +42 -4
  93. package/dist/server/sources.js +68 -11
  94. package/dist/utils/buffer-context.js +30 -20
  95. package/dist/utils/line-splitter.js +52 -0
  96. package/dist/utils/read-lines.js +65 -0
  97. package/dist/utils/tar.js +51 -1
  98. package/package.json +1 -1
  99. package/dist/dashboard/assets/index-gIBDC_m8.css +0 -2
@@ -186,8 +186,8 @@ function registerWorkCommands(remote, context) {
186
186
  }
187
187
  return { type: 'ref', repo, ref, ...(commit ? { commit } : {}) };
188
188
  };
189
- const connect = async (name) => {
190
- const chosen = await getServer(name);
189
+ const connect = async (name, how) => {
190
+ const chosen = await getServer(name, how);
191
191
  // a CI job or an agent brings its own token, a person signs in
192
192
  const token = await (0, token_source_1.getTokenSource)(environment, chosen.name, chosen.server).token();
193
193
  return { ...chosen, token };
@@ -340,7 +340,7 @@ function registerWorkCommands(remote, context) {
340
340
  remote
341
341
  .command('run <tasks...>')
342
342
  .description('run tasks of a published build file on a server from a git ref, print their output and exit as they did')
343
- .addOption(new commander_1.Option('--server <name>', 'the server to run on; the default of remote use when left out'))
343
+ .addOption(new commander_1.Option('--server <name>', 'the server to run on; when left out, the default of remote use or the only registered server'))
344
344
  .addOption(new commander_1.Option('--build <hash>', 'the published version to run (sha256:...), or HAMMERKIT_BUILD; the hash of the build file here when left out'))
345
345
  .addOption(new commander_1.Option('--repo <host/path>', 'the repository, such as github.com/corp/payments; origin of the checkout here when left out'))
346
346
  .addOption(new commander_1.Option('--ref <ref>', 'the branch or tag to run; the branch checked out here when left out'))
@@ -355,7 +355,7 @@ function registerWorkCommands(remote, context) {
355
355
  const { definition, local } = await runDefinition(options);
356
356
  const source = await refSource(options);
357
357
  const ref = source.ref;
358
- const { name: serverName, server } = await getServer(options.server);
358
+ const { name: serverName, server } = await getServer(options.server, 'with --server <name>');
359
359
  const connection = { url: server.url, ...(0, token_source_1.getTokenSource)(environment, serverName, server) };
360
360
  const runOptions = {};
361
361
  for (const key of ['env', 'cache', 'timeout', 'maxTimeout']) {
@@ -407,7 +407,7 @@ function registerWorkCommands(remote, context) {
407
407
  .command('up <services...>')
408
408
  .description('start services of a published build file on a server from a git ref and keep them up until their ttl ends, ' +
409
409
  'with their endpoints at addresses of their own behind the sign-in of the server')
410
- .addOption(new commander_1.Option('--server <name>', 'the server to run on; the default of remote use when left out'))
410
+ .addOption(new commander_1.Option('--server <name>', 'the server to run on; when left out, the default of remote use or the only registered server'))
411
411
  .addOption(new commander_1.Option('--endpoint <service:port>', 'publish this port of a service, such as web:8080; may be given more than once').argParser(collectOption))
412
412
  .addOption(new commander_1.Option('--ttl <duration>', 'how long they stay once ready, such as 2h, then they are removed; the server default when left out'))
413
413
  .addOption(new commander_1.Option('--sleep-ttl <duration>', 'how long they stay up without a request, such as 30m, then they sleep until the next request wakes them; ' +
@@ -424,7 +424,7 @@ function registerWorkCommands(remote, context) {
424
424
  const { definition, local } = await runDefinition(options);
425
425
  const endpoints = (options.endpoint ?? []).map(service_tools_1.parseEndpoint);
426
426
  const source = await refSource(options);
427
- const { name: serverName, server } = await getServer(options.server);
427
+ const { name: serverName, server } = await getServer(options.server, 'with --server <name>');
428
428
  const connection = { url: server.url, ...(0, token_source_1.getTokenSource)(environment, serverName, server) };
429
429
  const submitted = await submitPublishing({ serverName, server, connection }, {
430
430
  definition,
@@ -683,11 +683,23 @@ function registerWorkCommands(remote, context) {
683
683
  const run = (await (0, server_client_1.callServer)(server, token, 'POST', `/v1/runs/${id}/cancel`)).body;
684
684
  environment.stdout.write(`${(0, server_client_1.printable)(run.id)} on ${serverName}: ${run.state === 'up' || run.state === 'running' ? 'stopping' : (0, server_client_1.printable)(run.state)}\n`);
685
685
  }));
686
+ remote
687
+ .command('retry <run> [server]')
688
+ .description('start a run that is over again, as a new run of yours: the same tasks or services, settings and commit')
689
+ .action(guarded('Remote retry was not successful', async (id, name) => {
690
+ if (!RUN_ID.test(id)) {
691
+ throw new Error(`${(0, server_client_1.printable)(id)} is not a run id (run_...)`);
692
+ }
693
+ const { name: serverName, server, token } = await connect(name);
694
+ const run = (await (0, server_client_1.callServer)(server, token, 'POST', `/v1/runs/${id}/retry`)).body;
695
+ environment.stdout.write(`${(0, server_client_1.printable)(run.id)} on ${serverName} retries ${(0, server_client_1.printable)(id)}: ${(0, server_client_1.printable)(run.state)}, ` +
696
+ `follow it with hammerkit remote logs ${(0, server_client_1.printable)(run.id)} --follow\n`);
697
+ }));
686
698
  remote
687
699
  .command('verify <tasks...>')
688
700
  .description('check that the server already passed tasks for the files checked out here, without running them; ' +
689
701
  'exits 1 at once for any it did not')
690
- .addOption(new commander_1.Option('--server <name>', 'the server to ask; the default of remote use when left out'))
702
+ .addOption(new commander_1.Option('--server <name>', 'the server to ask; when left out, the default of remote use or the only registered server'))
691
703
  .addOption(new commander_1.Option('--repo <host/path>', 'the repository, such as github.com/corp/payments; origin of the checkout here when left out'))
692
704
  .addOption(new commander_1.Option('--env <name>', 'the environment of the build file, as --env of run'))
693
705
  .action(guarded('Remote verify was not successful', async (tasks, options) => {
@@ -709,7 +721,7 @@ function registerWorkCommands(remote, context) {
709
721
  keys.push({ task, key: found.key });
710
722
  }
711
723
  }
712
- const { name: serverName, server, token } = await connect(options.server);
724
+ const { name: serverName, server, token } = await connect(options.server, 'with --server <name>');
713
725
  const answer = keys.length > 0
714
726
  ? await (0, server_client_1.callServer)(server, token, 'POST', '/v1/checks/lookup', { repo, keys })
715
727
  : { body: { checks: [] } };
@@ -0,0 +1,77 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildFileImageBuildTaskSchema = exports.buildFileImageBuildSchema = exports.buildFileRegistryLoginSchema = void 0;
4
+ const zod_1 = require("zod");
5
+ const build_file_base_task_schema_1 = require("./build-file-base-task-schema");
6
+ const size_schema_1 = require("./size-schema");
7
+ // A registry host, with a port where it has one: europe-west4-docker.pkg.dev, ghcr.io, localhost:5000
8
+ const REGISTRY = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*(:[0-9]{1,5})?$/i;
9
+ // The name of an image with its tag or digest, as `docker build --tag` takes it. A comma, a
10
+ // quote or a space would end it in BuildKit's `--output`, so none of them is in one. `$NAME`
11
+ // and `${NAME}` take the value of a variable, and the name is checked again with it.
12
+ const IMAGE = /^[a-z0-9$][a-z0-9._/:@${}-]*$/i;
13
+ // A platform as BuildKit takes it: os/arch, with a variant where it has one (linux/arm/v7)
14
+ const PLATFORM = /^[a-z0-9]+\/[a-z0-9_]+(\/[a-z0-9]+)?$/;
15
+ // the password of a registry login, read like a secret of the task, never written in the build file
16
+ const registryPasswordSchema = (0, zod_1.object)({
17
+ from: (0, zod_1.string)().regex(/^[A-Za-z][A-Za-z0-9_-]*:.+$/, 'from must be env:NAME, file:path or <provider>:<ref>'),
18
+ account: (0, zod_1.string)().optional(),
19
+ })
20
+ .strict()
21
+ .describe('the password, a secret from env:NAME, file:path or <provider>:<ref>');
22
+ exports.buildFileRegistryLoginSchema = (0, zod_1.object)({
23
+ registry: (0, zod_1.string)().regex(REGISTRY, 'registry must be a host, with a port where it has one (ghcr.io, localhost:5000)'),
24
+ // a user name of basic auth holds no colon; a quote or a backslash would end it in the JSON
25
+ user: (0, zod_1.string)().regex(/^[^:"\\\s]+$/, 'user must not hold a colon, a quote, a backslash or a space'),
26
+ password: registryPasswordSchema,
27
+ })
28
+ .strict()
29
+ .describe('a sign-in to a registry, for the push and the cache');
30
+ exports.buildFileImageBuildSchema = (0, zod_1.object)({
31
+ // the folder sent to the build, relative to the task's directory
32
+ context: (0, zod_1.string)().optional().describe('the build context, `.` when left out'),
33
+ // the Dockerfile, relative to the task's directory
34
+ dockerfile: (0, zod_1.string)().optional().describe('the Dockerfile, Dockerfile in the context when left out'),
35
+ tags: (0, zod_1.union)([(0, zod_1.string)().regex(IMAGE, 'a tag must be an image name'), (0, zod_1.array)((0, zod_1.string)().regex(IMAGE)).min(1)])
36
+ .optional()
37
+ .describe('the names of the image, with their tags, as docker build --tag'),
38
+ push: (0, zod_1.boolean)().optional().describe('push the image to its registry, as docker build --push'),
39
+ // an image the layers are read from before the build and written to after it
40
+ cache: (0, zod_1.string)()
41
+ .regex(IMAGE, 'cache must be an image name, such as ghcr.io/acme/app:buildcache')
42
+ .optional()
43
+ .describe('an image in a registry the build reads its layers from and writes them to'),
44
+ // a file the task writes <name>@<digest> of the image to, which another task deploys
45
+ digest: (0, zod_1.string)().optional().describe('a file the task writes <image>@<digest> to'),
46
+ login: (0, zod_1.array)(exports.buildFileRegistryLoginSchema).optional(),
47
+ // the registries of the tags and the cache speak plain HTTP, as a registry:2 on a network of
48
+ // your own does (docker's --insecure-registry)
49
+ insecure: (0, zod_1.boolean)().optional().describe('reach the registries over plain HTTP'),
50
+ // the platforms of the image, as docker build --platform: one image for each, under one name.
51
+ // A RUN step for a platform other than the machine's runs in BuildKit's own QEMU.
52
+ platforms: (0, zod_1.union)([
53
+ (0, zod_1.string)().regex(PLATFORM, 'a platform is os/arch, such as linux/arm64'),
54
+ (0, zod_1.array)((0, zod_1.string)().regex(PLATFORM, 'a platform is os/arch, such as linux/arm64')).min(1),
55
+ ])
56
+ .optional()
57
+ .describe('the platforms to build for, such as linux/amd64 and linux/arm64, as docker build --platform'),
58
+ })
59
+ .strict()
60
+ .refine((build) => !build.push || build.tags !== undefined, {
61
+ message: 'push needs tags, the names of the image to push',
62
+ })
63
+ .refine((build) => build.digest === undefined || build.tags !== undefined, {
64
+ message: 'digest needs tags, the name the digest is written with',
65
+ })
66
+ .describe('builds a Dockerfile with BuildKit, as docker build does');
67
+ // A task that builds an image: hammerkit runs BuildKit for it, so it names no image, commands or
68
+ // shell of its own, and doesn't extend another task or take arguments.
69
+ exports.buildFileImageBuildTaskSchema = build_file_base_task_schema_1.buildFileBaseTaskSchema
70
+ .omit({ extend: true, reset: true, cmds: true, shell: true, args: true })
71
+ .extend({
72
+ build: exports.buildFileImageBuildSchema,
73
+ volumeSize: size_schema_1.sizeSchema.describe('size of its claim on Kubernetes, e.g. 10Gi').optional(),
74
+ })
75
+ .strict()
76
+ .describe('task that builds an image');
77
+ //# sourceMappingURL=build-file-image-build-schema.js.map
@@ -1,16 +1,23 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isBuildFileLocalTaskSchema = exports.isBuildFileContainerTaskSchema = exports.buildFileTaskSchema = void 0;
3
+ exports.isBuildFileLocalTaskSchema = exports.isBuildFileImageBuildTaskSchema = exports.isBuildFileContainerTaskSchema = exports.buildFileTaskSchema = void 0;
4
4
  const zod_1 = require("zod");
5
5
  const build_file_container_task_schema_1 = require("./build-file-container-task-schema");
6
6
  const build_file_local_task_schema_1 = require("./build-file-local-task-schema");
7
+ const build_file_image_build_schema_1 = require("./build-file-image-build-schema");
8
+ // A task with `build` is tried first: it fails at once without one, and with one its own
9
+ // errors are reported, not that the other kinds don't know `build` (zod gives the first
10
+ // option's errors that aren't fatal).
7
11
  exports.buildFileTaskSchema = (0, zod_1.union)([
12
+ build_file_image_build_schema_1.buildFileImageBuildTaskSchema,
8
13
  build_file_container_task_schema_1.buildFileContainerTaskSchema,
9
14
  build_file_local_task_schema_1.buildFileLocalTaskSchema,
10
15
  build_file_container_task_schema_1.buildFileExtendingContainerTaskSchema,
11
16
  ]);
12
17
  const isBuildFileContainerTaskSchema = (val) => 'image' in val;
13
18
  exports.isBuildFileContainerTaskSchema = isBuildFileContainerTaskSchema;
14
- const isBuildFileLocalTaskSchema = (val) => !('image' in val);
19
+ const isBuildFileImageBuildTaskSchema = (val) => 'build' in val;
20
+ exports.isBuildFileImageBuildTaskSchema = isBuildFileImageBuildTaskSchema;
21
+ const isBuildFileLocalTaskSchema = (val) => !('image' in val) && !('build' in val);
15
22
  exports.isBuildFileLocalTaskSchema = isBuildFileLocalTaskSchema;
16
23
  //# sourceMappingURL=build-file-task-schema.js.map
@@ -188,6 +188,11 @@ function applySchemaExtension(reference, task) {
188
188
  task.extension = 'applying';
189
189
  task.depBases = [];
190
190
  task.needBases = [];
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
+ }
191
196
  const reset = new Set(task.schema.reset ?? []);
192
197
  if (!task.schema.extend) {
193
198
  if (reset.size > 0) {
@@ -198,6 +203,10 @@ function applySchemaExtension(reference, task) {
198
203
  }
199
204
  const name = task.schema.extend;
200
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`);
209
+ }
201
210
  applySchemaExtension(reference, extend);
202
211
  task.schema.shell = task.schema.shell ?? extend.schema.shell;
203
212
  task.schema.cache = task.schema.cache ?? extend.schema.cache;
@@ -239,7 +248,7 @@ function applySchemaExtension(reference, task) {
239
248
  task.extension = 'applied';
240
249
  }
241
250
  function rejectContainerPropertiesWithoutImage(task) {
242
- if ((0, build_file_task_schema_1.isBuildFileContainerTaskSchema)(task.schema)) {
251
+ if ((0, build_file_task_schema_1.isBuildFileContainerTaskSchema)(task.schema) || (0, build_file_task_schema_1.isBuildFileImageBuildTaskSchema)(task.schema)) {
243
252
  return;
244
253
  }
245
254
  const schema = task.schema;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.appendBuildFile = exports.createParseContext = void 0;
3
+ exports.appendBuildFile = exports.MAX_BUILD_FILE_ITEMS = exports.MAX_BUILD_FILE_BYTES = exports.MAX_INCLUDE_INPUT_BYTES = exports.MAX_BUILD_FILES = exports.MAX_INCLUDE_DEPTH = exports.createParseContext = void 0;
4
4
  const build_file_schema_1 = require("./build-file-schema");
5
5
  const read_build_file_1 = require("../parser/read-build-file");
6
6
  const path_1 = require("path");
@@ -20,6 +20,17 @@ async function createParseContext(fileName, environment, options) {
20
20
  return { ctx, scope };
21
21
  }
22
22
  exports.createParseContext = createParseContext;
23
+ // How deep includes and references may nest, how many build files one parse may read (a
24
+ // file included with other inputs counts again), and how large the inputs one include
25
+ // passes on may be. A file that includes itself with inputs that change each time ends at
26
+ // these instead of reading on without end.
27
+ exports.MAX_INCLUDE_DEPTH = 32;
28
+ exports.MAX_BUILD_FILES = 1000;
29
+ exports.MAX_INCLUDE_INPUT_BYTES = 64 * 1024;
30
+ // What the build files of one parse may take together, and how many tasks and services they
31
+ // may declare, a file included again counted again.
32
+ exports.MAX_BUILD_FILE_BYTES = 16 * 1024 * 1024;
33
+ exports.MAX_BUILD_FILE_ITEMS = 10000;
23
34
  async function appendBuildFile(cwd, ctx, environment, fileName, namePrefix, remote, inputs,
24
35
  // on a server: the file is included with `publish: false`, or below such an include
25
36
  leftOut = false) {
@@ -30,12 +41,26 @@ leftOut = false) {
30
41
  if (ctx.files[key]) {
31
42
  return ctx.files[key];
32
43
  }
33
- const input = await (0, read_build_file_1.read)(fileName, environment);
44
+ if (namePrefix.length > exports.MAX_INCLUDE_DEPTH) {
45
+ throw new Error(`${relativeName} (${fileName}) is included ${namePrefix.length} levels deep, at most ${exports.MAX_INCLUDE_DEPTH} are read`);
46
+ }
47
+ if (Object.keys(ctx.files).length >= exports.MAX_BUILD_FILES) {
48
+ throw new Error(`${relativeName} (${fileName}): the build file includes more than ${exports.MAX_BUILD_FILES} files, counting a file included with other inputs again`);
49
+ }
50
+ if (inputs && Buffer.byteLength(JSON.stringify(inputs), 'utf8') > exports.MAX_INCLUDE_INPUT_BYTES) {
51
+ throw new Error(`${relativeName} (${fileName}): the inputs passed to it take more than ${exports.MAX_INCLUDE_INPUT_BYTES} bytes`);
52
+ }
53
+ const input = await readCounted(ctx, fileName, environment, relativeName);
34
54
  (0, removed_properties_1.assertNoRemovedProperties)(input, fileName);
35
55
  const result = await build_file_schema_1.buildFileSchema.safeParseAsync(input);
36
56
  if (!result.success) {
37
57
  throw new parse_error_1.ParseError(result.error, fileName);
38
58
  }
59
+ const read = readOf(ctx);
60
+ read.items += Object.keys(result.data.tasks ?? {}).length + Object.keys(result.data.services ?? {}).length;
61
+ if (read.items > exports.MAX_BUILD_FILE_ITEMS) {
62
+ throw new Error(`${relativeName} (${fileName}): the build file declares more than ${exports.MAX_BUILD_FILE_ITEMS} tasks and services, counting a file included with other inputs again`);
63
+ }
39
64
  const scope = {
40
65
  fileName,
41
66
  cwd,
@@ -77,6 +102,25 @@ leftOut = false) {
77
102
  return scope;
78
103
  }
79
104
  exports.appendBuildFile = appendBuildFile;
105
+ // A build file, parsed once per parse and counted each time it is read.
106
+ async function readCounted(ctx, fileName, environment, relativeName) {
107
+ const read = readOf(ctx);
108
+ let parsed = read.parsed.get(fileName);
109
+ if (!parsed) {
110
+ parsed = await (0, read_build_file_1.readSized)(fileName, environment);
111
+ read.parsed.set(fileName, parsed);
112
+ }
113
+ read.bytes += parsed.bytes;
114
+ if (read.bytes > exports.MAX_BUILD_FILE_BYTES) {
115
+ throw new Error(`${relativeName} (${fileName}): the build file includes more than ${exports.MAX_BUILD_FILE_BYTES} bytes of build files, counting a file included with other inputs again`);
116
+ }
117
+ // every scope gets a value of its own
118
+ return structuredClone(parsed.value);
119
+ }
120
+ function readOf(ctx) {
121
+ ctx.read ?? (ctx.read = { bytes: 0, items: 0, parsed: new Map() });
122
+ return ctx.read;
123
+ }
80
124
  // The scope of a git source a server does not fetch, see ParseScope.notFetched
81
125
  function notFetched(cwd, namePrefix, include) {
82
126
  return {
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getWorkContext = exports.defaultEnvironment = void 0;
4
4
  const work_scope_1 = require("../executer/work-scope");
5
+ const work_tree_1 = require("../planner/work-tree");
5
6
  const label_values_1 = require("../executer/label-values");
6
7
  const append_work_service_1 = require("../planner/utils/append-work-service");
7
8
  const append_work_task_1 = require("../planner/utils/append-work-task");
@@ -70,6 +71,14 @@ function getWorkContext(context, scope, environment) {
70
71
  throw new Error(`no task or service named ${unknown.join(', ')}, see hammerkit ls`);
71
72
  }
72
73
  }
74
+ if (!(0, work_scope_1.isContextTaskFilter)(scope) && scope.taskNames) {
75
+ filteredWorkTree.named = scope.taskNames;
76
+ const known = new Set(tasks.map((task) => task.name));
77
+ const unknown = scope.taskNames.filter((name) => !known.has(name));
78
+ if (unknown.length > 0) {
79
+ throw new Error(`no task named ${unknown.join(', ')}, see hammerkit ls`);
80
+ }
81
+ }
73
82
  if (scope.args) {
74
83
  (0, task_arguments_1.applyArguments)({ tasks: selectedTasks, services: scope.args.services ? selectedServices : [] }, scope.args.values, scope.args.cache);
75
84
  }
@@ -89,7 +98,7 @@ function keepRequirersInScope(workTree) {
89
98
  service.requiredBy = service.requiredBy.filter((required) => inScope.has(required));
90
99
  // an init task asked for alone is what its service starts for
91
100
  const init = service.data.type === 'container-service' ? service.data.init : null;
92
- if (init && workTree.requested?.length === 1 && workTree.requested[0] === init.task.name) {
101
+ if (init && (0, work_tree_1.isAskedByName)(workTree, init.task.name)) {
93
102
  service.requiredBy.push(init.task);
94
103
  }
95
104
  }
@@ -131,6 +140,9 @@ function matchesTaskWorkScope(task, scope) {
131
140
  if (scope.serviceNames) {
132
141
  return false;
133
142
  }
143
+ if (scope.taskNames) {
144
+ return scope.taskNames.includes(task.name);
145
+ }
134
146
  if (scope.names) {
135
147
  return scope.names.includes(task.name);
136
148
  }
@@ -143,6 +155,9 @@ function matchesServiceWorkScope(service, scope) {
143
155
  if (scope.serviceNames) {
144
156
  return scope.serviceNames.includes(service.name);
145
157
  }
158
+ if (scope.taskNames) {
159
+ return false;
160
+ }
146
161
  if (scope.names) {
147
162
  return scope.names.includes(service.name);
148
163
  }
@@ -1,10 +1,16 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.collectSecretCatalog = exports.emptySecretCatalog = void 0;
3
+ exports.collectSecretCatalog = exports.emptySecretCatalog = exports.declared = void 0;
4
4
  const merge_environment_variables_1 = require("../environment/merge-environment-variables");
5
5
  const replace_env_variables_1 = require("../environment/replace-env-variables");
6
6
  const units_1 = require("../utils/units");
7
7
  const DEFAULT_TIMEOUT = '30s';
8
+ // What a record of the catalog holds under a name a build file or a config gives, only when it
9
+ // was declared there: `constructor` or `toString` is no provider or account of any catalog.
10
+ function declared(record, name) {
11
+ return Object.prototype.hasOwnProperty.call(record, name) ? record[name] : undefined;
12
+ }
13
+ exports.declared = declared;
8
14
  function emptySecretCatalog() {
9
15
  return { providers: {}, accounts: {} };
10
16
  }
@@ -51,6 +57,7 @@ function collectSecretCatalog(files, environment, context, host) {
51
57
  }
52
58
  }
53
59
  if (host) {
60
+ catalog.hostConfig = host.fileName;
54
61
  // the host config has no envs of its own: `${NAME}` is read from the process
55
62
  for (const [name, provider] of Object.entries(host.secretProviders ?? {})) {
56
63
  catalog.providers[name] = toProvider(name, provider, {}, host.fileName);
@@ -8,8 +8,9 @@ const http_1 = require("./http");
8
8
  const oauth_1 = require("./oauth");
9
9
  const policy_1 = require("./policy");
10
10
  const overview_1 = require("./overview");
11
- // Approving and publishing take a sign-in of the last minutes: the groups of a session are
12
- // those of its sign-in, and somebody taken out of a group must not decide for hours.
11
+ // Approving, publishing and retrying a run take a sign-in of the last minutes: the groups of a
12
+ // session are those of its sign-in, and somebody taken out of a group must not decide, nor
13
+ // start runs with the accounts the group gave them, for hours.
13
14
  exports.DECIDE_WITHIN_MS = 15 * 60000;
14
15
  const RUN = 'run_[A-Za-z0-9_-]{16}';
15
16
  const SANDBOX = 'sbx_[A-Za-z0-9_-]{16}';
@@ -43,8 +44,9 @@ const READS = [
43
44
  const ACTIONS = [`runs/${RUN}/(cancel|extend|wake)`].map(path);
44
45
  // what the delete buttons remove: a sandbox of the person's
45
46
  const REMOVALS = [`sandboxes/${SANDBOX}`].map(path);
46
- // what needs a recent sign-in
47
+ // what needs a recent sign-in: deciding, and starting a run with the person's accounts
47
48
  const DECISIONS = [`approvals/${RUN}/(approve|reject)`, `proposals/${HASH}/(approve|reject)`].map(path);
49
+ const STARTS = [`runs/${RUN}/retry`].map(path);
48
50
  exports.HEADERS = {
49
51
  'cache-control': 'no-store',
50
52
  'x-robots-tag': 'noindex',
@@ -116,7 +118,8 @@ async function api(context, principal, viewer, now, req, res, url) {
116
118
  const target = url.pathname.slice('/api'.length);
117
119
  const read = READS.some((pattern) => pattern.test(target));
118
120
  const action = ACTIONS.some((pattern) => pattern.test(target));
119
- const decision = DECISIONS.some((pattern) => pattern.test(target));
121
+ const start = STARTS.some((pattern) => pattern.test(target));
122
+ const decision = start || DECISIONS.some((pattern) => pattern.test(target));
120
123
  const removal = REMOVALS.some((pattern) => pattern.test(target));
121
124
  if (!read && !action && !decision && !removal) {
122
125
  return (0, http_1.send)(res, 404, { error: 'not found' });
@@ -139,7 +142,7 @@ async function api(context, principal, viewer, now, req, res, url) {
139
142
  // an API token is new; a sign-in in the browser has to be of the last minutes to decide
140
143
  if (decision && context.signedInAt !== undefined && now - context.signedInAt > exports.DECIDE_WITHIN_MS) {
141
144
  return (0, http_1.send)(res, 403, {
142
- error: `approving and rejecting take a sign-in of the last ${exports.DECIDE_WITHIN_MS / 60000} minutes`,
145
+ error: `${start ? 'retrying a run takes' : 'approving and rejecting take'} a sign-in of the last ${exports.DECIDE_WITHIN_MS / 60000} minutes`,
143
146
  signInAgain: true,
144
147
  });
145
148
  }
@@ -13,6 +13,7 @@ const git_checkout_1 = require("./git-checkout");
13
13
  const run_plan_1 = require("./run-plan");
14
14
  const work_network_1 = require("../planner/work-network");
15
15
  const execute_docker_1 = require("../executer/execute-docker");
16
+ const run_source_environment_1 = require("./run-source-environment");
16
17
  // `.git` as a file system may read it: any case, and a name Windows reads without its
17
18
  // trailing dots and spaces, or by its short name
18
19
  function isGitDirectory(segment) {
@@ -43,12 +44,21 @@ exports.defaultWorker = defaultWorker;
43
44
  // owner may write in the sandbox is not part of it. It leaves entries a run from main can
44
45
  // find, keyed by the files it ran on, as a ref run of a branch does: so only a caller who
45
46
  // may push a branch of the repository and run from it may check (server.ts).
47
+ //
48
+ // An approved run on a sandbox runs on a copy of the approved files too, but its owner
49
+ // may not use its accounts without the approval: it has a cache of its own, so what the
50
+ // owner's other runs built from files nobody approved (ignored ones) is not restored in it.
46
51
  function cacheNamespace(run) {
47
52
  const repository = run.source.type === 'ref' || (run.source.type === 'sandbox' && run.source.check);
53
+ const kind = repository
54
+ ? 'ref'
55
+ : run.source.type === 'sandbox' && (run.approvals?.length ?? 0) > 0
56
+ ? 'approved'
57
+ : run.source.type;
48
58
  const key = repository
49
59
  ? `ref\0${run.source.repo}`
50
- : `${run.source.type}\0${run.owner.iss}\0${run.owner.sub}`;
51
- return `${repository ? 'ref' : run.source.type}-${(0, crypto_1.createHash)('sha256').update(key).digest('hex').slice(0, 24)}`;
60
+ : `${kind}\0${run.owner.iss}\0${run.owner.sub}`;
61
+ return `${kind}-${(0, crypto_1.createHash)('sha256').update(key).digest('hex').slice(0, 24)}`;
52
62
  }
53
63
  exports.cacheNamespace = cacheNamespace;
54
64
  // The docker volumes of a run's services are its caller's, within the cache's source trust:
@@ -193,7 +203,7 @@ class HostExecutor {
193
203
  // what was approved is what runs: the accounts are read again from the files with
194
204
  // the environment of the run, and the run may use no more than it was admitted for
195
205
  const policy = source.type === 'sandbox' && sandboxes ? sandboxes.policy : planning.policy;
196
- const planned = await (0, run_plan_1.planRun)(bundle, run, planning.environment, policy);
206
+ const planned = await (0, run_plan_1.planRun)(bundle, run, (0, run_source_environment_1.runPlanningEnvironment)(planning.environment, run.source), policy);
197
207
  const extra = planned.accounts.filter((account) => !run.accounts.includes(account));
198
208
  if (extra.length > 0) {
199
209
  throw new Error(`the run would use ${extra.join(', ')}, which it was not admitted for`);
@@ -212,77 +222,93 @@ class HostExecutor {
212
222
  const root = this.directoryOf(run);
213
223
  let attachment;
214
224
  try {
215
- // where the process of the run starts: the checkout of a ref, or for a sandbox the
216
- // published files, so what the process and the secret providers it starts read of
217
- // their directory is never what a task wrote
218
- let cwd;
225
+ // The process of the run starts in the published files, which it reads its build files
226
+ // from, and its tasks work on other files (`work`): a checkout, a sandbox or a copy of
227
+ // one. The published files are a directory of the run no task mounts, so what the
228
+ // process parses for each task it runs, and what the secret providers it starts read
229
+ // of their directory, is what was published and never what a task wrote.
230
+ const published = (0, path_1.join)(root, 'bundle');
231
+ await (0, promises_1.mkdir)(published, { recursive: true });
232
+ await this.writeBundle(published, bundle.files);
219
233
  let input;
220
234
  let claim;
221
- // the files of the sandbox the tasks work on
235
+ // the files the tasks work on
222
236
  let work;
223
237
  const sourceStarted = new Date();
224
- if (source.type === 'sandbox' && source.check) {
225
- // a check works on the files a push of the sandbox commits, copied out of it: never
226
- // on the sandbox, whose ignored files (node_modules, outputs) its owner writes
238
+ // A check works on the files a push of the sandbox commits, copied out of it, and so
239
+ // does a run that was approved: what was approved is those files, and the sandbox has
240
+ // more (its ignored files, node_modules, outputs), which its owner and their runs write
241
+ // while the run waits and runs.
242
+ const copied = source.type === 'sandbox' && (source.check || (run.approvals?.length ?? 0) > 0);
243
+ // (`source.type` again: TypeScript narrows `source` by it, not by `copied`)
244
+ if (source.type === 'sandbox' && copied) {
227
245
  const { registry, network } = sandboxes;
228
- cwd = (0, path_1.join)(root, 'source');
246
+ const what = source.check ? 'the check' : 'the approved run';
247
+ if (!source.check) {
248
+ // what was approved is what runs: the files may have changed since, by a run
249
+ // before this one on the sandbox (the copy checks it again, under the sandbox's lock)
250
+ const state = await registry.state(source.id, abortCtrl.signal);
251
+ if (state.tree !== source.tree) {
252
+ throw new Error(`the files of the sandbox ${source.id} changed since the run was approved, they are ${state.tree} now and were ${source.tree}, submit the run again`);
253
+ }
254
+ }
255
+ work = (0, path_1.join)(root, 'source');
229
256
  try {
230
- await registry.exportTree(source.id, source.tree, cwd, abortCtrl.signal);
257
+ await registry.exportTree(source.id, source.tree, work, abortCtrl.signal);
231
258
  }
232
259
  catch (e) {
233
- throw new Error(`the files of the sandbox ${source.id} could not be copied for the check, submit it again: ${e instanceof Error ? e.message : String(e)}`);
260
+ throw new Error(`the files of the sandbox ${source.id} could not be copied for ${what}, submit it again: ${e instanceof Error ? e.message : String(e)}`);
234
261
  }
235
262
  // a repository of its own, as a checkout of the commit is: the root of the project,
236
263
  // which the paths of the tasks' keys are relative to, is the one of git
237
- await (0, git_checkout_1.git)(['init', '--quiet', cwd], {}, abortCtrl.signal, `the check of sandbox ${source.id}`, 'init');
264
+ await (0, git_checkout_1.git)(['init', '--quiet', work], {}, abortCtrl.signal, `${what} of sandbox ${source.id}`, 'init');
238
265
  context.emit({
239
266
  type: 'log',
240
267
  task: 'hammerkit',
241
268
  stream: 'stdout',
242
- text: `check of sandbox ${source.id} of ${source.repo}: files ${source.tree}, fetched at ${source.commit}`,
269
+ text: `${source.check ? 'check' : 'approved run'} of sandbox ${source.id} of ${source.repo}: files ${source.tree}, fetched at ${source.commit}`,
243
270
  });
244
- await this.writeBundle(cwd, bundle.files);
271
+ // the tasks see the published build files in place of the sandbox's own
272
+ await this.writeBundle(work, bundle.files);
245
273
  input = {
246
- entry: (0, path_1.join)(cwd, version.entry),
274
+ entry: (0, path_1.join)(published, version.entry),
275
+ directory: { read: published, work },
247
276
  ...(planning.policy.network ? { network: (0, work_network_1.toNetworkSchema)(planning.policy.network) } : {}),
248
277
  sandboxNetwork: network,
249
278
  };
250
279
  }
251
280
  else if (source.type === 'ref') {
252
- cwd = (0, path_1.join)(root, 'source');
281
+ work = (0, path_1.join)(root, 'source');
253
282
  const { repo, ref, commit: pinned } = source;
254
283
  const credentials = await repos.credentials(repo);
255
284
  let commit;
256
285
  try {
257
286
  // a woken service run starts the commit it started first, where the ref is now or not
258
287
  const fetched = run.wakes ? pinned : ref;
259
- commit = await (0, git_checkout_1.checkoutRef)(repos.url(repo), fetched, cwd, credentials.env, abortCtrl.signal, pinned);
288
+ commit = await (0, git_checkout_1.checkoutRef)(repos.url(repo), fetched, work, credentials.env, abortCtrl.signal, pinned);
260
289
  }
261
290
  catch (e) {
262
291
  throw repos.scrub(e, credentials.values);
263
292
  }
264
293
  context.emit({ type: 'log', task: 'hammerkit', stream: 'stdout', text: `checked out ${repo} at ${commit}` });
265
- await this.writeBundle(cwd, bundle.files);
294
+ // the tasks see the published build files in place of the checkout's own
295
+ await this.writeBundle(work, bundle.files);
266
296
  // what the version was checked against at publish holds while it runs too
267
297
  input = {
268
- entry: (0, path_1.join)(cwd, version.entry),
298
+ entry: (0, path_1.join)(published, version.entry),
299
+ directory: { read: published, work },
269
300
  ...(planning.policy.network ? { network: (0, work_network_1.toNetworkSchema)(planning.policy.network) } : {}),
270
301
  };
271
302
  }
272
303
  else {
273
- // the published files are read from a directory of the run and work on the
274
- // sandbox, whose own build files are just files
304
+ // a run its caller may run without an approval works on the sandbox itself, whose
305
+ // own build files are just files
275
306
  const { registry, network } = sandboxes;
276
307
  // read before the run attaches: until then the walk of the last run's measure holds
277
308
  const state = await registry.state(source.id, abortCtrl.signal);
278
309
  attachment = await registry.attach(source.id, (0, path_1.join)(root, 'sandbox'));
279
310
  work = attachment.directory;
280
311
  claim = attachment.claim;
281
- // what was approved is what runs: the files may have changed since, by a run
282
- // before this one on the sandbox
283
- if (run.approvals?.length && state.tree !== source.tree) {
284
- throw new Error(`the files of the sandbox ${source.id} changed since the run was approved, they are ${state.tree} now and were ${source.tree}, submit the run again`);
285
- }
286
312
  if (claim && !this.options.placement) {
287
313
  throw new Error(`the sandbox ${source.id} is a claim on a cluster, this server runs tasks on its own docker`);
288
314
  }
@@ -292,10 +318,6 @@ class HostExecutor {
292
318
  stream: 'stdout',
293
319
  text: `sandbox ${source.id} of ${source.repo} at ${state.commit}, files ${state.tree}${state.clean ? '' : ' with changes'}`,
294
320
  });
295
- const published = (0, path_1.join)(root, 'bundle');
296
- await (0, promises_1.mkdir)(published, { recursive: true });
297
- await this.writeBundle(published, bundle.files);
298
- cwd = published;
299
321
  input = {
300
322
  entry: (0, path_1.join)(published, version.entry),
301
323
  directory: { read: published, work },
@@ -311,7 +333,7 @@ class HostExecutor {
311
333
  await (0, promises_1.mkdir)(cache, { recursive: true });
312
334
  const placement = this.options.placement;
313
335
  const namespaceStarted = new Date();
314
- const placed = placement ? await placement.prepare(run, context, { root: work ?? cwd, claim }) : undefined;
336
+ const placed = placement ? await placement.prepare(run, context, { root: work, claim }) : undefined;
315
337
  if (placed) {
316
338
  emitPhase(context, 'namespace', namespaceStarted);
317
339
  }
@@ -323,6 +345,7 @@ class HostExecutor {
323
345
  accounts: run.accounts,
324
346
  volumeScope: volumeScope(run, this.options.directory),
325
347
  ...((0, checks_1.isCheckRun)(run) ? { check: true } : {}),
348
+ ...(context.durations ? { durations: context.durations } : {}),
326
349
  catalog: planning.environment.hosted?.catalog,
327
350
  ...(run.up
328
351
  ? {
@@ -334,7 +357,7 @@ class HostExecutor {
334
357
  : {}),
335
358
  ...(placed ? { kubernetes: placed.kubernetes } : {}),
336
359
  ...(!placed && this.options.capabilityRuntime ? { capabilityRuntime: this.options.capabilityRuntime } : {}),
337
- }, cwd, { ...this.processEnvironment(home, cache), ...placed?.env }, context, abortCtrl.signal);
360
+ }, published, { ...(0, run_source_environment_1.withRunSource)(this.processEnvironment(home, cache), run.source), ...placed?.env }, context, abortCtrl.signal);
338
361
  }
339
362
  finally {
340
363
  if (placement && placed) {