hammerkit 2.1.0-next.13 → 2.1.0-next.14

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.
@@ -423,6 +423,11 @@ async function followRun(connection, submitted, options = {}) {
423
423
  const lines = [];
424
424
  let from = submitted.moved?.logFrom ?? 1;
425
425
  let truncated = false;
426
+ // where the log went on after a server that was killed lost its end (LogPage.lost), as the
427
+ // follow last heard it, and the last line it read itself: it reads again from `lost` only
428
+ // when it read lines there, which are gone, not when it started past it (a moved run)
429
+ let lost;
430
+ let read = 0;
426
431
  const add = (line) => {
427
432
  lines.push(line);
428
433
  options.onLine?.(line);
@@ -445,9 +450,24 @@ async function followRun(connection, submitted, options = {}) {
445
450
  return;
446
451
  }
447
452
  truncated = page.truncated;
453
+ if (page.lost !== undefined && page.lost !== lost) {
454
+ lost = page.lost;
455
+ if (read >= page.lost) {
456
+ // the lines from there on are not the ones read before: they are gone with the server
457
+ add({
458
+ line: 0,
459
+ task: 'hammerkit',
460
+ stream: 'stderr',
461
+ text: `… the server restarted and lost the last lines it had sent, the log goes on from line ${page.lost}`,
462
+ });
463
+ from = page.lost;
464
+ continue;
465
+ }
466
+ }
448
467
  for (const line of page.lines) {
449
468
  add(line);
450
469
  from = line.line + 1;
470
+ read = line.line;
451
471
  }
452
472
  if (!page.next) {
453
473
  return;
@@ -10,6 +10,7 @@ const path_1 = require("path");
10
10
  const readline_1 = require("readline");
11
11
  const resolve_git_source_1 = require("../includes/resolve-git-source");
12
12
  const git_checkout_1 = require("./git-checkout");
13
+ const runs_1 = require("./runs");
13
14
  const run_plan_1 = require("./run-plan");
14
15
  const work_network_1 = require("../planner/work-network");
15
16
  const execute_docker_1 = require("../executer/execute-docker");
@@ -22,8 +23,12 @@ function isGitDirectory(segment) {
22
23
  return name === '.git' || name === 'git~1';
23
24
  }
24
25
  // A cancelled run gets this long to stop its tasks and remove its containers, after that
25
- // its process is killed
26
+ // its process is killed. A server without a store waits for it on close (CLOSE_TIMEOUT in
27
+ // runs.ts bounds only a server that detaches its runs)
26
28
  const STOP_GRACE_MS = 15000;
29
+ // A run the server leaves to the next one gets this long to stop its tasks on this machine: the
30
+ // rest of what CLOSE_TIMEOUT gives it is for its execution to end (its directory, its volumes)
31
+ const DETACH_GRACE_MS = runs_1.CLOSE_TIMEOUT - 5000;
27
32
  // what is kept of the error output of a process that died without saying why
28
33
  const MAX_STDERR = 2 * 1024;
29
34
  /**
@@ -370,11 +375,14 @@ class HostExecutor {
370
375
  : {}),
371
376
  ...(placed ? { kubernetes: placed.kubernetes } : {}),
372
377
  ...(!placed && this.options.capabilityRuntime ? { capabilityRuntime: this.options.capabilityRuntime } : {}),
373
- }, published, { ...(0, run_source_environment_1.withRunSource)(this.processEnvironment(home, cache), run.source), ...placed?.env }, context, abortCtrl.signal);
378
+ }, published, { ...(0, run_source_environment_1.withRunSource)(this.processEnvironment(home, cache), run.source), ...placed?.env }, context, abortCtrl.signal, !!placed);
374
379
  }
375
380
  finally {
376
381
  if (placement && placed) {
377
- await placement.release(run, context);
382
+ // a run that resumes with the next server finds its Jobs and services where they are
383
+ if (!(0, runs_1.isDetached)(context)) {
384
+ await placement.release(run, context);
385
+ }
378
386
  }
379
387
  else if (run.up && !context.keep?.()) {
380
388
  // the services are gone with the process, their volumes stay only while the run sleeps
@@ -445,7 +453,10 @@ class HostExecutor {
445
453
  // engine stops its tasks and removes its containers; a signal on Windows would end the
446
454
  // process at once and leave its tasks running in the directory of the run. The process is
447
455
  // killed if it has not stopped after the grace period.
448
- runInProcess(command, input, cwd, env, context, signal) {
456
+ // A run that the server leaves to the next one (RunContext.detached) and whose tasks are on
457
+ // a cluster: the process is killed at once, so its Jobs and services stay. One whose tasks
458
+ // are on this machine stops them as a cancel does, in less time.
459
+ runInProcess(command, input, cwd, env, context, signal, onCluster) {
449
460
  return new Promise((resolvePromise, reject) => {
450
461
  const child = (0, child_process_1.spawn)(command[0], command.slice(1), {
451
462
  cwd,
@@ -460,12 +471,18 @@ class HostExecutor {
460
471
  let stderr = '';
461
472
  let killTimer;
462
473
  const stop = () => {
474
+ const detaching = (0, runs_1.isDetached)(context);
475
+ if (detaching && onCluster) {
476
+ child.kill('SIGKILL');
477
+ return;
478
+ }
463
479
  child.stdin.write('cancel\n', (e) => {
464
480
  if (e) {
465
481
  child.kill();
466
482
  }
467
483
  });
468
- killTimer = setTimeout(() => child.kill('SIGKILL'), this.options.stopGraceMs ?? STOP_GRACE_MS);
484
+ const grace = this.options.stopGraceMs ?? STOP_GRACE_MS;
485
+ killTimer = setTimeout(() => child.kill('SIGKILL'), detaching ? Math.min(grace, DETACH_GRACE_MS) : grace);
469
486
  killTimer.unref();
470
487
  };
471
488
  if (signal.aborted) {
@@ -19,6 +19,7 @@ const version_1 = require("../version");
19
19
  const executor_1 = require("./executor");
20
20
  const kept_claims_1 = require("../kubernetes/kept-claims");
21
21
  const units_1 = require("../utils/units");
22
+ const runs_1 = require("./runs");
22
23
  const server_config_1 = require("./server-config");
23
24
  // the name of the quota and limit range the server keeps in a caller's namespace
24
25
  const POLICY_NAME = 'hammerkit';
@@ -270,8 +271,11 @@ class KubernetesExecutor {
270
271
  // per caller namespace, what changes objects of the whole namespace: its setup, the
271
272
  // removal of what a stopped server left, the sweeps of kept claims. The last one waiting.
272
273
  this.queues = new Map();
273
- // per caller namespace, the runs that execute in it and mount kept claims: by run label,
274
- // their volume scope
274
+ // per caller namespace, the runs that execute in it: by run label, the volume scope of the
275
+ // kept claims they mount, if any. Every run that executes is here, not only those that mount
276
+ // kept claims: a tidy of the namespace (after a release that failed, or the first after a
277
+ // restart) leaves the objects of all of them, a resumed run's too once it no longer counts
278
+ // as resuming
275
279
  this.active = new Map();
276
280
  // per caller namespace, when its kept claims are next looked at
277
281
  this.sweeps = new Map();
@@ -285,6 +289,9 @@ class KubernetesExecutor {
285
289
  this.serviceRuns = new Map();
286
290
  this.serviceRunsSwept = false;
287
291
  this.asleep = new Set();
292
+ // the runs whose execution got its place on the cluster, until it ended: their release
293
+ // removes what they made
294
+ this.placed = new Set();
288
295
  this.access = getClusterAccess(config.backend, processEnvs);
289
296
  this.instance = (0, kubernetes_instance_1.createKubernetesInstances)({
290
297
  type: 'kubernetes',
@@ -316,6 +323,7 @@ class KubernetesExecutor {
316
323
  log: options.log,
317
324
  });
318
325
  }
326
+ this.resuming = new ResumingRuns(config.backend.namespacePrefix, (run) => this.namespaceOf(run));
319
327
  this.host = new executor_1.HostExecutor({ ...options, placement: this.placement() });
320
328
  }
321
329
  // what the namespaces of the server's callers and service runs request and use
@@ -345,6 +353,38 @@ class KubernetesExecutor {
345
353
  });
346
354
  }
347
355
  async execute(run, context) {
356
+ // what a run that resumes left is this execution's from now: the end of a run that got its
357
+ // place on the cluster (release) removes it, the end of one that did not removes it here
358
+ const left = this.resuming.has(run);
359
+ try {
360
+ await this.executeOn(run, context);
361
+ }
362
+ finally {
363
+ const placed = this.placed.delete(run.id);
364
+ if (left && !placed && !(0, runs_1.isDetached)(context)) {
365
+ await this.removeLeft(run);
366
+ }
367
+ }
368
+ }
369
+ // What a run left on the cluster, that no release removes
370
+ async removeLeft(run) {
371
+ const say = (text) => this.log?.(`run=${run.id} ${text}`);
372
+ this.resuming.forget(run);
373
+ try {
374
+ if (!run.up) {
375
+ await this.removeRun(run, getCallerNamespace(this.config.backend.namespacePrefix, run.owner), say);
376
+ return;
377
+ }
378
+ // a namespace is kept only for a run that has one from start to end
379
+ const namespace = this.namespaceOf(run);
380
+ this.asleep.delete(namespace);
381
+ await this.enqueue(namespace, () => this.removeServiceRun(namespace, say));
382
+ }
383
+ catch (e) {
384
+ say(`what the run left could not be removed: ${(0, log_1.getErrorMessage)(e)}`);
385
+ }
386
+ }
387
+ async executeOn(run, context) {
348
388
  if (run.up) {
349
389
  if (run.source.type === 'sandbox') {
350
390
  throw new Error('on a cluster a service run starts from a branch, push the sandbox and start it from there');
@@ -352,6 +392,8 @@ class KubernetesExecutor {
352
392
  // in a namespace of its own, apart from the caller's runs and their claims
353
393
  return this.host.execute(run, context);
354
394
  }
395
+ // it executes: its objects are kept from a tidy as those of any run that executes
396
+ this.resuming.forget(run);
355
397
  const namespace = getCallerNamespace(this.config.backend.namespacePrefix, run.owner);
356
398
  const label = (0, job_placement_1.getRunLabelValue)(run.id);
357
399
  let runs = this.active.get(namespace);
@@ -359,9 +401,7 @@ class KubernetesExecutor {
359
401
  runs = new Map();
360
402
  this.active.set(namespace, runs);
361
403
  }
362
- if (this.holds(run)) {
363
- runs.set(label, getVolumeScope(run));
364
- }
404
+ runs.set(label, this.holds(run) ? getVolumeScope(run) : undefined);
365
405
  // the caller is promised its share while the run executes
366
406
  this.quotas?.enter(namespace, run.id);
367
407
  try {
@@ -372,9 +412,12 @@ class KubernetesExecutor {
372
412
  if (runs.size === 0 && this.active.get(namespace) === runs) {
373
413
  this.active.delete(namespace);
374
414
  }
375
- await this.quotas
376
- ?.leave(namespace, run.id)
377
- .catch((e) => this.log?.(`the quotas could not be worked out again: ${(0, log_1.getErrorMessage)(e)}`));
415
+ // a run the next server resumes still has its Jobs, under the quota it had
416
+ if (!(0, runs_1.isDetached)(context)) {
417
+ await this.quotas
418
+ ?.leave(namespace, run.id)
419
+ .catch((e) => this.log?.(`the quotas could not be worked out again: ${(0, log_1.getErrorMessage)(e)}`));
420
+ }
378
421
  }
379
422
  }
380
423
  // A service run moves to another commit in its namespace: unchanged services stay, the
@@ -390,25 +433,31 @@ class KubernetesExecutor {
390
433
  }
391
434
  /**
392
435
  * A service run that slept with its volumes ended without waking: its namespace goes, with
393
- * the claims in it.
436
+ * the claims in it. A run that resumed after a restart ended: what an execution before the
437
+ * restart left goes, as no execution may have removed it (one cancelled in the queue).
394
438
  */
395
439
  async forget(run) {
396
- if (!run.up) {
397
- return;
398
- }
399
- // a namespace is kept only for a run that has one from start to end
400
- const namespace = getServiceRunNamespace(this.config.backend.namespacePrefix, run.id);
401
- this.asleep.delete(namespace);
402
- await this.enqueue(namespace, () => this.removeServiceRun(namespace, (text) => this.log?.(`run=${run.id} ${text}`)));
440
+ await this.removeLeft(run);
403
441
  }
404
442
  /**
405
- * The service runs of a previous start that sleep with their volumes: their namespaces stay,
406
- * without what runs in them (a server that stopped without putting the run to sleep left
407
- * it). The namespaces of any other service run go.
443
+ * The runs of a previous start that are not over: the service runs that sleep with their
444
+ * volumes, whose namespaces stay without what runs in them (a server that stopped without
445
+ * putting the run to sleep left it), and the runs that resume (queued), whose Jobs and
446
+ * services stay where they are until they execute again or end. The namespaces of any other
447
+ * service run go.
408
448
  */
409
449
  restored(runs) {
450
+ for (const run of runs.filter((candidate) => candidate.state === 'queued')) {
451
+ try {
452
+ this.resuming.add(run, this.holds(run) ? getVolumeScope(run) : undefined);
453
+ }
454
+ catch (e) {
455
+ // its objects are not kept from a sweep, the run does not start for nothing
456
+ this.log?.(`what run ${run.id} left on the cluster is not kept for it: ${(0, log_1.getErrorMessage)(e)}`);
457
+ }
458
+ }
410
459
  if (this.keepServiceRuns) {
411
- for (const run of runs.filter((candidate) => candidate.up)) {
460
+ for (const run of runs.filter((candidate) => candidate.up && candidate.state !== 'queued')) {
412
461
  const namespace = getServiceRunNamespace(this.config.backend.namespacePrefix, run.id);
413
462
  this.asleep.add(namespace);
414
463
  this.enqueue(namespace, () => removeRunObjects(this.instance, namespace, job_placement_1.RUN_LABEL, RELEASE_TIMEOUT, { claims: false })).catch((e) => this.log?.(`what runs in the namespace ${namespace} of run ${run.id} could not be removed: ${(0, log_1.getErrorMessage)(e)}`));
@@ -479,8 +528,12 @@ class KubernetesExecutor {
479
528
  if (this.keep === 0) {
480
529
  return new Set();
481
530
  }
482
- return new Set([...(this.active.get(namespace) ?? new Map()).entries()]
483
- .filter(([label]) => label !== except)
531
+ return new Set([
532
+ ...(this.active.get(namespace) ?? new Map()).entries(),
533
+ // a run that resumes mounts them again
534
+ ...this.resuming.scopes(namespace),
535
+ ]
536
+ .filter(([label, scope]) => label !== except && scope !== undefined)
484
537
  .map(([, scope]) => scope));
485
538
  }
486
539
  // What changes objects of a whole namespace happens one at a time, not what its runs do
@@ -506,6 +559,9 @@ class KubernetesExecutor {
506
559
  }
507
560
  this.serviceRuns.set(namespace, (this.serviceRuns.get(namespace) ?? 0) + 1);
508
561
  this.asleep.delete(namespace);
562
+ // its execution holds the namespace now, and its release removes it
563
+ this.resuming.forget(run);
564
+ this.placed.add(run.id);
509
565
  this.sweepServiceRuns();
510
566
  const up = run.up;
511
567
  // after what a stop of its sleep left in it went (see restored)
@@ -537,7 +593,9 @@ class KubernetesExecutor {
537
593
  // release failed: the objects of a run that does not execute. One that starts
538
594
  // after this waits for it here before it makes any.
539
595
  if (!this.tidy.has(namespace)) {
540
- const running = [...new Set([label, ...(this.active.get(namespace)?.keys() ?? [])])];
596
+ const running = [
597
+ ...new Set([label, ...(this.active.get(namespace)?.keys() ?? []), ...this.resuming.labels(namespace)]),
598
+ ];
541
599
  await removeRunObjects(this.instance, namespace, `${job_placement_1.RUN_LABEL},${job_placement_1.RUN_LABEL} notin (${running.join(',')})`, RELEASE_TIMEOUT);
542
600
  this.tidy.add(namespace);
543
601
  }
@@ -557,6 +615,7 @@ class KubernetesExecutor {
557
615
  // tasks run
558
616
  await this.quotas?.apply(namespace);
559
617
  context.emit({ type: 'log', task: 'hammerkit', stream: 'stdout', text: `runs in the namespace ${namespace}` });
618
+ this.placed.add(run.id);
560
619
  return {
561
620
  kubernetes: this.environmentOf(run, namespace, work, capabilitiesProblem),
562
621
  env: this.access.env,
@@ -599,38 +658,33 @@ class KubernetesExecutor {
599
658
  }
600
659
  return;
601
660
  }
602
- try {
603
- const selector = `${job_placement_1.RUN_LABEL}=${(0, job_placement_1.getRunLabelValue)(run.id)}`;
604
- await removeRunObjects(this.instance, namespace, selector, RELEASE_TIMEOUT);
605
- }
606
- catch (e) {
607
- // the next run removes what is left
608
- this.tidy.delete(namespace);
609
- context.emit({
610
- type: 'log',
611
- task: 'hammerkit',
612
- stream: 'stderr',
613
- text: `what the run made in ${namespace} could not be removed: ${(0, log_1.getErrorMessage)(e)}`,
614
- });
615
- }
616
- if (this.keep > 0) {
617
- try {
618
- await (0, kept_claims_1.expireKeptClaims)(this.instance, namespace, (0, job_placement_1.getRunLabelValue)(run.id), new Date(Date.now() + this.keep));
619
- }
620
- catch (e) {
621
- // without an expiry, the next look at the namespace removes them
622
- context.emit({
623
- type: 'log',
624
- task: 'hammerkit',
625
- stream: 'stderr',
626
- text: `the claims the run kept in ${namespace} could not be given their expiry: ${(0, log_1.getErrorMessage)(e)}`,
627
- });
628
- }
629
- this.sweepLater(namespace, this.keep);
630
- }
661
+ await this.removeRun(run, namespace, (text) => context.emit({ type: 'log', task: 'hammerkit', stream: 'stderr', text }));
631
662
  },
632
663
  };
633
664
  }
665
+ // The end of a run of tasks: what it made in the caller's namespace goes, but for the claims
666
+ // it keeps, which expire from now
667
+ async removeRun(run, namespace, say) {
668
+ try {
669
+ const selector = `${job_placement_1.RUN_LABEL}=${(0, job_placement_1.getRunLabelValue)(run.id)}`;
670
+ await removeRunObjects(this.instance, namespace, selector, RELEASE_TIMEOUT);
671
+ }
672
+ catch (e) {
673
+ // the next run removes what is left
674
+ this.tidy.delete(namespace);
675
+ say(`what the run made in ${namespace} could not be removed: ${(0, log_1.getErrorMessage)(e)}`);
676
+ }
677
+ if (this.keep > 0) {
678
+ try {
679
+ await (0, kept_claims_1.expireKeptClaims)(this.instance, namespace, (0, job_placement_1.getRunLabelValue)(run.id), new Date(Date.now() + this.keep));
680
+ }
681
+ catch (e) {
682
+ // without an expiry, the next look at the namespace removes them
683
+ say(`the claims the run kept in ${namespace} could not be given their expiry: ${(0, log_1.getErrorMessage)(e)}`);
684
+ }
685
+ this.sweepLater(namespace, this.keep);
686
+ }
687
+ }
634
688
  // The cluster as the process of a run sees it: the namespace its tasks and services go in.
635
689
  environmentOf(run, namespace, work, capabilitiesProblem) {
636
690
  const backend = this.config.backend;
@@ -686,6 +740,7 @@ class KubernetesExecutor {
686
740
  isCallerNamespace(this.config.backend.namespacePrefix, name) &&
687
741
  !this.serviceRuns.has(name) &&
688
742
  !this.asleep.has(name) &&
743
+ !this.resuming.keeps(name) &&
689
744
  !namespace.metadata?.deletionTimestamp) {
690
745
  this.log?.(`removing the namespace ${name} of a service run from before the server started`);
691
746
  await removeServiceRunNamespace(this.instance, name, 0);
@@ -747,6 +802,54 @@ class KubernetesExecutor {
747
802
  }
748
803
  }
749
804
  exports.KubernetesExecutor = KubernetesExecutor;
805
+ // What the runs that resume after a restart left on the cluster, which the sweeps leave: the
806
+ // namespaces of service runs, and per caller namespace the runs by run label, with the volume
807
+ // scope of the kept claims they mount
808
+ class ResumingRuns {
809
+ constructor(prefix, namespaceOf) {
810
+ this.prefix = prefix;
811
+ this.namespaceOf = namespaceOf;
812
+ this.serviceRuns = new Set();
813
+ this.runs = new Map();
814
+ }
815
+ add(run, scope) {
816
+ if (run.up) {
817
+ this.serviceRuns.add(this.namespaceOf(run));
818
+ return;
819
+ }
820
+ const namespace = getCallerNamespace(this.prefix, run.owner);
821
+ const runs = this.runs.get(namespace) ?? new Map();
822
+ runs.set((0, job_placement_1.getRunLabelValue)(run.id), scope);
823
+ this.runs.set(namespace, runs);
824
+ }
825
+ has(run) {
826
+ return run.up
827
+ ? this.serviceRuns.has(this.namespaceOf(run))
828
+ : !!this.runs.get(getCallerNamespace(this.prefix, run.owner))?.has((0, job_placement_1.getRunLabelValue)(run.id));
829
+ }
830
+ forget(run) {
831
+ if (run.up) {
832
+ this.serviceRuns.delete(this.namespaceOf(run));
833
+ return;
834
+ }
835
+ const namespace = getCallerNamespace(this.prefix, run.owner);
836
+ const runs = this.runs.get(namespace);
837
+ runs?.delete((0, job_placement_1.getRunLabelValue)(run.id));
838
+ if (runs?.size === 0) {
839
+ this.runs.delete(namespace);
840
+ }
841
+ }
842
+ // whether the namespace of a service run is kept for it
843
+ keeps(namespace) {
844
+ return this.serviceRuns.has(namespace);
845
+ }
846
+ labels(namespace) {
847
+ return [...(this.runs.get(namespace)?.keys() ?? [])];
848
+ }
849
+ scopes(namespace) {
850
+ return [...(this.runs.get(namespace)?.entries() ?? [])];
851
+ }
852
+ }
750
853
  const ENFORCE_LABEL = 'pod-security.kubernetes.io/enforce';
751
854
  const AUDIT_LABEL = 'pod-security.kubernetes.io/audit';
752
855
  /**
@@ -113,6 +113,23 @@ class LogIndex {
113
113
  lines(task) {
114
114
  return this.taskLines.get(task) ?? [];
115
115
  }
116
+ // How many lines of the log, or of one task, the first `count` events hold
117
+ linesBefore(count, task) {
118
+ const lines = task !== undefined ? this.lines(task) : undefined;
119
+ let low = 0;
120
+ let high = lines ? lines.length : this.size;
121
+ // the lines are in the order of their events
122
+ while (low < high) {
123
+ const middle = (low + high) >> 1;
124
+ if (this.lineEvent[lines ? lines[middle] : middle] < count) {
125
+ low = middle + 1;
126
+ }
127
+ else {
128
+ high = middle;
129
+ }
130
+ }
131
+ return low;
132
+ }
116
133
  text(events, line) {
117
134
  const event = events[this.lineEvent[line]];
118
135
  return { task: event.task, stream: event.stream, text: event.text.slice(this.lineStart[line], this.lineEnd[line]) };
@@ -145,9 +162,15 @@ class LogIndex {
145
162
  }
146
163
  exports.LogIndex = LogIndex;
147
164
  // The lines of the log a query selects, see LogQuery.
148
- function readLogs(events, index, query, truncated) {
165
+ // `lostAfter`: Run.lostAfter
166
+ function readLogs(events, index, query, truncated, lostAfter) {
149
167
  const selected = query.task !== undefined ? index.lines(query.task) : undefined;
150
168
  const total = selected ? selected.length : index.size;
169
+ const lost = lostAfter !== undefined
170
+ ? index.linesBefore(lostAfter, query.task) + 1
171
+ : query.from !== undefined && query.from > total + 1
172
+ ? total + 1
173
+ : undefined;
151
174
  const at = (position) => (selected ? selected[position] : position);
152
175
  const hits = query.grep !== undefined ? index.matches(events, query.grep, query.ignoreCase) : undefined;
153
176
  const toLine = (position) => ({
@@ -215,6 +238,7 @@ function readLogs(events, index, query, truncated) {
215
238
  total,
216
239
  ...(next !== undefined ? { next } : {}),
217
240
  truncated,
241
+ ...(lost !== undefined ? { lost } : {}),
218
242
  };
219
243
  }
220
244
  exports.readLogs = readLogs;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.unavailableExecutor = exports.RunRegistry = exports.MAX_COMMANDS = exports.MAX_TASK_ERROR = exports.MAX_CAUSES = exports.SANDBOX_ID_PATTERN = exports.RUN_ID_PATTERN = exports.QuotaError = exports.ShuttingDownError = exports.RunError = exports.RUN_PHASES = exports.isFinal = void 0;
3
+ exports.unavailableExecutor = exports.RunRegistry = exports.MAX_COMMANDS = exports.MAX_TASK_ERROR = exports.MAX_CAUSES = exports.MAX_RESUMES = exports.CLOSE_TIMEOUT = exports.SANDBOX_ID_PATTERN = exports.RUN_ID_PATTERN = exports.QuotaError = exports.ShuttingDownError = exports.RunError = exports.isDetached = exports.RUN_PHASES = exports.isFinal = void 0;
4
4
  const crypto_1 = require("crypto");
5
5
  const oauth_1 = require("./oauth");
6
6
  const run_logs_1 = require("./run-logs");
@@ -30,6 +30,11 @@ function ranFor(result) {
30
30
  }
31
31
  return result.durationMs;
32
32
  }
33
+ // Whether the server stops and leaves the run to the next one (RunContext.detached)
34
+ function isDetached(context) {
35
+ return context.signal.aborted && !!context.detached?.();
36
+ }
37
+ exports.isDetached = isDetached;
33
38
  // The server can not take the run now; `status` is what the caller is told
34
39
  class RunError extends Error {
35
40
  constructor() {
@@ -79,6 +84,18 @@ function servicePlaces(runs, asleep = false) {
79
84
  function onSandbox(run, sandbox) {
80
85
  return run.source.type === 'sandbox' && run.source.id === sandbox;
81
86
  }
87
+ // How long a server that stops waits for the executions it detaches: a pod gets 30s by
88
+ // default, and the records are written after. The process of a detached run gets less than
89
+ // this to stop its tasks on a host (DETACH_GRACE_MS in executor.ts), so what its execution
90
+ // does after (its directory, a release of its volumes) fits too. A server without a store
91
+ // cancels its runs and waits for them as long as they take (STOP_GRACE_MS, then a kill).
92
+ exports.CLOSE_TIMEOUT = 15000;
93
+ // how often the record of a run that executes is written while it says something
94
+ const PERSIST_EVERY = 2000;
95
+ // how often a run is resumed in a row without getting anywhere, then it fails
96
+ exports.MAX_RESUMES = 3;
97
+ // what a move that waited or executed when the server stopped says
98
+ const MOVE_LOST = 'not applied, the server restarted';
82
99
  // the tasks of a run whose check keys are kept, a build file has fewer
83
100
  const MAX_KEYED_TASKS = 1000;
84
101
  // how much of the end of a task's output its result carries
@@ -122,6 +139,50 @@ function taskEventSize(event) {
122
139
  const causes = (event.causes ?? []).reduce((sum, cause) => sum + Buffer.byteLength(cause) + 4, 0);
123
140
  return 64 + causes + Buffer.byteLength(event.error ?? '') + (event.commands?.length ?? 0) * 64;
124
141
  }
142
+ // what an event weighs against the log limits of a run; a state change weighs nothing, it is
143
+ // always kept
144
+ function eventSize(event) {
145
+ if (event.type === 'state') {
146
+ return 0;
147
+ }
148
+ return event.type === 'log' ? Buffer.byteLength(event.text) + 64 : event.type === 'task' ? taskEventSize(event) : 64;
149
+ }
150
+ // The check keys of a record, as the registry keeps them: by task, a key or null
151
+ function checkKeys(keys) {
152
+ if (!keys || typeof keys !== 'object' || Array.isArray(keys)) {
153
+ return {};
154
+ }
155
+ return Object.fromEntries(Object.entries(keys)
156
+ .filter(([, key]) => key === null || typeof key === 'string')
157
+ .slice(0, MAX_KEYED_TASKS));
158
+ }
159
+ // What keeps the run of a record from executing again: what it runs, from where, is not in it
160
+ function unresumable(run) {
161
+ if (typeof run.id !== 'string' || !exports.RUN_ID_PATTERN.test(run.id)) {
162
+ return 'its id is not one of a run';
163
+ }
164
+ if (!run.owner || typeof run.owner.iss !== 'string' || typeof run.owner.sub !== 'string') {
165
+ return 'it names no owner';
166
+ }
167
+ if (typeof run.definition !== 'string') {
168
+ return 'it names no build file';
169
+ }
170
+ if (!Array.isArray(run.tasks) || !Array.isArray(run.accounts) || !run.options || typeof run.options !== 'object') {
171
+ return 'it names no tasks';
172
+ }
173
+ if (!run.source || !['ref', 'upload', 'sandbox'].includes(run.source.type)) {
174
+ return 'it names no source';
175
+ }
176
+ if (run.up &&
177
+ (typeof run.up.name !== 'string' ||
178
+ !Array.isArray(run.up.services) ||
179
+ !run.up.services.every((service) => typeof service === 'string') ||
180
+ !Array.isArray(run.up.endpoints) ||
181
+ !run.up.endpoints.every((endpoint) => endpoint && typeof endpoint.host === 'string'))) {
182
+ return 'it names no services';
183
+ }
184
+ return undefined;
185
+ }
125
186
  // Where runs are kept while the server is up. Everything is scoped to the
126
187
  // caller that submitted the run: the same id asked for by someone else is
127
188
  // "not found", so ids can't be used to find out which runs exist.
@@ -134,10 +195,15 @@ class RunRegistry {
134
195
  this.closed = false;
135
196
  // callers that wait for a run to finish, let go when the server stops
136
197
  this.waiters = new Set();
137
- // the moves of service runs that execute beside their services
138
- this.moving = new Set();
198
+ // the executions of runs, until they ended, and the moves of service runs that execute
199
+ // beside their services
200
+ this.executions = new Map();
201
+ this.moving = new Map();
139
202
  // the records of evicted runs still being removed from the store, waited for by close
140
203
  this.removing = new Set();
204
+ // close wrote every run down with all it said: a later write (a stop, an extend, a run that
205
+ // ends after the server stopped waiting for it) has it all too
206
+ this.written = false;
141
207
  this.maxConcurrent = options.maxConcurrent ?? 4;
142
208
  this.keep = options.keep ?? 200;
143
209
  this.maxEvents = options.maxEvents ?? 5000;
@@ -148,8 +214,8 @@ class RunRegistry {
148
214
  }
149
215
  /**
150
216
  * Takes back the runs of a previous start. Those that waited for an approval wait
151
- * again, for what is left of their time; those that were queued or running when the
152
- * server stopped failed with it, and say so.
217
+ * again, for what is left of their time, and those that were asleep sleep on. Those that
218
+ * were queued, running or up go back in the queue under their id (resume).
153
219
  */
154
220
  async restore() {
155
221
  const store = this.options.store;
@@ -159,8 +225,10 @@ class RunRegistry {
159
225
  return;
160
226
  }
161
227
  const { records, skipped } = await store.load();
228
+ // the queue as it was: the runs that executed first, then the others as they were queued
229
+ const resuming = [];
162
230
  skipped.forEach((name) => this.options.log?.(`skip run record ${name}: it can not be read`));
163
- for (const { run, events } of records) {
231
+ for (const { run, events, keys, clean } of records) {
164
232
  // a move that executed went with the server
165
233
  delete run.moving;
166
234
  const entry = {
@@ -172,7 +240,7 @@ class RunRegistry {
172
240
  bytes: 0,
173
241
  tails: new Map(Object.entries(run.results ?? {}).map(([task, result]) => [task, result.lastLog])),
174
242
  saving: Promise.resolve(),
175
- keys: {},
243
+ keys: checkKeys(keys),
176
244
  };
177
245
  this.entries.set(run.id, entry);
178
246
  if (run.state === 'awaiting-approval') {
@@ -185,41 +253,109 @@ class RunRegistry {
185
253
  this.finish(entry, 'rejected', 'nobody approved it in time');
186
254
  }
187
255
  }
188
- else if (this.maySleep(entry) && ['queued', 'running', 'up', 'asleep'].includes(run.state)) {
189
- // the services went with the process that held them, the next request wakes them
190
- if (run.state === 'queued' || run.state === 'running' || run.state === 'up') {
191
- // a server that stopped without putting the run to sleep left its volumes where they
192
- // were, for the wake to mount
193
- if (this.keepsVolumes()) {
194
- run.volumesKept = true;
256
+ else if (run.state === 'asleep') {
257
+ if (this.maySleep(entry)) {
258
+ this.expireLater(entry);
259
+ if (!this.keepsVolumes()) {
260
+ // the backend no longer keeps them, the sweep below removes them
261
+ delete run.volumesKept;
195
262
  }
196
- this.sleep(entry);
197
263
  }
198
264
  else {
199
- this.expireLater(entry);
200
- }
201
- if (!this.keepsVolumes()) {
202
- // the backend no longer keeps them, the sweep below removes them
203
- delete run.volumesKept;
265
+ // its time ran out while the server was down: it ends now, and gives its place back
266
+ run.stoppedBy ?? (run.stoppedBy = 'ttl');
267
+ this.finish(entry, 'succeeded');
204
268
  }
205
269
  }
206
- else if (run.state === 'asleep') {
207
- // its time ran out while the server was down: it ends now, and gives its place back
208
- run.stoppedBy ?? (run.stoppedBy = 'ttl');
209
- this.finish(entry, 'succeeded');
270
+ else if (run.state === 'queued' || run.state === 'running' || run.state === 'up') {
271
+ resuming.push({
272
+ entry,
273
+ executed: run.state !== 'queued',
274
+ queuedAt: String(run.queuedAt ?? run.createdAt ?? ''),
275
+ clean: clean === true,
276
+ });
210
277
  }
211
- else if (run.state === 'queued' || run.state === 'running') {
212
- this.finish(entry, 'failed', `the server stopped while the run was ${run.state}, submit it again`);
278
+ }
279
+ resuming
280
+ .sort((a, b) => Number(b.executed) - Number(a.executed) || a.queuedAt.localeCompare(b.queuedAt))
281
+ .forEach(({ entry, clean }) => this.resume(entry, clean));
282
+ this.evict();
283
+ try {
284
+ this.options.executor.restored?.([...this.entries.values()]
285
+ .filter((entry) => !isFinal(entry.run.state) && (entry.run.volumesKept || entry.resumed))
286
+ .map((entry) => this.copy(entry.run)));
287
+ }
288
+ catch (e) {
289
+ // the server starts all the same, what the backend kept is looked at again on the next start
290
+ this.options.log?.(`the backend could not take back what it kept: ${e instanceof Error ? e.message : e}`);
291
+ }
292
+ this.dispatch();
293
+ }
294
+ // A run that was queued or executing when the server stopped goes back in the queue, under
295
+ // its id and with what it was pinned to; its tasks that finished are taken from the cache.
296
+ // It ends instead when it was to end: a cancel or a stop came while the server stopped, its
297
+ // time ran out, or it took the server down too often. One that can not be read fails.
298
+ // `clean`: the server that stopped wrote it down with all it said.
299
+ resume(entry, clean) {
300
+ const run = entry.run;
301
+ const was = run.state;
302
+ // what an execution before the restart left goes when the run ends before it executes again
303
+ entry.resumed = !!run.startedAt;
304
+ const unreadable = unresumable(run);
305
+ if (unreadable) {
306
+ // enough of a run to show how it ended, to nobody when its owner is not known
307
+ if (!run.owner || typeof run.owner.iss !== 'string' || typeof run.owner.sub !== 'string') {
308
+ run.owner = { iss: '', sub: '' };
213
309
  }
214
- else if (run.state === 'up') {
215
- // the services went with the process that held them
216
- this.finish(entry, 'failed', 'the server stopped while the services were up, start them again');
310
+ run.tasks = Array.isArray(run.tasks) ? run.tasks : [];
311
+ run.accounts = Array.isArray(run.accounts) ? run.accounts : [];
312
+ run.options = run.options && typeof run.options === 'object' ? run.options : {};
313
+ if (!run.source || typeof run.source !== 'object') {
314
+ run.source = { type: 'upload', snapshot: '' };
217
315
  }
316
+ this.finish(entry, 'failed', `the server stopped while the run was ${was} and its record can not resume it: ${unreadable}, submit it again`);
317
+ return;
218
318
  }
219
- this.evict();
220
- this.options.executor.restored?.([...this.entries.values()]
221
- .filter((entry) => entry.run.volumesKept && !isFinal(entry.run.state))
222
- .map((entry) => this.copy(entry.run)));
319
+ if (run.cancelling) {
320
+ this.finish(entry, 'cancelled');
321
+ return;
322
+ }
323
+ if (run.up && run.stoppedBy) {
324
+ // stopped while it was up, or replaced
325
+ this.finish(entry, 'succeeded');
326
+ return;
327
+ }
328
+ if (run.up && run.upAt && !(Date.parse(run.expiresAt ?? '') > this.now())) {
329
+ run.stoppedBy = 'ttl';
330
+ this.finish(entry, 'succeeded');
331
+ return;
332
+ }
333
+ // the time a run gets counts from its first start; a service run that was up gets it again
334
+ const limit = this.options.maxDuration;
335
+ if (limit && run.startedAt && !run.upAt && this.now() - Date.parse(run.startedAt) >= limit) {
336
+ this.finish(entry, 'failed', this.tooLong());
337
+ return;
338
+ }
339
+ if (was !== 'queued') {
340
+ run.resumes = (run.resumes ?? 0) + 1;
341
+ if (run.resumes > exports.MAX_RESUMES) {
342
+ this.finish(entry, 'failed', `the server stopped ${run.resumes} times in a row while the run was ${was}, it is not resumed again, submit it again`);
343
+ return;
344
+ }
345
+ if (!clean) {
346
+ // a server that was killed: what the run said since it was last written down is gone
347
+ run.lostAfter = entry.events.length;
348
+ }
349
+ }
350
+ // what it said counts against its limits as before
351
+ entry.bytes = entry.events.reduce((sum, event) => sum + eventSize(event), 0);
352
+ delete run.sleepsAt;
353
+ run.state = 'queued';
354
+ run.queuedAt = this.timestamp();
355
+ const lost = was !== 'queued' && !clean ? ', the last of its log before is lost' : '';
356
+ this.record(entry, { type: 'log', task: 'hammerkit', stream: 'stdout', text: `resumed after a server restart${lost}` }, true);
357
+ this.record(entry, { type: 'state', state: 'queued' });
358
+ this.queue.push(entry);
223
359
  }
224
360
  // A run that needs approvals (for the accounts named) waits for them, the others
225
361
  // are queued at once.
@@ -492,12 +628,16 @@ class RunRegistry {
492
628
  this.finish(entry, 'cancelled', reason);
493
629
  }
494
630
  else if (entry.run.state === 'running') {
631
+ // written down at once: a server that stops before the run did ends it on its next start
632
+ entry.run.cancelling = true;
633
+ this.persist(entry);
495
634
  entry.abort.abort();
496
635
  }
497
636
  else if (entry.run.state === 'up') {
498
637
  (_a = entry.run).stoppedBy ?? (_a.stoppedBy = by ?? 'replaced');
499
638
  entry.sleeping = false;
500
639
  entry.restartTo = undefined;
640
+ this.persist(entry);
501
641
  entry.mover?.abort.abort();
502
642
  entry.abort.abort();
503
643
  }
@@ -574,7 +714,11 @@ class RunRegistry {
574
714
  if (!entry) {
575
715
  return undefined;
576
716
  }
577
- const events = entry.events.filter((event) => event.seq > after);
717
+ // a cursor past the end comes from a server that was killed after it sent what it did not
718
+ // write down: those events are gone, the ones said again since have their numbers
719
+ const last = entry.events.length;
720
+ const from = after > last ? Math.min(entry.run.lostAfter ?? last, last) : after;
721
+ const events = entry.events.filter((event) => event.seq > from);
578
722
  const finished = FINAL_STATES.includes(entry.run.state);
579
723
  if (!finished) {
580
724
  entry.listeners.add(listener);
@@ -622,46 +766,47 @@ class RunRegistry {
622
766
  if (!entry) {
623
767
  return undefined;
624
768
  }
625
- // only the events since the last read are looked at
626
- entry.index ?? (entry.index = new run_logs_1.LogIndex());
627
- entry.index.update(entry.events);
628
- return { events: entry.events, index: entry.index, truncated: entry.truncated };
769
+ return this.logOf(entry);
629
770
  }
630
771
  // The log of any run, for a caller whose right to read it was checked already (an
631
772
  // entitlement with `observe`).
632
773
  logsOf(id) {
633
774
  const entry = this.entries.get(id);
634
- if (!entry) {
635
- return undefined;
636
- }
775
+ return entry ? this.logOf(entry) : undefined;
776
+ }
777
+ logOf(entry) {
778
+ // only the events since the last read are looked at
637
779
  entry.index ?? (entry.index = new run_logs_1.LogIndex());
638
780
  entry.index.update(entry.events);
639
- return { events: entry.events, index: entry.index, truncated: entry.truncated };
781
+ return {
782
+ events: entry.events,
783
+ index: entry.index,
784
+ truncated: entry.truncated,
785
+ ...(entry.run.lostAfter !== undefined ? { lostAfter: entry.run.lostAfter } : {}),
786
+ };
640
787
  }
641
- // Stops accepting runs and aborts the ones in flight.
788
+ /**
789
+ * Stops accepting runs. Without a store the runs in flight are cancelled. With one they are
790
+ * detached: a queued run stays in the queue of its record, and a running one or a service
791
+ * run that is up stops its execution without cancelling what it started (RunContext.detached).
792
+ * The next start takes them all back (restore). The executions get `closeTimeout` to stop,
793
+ * then every run is written down as it is.
794
+ */
642
795
  async close() {
643
796
  this.closed = true;
797
+ const detach = !!this.options.store;
644
798
  for (const entry of this.queue.splice(0)) {
645
- if (this.maySleep(entry) && this.options.store) {
646
- // a woken service run sleeps again, the next start keeps it
647
- this.sleep(entry);
648
- }
649
- else {
799
+ if (!detach) {
650
800
  this.finish(entry, 'cancelled');
651
801
  }
652
802
  }
653
803
  for (const entry of this.entries.values()) {
654
- if (entry.run.state === 'asleep') {
655
- this.clearTimer(entry);
804
+ if (entry.run.state === 'awaiting-approval' && !detach) {
805
+ this.finish(entry, 'cancelled');
656
806
  }
657
- else if (entry.run.state === 'awaiting-approval') {
658
- if (this.options.store) {
659
- // the record keeps it waiting, the next start takes it back
660
- this.clearTimer(entry);
661
- }
662
- else {
663
- this.finish(entry, 'cancelled');
664
- }
807
+ else if (!isFinal(entry.run.state)) {
808
+ // the record keeps it waiting, asleep or up; the next start takes it back, with its time
809
+ this.clearTimer(entry);
665
810
  }
666
811
  }
667
812
  // who waits for a run that waits for an approval is told how it stands now
@@ -669,19 +814,44 @@ class RunRegistry {
669
814
  done();
670
815
  }
671
816
  for (const entry of this.entries.values()) {
817
+ if (detach && !isFinal(entry.run.state)) {
818
+ // the next server starts the run at the commit it is at
819
+ this.dropMove(entry);
820
+ }
672
821
  if (entry.run.state === 'running' || entry.run.state === 'up') {
673
- // a service run that may sleep is asleep in its record, the next request after the
674
- // start wakes it
675
- entry.sleeping = this.maySleep(entry) && !!this.options.store;
822
+ // one that stops already (a cancel, its ttl, a sleep, a move) ends as it would
823
+ if (detach && !entry.abort.signal.aborted) {
824
+ entry.detached = true;
825
+ clearTimeout(entry.durationTimer);
826
+ }
676
827
  entry.mover?.abort.abort();
677
828
  entry.abort.abort();
678
829
  }
679
830
  }
680
- while (this.running > 0 ||
681
- this.moving.size > 0 ||
682
- [...this.entries.values()].some((entry) => entry.run.state === 'running' || entry.run.state === 'up')) {
831
+ // a server without a store waits for its cancels to clean up, however long they take
832
+ const deadline = detach ? Date.now() + (this.options.closeTimeout ?? exports.CLOSE_TIMEOUT) : Infinity;
833
+ const stopping = () => new Set([
834
+ ...this.executions.values(),
835
+ ...this.moving.values(),
836
+ ...[...this.entries.values()].filter((entry) => (entry.run.state === 'running' || entry.run.state === 'up') && !entry.detached),
837
+ ]);
838
+ while (stopping().size > 0 && Date.now() < deadline) {
683
839
  await new Promise((resolve) => setTimeout(resolve, 10));
684
840
  }
841
+ const left = stopping().size;
842
+ if (left > 0) {
843
+ this.options.log?.(`the server stops while ${left} ${left === 1 ? 'run still stops, it is' : 'runs still stop, they are'} written down as ${left === 1 ? 'it is' : 'they are'}`);
844
+ }
845
+ if (detach) {
846
+ // with all they said, for the start that resumes them
847
+ this.written = true;
848
+ for (const entry of this.entries.values()) {
849
+ clearTimeout(entry.persistTimer);
850
+ if (!isFinal(entry.run.state)) {
851
+ this.persist(entry, true);
852
+ }
853
+ }
854
+ }
685
855
  // the runs that were stopped are written down before the server is gone, and the records
686
856
  // of evicted runs are gone from the store
687
857
  await Promise.all([...this.entries.values()].map((entry) => entry.saving));
@@ -860,7 +1030,8 @@ class RunRegistry {
860
1030
  // does not keep the others from the machine. A run on a sandbox another run works on
861
1031
  // waits for it, as does one that needs what an executing run holds.
862
1032
  dispatch() {
863
- while (this.running < this.maxConcurrent) {
1033
+ // the runs left in the queue start with the next server
1034
+ while (this.running < this.maxConcurrent && !this.closed) {
864
1035
  const perCaller = this.options.limits?.running ?? Infinity;
865
1036
  const index = this.queue.findIndex((entry) => this.runningOf(entry.run.owner) < perCaller && !this.sandboxBusy(entry.run) && !this.held(entry.run));
866
1037
  if (index < 0) {
@@ -874,26 +1045,35 @@ class RunRegistry {
874
1045
  }
875
1046
  const [entry] = this.queue.splice(index, 1);
876
1047
  this.running++;
877
- this.execute(entry).finally(() => {
1048
+ const execution = this.execute(entry).finally(() => {
1049
+ this.executions.delete(execution);
878
1050
  // a service run that is up gave its place back already
879
1051
  if (!entry.released) {
880
1052
  this.running--;
881
1053
  }
882
1054
  this.dispatch();
883
1055
  });
1056
+ this.executions.set(execution, entry);
884
1057
  }
885
1058
  }
886
1059
  async execute(entry) {
1060
+ // a run that resumes executes again: what it left is this execution's to remove, and its
1061
+ // time counts from its first start (a service run that was up gets it again)
1062
+ const continues = entry.resumed && !!entry.run.startedAt && !entry.run.upAt;
1063
+ entry.resumed = false;
887
1064
  entry.run.state = 'running';
888
- entry.run.startedAt = this.timestamp();
1065
+ if (!continues) {
1066
+ entry.run.startedAt = this.timestamp();
1067
+ }
889
1068
  this.record(entry, { type: 'state', state: 'running' });
890
1069
  // a service run gets this long to be up, then its ttl counts
891
1070
  const limit = this.options.maxDuration;
1071
+ const ran = continues ? Math.max(0, this.now() - Date.parse(entry.run.startedAt)) : 0;
892
1072
  entry.durationTimer = limit
893
1073
  ? setTimeout(() => {
894
1074
  entry.timedOut = true;
895
1075
  entry.abort.abort();
896
- }, limit)
1076
+ }, Math.max(0, limit - ran))
897
1077
  : undefined;
898
1078
  entry.durationTimer?.unref();
899
1079
  const token = {};
@@ -908,6 +1088,7 @@ class RunRegistry {
908
1088
  await this.options.executor.execute(run, {
909
1089
  emit: (event) => this.record(entry, event),
910
1090
  signal: entry.abort.signal,
1091
+ detached: () => !!entry.detached,
911
1092
  ...(Object.keys(durations).length > 0 ? { durations } : {}),
912
1093
  ...(this.options.artifacts && !entry.run.up
913
1094
  ? {
@@ -924,8 +1105,8 @@ class RunRegistry {
924
1105
  }
925
1106
  : {}),
926
1107
  });
927
- if (entry.holder !== token) {
928
- // a move took the services over
1108
+ if (entry.holder !== token || entry.detached) {
1109
+ // a move took the services over, or the run resumes with the next server
929
1110
  return;
930
1111
  }
931
1112
  if (this.fallBack(entry, entry.timedOut ? this.tooLong() : 'its services stopped before they were up')) {
@@ -944,7 +1125,7 @@ class RunRegistry {
944
1125
  }
945
1126
  catch (e) {
946
1127
  const message = e instanceof Error ? e.message : String(e);
947
- if (entry.holder !== token) {
1128
+ if (entry.holder !== token || entry.detached) {
948
1129
  return;
949
1130
  }
950
1131
  if (this.fallBack(entry, entry.timedOut ? this.tooLong() : message)) {
@@ -983,6 +1164,7 @@ class RunRegistry {
983
1164
  this.moveTo(entry, landing.change);
984
1165
  }
985
1166
  entry.run.state = 'up';
1167
+ delete entry.run.resumes;
986
1168
  // one reading of the clock, so the ttl is exactly expiresAt - upAt
987
1169
  const now = this.now();
988
1170
  // the ttl counts from the first time, not from a wake
@@ -1189,7 +1371,7 @@ class RunRegistry {
1189
1371
  ...(change.plan ? { plan: change.plan } : {}),
1190
1372
  };
1191
1373
  const execution = this.executeMove(entry, token, abort, run);
1192
- this.moving.add(execution);
1374
+ this.moving.set(execution, entry);
1193
1375
  void execution.finally(() => this.moving.delete(execution));
1194
1376
  }
1195
1377
  // A move beside the services of a run that is up: once its services are ready it holds them
@@ -1200,6 +1382,7 @@ class RunRegistry {
1200
1382
  await this.options.executor.execute(run, {
1201
1383
  emit: (event) => this.record(entry, event),
1202
1384
  signal: abort.signal,
1385
+ detached: () => !!entry.detached,
1203
1386
  up: (targets) => this.moved(entry, token, targets),
1204
1387
  keep: () => (entry.holder === token ? this.keepOf(entry) : 'everything'),
1205
1388
  });
@@ -1213,6 +1396,10 @@ class RunRegistry {
1213
1396
  failure = `the move took longer than ${(0, units_1.formatDuration)(this.options.maxDuration)} and was stopped`;
1214
1397
  }
1215
1398
  this.releaseMover(mover);
1399
+ if (entry.detached) {
1400
+ // the run resumes with the next server, at the commit it is at
1401
+ return;
1402
+ }
1216
1403
  if (entry.holder === token) {
1217
1404
  // the run's services were this execution's
1218
1405
  if (entry.restartTo || entry.sleeping) {
@@ -1280,12 +1467,7 @@ class RunRegistry {
1280
1467
  if (this.closed) {
1281
1468
  // the record keeps it asleep, at the commit it was up at
1282
1469
  this.moveTo(entry, restart, 'the server stopped before the services were up at the commit');
1283
- if (this.maySleep(entry) && this.options.store) {
1284
- this.sleep(entry);
1285
- }
1286
- else {
1287
- this.finish(entry, 'failed', 'the server stopped while the services were up, start them again');
1288
- }
1470
+ this.leaveForRestart(entry);
1289
1471
  return;
1290
1472
  }
1291
1473
  // up at its commit, the run is there (markUp); else it goes back (fallBack)
@@ -1322,17 +1504,49 @@ class RunRegistry {
1322
1504
  text: `did not get up at ${landing.change.source.commit}, starting again at ${from.commit}: ${error}`,
1323
1505
  });
1324
1506
  if (this.closed) {
1325
- if (this.maySleep(entry) && this.options.store) {
1326
- this.sleep(entry);
1327
- }
1328
- else {
1329
- this.finish(entry, 'failed', 'the server stopped while the services were up, start them again');
1330
- }
1507
+ this.leaveForRestart(entry);
1331
1508
  return true;
1332
1509
  }
1333
1510
  this.requeue(entry);
1334
1511
  return true;
1335
1512
  }
1513
+ // The server stops: a move that waits, executes beside the services or starts them at its
1514
+ // commit does not get there, the run stays at the commit it is at and says so
1515
+ dropMove(entry) {
1516
+ const landing = entry.landing && !entry.landing.recorded ? entry.landing : undefined;
1517
+ const change = entry.mover?.change ?? entry.pendingMove ?? landing?.change;
1518
+ if (!change) {
1519
+ return;
1520
+ }
1521
+ entry.pendingMove = undefined;
1522
+ if (landing) {
1523
+ entry.landing = undefined;
1524
+ entry.run.source = { ...landing.from.source };
1525
+ if (landing.from.plan) {
1526
+ entry.run.plan = landing.from.plan;
1527
+ }
1528
+ }
1529
+ // the execution of a move ends with the server, its record says where it got
1530
+ const mover = entry.mover;
1531
+ entry.mover = undefined;
1532
+ this.moveTo(entry, change, MOVE_LOST);
1533
+ entry.mover = mover;
1534
+ }
1535
+ // The server stops while the services of a run stop to start again at another commit: it
1536
+ // sleeps in its record if it may, else the next server resumes it at the commit it was up at
1537
+ leaveForRestart(entry) {
1538
+ if (this.maySleep(entry) && this.options.store) {
1539
+ this.sleep(entry);
1540
+ }
1541
+ else if (this.options.store) {
1542
+ entry.targets = undefined;
1543
+ entry.run.state = 'queued';
1544
+ this.record(entry, { type: 'state', state: 'queued' });
1545
+ }
1546
+ else {
1547
+ this.finish(entry, 'failed', 'the server stopped while the services were up, start them again');
1548
+ }
1549
+ }
1336
1550
  // where a run that moves goes back to: the commit it is at (service runs start from a ref)
1337
1551
  landingFrom(entry) {
1338
1552
  return {
@@ -1401,8 +1615,8 @@ class RunRegistry {
1401
1615
  // the record, so the volumes are removed (RunExecutor.forget) when the run ends asleep, or
1402
1616
  // when a stop came after the sleep began.
1403
1617
  keepOf(entry) {
1404
- // a run that starts again at another commit keeps them on any server
1405
- if (entry.restartTo || entry.landing || (entry.sleeping && this.keepsVolumes())) {
1618
+ // a run that starts again at another commit, or with the next server, keeps them on any server
1619
+ if (entry.restartTo || entry.landing || entry.detached || (entry.sleeping && this.keepsVolumes())) {
1406
1620
  entry.run.volumesKept = true;
1407
1621
  return 'volumes';
1408
1622
  }
@@ -1439,7 +1653,7 @@ class RunRegistry {
1439
1653
  }
1440
1654
  const sleepTtl = entry.run.up.sleepTtl;
1441
1655
  if (entry.run.state === 'up' && sleepTtl) {
1442
- // only kept in memory: a server that stops puts the run to sleep anyway
1656
+ // only kept in memory: a run that resumes after a restart is up for its sleepTtl from then
1443
1657
  entry.run.sleepsAt = new Date(this.now() + sleepTtl).toISOString();
1444
1658
  return undefined;
1445
1659
  }
@@ -1475,7 +1689,7 @@ class RunRegistry {
1475
1689
  return undefined;
1476
1690
  }
1477
1691
  // The end of a run that was up: stopped by somebody, its ttl or a newer run it succeeded,
1478
- // stopped by the server going away it failed, as its record says after a restart.
1692
+ // stopped by a server without a store going away it failed (one with a store detaches it).
1479
1693
  endServices(entry, failure) {
1480
1694
  if (entry.timedOut) {
1481
1695
  this.finish(entry, 'failed', this.tooLong());
@@ -1503,14 +1717,17 @@ class RunRegistry {
1503
1717
  entry.mover?.abort.abort();
1504
1718
  entry.mover = undefined;
1505
1719
  delete entry.run.moving;
1506
- if (entry.run.volumesKept) {
1507
- // it ends without waking: what was kept for it goes
1720
+ if (entry.run.volumesKept || entry.resumed) {
1721
+ // it ends without waking, or after a restart: what was kept for it, or what an execution
1722
+ // before the restart left, goes
1508
1723
  delete entry.run.volumesKept;
1724
+ entry.resumed = false;
1509
1725
  const run = this.copy(entry.run);
1510
1726
  Promise.resolve()
1511
1727
  .then(() => this.options.executor.forget?.(run))
1512
1728
  .catch((e) => this.options.log?.(`the volumes run ${run.id} kept could not be removed: ${e instanceof Error ? e.message : e}`));
1513
1729
  }
1730
+ delete entry.run.cancelling;
1514
1731
  entry.run.state = state;
1515
1732
  entry.run.finishedAt = this.timestamp();
1516
1733
  if (error) {
@@ -1552,11 +1769,15 @@ class RunRegistry {
1552
1769
  }
1553
1770
  else if (event.type === 'task') {
1554
1771
  this.keepResult(entry, event);
1772
+ if (event.state === 'succeeded' || event.state === 'failed') {
1773
+ // it got somewhere since the last restart
1774
+ delete entry.run.resumes;
1775
+ }
1555
1776
  }
1556
1777
  // an executor that keeps talking can't fill the memory of the server or its disk; the
1557
1778
  // state changes, which are few, are always kept, and the results above are kept apart
1558
1779
  if (!force && event.type !== 'state') {
1559
- const size = event.type === 'log' ? Buffer.byteLength(event.text) + 64 : event.type === 'task' ? taskEventSize(event) : 64;
1780
+ const size = eventSize(event);
1560
1781
  if (entry.events.length >= this.maxEvents || entry.bytes + size > this.maxLogBytes) {
1561
1782
  if (!entry.truncated) {
1562
1783
  entry.truncated = true;
@@ -1639,18 +1860,32 @@ class RunRegistry {
1639
1860
  for (const listener of entry.listeners) {
1640
1861
  listener(stored);
1641
1862
  }
1642
- // what a restart must not lose: the runs that wait, and how a run ended. A running
1643
- // run is not kept up to date, it fails with the server.
1863
+ // what a restart must not lose: the runs that wait, and how a run ended, at once; what a
1864
+ // run says while it executes every so often, as the next server resumes it
1644
1865
  if (event.type === 'state' || event.type === 'approval' || event.type === 'extended' || event.type === 'moved') {
1645
1866
  this.persist(entry);
1646
1867
  }
1868
+ else if (this.options.store && !entry.persistTimer && !this.closed) {
1869
+ entry.persistTimer = setTimeout(() => this.persist(entry), this.options.persistEvery ?? PERSIST_EVERY);
1870
+ entry.persistTimer.unref();
1871
+ }
1647
1872
  }
1648
- persist(entry) {
1873
+ // `clean`: the server stops, and the record has all the run said
1874
+ persist(entry, clean = false) {
1649
1875
  const store = this.options.store;
1876
+ clearTimeout(entry.persistTimer);
1877
+ entry.persistTimer = undefined;
1650
1878
  if (!store) {
1651
1879
  return;
1652
1880
  }
1653
- const record = { run: this.copy(entry.run), events: [...entry.events] };
1881
+ // the check keys of a run that resumes are the ones from before anything of it ran
1882
+ const keys = isFinal(entry.run.state) || Object.keys(entry.keys).length === 0 ? {} : { keys: { ...entry.keys } };
1883
+ const record = {
1884
+ run: this.copy(entry.run),
1885
+ events: [...entry.events],
1886
+ ...keys,
1887
+ ...(clean || this.written ? { clean: true } : {}),
1888
+ };
1654
1889
  entry.saving = entry.saving
1655
1890
  .then(() => store.save(record))
1656
1891
  .catch((e) => this.options.log?.(`could not keep run ${record.run.id}: ${e instanceof Error ? e.message : e}`));
@@ -245,7 +245,10 @@ async function handleRuns(config, registry, definitions, sources, sandboxes, pla
245
245
  const logs = (0, run_access_1.findReadableRun)(config, registry, principal, id) ? registry.logsOf(id) : undefined;
246
246
  // with the tasks, services and the server's own lines (`hammerkit`) the log has
247
247
  logs
248
- ? (0, http_2.send)(res, 200, { ...(0, run_logs_1.readLogs)(logs.events, logs.index, query, logs.truncated), names: logs.index.names() })
248
+ ? (0, http_2.send)(res, 200, {
249
+ ...(0, run_logs_1.readLogs)(logs.events, logs.index, query, logs.truncated, logs.lostAfter),
250
+ names: logs.index.names(),
251
+ })
249
252
  : (0, http_2.send)(res, 404, { error: 'not found' });
250
253
  }
251
254
  else {
@@ -1079,8 +1082,9 @@ async function startServer(config, environment, options = {}) {
1079
1082
  .catch((e) => log(`the outputs of old runs could not be removed: ${e instanceof Error ? e.message : e}`));
1080
1083
  const sweepingArtifacts = setInterval(sweepArtifacts, ARTIFACT_SWEEP_MS);
1081
1084
  sweepingArtifacts.unref();
1082
- // the executor hears which service runs sleep with their volumes kept, and removes what it
1083
- // kept for any other (RunExecutor.restored)
1085
+ // the runs the server before stopped resume, and the executor hears which service runs sleep
1086
+ // with their volumes kept and which runs resume, and removes what it kept for any other
1087
+ // (RunExecutor.restored)
1084
1088
  await registry.restore();
1085
1089
  void sweepArtifacts();
1086
1090
  const proposals = new proposals_1.ProposalRegistry({
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "hammerkit",
3
3
  "description": "Containerized build tool with incremental caching that runs the same build file locally, in Docker and on Kubernetes.",
4
- "version": "2.1.0-next.13",
4
+ "version": "2.1.0-next.14",
5
5
  "keywords": [
6
6
  "build",
7
7
  "build-tool",