hammerkit 2.1.0 → 2.2.0-next.2

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 (103) hide show
  1. package/build.schema.json +126 -28
  2. package/dist/cache/backends/registry/push-credentials.js +50 -0
  3. package/dist/cache/backends/registry/registry-client.js +41 -10
  4. package/dist/cache/backends/registry-cache-backend.js +6 -1
  5. package/dist/cache/cache-inventory.js +3 -0
  6. package/dist/cli.js +5 -0
  7. package/dist/dashboard/assets/graph-canvas-D6GMgkoe.js +8 -0
  8. package/dist/dashboard/assets/index-BNq9j5Jo.js +23 -0
  9. package/dist/dashboard/assets/index-DP3_hKOe.css +2 -0
  10. package/dist/dashboard/index.html +2 -2
  11. package/dist/docker/item-network.js +6 -5
  12. package/dist/docker/remove-orphaned-containers.js +5 -4
  13. package/dist/environment/replace-env-variables.js +8 -5
  14. package/dist/environment/run-source-envs.js +2 -1
  15. package/dist/executer/archive-task-entry.js +1 -1
  16. package/dist/executer/check-readiness.js +8 -4
  17. package/dist/executer/docker-healthcheck.js +73 -0
  18. package/dist/executer/docker-service.js +21 -15
  19. package/dist/executer/event-cache.js +7 -1
  20. package/dist/executer/execute-work-task.js +8 -0
  21. package/dist/executer/runner-commands.js +36 -0
  22. package/dist/file/get-file-context.js +4 -7
  23. package/dist/harness/connect.js +12 -8
  24. package/dist/harness/reconnect.js +141 -0
  25. package/dist/harness/sandbox-client.js +241 -33
  26. package/dist/harness/service-tools.js +11 -2
  27. package/dist/kubernetes/ensure-kubernetes-deployment-exists.js +62 -14
  28. package/dist/kubernetes/ensure-persistent-data.js +1 -1
  29. package/dist/kubernetes/follow-pod-logs.js +8 -5
  30. package/dist/kubernetes/kept-claims.js +38 -14
  31. package/dist/kubernetes/sandbox-runner.js +526 -156
  32. package/dist/kubernetes/store-kubernetes-data.js +18 -3
  33. package/dist/kubernetes/sync-changes.js +463 -0
  34. package/dist/kubernetes/volumes.js +23 -1
  35. package/dist/network/healthcheck-request.js +38 -0
  36. package/dist/optimizer/get-work-cache-stats.js +7 -0
  37. package/dist/optimizer/work-task-cache-description.js +5 -3
  38. package/dist/planner/image-build.js +5 -0
  39. package/dist/planner/service-definition.js +2 -1
  40. package/dist/planner/utils/append-work-service.js +12 -4
  41. package/dist/planner/utils/dependency-outputs.js +7 -6
  42. package/dist/planner/validate.js +41 -0
  43. package/dist/planner/work-healthcheck.js +23 -2
  44. package/dist/planner/work-item-status.js +12 -2
  45. package/dist/planner/work-runtime-aggregate.js +1 -0
  46. package/dist/planner/work-runtime-docker.js +33 -6
  47. package/dist/planner/work-runtime-kubernetes.js +313 -70
  48. package/dist/planner/work-runtime-local.js +8 -4
  49. package/dist/planner/work-secret.js +33 -11
  50. package/dist/planner/work-service-id.js +30 -6
  51. package/dist/planner/work-service.js +2 -2
  52. package/dist/program.js +19 -1
  53. package/dist/remote/annotations.js +8 -2
  54. package/dist/remote/bundle.js +6 -8
  55. package/dist/remote/device-login.js +4 -1
  56. package/dist/remote/remote-commands.js +16 -7
  57. package/dist/remote/remote-status.js +1 -1
  58. package/dist/remote/remote-work-commands.js +220 -68
  59. package/dist/remote/server-client.js +38 -40
  60. package/dist/schema/build-file-base-task-schema.js +16 -1
  61. package/dist/schema/build-file-image-build-schema.js +5 -8
  62. package/dist/schema/build-file-service-container-healthcheck.js +25 -7
  63. package/dist/schema/reference-parser.js +108 -43
  64. package/dist/schema/work-scope-parser.js +8 -0
  65. package/dist/secrets/prefetch-secrets.js +20 -1
  66. package/dist/server/artifacts-api.js +56 -0
  67. package/dist/server/borrowed-quota.js +216 -0
  68. package/dist/server/cache-push.js +50 -0
  69. package/dist/server/capacity.js +18 -6
  70. package/dist/server/definitions-api.js +62 -8
  71. package/dist/server/executor.js +131 -31
  72. package/dist/server/http.js +4 -1
  73. package/dist/server/keep-artifacts.js +230 -0
  74. package/dist/server/kubernetes-backend.js +292 -79
  75. package/dist/server/kubernetes-sandbox-storage.js +86 -24
  76. package/dist/server/overview.js +73 -9
  77. package/dist/server/paging.js +167 -0
  78. package/dist/server/plan.js +54 -8
  79. package/dist/server/run-access.js +24 -0
  80. package/dist/server/run-artifacts.js +171 -0
  81. package/dist/server/run-logs.js +25 -1
  82. package/dist/server/run-request.js +11 -0
  83. package/dist/server/run-source-environment.js +1 -1
  84. package/dist/server/run-worker.js +305 -40
  85. package/dist/server/runs.js +531 -105
  86. package/dist/server/sandbox-files-api.js +27 -12
  87. package/dist/server/sandbox-files.js +12 -10
  88. package/dist/server/sandbox-follow.js +54 -0
  89. package/dist/server/sandbox-pod.js +1 -1
  90. package/dist/server/sandbox-storage.js +38 -1
  91. package/dist/server/sandbox-sync.js +392 -0
  92. package/dist/server/sandboxes-api.js +116 -19
  93. package/dist/server/sandboxes.js +38 -3
  94. package/dist/server/server-config.js +133 -2
  95. package/dist/server/server.js +189 -39
  96. package/dist/server/task-order.js +56 -0
  97. package/dist/utils/project-path.js +20 -0
  98. package/dist/utils/tar-files.js +52 -0
  99. package/dist/utils/tar.js +37 -1
  100. package/package.json +1 -1
  101. package/dist/dashboard/assets/graph-canvas-DtJSpova.js +0 -8
  102. package/dist/dashboard/assets/index-BndChMep.css +0 -2
  103. package/dist/dashboard/assets/index-DRSwIRXd.js +0 -17
