hammerkit 2.1.0-next.17 → 2.1.0-next.19

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.
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.workerMain = exports.readInput = exports.taskCommands = exports.taskCauses = exports.describeFailures = exports.failedTasks = exports.runTasks = exports.relayStatus = exports.removeCommandsOfRun = exports.getRunnerCommands = exports.getLogEvent = exports.getEndpointTargets = exports.publishEndpoints = exports.getRunNetwork = exports.workerInputSchema = void 0;
3
+ exports.workerMain = exports.readInput = exports.ChangeQueue = exports.applyChanges = exports.isInside = exports.syncLine = exports.syncServices = exports.taskCommands = exports.taskCauses = exports.describeFailures = exports.failedTasks = exports.runTasks = exports.relayStatus = exports.removeCommandsOfRun = exports.getRunnerCommands = exports.getLogEvent = exports.getEndpointTargets = exports.publishEndpoints = exports.getRunNetwork = exports.workerInputSchema = void 0;
4
4
  const readline_1 = require("readline");
5
+ const promises_1 = require("fs/promises");
6
+ const path_1 = require("path");
5
7
  const zod_1 = require("zod");
6
8
  const cli_1 = require("../cli");
7
9
  const get_file_context_1 = require("../file/get-file-context");
@@ -79,6 +81,7 @@ exports.workerInputSchema = zod_1.z
79
81
  .object({
80
82
  services: zod_1.z.array(zod_1.z.string()).min(1),
81
83
  endpoints: zod_1.z.array(zod_1.z.object({ service: zod_1.z.string(), port: zod_1.z.number().int() }).strict()),
84
+ restart: zod_1.z.array(zod_1.z.string()).optional(),
82
85
  })
83
86
  .strict()
84
87
  .optional(),
@@ -252,7 +255,10 @@ cancelled, emit,
252
255
  // a service run: its services are ready, at these addresses
253
256
  up,
254
257
  // its commands in a sandbox's runner
255
- commands = getRunnerCommands(input, emit)) {
258
+ commands = getRunnerCommands(input, emit),
259
+ // a service run: hands the changed files of its sandbox to the services that are up while
260
+ // they are up (undefined once they are not)
261
+ register) {
256
262
  const secrets = (0, redact_1.createSecretRegistry)();
257
263
  const status = (0, work_item_status_1.statusConsole)((0, empty_writable_1.emptyWritable)(), secrets);
258
264
  // the process starts in a directory of the server, the tasks work on the run's files
@@ -342,6 +348,10 @@ commands = getRunnerCommands(input, emit)) {
342
348
  const execution = input.up
343
349
  ? cli.up({ ...execOptions, workers: cli.defaultWorkers(), daemon: false, wait: 'ready' })
344
350
  : cli.exec({ ...execOptions, workers: cli.defaultWorkers() });
351
+ if (input.up) {
352
+ const up = input.up;
353
+ register?.((changes) => syncServices(workTree, up, changes));
354
+ }
345
355
  const seen = new Map();
346
356
  const failedServices = new Set();
347
357
  let ready = false;
@@ -405,6 +415,9 @@ commands = getRunnerCommands(input, emit)) {
405
415
  }
406
416
  finally {
407
417
  watch.close();
418
+ if (input.up) {
419
+ register?.(undefined);
420
+ }
408
421
  if (input.up && input.kubernetes?.server?.serviceRun && !ready && service_rollouts_1.serviceRollouts.size > 0) {
409
422
  // a move (or a start) whose services did not all get up: the run stays where it was
410
423
  await service_rollouts_1.serviceRollouts.undo((0, kubernetes_instance_1.createKubernetesInstances)(input.kubernetes), (text) => emit({ type: 'log', task: 'hammerkit', stream: 'stderr', text }));
@@ -600,11 +613,126 @@ redact) {
600
613
  }
601
614
  }
602
615
  }
