hammerkit 2.0.0-next.2 → 2.0.0-next.21

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 (112) hide show
  1. package/dist/cache/backends/registry/registry-client.js +8 -2
  2. package/dist/cache/explain.js +7 -5
  3. package/dist/cache/last-resolved.js +11 -0
  4. package/dist/cli.js +4 -1
  5. package/dist/dashboard/assets/graph-canvas-DLioOiRN.css +1 -0
  6. package/dist/dashboard/assets/graph-canvas-DtJSpova.js +8 -0
  7. package/dist/dashboard/assets/index-BndChMep.css +2 -0
  8. package/dist/dashboard/assets/index-DRSwIRXd.js +17 -0
  9. package/dist/dashboard/index.html +3 -3
  10. package/dist/dashboard/logo.png +0 -0
  11. package/dist/docker/item-network.js +51 -18
  12. package/dist/docker/package.js +85 -76
  13. package/dist/docker/server-tools.js +96 -0
  14. package/dist/docker/stream.js +15 -7
  15. package/dist/environment/replace-env-variables.js +1 -1
  16. package/dist/environment/run-source-envs.js +18 -0
  17. package/dist/executer/check-container-binds.js +158 -0
  18. package/dist/executer/docker-service.js +42 -3
  19. package/dist/executer/docker-task.js +21 -5
  20. package/dist/executer/execute-command.js +9 -15
  21. package/dist/executer/execute-work-task.js +14 -2
  22. package/dist/executer/execute-work-tree.js +2 -1
  23. package/dist/executer/execution-steps.js +3 -2
  24. package/dist/executer/local-task.js +3 -0
  25. package/dist/executer/print-container-options.js +10 -10
  26. package/dist/executer/process-manager.js +84 -5
  27. package/dist/executer/scheduler/enqueue-next.js +6 -1
  28. package/dist/executer/scheduler/state-key.js +71 -34
  29. package/dist/executer/task-priority.js +131 -0
  30. package/dist/executer/watch-loop.js +18 -5
  31. package/dist/file/get-file-context.js +5 -1
  32. package/dist/file/stat-beneath.js +66 -0
  33. package/dist/file/within-root.js +13 -4
  34. package/dist/harness/connect.js +1 -6
  35. package/dist/harness/mcp-command.js +1 -1
  36. package/dist/harness/sandbox-client.js +39 -4
  37. package/dist/harness/service-tools.js +2 -2
  38. package/dist/kubernetes/await-running-state.js +98 -18
  39. package/dist/kubernetes/claim-layout.js +10 -1
  40. package/dist/kubernetes/ensure-kubernetes-deployment-exists.js +10 -1
  41. package/dist/kubernetes/ensure-persistent-data.js +129 -26
  42. package/dist/kubernetes/follow-pod-logs.js +128 -29
  43. package/dist/kubernetes/kept-claims.js +16 -1
  44. package/dist/kubernetes/network-gate.js +74 -11
  45. package/dist/kubernetes/network-policy.js +35 -13
  46. package/dist/kubernetes/quota-wait.js +97 -0
  47. package/dist/kubernetes/remove-stale-items.js +15 -2
  48. package/dist/kubernetes/restore-kubernetes-data.js +28 -4
  49. package/dist/kubernetes/sandbox-runner.js +3 -4
  50. package/dist/kubernetes/store-kubernetes-data.js +14 -2
  51. package/dist/kubernetes/transfer-tools.js +66 -0
  52. package/dist/kubernetes/volumes.js +78 -14
  53. package/dist/optimizer/calculate-checksum.js +46 -3
  54. package/dist/optimizer/check-key.js +7 -0
  55. package/dist/optimizer/check-keys.js +19 -5
  56. package/dist/optimizer/get-work-cache-stats.js +55 -31
  57. package/dist/optimizer/work-task-cache-description.js +36 -7
  58. package/dist/parser/read-build-file.js +8 -3
  59. package/dist/planner/utils/append-work-service.js +1 -1
  60. package/dist/planner/utils/append-work-task.js +1 -1
  61. package/dist/planner/utils/assert-item-paths.js +6 -7
  62. package/dist/planner/utils/template-value.js +20 -4
  63. package/dist/planner/work-item-executions.js +27 -0
  64. package/dist/planner/work-runtime-docker.js +31 -50
  65. package/dist/planner/work-runtime-kubernetes.js +70 -41
  66. package/dist/planner/work-runtime-local.js +3 -7
  67. package/dist/planner/work-secret.js +135 -13
  68. package/dist/planner/work-tree.js +10 -0
  69. package/dist/remote/collect-bundle.js +9 -1
  70. package/dist/remote/host-config.js +49 -3
  71. package/dist/remote/location.js +5 -5
  72. package/dist/remote/remote-commands.js +12 -14
  73. package/dist/remote/remote-work-commands.js +31 -10
  74. package/dist/schema/schema-parser.js +46 -2
  75. package/dist/schema/work-scope-parser.js +16 -1
  76. package/dist/secrets/secret-catalog.js +8 -1
  77. package/dist/server/capacity.js +71 -41
  78. package/dist/server/dashboard.js +35 -14
  79. package/dist/server/endpoints.js +10 -1
  80. package/dist/server/executor.js +68 -35
  81. package/dist/server/kubernetes-backend.js +29 -4
  82. package/dist/server/kubernetes-sandbox-storage.js +14 -4
  83. package/dist/server/oauth.js +16 -1
  84. package/dist/server/overview.js +100 -13
  85. package/dist/server/plan.js +41 -6
  86. package/dist/server/policy.js +22 -9
  87. package/dist/server/repo-access.js +4 -3
  88. package/dist/server/run-environment.js +5 -2
  89. package/dist/server/run-plan.js +18 -6
  90. package/dist/server/run-retry.js +57 -0
  91. package/dist/server/run-source-environment.js +39 -0
  92. package/dist/server/run-worker.js +71 -9
  93. package/dist/server/runs.js +133 -7
  94. package/dist/server/sandbox-files.js +339 -55
  95. package/dist/server/sandbox-patch.js +43 -17
  96. package/dist/server/sandboxes.js +57 -23
  97. package/dist/server/server-config.js +28 -5
  98. package/dist/server/server.js +150 -20
  99. package/dist/server/service-runs.js +50 -5
  100. package/dist/server/sources.js +68 -11
  101. package/dist/server/timings.js +23 -3
  102. package/dist/utils/buffer-context.js +30 -20
  103. package/dist/utils/limit.js +30 -0
  104. package/dist/utils/line-splitter.js +52 -0
  105. package/dist/utils/read-lines.js +65 -0
  106. package/dist/utils/tar.js +51 -1
  107. package/dist/utils/units.js +36 -1
  108. package/dist/utils/web-links.js +34 -0
  109. package/package.json +1 -1
  110. package/dist/dashboard/assets/index-CjnKm5-3.css +0 -2
  111. package/dist/dashboard/assets/index-zPXa4klZ.js +0 -13
  112. package/dist/dashboard/favicon.svg +0 -1
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.kubernetesForwardRuntime = exports.isRolledOut = exports.kubernetesServiceRuntime = exports.kubernetesTaskRuntime = exports.getTaskJobContainers = exports.describeFailedJob = void 0;
6
+ exports.kubernetesForwardRuntime = exports.isRolledOut = exports.kubernetesServiceRuntime = exports.kubernetesTaskRuntime = exports.getTaskJobContainers = exports.describeFailedJob = exports.recordJobExecution = void 0;
7
7
  const abort_1 = require("../executer/abort");