@@ -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
  }
@@ -14,12 +14,27 @@ const resources_schema_1 = require("./resources-schema");
14
14
  const runner_schema_1 = require("./runner-schema");
15
15
  const network_schema_1 = require("./network-schema");
16
16
  // what `extend` adds to (the rest, e.g. `image` or `shell`, the task just overrides)
17
- exports.RESET_PROPERTIES = ['deps', 'needs', 'src', 'generates', 'cmds', 'mounts', 'envs', 'labels'];
17
+ exports.RESET_PROPERTIES = [
18
+ 'deps',
19
+ 'needs',
20
+ 'src',
21
+ 'generates',
22
+ 'cmds',
23
+ 'mounts',
24
+ 'envs',
25
+ 'labels',
26
+ 'build',
27
+ 'secrets',
28
+ 'capAdd',
29
+ ];
18
30
  exports.buildFileBaseTaskSchema = (0, zod_1.object)({
19
31
  deps: (0, zod_1.array)((0, zod_1.string)()).optional(),
20
32
  needs: (0, zod_1.array)(build_file_need_schema_1.buildFileNeedSchema).optional(),
21
33
  description: (0, zod_1.string)().optional(),
22
34
  extend: (0, zod_1.string)().optional(),
35
+ // true: a base other tasks extend, which doesn't run itself: not listed, no dependency, not
36
+ // published by a server. Unlike a task, it passes on its secrets, resources and claim too.
37
+ abstract: (0, zod_1.boolean)().optional(),
23
38
  // properties of the `extend` base this task does not inherit
24
39
  reset: (0, zod_1.array)((0, zod_1.enum)(exports.RESET_PROPERTIES)).optional(),
25
40
  envs: envs_schema_1.envsSchema.optional(),
@@ -57,17 +57,14 @@ exports.buildFileImageBuildSchema = (0, zod_1.object)({
57
57
  .describe('the platforms to build for, such as linux/amd64 and linux/arm64, as docker build --platform'),
58
58
  })
59
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
- })
60
+ // that push and digest need tags is checked once `extend` has merged in the base's
61
+ // (parseWorkImageBuild): a base may set push for tasks that set their tags
66
62
  .describe('builds a Dockerfile with BuildKit, as docker build does');