616
+ /**
617
+ * Hands the files of a sandbox that changed to the services of a service run that are up:
618
+ * each one that takes files (its runtime says so) syncs them, and starts again when the run
619
+ * lists it in `restart`. The other services are not touched.
620
+ */
621
+ async function syncServices(workTree, up, changes) {
622
+ // one service that fails does not hold back the others: they are all tried, and the failures
623
+ // are said together
624
+ const failed = [];
625
+ for (const service of Object.values(workTree.services)) {
626
+ if (!up.services.includes(service.name)) {
627
+ continue;
628
+ }
629
+ try {
630
+ await service.runtime.syncFiles?.({ ...changes, restart: (up.restart ?? []).includes(service.name) });
631
+ }
632
+ catch (e) {
633
+ failed.push(`${service.name}: ${(0, log_1.getErrorMessage)(e)}`);
634
+ }
635
+ }
636
+ if (failed.length > 0) {
637
+ throw new Error(`the changed files were not synced to ${failed.join('; ')}`);
638
+ }
639
+ }
640
+ exports.syncServices = syncServices;
641
+ // The line `sync <json>` the server writes for a batch of changes: the folder the batch is
642
+ // staged in (`staging`), which the batch folder must be inside to be removed after it
643
+ exports.syncLine = zod_1.z
644
+ .object({
645
+ staging: zod_1.z.string(),
646
+ changes: zod_1.z
647
+ .object({
648
+ dir: zod_1.z.string(),
649
+ written: zod_1.z.array(zod_1.z.string()),
650
+ deleted: zod_1.z.array(zod_1.z.string()),
651
+ restart: zod_1.z.boolean(),
652
+ })
653
+ .strict(),
654
+ })
655
+ .strict();
656
+ // The staging folder and the batch of a sync line, as far as they are named: what a refused line
657
+ // still names, so its batch can be removed (see applyChanges)
658
+ const batchOf = zod_1.z.object({ staging: zod_1.z.string(), changes: zod_1.z.object({ dir: zod_1.z.string() }) });
659
+ // Whether `path` is a folder inside `root`, not `root` itself
660
+ function isInside(root, path) {
661
+ const rel = (0, path_1.relative)((0, path_1.resolve)(root), (0, path_1.resolve)(path));
662
+ return rel !== '' && rel.split(path_1.sep)[0] !== '..' && !(0, path_1.isAbsolute)(rel);
663
+ }
664
+ exports.isInside = isInside;
665
+ /**
666
+ * Applies one batch of changes to the services that are up (`sync`). The batch folder goes
667
+ * afterwards, whatever came of it, but only when it is inside the staging folder. A line that
668
+ * does not parse is logged and nothing else is done.
669
+ */
670
+ async function applyChanges(request, sync, log) {
671
+ let json;
672
+ try {
673
+ json = JSON.parse(request);
674
+ }
675
+ catch {
676
+ json = undefined;
677
+ }
678
+ const parsed = exports.syncLine.safeParse(json);
679
+ if (!parsed.success) {
680
+ log('the changed files of the sandbox could not be read');
681
+ // the batch is still the server's to see gone: a line that does not match names it loosely
682
+ const named = batchOf.safeParse(json);
683
+ if (named.success) {
684
+ await removeBatch(named.data.staging, (0, path_1.dirname)(named.data.changes.dir), log);
685
+ }
686
+ return;
687
+ }
688
+ const { staging, changes } = parsed.data;
689
+ const batch = (0, path_1.dirname)(changes.dir);
690
+ try {
691
+ if (!sync) {
692
+ log('no service of the run is up to take the changed files of the sandbox');
693
+ return;
694
+ }
695
+ await sync(changes);
696
+ }
697
+ catch (e) {
698
+ log(`the changed files of the sandbox could not be synced: ${(0, log_1.getErrorMessage)(e)}`);
699
+ }
700
+ finally {
701
+ await removeBatch(staging, batch, log);
702
+ }
703
+ }
704
+ exports.applyChanges = applyChanges;
705
+ // Removes a batch folder once it was applied or refused, when it is inside the staging folder
706
+ // of its run. Outside, it is left where it is: it is not the server's to remove.
707
+ async function removeBatch(staging, batch, log) {
708
+ if (!isInside(staging, batch)) {
709
+ log(`${batch} is not in the staging folder of the run, it is left where it is`);
710
+ return;
711
+ }
712
+ await (0, promises_1.rm)(batch, { recursive: true, force: true }).catch((e) => log(`${batch} could not be removed: ${(0, log_1.getErrorMessage)(e)}`));
713
+ }
714
+ /**
715
+ * The batches of changes of a run, applied one after another in the order they came. A batch
716
+ * that fails does not stop the ones after it.
717
+ */
718
+ class ChangeQueue {
719
+ constructor(apply, fail) {
720
+ this.apply = apply;
721
+ this.fail = fail;
722
+ this.last = Promise.resolve();
723
+ }
724
+ push(request) {
725
+ this.last = this.last.then(() => this.apply(request)).catch((e) => this.fail(e));
726
+ return this.last;
727
+ }
728
+ }
729
+ exports.ChangeQueue = ChangeQueue;
603
730
  // The run is the first line of the standard input. The server keeps it open and writes