8
8
  const kubernetes_service_1 = require("../executer/kubernetes-service");
9
9
  const kubernetes_instance_1 = require("../kubernetes/kubernetes-instance");
@@ -12,6 +12,7 @@ const apply_1 = require("../kubernetes/apply");
12
12
  const ensure_kubernetes_service_exists_1 = require("../kubernetes/ensure-kubernetes-service-exists");
13
13
  const ensure_kubernetes_deployment_exists_1 = require("../kubernetes/ensure-kubernetes-deployment-exists");
14
14
  const follow_pod_logs_1 = require("../kubernetes/follow-pod-logs");
15
+ const work_item_executions_1 = require("./work-item-executions");
15
16
  const service_definition_1 = require("./service-definition");
16
17
  const ensure_namespace_1 = require("../kubernetes/ensure-namespace");
17
18
  const ensure_persistent_data_1 = require("../kubernetes/ensure-persistent-data");
@@ -62,32 +63,17 @@ async function getJobPod(instance, kubernetes, job) {
62
63
  .sort((a, b) => (a.metadata?.creationTimestamp?.toISOString() ?? '').localeCompare(b.metadata?.creationTimestamp?.toISOString() ?? ''))
63
64
  .pop();
64
65
  }
65
- // a task's log is kept to this, the run's own cap is smaller
66
- const MAX_JOB_LOG_BYTES = 4 * 1024 * 1024;
67
- // What the command printed, as the task's output: read from the cluster once the Job
68
- // has ended. Without a pod (it never started) there is nothing to say.
69
- async function writeJobLogs(instance, kubernetes, task, job, container) {
70
- try {
71
- const pod = await getJobPod(instance, kubernetes, job);
72
- if (!pod?.metadata?.name) {
73
- return;
74
- }
75
- const log = await instance.coreApi.readNamespacedPodLog({
76
- name: pod.metadata.name,
77
- namespace: kubernetes.namespace,
78
- container,
79
- limitBytes: MAX_JOB_LOG_BYTES,
80
- });
81
- for (const line of String(log ?? '').split(/\r?\n/)) {
82
- if (line.length > 0) {
83
- task.status.console('stdout', line);
84
- }
85
- }
86
- }
87
- catch (e) {
88
- task.status.write('debug', `the log of ${job} could not be read: ${(0, log_1.getErrorMessage)(e)}`);
66
+ // When the command of a Job ran, as its container says: what the task spent before it (the
67
+ // pod scheduled, the image pulled, the init containers) and after it is not the command's.
68
+ async function recordJobExecution(instance, kubernetes, task, job, container) {
69
+ const pod = await getJobPod(instance, kubernetes, job).catch(() => undefined);
70
+ const status = pod?.status?.containerStatuses?.find((s) => s.name === container);
71
+ const terminated = status?.state?.terminated ?? status?.lastState?.terminated;
72
+ if (terminated?.startedAt && terminated.finishedAt) {
73
+ (0, work_item_executions_1.recordExecution)(task, new Date(terminated.startedAt), new Date(terminated.finishedAt));
89
74
  }
90
75
  }
76
+ exports.recordJobExecution = recordJobExecution;
91
77
  // the command of a Job exited with this code, as a crash on docker or a host
92
78
  class JobCrash extends Error {
93
79
  constructor(exitCode) {
@@ -170,6 +156,9 @@ function kubernetesTaskRuntime(task, kubernetes) {
170
156
  // on a server that keeps them, the task's claim stays after the run with the state of its
171
157
  // outputs, and the next run of the same source mounts them as they are (see kept-claims)
172
158
  const kept = (0, kept_claims_1.isKeptClaim)(task, kubernetes);
159
+ // on a service run, the claim names the last state whose folder is whole (see
160
+ // rememberedClaimState): a wake or a move at that state mounts it without an upload
161
+ const remembers = kept || !!kubernetes.server?.serviceRun;
173
162
  const claim = (0, volumes_1.getVolumeName)(task, kubernetes);
174
163
  return {
175
164
  initialize() {
@@ -182,6 +171,21 @@ function kubernetesTaskRuntime(task, kubernetes) {
182
171
  stateKey &&
183
172
  (await (0, ensure_persistent_data_1.getStateDirsInUse)(instance, kubernetes.namespace, claim)).has((0, volumes_1.getStateFilesDir)(stateKey))) {
184
173
  task.status.write('info', `${task.name}: services of the run use its outputs of this state, they stay`);
174
+ await (0, kept_claims_1.recordClaimState)(instance, kubernetes, claim, stateKey);
175
+ return;
176
+ }
177
+ if (remembers && !kept) {
178
+ // the folder of the state is written now: until it is whole, the claim names no state
179
+ // (a restore without a state key says none, and the next run uploads again)
180
+ await (0, kept_claims_1.forgetClaimState)(instance, kubernetes, claim);
181
+ await (0, restore_kubernetes_data_1.restoreKubernetesData)(task, kubernetes, instance, environment, path, {
182
+ stateKey,
183
+ // the folders of other states no pod of the run mounts go, as before a Job
184
+ ...(stateKey ? { otherStates: await (0, ensure_persistent_data_1.getStateDirsInUse)(instance, kubernetes.namespace, claim) } : {}),
185
+ });
186
+ if (stateKey) {
187
+ await (0, kept_claims_1.recordClaimState)(instance, kubernetes, claim, stateKey);
188
+ }
185
189
  return;
186
190
  }
187
191
  if (!kept) {
@@ -231,11 +235,14 @@ function kubernetesTaskRuntime(task, kubernetes) {
231
235
  try {
232
236
  if (files && (await (0, ensure_persistent_data_1.getStateDirsInUse)(instance, kubernetes.namespace, claim)).has(files.dir)) {
233
237
  task.status.write('info', `${task.name}: services of the run use its outputs of this state, they stay`);
238
+ await (0, kept_claims_1.recordClaimState)(instance, kubernetes, claim, options.stateKey);
234
239
  return;
235
240
  }
236
241
  // the task writes to it now: what it holds stops being the outputs of a state, and
237
- // goes, as a new claim would hold nothing
238
- const reset = kept && (await (0, kept_claims_1.forgetClaimState)(instance, kubernetes, claim));
242
+ // goes, as a new claim would hold nothing (on a service run, the folders of other
243
+ // states that no pod mounts go)
244
+ const forgotten = remembers && (await (0, kept_claims_1.forgetClaimState)(instance, kubernetes, claim));
245
+ const reset = kept && forgotten;
239
246
  await (0, ensure_persistent_data_1.ensurePersistentData)(instance, kubernetes, environment, task, persistence, { reset, files });
240
247
  }
241
248
  catch (e) {
@@ -373,24 +380,37 @@ function kubernetesTaskRuntime(task, kubernetes) {
373
380
  };
374
381
  try {
375
382
  const pod = await (0, apply_1.apply)(instance, spec);
376
- if (!pod.status?.succeeded) {
377
- try {
378
- await (0, await_running_state_1.awaitJobCompletion)(instance, kubernetes, spec.metadata.name, options.abort);
379
- }
380
- catch (e) {
381
- if (!(e instanceof abort_1.AbortError)) {
382
- await writeJobLogs(instance, kubernetes, task, podName, container);
383
- const failure = await describeFailedJob(instance, kubernetes, task.name, podName, container, inJob);
384
- if (failure?.type === 'crash') {
385
- throw new JobCrash(failure.exitCode);
383
+ // what the command prints, while it prints it; the last lines once the pod ended
384
+ const logs = (0, follow_pod_logs_1.followPodLogs)(instance, kubernetes.namespace, `job-name=${podName}`, container, (line) => task.status.console('stdout', line), { onError: (text) => task.status.write('debug', text) });
385
+ try {
386
+ if (!pod.status?.succeeded) {
387
+ try {
388
+ await (0, await_running_state_1.awaitJobCompletion)(instance, kubernetes, spec.metadata.name, options.abort, 1000, {
389
+ onWaiting: (text) => task.status.write('warn', `${task.name} ${text}`),
390
+ timeout: ensure_persistent_data_1.QUOTA_TIMEOUT,
391
+ onRefused: options.onQuotaRefused,
392
+ });
393
+ }
394
+ catch (e) {
395
+ if (!(e instanceof abort_1.AbortError)) {
396
+ await logs.settle();
397
+ await recordJobExecution(instance, kubernetes, task.data, podName, container);
398
+ const failure = await describeFailedJob(instance, kubernetes, task.name, podName, container, inJob);
399
+ if (failure?.type === 'crash') {
400
+ throw new JobCrash(failure.exitCode);
401
+ }
402
+ throw new Error(failure?.message ?? (0, log_1.getErrorMessage)(e));
386
403
  }
387
- throw new Error(failure?.message ?? (0, log_1.getErrorMessage)(e));
404
+ throw e;
388
405
  }
389
- throw e;
390
406
  }
407
+ await logs.settle();
408
+ }
409
+ finally {
410
+ logs.stop();
391
411
  }
392
- await writeJobLogs(instance, kubernetes, task, podName, container);
393
412
  task.status.write('debug', 'pod completed');
413
+ await recordJobExecution(instance, kubernetes, task.data, podName, container);
394
414
  // its init containers are done with the credentials
395
415
  await (0, job_secrets_1.removeJobCredentials)(instance, kubernetes, task);
396
416
  if (i < task.data.cmds.length) {
@@ -415,7 +435,7 @@ function kubernetesTaskRuntime(task, kubernetes) {
415
435
  }
416
436
  // the finished job stays for its state, the values it read need not
417
437
  await removeTaskSecrets(instance, kubernetes, task);
418
- if (kept) {
438
+ if (remembers) {
419
439
  await (0, kept_claims_1.recordClaimState)(instance, kubernetes, claim, options.stateKey);
420
440
  }
421
441
  }
@@ -471,6 +491,15 @@ function kubernetesTaskRuntime(task, kubernetes) {
471
491
  // the server removes the Jobs of a run at its end, the claim says
472
492
  return (0, kept_claims_1.useClaimState)(instance, kubernetes, claim);
473
493
  }
494
+ if (remembers) {
495
+ // a service run that sleeps loses its Jobs but keeps its claims, the claim says. One
496
+ // that names no state is being written (or was, and that failed): the folder of the
497
+ // state of an earlier Job may be gone. Only a task without a claim goes by its Jobs.
498
+ const remembered = await (0, kept_claims_1.rememberedClaimState)(instance, kubernetes, claim);
499
+ if (remembered !== undefined) {
500
+ return remembered;
501
+ }
502
+ }
474
503
  const jobs = await instance.batchApi.listNamespacedJob({
475
504
  namespace: kubernetes.namespace,
476
505
  labelSelector: (0, resources_1.getItemSelector)(task, kubernetes),
@@ -4,8 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.getLocalWorkRuntime = exports.getStateFilename = void 0;
7
- const tar_1 = require("tar");
8
- const tar_2 = require("../utils/tar");
7
+ const tar_1 = require("../utils/tar");
9
8
  const path_1 = require("path");
10
9
  const local_task_1 = require("../executer/local-task");
11
10
  const event_cache_1 = require("../executer/event-cache");
@@ -122,7 +121,7 @@ async function archiveLocal(environment, task, path) {
122
121
  for (const generatedArchive of (0, event_cache_1.getArchivePaths)(task.data, path)) {
123
122
  await environment.file.writeStream(generatedArchive.filename,
124
123
  // tar's stream is a Minipass stream; Readable.from adapts it to a Node one
125
- stream_1.Readable.from((0, tar_2.packArchive)({ cwd: task.data.cwd, gzip: true }, [(0, path_1.relative)(task.data.cwd, generatedArchive.path)])));
124
+ stream_1.Readable.from((0, tar_1.packArchive)({ cwd: task.data.cwd, gzip: true }, [(0, path_1.relative)(task.data.cwd, generatedArchive.path)])));
126
125
  }
127
126
  }
128
127
  async function restoreLocal(environment, task, path) {
@@ -131,10 +130,7 @@ async function restoreLocal(environment, task, path) {
131
130
  // a cache hit means exactly the stored outputs: whatever a failed or
132
131
  // older run left in the folder goes first
133
132
  await environment.file.remove(generate.path);
134
- await (0, tar_1.extract)({
135
- file: generate.filename,
136
- cwd: task.cwd,
137
- });
133
+ await (0, tar_1.extractOutput)(generate.filename, task.cwd, (0, path_1.relative)(task.cwd, generate.path), !!environment.hosted);
138
134
  }
139
135
  }
140
136
  }
@@ -8,6 +8,7 @@ const normalize_path_1 = require("./utils/normalize-path");
8
8
  const template_value_1 = require("./utils/template-value");
9
9
  const portable_path_1 = require("./utils/portable-path");
10
10
  const abort_1 = require("../executer/abort");
11
+ const secret_catalog_1 = require("../secrets/secret-catalog");
11
12
  const provider_values_1 = require("../secrets/provider-values");
12
13
  // Where the value comes from, for messages and for what makes a service
13
14
  // different: never the value.
@@ -30,6 +31,8 @@ function getPortableSecretName(projectRoot, secret) {
30
31
  }
31
32
  exports.getPortableSecretName = getPortableSecretName;
32
33
  function parseWorkSecrets(cwd, projectRoot, secrets, envs, environment, catalog,
34
+ // what the secrets belong to, for messages: `task build` or `service db`
35
+ owner,
33
36
  // the service account of the task or service the secrets belong to
34
37
  account) {
35
38
  return (secrets ?? []).map((secret) => {
@@ -38,7 +41,7 @@ account) {
38
41
  ? { type: 'env', name: secret.env }
39
42
  : { type: 'file', path: (0, normalize_path_1.normalizePath)(cwd, cwd, (0, template_value_1.templateValue)(secret.path ?? '', envs)) };
40
43
  const name = target.type === 'env' ? target.name : secret.path;
41
- const source = parseSecretSource(secret, ref, cwd, envs, catalog, account, `secret ${name}`);
44
+ const source = parseSecretSource(secret, ref, cwd, envs, catalog, account, owner, `secret ${name}`);
42
45
  const workSecret = {
43
46
  source,
44
47
  target,
@@ -49,7 +52,7 @@ account) {
49
52
  });
50
53
  }
51
54
  exports.parseWorkSecrets = parseWorkSecrets;
52
- function parseSecretSource(secret, ref, cwd, envs, catalog, taskAccount, label) {
55
+ function parseSecretSource(secret, ref, cwd, envs, catalog, taskAccount, owner, label) {
53
56
  const kind = secret.from.substring(0, secret.from.indexOf(':'));
54
57
  if (kind === 'env') {
55
58
  return { type: 'env', name: ref };
@@ -57,30 +60,29 @@ function parseSecretSource(secret, ref, cwd, envs, catalog, taskAccount, label)
57
60
  if (kind === 'file') {
58
61
  return { type: 'file', path: (0, normalize_path_1.normalizePath)(cwd, (0, os_1.homedir)(), (0, template_value_1.templateValue)(ref, envs)) };
59
62
  }
60
- const provider = catalog.providers[kind];
63
+ const reads = `${owner} reads ${label} from ${secret.from}`;
64
+ const provider = (0, secret_catalog_1.declared)(catalog.providers, kind);
61
65
  if (!provider) {
62
- const declared = Object.keys(catalog.providers);
63
- throw new Error(`${label}: unknown secret provider ${kind}, ${declared.length > 0 ? `declared: ${declared.join(', ')}` : 'none is declared'}`);
66
+ throw new Error(unknownProviderMessage(catalog, reads, kind));
64
67
  }
65
68
  const providerRef = (0, template_value_1.templateValue)(ref, envs);
66
69
  if (providerRef.length === 0 || providerRef.startsWith('-')) {
67
- throw new Error(`${label}: a reference for ${kind} must not be empty or start with -`);
70
+ throw new Error(`${reads}: a reference for ${kind} must not be empty or start with -`);
68
71
  }
69
72
  const accountName = catalog.explicitAccounts
70
73
  ? secret.account
71
74
  : secret.account ?? taskAccount ?? Object.values(catalog.accounts).find((a) => a.default)?.name;
72
75
  if (!accountName) {
73
- throw new Error(catalog.explicitAccounts
74
- ? `${label}: ${kind}:${providerRef} needs account: on the secret, a server uses neither a task's account nor a default`
75
- : `${label}: ${kind}:${providerRef} needs an account, and none is named or marked default: true`);
76
+ throw new Error(missingAccountMessage(catalog, reads, owner));
76
77
  }
77
- const account = catalog.accounts[accountName];
78
+ const account = (0, secret_catalog_1.declared)(catalog.accounts, accountName);
78
79
  if (!account) {
79
- throw new Error(`${label}: unknown secret account ${accountName}, declared: ${Object.keys(catalog.accounts).join(', ') || 'none'}`);
80
+ const namedBy = secret.account ? 'the account: of the secret' : `the account: of ${owner}`;
81
+ throw new Error(unknownAccountMessage(catalog, reads, owner, accountName, namedBy, kind));
80
82
  }
81
- const credentials = account.providers[kind];
83
+ const credentials = (0, secret_catalog_1.declared)(account.providers, kind);
82
84
  if (!credentials) {
83
- throw new Error(`${label}: account ${accountName} has no credentials for provider ${kind}`);
85
+ throw new Error(missingCredentialsMessage(catalog, reads, account, kind));
84
86
  }
85
87
  return {
86
88
  type: 'provider',
@@ -90,6 +92,126 @@ function parseSecretSource(secret, ref, cwd, envs, catalog, taskAccount, label)
90
92
  binding: { definition: provider, account: { name: accountName, env: credentials.env } },
91
93
  };
92
94
  }
95
+ // The messages below say what is wrong, where the names come from and what to write: a
96
+ // person who only ran a task should not need to know how secrets are declared. On a
97
+ // server the build file can only change what it names, the operator declares the rest.
98
+ const SECRET_PROVIDERS_DOCS = 'https://hammerkit.dev/docs/task/secret-providers';
99
+ // `tests, dev in ~/.hammerkit/config.yaml and ci in .hammerkit.yaml`, or `none`
100
+ function listDeclared(definitions, server) {
101
+ if (definitions.length === 0) {
102
+ return 'none';
103
+ }
104
+ if (server) {
105
+ return definitions.map((d) => d.name).join(', ');
106
+ }
107
+ const byFile = new Map();
108
+ for (const definition of definitions) {
109
+ byFile.set(definition.declaredIn, [...(byFile.get(definition.declaredIn) ?? []), definition.name]);
110
+ }
111
+ return [...byFile.entries()].map(([file, names]) => `${names.join(', ')} in ${file}`).join(' and ');
112
+ }
113
+ // A build file is checked as a whole when it is read, so one wrong secret stops
114
+ // the tasks that don't read it, too.
115
+ function seeDocs(anchor) {
116
+ return `Every task of the build file is checked when it is read, so this stops other tasks too. See ${SECRET_PROVIDERS_DOCS}#${anchor}`;
117
+ }
118
+ function hostConfigOf(catalog) {
119
+ return catalog.hostConfig ?? 'the host config';
120
+ }
121
+ function indent(lines) {
122
+ return lines.map((line) => ` ${line}`).join('\n');
123
+ }
124
+ // A variable of this machine to hold the credential, for snippets: `${OPERATOR_CREDENTIALS}`
125
+ function credentialVariable(account, key, keys) {
126
+ const prefix = account.toUpperCase().replace(/[^A-Z0-9]+/g, '_');
127
+ return `\${${prefix}_${keys === 1 ? 'CREDENTIALS' : key}}`;
128
+ }
129
+ // The credential variables a provider's command reads, as another account passes them;
130
+ // a placeholder when no account has credentials for the provider yet
131
+ function credentialLines(catalog, account, provider) {
132
+ const sibling = Object.values(catalog.accounts).find((a) => (0, secret_catalog_1.declared)(a.providers, provider));
133
+ const keys = sibling ? Object.keys(sibling.providers[provider].env) : [];
134
+ if (keys.length === 0) {
135
+ return [`<VARIABLE>: \${<VARIABLE OF THIS MACHINE>} # what ${provider} reads its credential from`];
136
+ }
137
+ return keys.map((key) => `${key}: ${credentialVariable(account, key, keys.length)}`);
138
+ }
139
+ function unknownProviderMessage(catalog, reads, kind) {
140
+ const declaredProviders = listDeclared(Object.values(catalog.providers), !!catalog.explicitAccounts);
141
+ if (catalog.explicitAccounts) {
142
+ return (`${reads}, but this server has no secret provider ${kind} (it has: ${declaredProviders}). ` +
143
+ `Use one of its providers, or ask the operator of the server to add ${kind} to its config.`);
144
+ }
145
+ return [
146
+ `${reads}, but no secret provider ${kind} is declared (declared: ${declaredProviders}).`,
147
+ `A provider is the command that prints a secret's value. Declare it in the host config, ${hostConfigOf(catalog)}:`,
148
+ '',
149
+ indent(['secretProviders:', ` ${kind}:`, ` command: [<command>, <its arguments>, '{{ref}}']`]),
150
+ '',
151
+ seeDocs('providers'),
152
+ ].join('\n');
153
+ }
154
+ function missingAccountMessage(catalog, reads, owner) {
155
+ const declaredAccounts = listDeclared(Object.values(catalog.accounts), !!catalog.explicitAccounts);
156
+ if (catalog.explicitAccounts) {
157
+ return (`${reads}, but names no account. A server reads every secret as the account the secret names, ` +
158
+ `never as the account of a task or a default: add account: to the secret (this server has: ${declaredAccounts}).`);
159
+ }
160
+ return [
161
+ `${reads}, but neither the secret nor ${owner} names an account, and no account is marked default: true (declared: ${declaredAccounts}).`,
162
+ `An account says which credential a secret is read with. Name one with account: on the secret or on ${owner}, ` +
163
+ `or mark one as the default in ${hostConfigOf(catalog)}:`,
164
+ '',
165
+ indent(['secretAccounts:', ' <account>:', ' default: true']),
166
+ '',
167
+ seeDocs('accounts'),
168
+ ].join('\n');
169
+ }
170
+ function unknownAccountMessage(catalog, reads, owner, account, namedBy, provider) {
171
+ const declaredAccounts = listDeclared(Object.values(catalog.accounts), !!catalog.explicitAccounts);
172
+ if (catalog.explicitAccounts) {
173
+ return (`${reads} as account ${account}, but this server has no account ${account} (it has: ${declaredAccounts}). ` +
174
+ `Name one of its accounts with account: on the secret, or ask the operator of the server to add ${account} to its config.`);
175
+ }
176
+ return [
177
+ `${reads} as account ${account} (${namedBy}), but no account ${account} is declared (declared: ${declaredAccounts}).`,
178
+ `An account says which credential a secret is read with, and each machine declares its own in its host config, ` +
179
+ `${hostConfigOf(catalog)}. Add ${account} there:`,
180
+ '',
181
+ indent([
182
+ 'secretAccounts:',
183
+ ` ${account}:`,
184
+ ' providers:',
185
+ ` ${provider}:`,
186
+ ' env:',
187
+ ...credentialLines(catalog, account, provider).map((line) => ` ${line}`),
188
+ ]),
189
+ '',
190
+ `Or read the secret as one of the declared accounts with account: on the secret${namedBy === 'the account: of the secret' ? '' : ` or on ${owner}`}.`,
191
+ seeDocs('accounts'),
192
+ ].join('\n');
193
+ }
194
+ function missingCredentialsMessage(catalog, reads, account, provider) {
195
+ if (catalog.explicitAccounts) {
196
+ return (`${reads} as account ${account.name}, but that account of this server has no credentials for ${provider}. ` +
197
+ `Ask the operator of the server to add them to its config.`);
198
+ }
199
+ return [
200
+ `${reads} as account ${account.name}, but account ${account.name} (in ${account.declaredIn}) has no credentials for provider ${provider}.`,
201
+ `Add the variables that make ${provider} act as ${account.name}:`,
202
+ '',
203
+ indent([
204
+ 'secretAccounts:',
205
+ ` ${account.name}:`,
206
+ ' providers:',
207
+ ` ${provider}:`,
208
+ ' env:',
209
+ ...credentialLines(catalog, account.name, provider).map((line) => ` ${line}`),
210
+ ]),
211
+ '',
212
+ seeDocs('accounts'),
213
+ ].join('\n');
214
+ }
93
215
  function readSecretValueSync(secret, environment) {
94
216
  if (secret.source.type === 'env') {
95
217
  const value = environment.processEnvs[secret.source.name];
@@ -1,3 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isAskedByName = void 0;
4
+ // Whether a task was asked for by name: one of the tasks named, or the one task the run
5
+ // was asked for. An init task asked for by name starts its service and runs.
6
+ function isAskedByName(workTree, name) {
7
+ if (workTree.named) {
8
+ return workTree.named.includes(name);
9
+ }
10
+ return workTree.requested?.length === 1 && workTree.requested[0] === name;
11
+ }
12
+ exports.isAskedByName = isAskedByName;
3
13
  //# sourceMappingURL=work-tree.js.map
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.collectBundle = void 0;
4
+ const promises_1 = require("node:fs/promises");
4
5
  const path_1 = require("path");
5
6
  const resolve_git_source_1 = require("../includes/resolve-git-source");
6
7
  const schema_parser_1 = require("../schema/schema-parser");
@@ -10,7 +11,10 @@ const bundle_1 = require("./bundle");
10
11
  // The build file is read with the parser of a run, so what it pulls in is what a
11
12
  // run would read. Git includes are not part of it (the server fetches them, at
12
13
  // the commit they are pinned to), and neither is anything outside of the
13
- // directory of the build file, which a server could not reproduce.
14
+ // directory of the build file, which a server could not reproduce. That holds for
15
+ // where a file really is too: a link to a file outside of the directory is refused
16
+ // rather than followed, so publishing a checkout never sends a file of this machine
17
+ // that the checkout only points to.
14
18
  async function collectBundle(fileName, environment) {
15
19
  if (!(await environment.file.exists(fileName))) {
16
20
  throw new Error(`there is no build file at ${fileName}`);
@@ -24,11 +28,15 @@ async function collectBundle(fileName, environment) {
24
28
  paths.add((0, path_1.resolve)(scope.fileName));
25
29
  }
26
30
  }
31
+ const realRoot = await (0, promises_1.realpath)(root);
27
32
  const files = {};
28
33
  for (const path of [...paths].sort()) {
29
34
  if (!(0, resolve_git_source_1.isWithin)(root, path)) {
30
35
  throw new Error(`${path} is outside of ${root}: a published build file can only include files below its own directory`);
31
36
  }
37
+ if (!(0, resolve_git_source_1.isWithin)(realRoot, await (0, promises_1.realpath)(path))) {
38
+ throw new Error(`${path} links to a file outside of ${root}: a published build file can only include files below its own directory`);
39
+ }
32
40
  files[(0, path_1.relative)(root, path).split(path_1.sep).join('/')] = await environment.file.read(path);
33
41
  }
34
42
  const result = bundle_1.bundleSchema.safeParse({ entry: (0, path_1.relative)(root, entryPath).split(path_1.sep).join('/'), files });
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.pinLogin = exports.setDefaultLocation = exports.removeServer = exports.addServer = exports.normalizeServerUrl = exports.validateServerName = exports.writeHostConfig = exports.readHostConfig = exports.getHostConfigPath = exports.getRegisteredServer = exports.getTokenCommand = exports.hasServer = exports.hostConfigSchema = exports.hostServerSchema = exports.RESERVED_SERVER_NAMES = void 0;
3
+ exports.pinLogin = exports.setDefaultLocation = exports.removeServer = exports.addServer = exports.normalizeServerUrl = exports.validateServerName = exports.writeHostConfig = exports.readHostConfig = exports.getHostConfigPath = exports.chooseServer = exports.notRegisteredMessage = exports.getRegisteredServer = exports.getTokenCommand = exports.hasServer = exports.hostConfigSchema = exports.hostServerSchema = exports.RESERVED_SERVER_NAMES = void 0;
4
4
  const path_1 = require("path");
5
5
  const zod_1 = require("zod");
6
6
  const yaml_1 = require("yaml");
@@ -69,6 +69,52 @@ function getRegisteredServer(config, name) {
69
69
  return { ...config.servers[name], ...(tokenCommand ? { tokenCommand } : {}) };
70
70
  }
71
71
  exports.getRegisteredServer = getRegisteredServer;
72
+ // `a, b and c`
73
+ function listNames(names) {
74
+ return names.length > 1 ? `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}` : names.join('');
75
+ }
76
+ // `(registered: a and b)`, for a name that is not one of them
77
+ function registeredNote(config) {
78
+ const names = Object.keys(config.servers).sort();
79
+ return names.length === 0 ? '(no server is registered yet)' : `(registered: ${listNames(names)})`;
80
+ }
81
+ // `server nope is not registered (registered: a and b)`, with how to add it unless it is being removed
82
+ function notRegisteredMessage(config, name, howToAdd = true) {
83
+ const add = howToAdd ? `, add it with: hammerkit remote add ${name} <url> --issuer <url>` : '';
84
+ return `server ${name} is not registered ${registeredNote(config)}${add}`;
85
+ }
86
+ exports.notRegisteredMessage = notRegisteredMessage;
87
+ // The server a remote command talks to: the one it names, else the default of `remote use`,
88
+ // else the only one registered. With several and no default, the person names one.
89
+ // A default that names a server no longer registered is an error, as it is for `hammerkit run`:
90
+ // a call never goes to another server than the one chosen. `how` says how a name is given,
91
+ // for the message: `with --server <name>`.
92
+ function chooseServer(config, name, how = 'as the last argument') {
93
+ if (name !== undefined) {
94
+ if (!hasServer(config.servers, name)) {
95
+ throw new Error(notRegisteredMessage(config, name));
96
+ }
97
+ return name;
98
+ }
99
+ const on = config.run.on;
100
+ if (on && !exports.RESERVED_SERVER_NAMES.includes(on)) {
101
+ if (!hasServer(config.servers, on)) {
102
+ throw new Error(`the default of remote use, server ${on}, is not registered ${registeredNote(config)}; ` +
103
+ `pick another with: hammerkit remote use <name>, or add it with: hammerkit remote add ${on} <url> --issuer <url>`);
104
+ }
105
+ return on;
106
+ }
107
+ const names = Object.keys(config.servers).sort();
108
+ if (names.length === 1) {
109
+ return names[0];
110
+ }
111
+ if (names.length === 0) {
112
+ throw new Error('no server is registered, add one with: hammerkit remote add <name> <url> --issuer <url>');
113
+ }
114
+ throw new Error(`${names.length} servers are registered (${listNames(names)}), name one ${how}, ` +
115
+ `or make one the default with: hammerkit remote use <name>`);
116
+ }
117
+ exports.chooseServer = chooseServer;
72
118
  function setTokenCommand(config, name, entry) {
73
119
  const commands = { ...(config.tokenCommands ?? {}) };
74
120
  if (entry) {
@@ -201,7 +247,7 @@ exports.addServer = addServer;
201
247
  async function removeServer(environment, name) {
202
248
  const config = await readHostConfig(environment);
203
249
  if (!hasServer(config.servers, name)) {
204
- throw new Error(`server "${name}" is not registered`);
250
+ throw new Error(notRegisteredMessage(config, name, false));
205
251
  }
206
252
  delete config.servers[name];
207
253
  setTokenCommand(config, name, undefined);
@@ -216,7 +262,7 @@ exports.removeServer = removeServer;
216
262
  async function setDefaultLocation(environment, on) {
217
263
  const config = await readHostConfig(environment);
218
264
  if (!exports.RESERVED_SERVER_NAMES.includes(on) && !hasServer(config.servers, on)) {
219
- throw new Error(`server "${on}" is not registered; add it with: hammerkit remote add ${on} <url> --issuer <url>`);
265
+ throw new Error(notRegisteredMessage(config, on));
220
266
  }
221
267
  config.run.on = on;
222
268
  await writeHostConfig(environment, config);
@@ -14,7 +14,7 @@ async function resolveRunLocation(workTree, environment, options = {}) {
14
14
  const config = await (0, host_config_1.readHostConfig)(environment);
15
15
  const explicit = options.local ? 'local' : options.on ?? (environment.processEnvs.HAMMERKIT_ON || undefined);
16
16
  if (explicit && explicit !== 'auto') {
17
- return explicit === 'local' ? { type: 'local' } : lookup(config.servers, explicit);
17
+ return explicit === 'local' ? { type: 'local' } : lookup(config, explicit);
18
18
  }
19
19
  const runners = getTaskRunners(workTree);
20
20
  if (runners.length > 1) {
@@ -24,13 +24,13 @@ async function resolveRunLocation(workTree, environment, options = {}) {
24
24
  if (!requested || requested === 'local' || requested === 'auto') {
25
25
  return { type: 'local' };
26
26
  }
27
- return lookup(config.servers, requested);
27
+ return lookup(config, requested);
28
28
  }
29
29
  exports.resolveRunLocation = resolveRunLocation;
30
- function lookup(servers, name) {
31
- const server = (0, host_config_1.hasServer)(servers, name) ? servers[name] : undefined;
30
+ function lookup(config, name) {
31
+ const server = (0, host_config_1.hasServer)(config.servers, name) ? config.servers[name] : undefined;
32
32
  if (!server) {
33
- throw new Error(`server ${name} is not registered, add it with: hammerkit remote add ${name} <url> --issuer <url>`);
33
+ throw new Error((0, host_config_1.notRegisteredMessage)(config, name));
34
34
  }
35
35
  return { type: 'server', name, server };
36
36
  }
@@ -94,21 +94,17 @@ passthrough = []) {
94
94
  await (0, host_config_1.setDefaultLocation)(environment, location);
95
95
  environment.stdout.write(`default location: ${location}\n`);
96
96
  }));
97
- const getServer = async (name) => {
97
+ // a command that takes a server: the named one, the default or the only one, see chooseServer
98
+ const getServer = async (name, how) => {
98
99
  const config = await (0, host_config_1.readHostConfig)(environment);
99
- const chosen = name ?? config.run.on;
100
- if (!chosen || !(0, host_config_1.hasServer)(config.servers, chosen)) {
101
- throw new Error(name
102
- ? `server ${name} is not registered, add it with: hammerkit remote add ${name} <url> --issuer <url>`
103
- : 'name a server, or set one as the default with: hammerkit remote use <name>');
104
- }
100
+ const chosen = (0, host_config_1.chooseServer)(config, name, how);
105
101
  return { name: chosen, server: (0, host_config_1.getRegisteredServer)(config, chosen) };
106
102
  };
107
103
  remote
108
- .command('login <name>')
109
- .description('sign in to a registered server with your identity provider (device code, works headless)')
110
- .action(guarded('Remote login was not successful', async (name) => {
111
- const { server } = await getServer(name);
104
+ .command('login [name]')
105
+ .description('sign in to a registered server with your identity provider (device code, works headless); the name can be left out when only one server is registered or one is set with remote use')
106
+ .action(guarded('Remote login was not successful', async (given) => {
107
+ const { name, server } = await getServer(given);
112
108
  if (server.tokenCommand) {
113
109
  // a sign-in would never be used: the command's token goes first
114
110
  throw new Error(`${name} takes its tokens from its token command (${server.tokenCommand}), it needs no sign-in; ` +
@@ -145,9 +141,11 @@ passthrough = []) {
145
141
  }
146
142
  }));
147
143
  remote
148
- .command('logout <name>')
149
- .description('forget the sign-in to a server')
150
- .action(guarded('Remote logout was not successful', async (name) => {
144
+ .command('logout [name]')
145
+ .description('forget the sign-in to a server; the name can be left out as for login')
146
+ .action(guarded('Remote logout was not successful', async (given) => {
147
+ // a sign-in outlives its server's registration, so a name given is taken as it is
148
+ const name = given ?? (0, host_config_1.chooseServer)(await (0, host_config_1.readHostConfig)(environment), undefined);
151
149
  const removed = await (0, credentials_1.removeToken)(environment, name);
152
150
  environment.stdout.write(removed ? `signed out of ${name}\n` : `not signed in to ${name}\n`);
153
151
  }));