67
63
  // 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.
64
+ // shell of its own and takes no arguments. It may extend another task, which merges `build` key
65
+ // by key (applySchemaExtension).
69
66
  exports.buildFileImageBuildTaskSchema = build_file_base_task_schema_1.buildFileBaseTaskSchema
70
- .omit({ extend: true, reset: true, cmds: true, shell: true, args: true })
67
+ .omit({ cmds: true, shell: true, args: true })
71
68
  .extend({
72
69
  build: exports.buildFileImageBuildSchema,
73
70
  volumeSize: size_schema_1.sizeSchema.describe('size of its claim on Kubernetes, e.g. 10Gi').optional(),
@@ -1,12 +1,30 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.buildFileServiceContainerHealthcheck = void 0;
3
+ exports.buildFileServiceContainerHealthcheck = exports.buildFileServiceTcpHealthcheck = exports.buildFileServiceHttpHealthcheck = void 0;
4
4
  const zod_1 = require("zod");
5
5
  const duration_schema_1 = require("./duration-schema");
6
- exports.buildFileServiceContainerHealthcheck = (0, zod_1.object)({
7
- cmd: (0, zod_1.string)(),
8
- // How long the service may take to pass `cmd` once its container runs
9
- // (default 20s, HAMMERKIT_HEALTHCHECK_TIMEOUT changes the default).
10
- timeout: duration_schema_1.durationSchema.optional(),
11
- });
6
+ // How long the service may take to pass its check once its container runs
7
+ // (default 20s, HAMMERKIT_HEALTHCHECK_TIMEOUT changes the default).
8
+ const timeout = duration_schema_1.durationSchema.optional();
9
+ const port = (0, zod_1.number)().int().min(1).max(65535);
10
+ // A request to a port of the service, from its own network: no tool of the image runs it.
11
+ exports.buildFileServiceHttpHealthcheck = (0, zod_1.object)({
12
+ port,
13
+ path: (0, zod_1.string)().startsWith('/', 'path must start with /').optional(),
14
+ scheme: (0, zod_1.enum)(['http', 'https']).optional(),
15
+ // the status codes that count as healthy, any 2xx or 3xx without
16
+ status: (0, zod_1.array)((0, zod_1.number)().int().min(100).max(599)).min(1).optional(),
17
+ })
18
+ .strict()
19
+ .describe('GET <scheme>://<service>:<port><path>, healthy on one of status (default any 2xx or 3xx)');
20
+ // a connection to a port of the service
21
+ exports.buildFileServiceTcpHealthcheck = (0, zod_1.object)({ port })
22
+ .strict()
23
+ .describe('healthy once <port> takes a connection');
24
+ // Exactly one of `cmd`, `http` or `tcp`.
25
+ exports.buildFileServiceContainerHealthcheck = (0, zod_1.union)([
26
+ (0, zod_1.object)({ cmd: (0, zod_1.string)(), timeout }).strict(),
27
+ (0, zod_1.object)({ http: exports.buildFileServiceHttpHealthcheck, timeout }).strict(),
28
+ (0, zod_1.object)({ tcp: exports.buildFileServiceTcpHealthcheck, timeout }).strict(),
29
+ ]).describe('exactly one of cmd, http or tcp, and how long it may take to pass');
12
30
  //# sourceMappingURL=build-file-service-container-healthcheck.js.map
@@ -29,8 +29,15 @@ class UnpublishedError extends Error {
29
29
  this.reason = reason;
30
30
  }
31
31
  }
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
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
34
41
  function findPublished(user, verb, find) {
35
42
  try {
36
43
  return find();
@@ -39,6 +46,9 @@ function findPublished(user, verb, find) {
39
46
  if (e instanceof UnpublishedError) {
40
47
  throw new Error(`${user} ${verb} ${e.name}, which is not published (${e.reason})`);
41
48
  }
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
+ }
42
52
  throw e;
43
53
  }
44
54
  }
@@ -67,6 +77,7 @@ async function parseReferences(ctx, mainScope, environment) {
67
77
  const reference = {
68
78
  files: {},
69
79
  tasks: {},
80
+ bases: {},
70
81
  services: {},
71
82
  envFiles: {},
72
83
  environments: {},
@@ -109,7 +120,8 @@ async function parseReferences(ctx, mainScope, environment) {
109
120
  if (isLeftOut(file, relativeName, task)) {
110
121
  continue;
111
122
  }
112
- reference.tasks[relativeName] = {
123
+ const tasks = task.abstract ? reference.bases : reference.tasks;
124
+ tasks[relativeName] = {
113
125
  type: 'task',
114
126
  schema: task,
115
127
  cwd: file.cwd,
@@ -159,7 +171,8 @@ async function parseReferences(ctx, mainScope, environment) {
159
171
  }
160
172
  }
161
173
  }
162
- for (const task of Object.values(reference.tasks)) {
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)]) {
163
176
  applySchemaExtension(reference, task);
164
177
  resolveDeps(reference, task, task.scope, task.schema);
165
178
  resolveNeeds(reference, task, task.scope, task.schema);
@@ -188,57 +201,67 @@ function applySchemaExtension(reference, task) {
188
201
  task.extension = 'applying';
189
202
  task.depBases = [];
190
203
  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
- }
196
- const reset = new Set(task.schema.reset ?? []);
197
- if (!task.schema.extend) {
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) {
198
208
  if (reset.size > 0) {
199
209
  throw new Error(`task ${task.relativeName} sets reset without extend`);
200
210
  }
201
211
  task.extension = 'applied';
202
212
  return;
203
213
  }
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`);
209
- }
214
+ const name = schema.extend;
215
+ const extend = findPublished(task.relativeName, 'extends', () => findBase(reference, task, name));
210
216
  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;
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
+ }
223
+ }
217
224
  if (!reset.has('cmds'))
218
- task.schema.cmds = extendArray(task.schema.cmds, extend.schema.cmds);
225
+ schema.cmds = extendArray(schema.cmds, base.cmds);
219
226
  if (!reset.has('src'))
220
- task.schema.src = extendArray(task.schema.src, extend.schema.src);
227
+ schema.src = extendArray(schema.src, base.src);
221
228
  if (!reset.has('generates'))
222
- task.schema.generates = extendArray(task.schema.generates, extend.schema.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
+ }
223
249
  if (!reset.has('labels'))
224
- task.schema.labels = extendObject(task.schema.labels, extend.schema.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);
225
253
  // the base's resolved envs: its own plus the top-level envs of its build file
226
254
  // (and the inputs an include passed), which carry the defaults it relies on
227
255
  if (!reset.has('envs'))
228
256
  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
- }
235
257
  rejectContainerPropertiesWithoutImage(task);
258
+ rejectCommandsOfImageBuild(task);
236
259
  // deps and needs resolve in the file that declares them, so every base up the
237
260
  // chain contributes its own, not only the nearest; what a task resets is not
238
261
  // passed on to the tasks extending it either
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];
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];
242
265
  for (const needBase of task.needBases) {
243
266
  resolveNeeds(reference, task, needBase.scope, needBase.schema);
244
267
  }
@@ -247,6 +270,20 @@ function applySchemaExtension(reference, task) {
247
270
  }
248
271
  task.extension = 'applied';
249
272
  }
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
+ }
250
287
  function rejectContainerPropertiesWithoutImage(task) {
251
288
  if ((0, build_file_task_schema_1.isBuildFileContainerTaskSchema)(task.schema) || (0, build_file_task_schema_1.isBuildFileImageBuildTaskSchema)(task.schema)) {
252
289
  return;
@@ -257,6 +294,22 @@ function rejectContainerPropertiesWithoutImage(task) {
257
294
  throw new Error(`task ${task.relativeName} sets ${property}, but neither it nor its base has an image`);
258
295
  }
259
296
  }
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
+ }
260
313
  function extendArray(base, extend) {
261
314
  if (!extend) {
262
315
  return base;
@@ -325,21 +378,30 @@ function resolveNeeds(reference, taskOrService, scope, schema) {
325
378
  throw new Error(`${taskOrService.relativeName} needs two services as ${twice}, give one another name with name:`);
326
379
  }
327
380
  }
328
- function findTask(ctx, scope, name, type) {
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) {
329
391
  refuseNotFetched(scope, name);
330
392
  const ref = (0, split_name_1.splitName)(name);
331
393
  if (ref.prefix) {
332
394
  if (scope.references[ref.prefix]) {
333
- return findTask(ctx, scope.references[ref.prefix].scope, ref.name, scope.references[ref.prefix].type);
395
+ return findTask(ctx, scope.references[ref.prefix].scope, ref.name, scope.references[ref.prefix].type, base);
334
396
  }
335
397
  else if (scope.schema.tasks && scope.schema.tasks[name]) {
336
- return resolveTask(ctx, scope, name, type ?? 'build-file');
398
+ return resolveTask(ctx, scope, name, type ?? 'build-file', base);
337
399
  }
338
400
  }
339
401
  else if (scope.schema.tasks && scope.schema.tasks[ref.name]) {
340
- return resolveTask(ctx, scope, ref.name, type ?? 'build-file');
402
+ return resolveTask(ctx, scope, ref.name, type ?? 'build-file', base);
341
403
  }
342
- throw new Error('unable to find ' + name); // TODO improve
404
+ throw new NotFoundError(scope, name);
343
405
  }
344
406
  exports.findTask = findTask;
345
407
  // A name in a git source a server did not fetch, since it is left out
@@ -348,9 +410,12 @@ function refuseNotFetched(scope, name) {
348
410
  throw new UnpublishedError(combinePath(scope.namePrefix, name), 'its build file is included with publish: false');
349
411
  }
350
412
  }
351
- function resolveTask(ctx, scope, name, type) {
413
+ function resolveTask(ctx, scope, name, type, base) {
352
414
  const fullName = combinePath(scope.namePrefix, name);
353
- const buildFileTask = ctx.tasks[fullName];
415
+ if (!base && ctx.bases[fullName]) {
416
+ throw new AbstractError(fullName);
417
+ }
418
+ const buildFileTask = ctx.tasks[fullName] ?? (base ? ctx.bases[fullName] : undefined);
354
419
  if (!buildFileTask && ctx.unpublished?.[fullName]) {
355
420
  throw new UnpublishedError(fullName, ctx.unpublished[fullName]);
356
421
  }
@@ -48,6 +48,7 @@ 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 ?? [])]);
51
52
  const apply = { servicesAlone: !(0, work_scope_1.isContextTaskFilter)(scope) && !!scope.names && !!scope.stop };
52
53
  const selectedTasks = [];
53
54
  const selectedServices = [];
@@ -86,6 +87,13 @@ function getWorkContext(context, scope, environment) {
86
87
  return filteredWorkTree;
87
88
  }
88
89
  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
+ }
89
97
  // The whole build file is planned first, so a shared service lists every task
90
98
  // and service that needs it. Those outside this run never start or end, and a
91
99
  // service waiting for them to finish would keep the run open forever.
@@ -1,15 +1,34 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.prefetchSecrets = void 0;
3
+ exports.prefetchSecrets = exports.requireReadableSecrets = 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;
7
25
  // Fetches the values a task id needs; a run drops the ones of the previous run
8
26
  // first (`newRun`), any other command reuses what the run already fetched. A task id is computed synchronously and holds the
9
27
  // digest of each `cache: true` secret, so those values must be in memory before
10
28
  // anything asks for an id. Secrets that don't affect the id are read when their
11
29
  // task starts, and a plan without provider secrets calls no provider.
12
30
  async function prefetchSecrets(workTree, environment, newRun = false) {
31
+ requireReadableSecrets(workTree, (secret) => secret.cache);
13
32
  if (newRun) {
14
33
  (0, provider_values_1.beginSecretRun)(environment);
15
34
  }
@@ -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