604
731
  // `cancel` on it to stop the run: that works the same on every platform, where a signal
605
- // on Windows ends the process without letting it stop its tasks.
732
+ // on Windows ends the process without letting it stop its tasks. It writes `sync <json>` on
733
+ // it for the files of a sandbox that changed (FileChanges), which `sync` takes.
606
734
  // `onEnd` is told when the input ends before the run does: the server is gone.
607
- function readInput(stdin, cancel) {
735
+ function readInput(stdin, cancel, sync = () => undefined) {
608
736
  const lines = (0, readline_1.createInterface)({ input: stdin, crlfDelay: Infinity });
609
737
  let first;
610
738
  let closing = false;
@@ -619,6 +747,9 @@ function readInput(stdin, cancel) {
619
747
  else if (line.trim() === 'cancel') {
620
748
  cancel();
621
749
  }
750
+ else if (line.startsWith('sync ')) {
751
+ sync(line.slice('sync '.length));
752
+ }
622
753
  });
623
754
  lines.on('close', () => {
624
755
  resolve(first ?? '');
@@ -658,7 +789,13 @@ async function workerMain(stdin, stdout, processEnvs, cwd, abortCtrl) {
658
789
  };
659
790
  const signals = ['SIGINT', 'SIGTERM', 'SIGHUP'];
660
791
  signals.forEach((signal) => process.on(signal, stop));
661
- const reader = readInput(stdin, stop);
792
+ // the changes of the sandbox, one batch after the other, for the services that are up
793
+ let sync;
794
+ const logLine = (text) => say({ kind: 'event', event: { type: 'log', task: 'hammerkit', stream: 'stderr', text } });
795
+ const batches = new ChangeQueue((request) => applyChanges(request, sync, logLine), (e) => logLine(`the changed files of the sandbox could not be synced: ${(0, log_1.getErrorMessage)(e)}`));
796
+ const reader = readInput(stdin, stop, (request) => {
797
+ void batches.push(request);
798
+ });
662
799
  let input;
663
800
  try {
664
801
  input = exports.workerInputSchema.parse(JSON.parse(await reader.input));
@@ -684,7 +821,9 @@ async function workerMain(stdin, stdout, processEnvs, cwd, abortCtrl) {
684
821
  try {
685
822
  let result;
686
823
  try {
687
- await runTasks(input, cwd, processEnvs, abortCtrl, () => cancelled, emit, (targets) => say({ kind: 'up', targets }), commands);
824
+ await runTasks(input, cwd, processEnvs, abortCtrl, () => cancelled, emit, (targets) => say({ kind: 'up', targets }), commands, (handler) => {
825
+ sync = handler;
826
+ });
688
827
  result = { kind: 'result', ok: true };
689
828
  }
690
829
  catch (e) {
@@ -711,6 +711,26 @@ class RunRegistry {
711
711
  entry.run.state !== 'up' &&
712
712
  entry.run.state !== 'asleep')?.run.id;
713
713
  }
714
+ // The service runs of a sandbox that take its changed files: up, and not replaced or stopped
715
+ // (a run of the same name that replaces one stops it, and it is still up until it ended, so
716
+ // only the newest of a name syncs). A host's executor takes none: its sandbox's files are live.
717
+ upOn(sandbox) {
718
+ if (!this.options.executor.syncFiles) {
719
+ return [];
720
+ }
721
+ return [...this.entries.values()]
722
+ .filter((entry) => entry.run.state === 'up' && !entry.run.stoppedBy && onSandbox(entry.run, sandbox))
723
+ .map((entry) => this.copy(entry.run));
724
+ }
725
+ // Hands the changed files of a sandbox to the services of a service run that is up. False when
726
+ // the run is not known here, is stopped, or its executor can not take them.
727
+ syncFiles(id, changes) {
728
+ const entry = this.entries.get(id);
729
+ if (!entry || entry.run.stoppedBy) {
730
+ return false;
731
+ }
732
+ return this.options.executor.syncFiles?.(this.copy(entry.run), changes) ?? false;
733
+ }
714
734
  // Cancels every run on a sandbox and resolves when none of them runs anymore.
715
735
  async stopSandbox(sandbox, reason) {
716
736
  const on = () => [...this.entries.values()].filter((entry) => onSandbox(entry.run, sandbox));
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SandboxFollow = void 0;
4
+ const log_1 = require("../log");
5
+ // How long a sandbox must stay unchanged before its service runs follow it, and how long
6
+ // they may wait while its files keep changing.
7
+ const DELAY_MS = 1000;
8
+ const MAX_WAIT_MS = 5000;
9
+ /**
10
+ * Batches the changes of each sandbox: a burst of edits (or of runs that wrote) makes one
11
+ * call of `follow` once the sandbox was quiet for `delay`, and at the latest `maxWait` after its
12
+ * first change, so a sandbox that never stops changing is still followed. Each sandbox has
13
+ * its own batch.
14
+ */
15
+ class SandboxFollow {
16
+ constructor(options) {
17
+ this.options = options;
18
+ // per sandbox, the timer of its batch and when the batch began
19
+ this.batches = new Map();
20
+ this.closed = false;
21
+ this.delay = options.delay ?? DELAY_MS;
22
+ this.maxWait = options.maxWait ?? MAX_WAIT_MS;
23
+ }
24
+ changed(sandbox) {
25
+ if (this.closed) {
26
+ return;
27
+ }
28
+ const now = Date.now();
29
+ const batch = this.batches.get(sandbox);
30
+ const since = batch?.since ?? now;
31
+ clearTimeout(batch?.timer);
32
+ const wait = Math.min(this.delay, since + this.maxWait - now);
33
+ const timer = setTimeout(() => this.run(sandbox), wait);
34
+ this.batches.set(sandbox, { timer, since });
35
+ }
36
+ close() {
37
+ this.closed = true;
38
+ for (const { timer } of this.batches.values()) {
39
+ clearTimeout(timer);
40
+ }
41
+ this.batches.clear();
42
+ }
43
+ async run(sandbox) {
44
+ this.batches.delete(sandbox);
45
+ try {
46
+ await this.options.follow(sandbox);
47
+ }
48
+ catch (e) {
49
+ this.options.log?.(`follow ${sandbox}: ${(0, log_1.getErrorMessage)(e)}`);
50
+ }
51
+ }
52
+ }
53
+ exports.SandboxFollow = SandboxFollow;
54
+ //# sourceMappingURL=sandbox-follow.js.map
@@ -24,6 +24,11 @@ class SandboxPushFailed extends Error {
24
24
  exports.SandboxPushFailed = SandboxPushFailed;
25
25
  // the commit a sandbox pushed last, in its own git data
26
26
  const PUSHED_REF = 'refs/hammerkit/pushed';
27
+ // the directories a path is in, from the top: `a/b/c` is in `a` and `a/b`
28
+ function ancestors(path) {
29
+ const parts = path.split('/');
30
+ return parts.slice(0, -1).map((_, i) => parts.slice(0, i + 1).join('/'));
31
+ }
27
32
  /**
28
33
  * Sandboxes as directories below `directory`, one per sandbox: `files` is the checkout the
29
34
  * tasks work on, `git` its git data. The git data is kept outside of the files on purpose:
@@ -182,9 +187,41 @@ class HostSandboxStorage {
182
187
  this.walked.delete(id);
183
188
  // the branch by its full name: a tag of the same name is never taken
184
189
  await this.git(id, ['fetch', '--quiet', '--depth', '1', '--', fetch.url, `refs/heads/${fetch.ref}`], fetch.env, fetch.signal, 'fetch');
185
- await this.git(id, ['checkout', '--quiet', ...(force ? ['--force'] : []), 'FETCH_HEAD'], fetch.env, fetch.signal, 'check out');
190
+ try {
191
+ // a fetch does not let git write over an ignored file of the sandbox: git takes it for
192
+ // expendable, and the state of the sandbox does not count it as a change. Only a create
193
+ // passes force, into an empty work tree, which has no ignored file to write over.
194
+ await this.git(id, ['checkout', '--quiet', ...(force ? ['--force'] : ['--no-overwrite-ignore']), 'FETCH_HEAD'], fetch.env, fetch.signal, 'check out');
195
+ }
196
+ catch (e) {
197
+ const ignored = force ? undefined : await this.ignoredInTheWay(id, fetch);
198
+ if (ignored === undefined) {
199
+ throw e;
200
+ }
201
+ throw new sandbox_files_1.SandboxFileError(409, `${JSON.stringify(ignored)} is ignored in the sandbox and ${fetch.ref} has something in its place: ` +
202
+ 'a fetch would overwrite it, move or delete it first');
203
+ }
186
204
  return (await this.git(id, ['rev-parse', 'HEAD'], fetch.env, fetch.signal, 'read')).trim();
187
205
  }
206
+ // The first ignored file of the sandbox that the ref has in its place: at its path, above it
207
+ // (the ref has a file where the sandbox has a directory of ignored files) or below it (the ref
208
+ // has files in a directory where the sandbox has an ignored file). A checkout over one of those
209
+ // would write over it. Read only once a checkout was refused.
210
+ async ignoredInTheWay(id, fetch) {
211
+ // a listing that fails names no file, so git's own error stands
212
+ const list = (args) => this.git(id, args, fetch.env, fetch.signal, 'read', {
213
+ // a sandbox with node_modules lists many files
214
+ maxBuffer: 64 * 1024 * 1024,
215
+ }).then((out) => out.split('\0'), () => []);
216
+ const ignored = await list(['ls-files', '-z', '--others', '--ignored', '--exclude-standard']);
217
+ if (ignored.every((path) => path === '')) {
218
+ return undefined;
219
+ }
220
+ const tracked = await list(['ls-tree', '-r', '-z', '--name-only', 'FETCH_HEAD']);
221
+ const files = new Set(tracked);
222
+ const directories = new Set(tracked.flatMap(ancestors));
223
+ return ignored.find((path) => path !== '' && (files.has(path) || directories.has(path) || ancestors(path).some((dir) => files.has(dir))));
224
+ }
188
225
  // One hold of the sandbox from the commit to the push: a prune in between would remove the
189
226
  // commit. A ref keeps the commit until the sandbox is moved to it, also when the push
190
227
  // failed late and the remote has it after all.