hammerkit 2.2.0-next.1 → 2.2.0-next.3

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.
@@ -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.registerWorkCommands = exports.describeArtifacts = exports.selectArtifacts = exports.keptProjectOutputs = exports.isProjectPath = exports.describePlan = exports.describeApproval = exports.keepRuns = exports.describeListedRun = exports.describeRunEnd = void 0;
6
+ exports.registerWorkCommands = exports.describeArtifacts = exports.selectArtifacts = exports.keptProjectOutputs = exports.isProjectPath = exports.describePlan = exports.decideDue = exports.decideBefore = exports.describeApproval = exports.keepRuns = exports.describeListedRun = exports.describeRunEnd = void 0;
7
7
  const commander_1 = require("commander");
8
8
  const colors_1 = __importDefault(require("colors"));
9
9
  const collect_bundle_1 = require("./collect-bundle");
@@ -140,10 +140,20 @@ function describeApproval(run) {
140
140
  ? `approved by ${(0, server_client_1.printable)(approval.approvedBy.sub)}`
141
141
  : 'waits for somebody who uses it to approve'}`),
142
142
  ...flagLines(run),
143
- ` decide before ${(0, server_client_1.printable)(run.approvals?.[0]?.expiresAt ?? '-')}`,
143
+ ` ${decideDue(run.approvals?.[0]?.expiresAt)}`,
144
144
  ];
145
145
  }
146
146
  exports.describeApproval = describeApproval;
147
+ // When a decision is due, or that there is no time limit to make it in.
148
+ function decideBefore(expiresAt) {
149
+ return expiresAt ? `before ${(0, server_client_1.printable)(expiresAt)}` : 'with no time limit';
150
+ }
151
+ exports.decideBefore = decideBefore;
152
+ // What a decision is due by, as a line of its own.
153
+ function decideDue(expiresAt) {
154
+ return expiresAt ? `decide before ${(0, server_client_1.printable)(expiresAt)}` : 'no time limit to decide';
155
+ }
156
+ exports.decideDue = decideDue;
147
157
  // What to look at first, one line.
148
158
  function flagLines(run) {
149
159
  const flagged = Object.entries(run.plan ?? {}).filter(([, entry]) => entry.flags.length > 0);
@@ -338,7 +348,7 @@ function registerWorkCommands(remote, context) {
338
348
  environment.stdout.write(`${line.trimStart()}\n`);
339
349
  }
340
350
  if (proposed) {
341
- environment.stdout.write(`it can not run before somebody who may publish approves it, until ${(0, server_client_1.printable)(version.expiresAt)}\n`);
351
+ environment.stdout.write(`it can not run before somebody who may publish approves it, ${decideBefore(version.expiresAt)}\n`);
342
352
  }
343
353
  return { version, proposed };
344
354
  };
@@ -513,7 +523,7 @@ function registerWorkCommands(remote, context) {
513
523
  },
514
524
  onWaiting: (run) => {
515
525
  for (const approval of run.approvals ?? []) {
516
- environment.stdout.write(`waiting until somebody who uses ${(0, server_client_1.printable)(approval.account)} approves it, before ${(0, server_client_1.printable)(approval.expiresAt)}: hammerkit remote approve ${(0, server_client_1.printable)(run.id)}\n`);
526
+ environment.stdout.write(`waiting until somebody who uses ${(0, server_client_1.printable)(approval.account)} approves it, ${decideBefore(approval.expiresAt)}: hammerkit remote approve ${(0, server_client_1.printable)(run.id)}\n`);
517
527
  }
518
528
  },
519
529
  });
@@ -586,7 +596,7 @@ function registerWorkCommands(remote, context) {
586
596
  onLine: (line) => environment.stdout.write(`[${(0, server_client_1.printable)(line.task)}] ${printableLine(line.text)}\n`),
587
597
  onWaiting: (run) => {
588
598
  for (const approval of run.approvals ?? []) {
589
- environment.stdout.write(`waiting until somebody who uses ${(0, server_client_1.printable)(approval.account)} approves it, before ${(0, server_client_1.printable)(approval.expiresAt)}: hammerkit remote approve ${(0, server_client_1.printable)(run.id)}\n`);
599
+ environment.stdout.write(`waiting until somebody who uses ${(0, server_client_1.printable)(approval.account)} approves it, ${decideBefore(approval.expiresAt)}: hammerkit remote approve ${(0, server_client_1.printable)(run.id)}\n`);
590
600
  }
591
601
  },
592
602
  });
@@ -1095,7 +1105,7 @@ function registerWorkCommands(remote, context) {
1095
1105
  environment.stdout.write(`${line}\n`);
1096
1106
  }
1097
1107
  if (proposal.state === 'waiting') {
1098
- environment.stdout.write(` decide before ${(0, server_client_1.printable)(proposal.expiresAt)}\n`);
1108
+ environment.stdout.write(` ${decideDue(proposal.expiresAt)}\n`);
1099
1109
  }
1100
1110
  else if (proposal.reason) {
1101
1111
  environment.stdout.write(` ${(0, server_client_1.printable)(proposal.state)}: ${(0, server_client_1.printable)(proposal.reason)}\n`);
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.cacheRegistriesOf = exports.cachePushOf = void 0;
4
+ const registry_reference_1 = require("../cache/backends/registry/registry-reference");
5
+ const policy_1 = require("./policy");
6
+ const repo_1 = require("./repo");
7
+ // a ref may name a commit, which is no branch of the repository (see git-checkout.ts)
8
+ const COMMIT = /^[0-9a-f]{40}([0-9a-f]{24})?$/i;
9
+ // Whether a run writes a registry cache, and with which credential (ADR-0010). Every run reads
10
+ // the caches of its build file; only a trusted run writes one, and the answer is null for all
11
+ // others, which fails closed:
12
+ // - a run from a git ref that resolved as a branch when the server pinned it (`branch`, so a tag
13
+ // that matches a branch pattern is not one), of a repository and branch `cache.push` lists
14
+ // - by a caller who may publish build files, who is trusted with what the cache then holds; a
15
+ // caller whose grant is gone is no longer one
16
+ // - with a password the server's environment holds for the rule's registry
17
+ //
18
+ // The build file takes no part in it: a run writes the registry of its own configuration only.
19
+ // `envs` is the server's own environment, not the one of a run, which holds the allowlist.
20
+ function cachePushOf(run, config, envs) {
21
+ const source = run.source;
22
+ if (source.type !== 'ref' || source.branch !== true || COMMIT.test(source.ref)) {
23
+ return null;
24
+ }
25
+ const grant = (0, policy_1.getGrant)(config.entitlements, {
26
+ iss: run.owner.iss,
27
+ sub: run.owner.sub,
28
+ groups: run.owner.groups ?? [],
29
+ claims: run.owner.claims ?? {},
30
+ });
31
+ if (!(0, policy_1.mayPublish)(grant)) {
32
+ return null;
33
+ }
34
+ // the first rule that covers the run decides, even when its password is missing
35
+ const rule = config.cache.push.find((entry) => (0, repo_1.matchesRepo)(entry.repo, source.repo) && (0, repo_1.matchesRef)(entry.refs, source.ref));
36
+ const password = rule ? envs[rule.registry.passwordEnv] : undefined;
37
+ if (!rule || !password) {
38
+ return null;
39
+ }
40
+ return { repository: rule.registry.repository, username: rule.registry.username, password };
41
+ }
42
+ exports.cachePushOf = cachePushOf;
43
+ // The registry hosts a server run may read its caches from: `cache.registries`, and the host of
44
+ // each `cache.push` rule, which the operator named already.
45
+ function cacheRegistriesOf(config) {
46
+ const hosts = config.cache.push.map((rule) => (0, registry_reference_1.parseRegistryReference)(rule.registry.repository).host);
47
+ return [...new Set([...config.cache.registries, ...hosts])];
48
+ }
49
+ exports.cacheRegistriesOf = cacheRegistriesOf;
50
+ //# sourceMappingURL=cache-push.js.map
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.HostExecutor = exports.relayWorkerLine = exports.removeServiceRunVolumes = exports.serviceRunScopes = exports.volumeScope = exports.cacheNamespace = exports.defaultWorker = void 0;
3
+ exports.HostExecutor = exports.relayWorkerLine = exports.removeServiceRunVolumes = exports.serviceRunScopes = exports.volumeScope = exports.pushCacheNamespace = exports.cacheNamespace = exports.defaultWorker = void 0;
4
4
  const child_process_1 = require("child_process");
5
5
  const crypto_1 = require("crypto");
6
6
  const checks_1 = require("./checks");
@@ -67,6 +67,14 @@ function cacheNamespace(run) {
67
67
  return `${kind}-${(0, crypto_1.createHash)('sha256').update(key).digest('hex').slice(0, 24)}`;
68
68
  }
69
69
  exports.cacheNamespace = cacheNamespace;
70
+ // The local cache of a run that pushes to a registry (ADR-0010). Only the runs that push write it,
71
+ // and a pushing run restores from it and from the registry, never from the cache the other runs of
72
+ // the repository share: what an untrusted run left there is no result to push.
73
+ function pushCacheNamespace(run) {
74
+ const key = `push\0${run.source.repo}`;
75
+ return `push-${(0, crypto_1.createHash)('sha256').update(key).digest('hex').slice(0, 24)}`;
76
+ }
77
+ exports.pushCacheNamespace = pushCacheNamespace;
70
78
  // The docker volumes of a run's services are its caller's, within the cache's source trust:
71
79
  // two callers of one repository share a cache, a task is keyed by what it reads, but not the
72
80
  // data their services keep. A service run's are its own: they stay while it sleeps and go
@@ -396,7 +404,10 @@ class HostExecutor {
396
404
  emitPhase(context, 'source', sourceStarted);
397
405
  const home = (0, path_1.join)(root, 'home');
398
406
  await (0, promises_1.mkdir)(home, { recursive: true });
399
- const cache = (0, path_1.join)(this.options.cache, cacheNamespace(run));
407
+ // a run writes a registry cache only with the server's credential for it (ADR-0010); a run
408
+ // that does has a local cache of its own, which no other run writes
409
+ const push = this.options.cachePush?.(run) ?? null;
410
+ const cache = (0, path_1.join)(this.options.cache, push ? pushCacheNamespace(run) : cacheNamespace(run));
400
411
  await (0, promises_1.mkdir)(cache, { recursive: true });
401
412
  const placement = this.options.placement;
402
413
  const namespaceStarted = new Date();
@@ -409,6 +420,8 @@ class HostExecutor {
409
420
  ...input,
410
421
  tasks: run.tasks,
411
422
  options: run.options,
423
+ ...(push ? { cachePush: push } : {}),
424
+ cacheRegistries: this.options.cacheRegistries ?? [],
412
425
  accounts: run.accounts,
413
426
  volumeScope: volumeScope(run, this.options.directory),
414
427
  ...((0, checks_1.isCheckRun)(run) ? { check: true } : {}),
@@ -20,6 +20,7 @@ const task_arguments_1 = require("../planner/utils/task-arguments");
20
20
  const work_network_1 = require("../planner/work-network");
21
21
  const run_source_envs_1 = require("../environment/run-source-envs");
22
22
  const prefetch_secrets_1 = require("../secrets/prefetch-secrets");
23
+ const registry_reference_1 = require("../cache/backends/registry/registry-reference");
23
24
  class DefinitionError extends Error {
24
25
  }
25
26
  exports.DefinitionError = DefinitionError;
@@ -72,12 +73,31 @@ function checkGitSource(path, where, source, noRemote) {
72
73
  }
73
74
  }
74
75
  // What a build file may not name on a server: the places it would run or store things
75
- // are the operator's. The docker host, a Kubernetes cluster and a remote cache are
76
- // credentials of the machine, not of the build file, and a project file that could carry
77
- // them could send runs, or the cache, anywhere.
76
+ // are the operator's. The docker host and a Kubernetes cluster are credentials of the machine,
77
+ // not of the build file, and a project file that could carry them could send runs anywhere. A
78
+ // remote cache is named by the build file only as a registry, which the server reads, and writes
79
+ // with its own credential for it (cache.push, ADR-0010).
78
80
  // A file a server leaves out (`publish: false`) is not checked, and neither is a service
79
81
  // with `publish: false`: what is left out is never run there.
80
- function findHostProblems(files) {
82
+ // What a registry cache a build file names needs to be on a server: a reference that parses, over
83
+ // https (a localhost registry is http, so refused), on a host the operator allows. Null when it is.
84
+ function checkRegistry(repository, allowed) {
85
+ let reference;
86
+ try {
87
+ reference = (0, registry_reference_1.parseRegistryReference)(repository);
88
+ }
89
+ catch (e) {
90
+ return (0, log_1.getErrorMessage)(e);
91
+ }
92
+ if (reference.insecure) {
93
+ return 'a server keeps its own cache, a build file names no path, s3 bucket or insecure registry (localhost is http)';
94
+ }
95
+ if (!allowed.includes(reference.host)) {
96
+ return `registry ${reference.host} is not one of the registries this server reads (cache.registries: ${allowed.join(', ') || 'none'})`;
97
+ }
98
+ return null;
99
+ }
100
+ function findHostProblems(files, allowed) {
81
101
  const problems = [];
82
102
  for (const [path, content] of Object.entries(files)) {
83
103
  let document;
@@ -94,9 +114,20 @@ function findHostProblems(files) {
94
114
  problems.push(`${path}: environments pick a docker host or a Kubernetes cluster, which are the server's to choose, remove them`);
95
115
  }
96
116
  for (const [name, cache] of Object.entries(document.caches ?? {})) {
97
- if (cache?.backend?.type !== 'local' || cache.backend.path !== undefined) {
98
- problems.push(`${path}: caches.${name}: a server keeps its own cache, a build file names no backend or path`);
117
+ const backend = cache?.backend;
118
+ if (backend?.type === 'local' && backend.path === undefined) {
119
+ continue;
120
+ }
121
+ // a registry is read over https from a host the operator allows; the server writes it only
122
+ // as a trusted run (cache.push), so the build file names no credential
123
+ if (backend?.type === 'registry' && typeof backend.repository === 'string' && !backend.insecure) {
124
+ const problem = checkRegistry(backend.repository, allowed);
125
+ if (problem) {
126
+ problems.push(`${path}: caches.${name}: ${problem}`);
127
+ }
128
+ continue;
99
129
  }
130
+ problems.push(`${path}: caches.${name}: a server keeps its own cache, a build file names no path, s3 bucket or insecure registry`);
100
131
  }
101
132
  for (const [name, service] of Object.entries(document.services ?? {})) {
102
133
  if (service &&
@@ -427,7 +458,7 @@ async function planBundle(bundle, environment, options = {}) {
427
458
  : (0, path_1.relative)(directory, from.fileName), `${block}.${name}`, source, options.noRemote),
428
459
  });
429
460
  if (options.policy) {
430
- const problems = findHostProblems(publishedBundleFiles(bundle, directory, scope));
461
+ const problems = findHostProblems(publishedBundleFiles(bundle, directory, scope), options.policy.cacheRegistries ?? []);
431
462
  if (problems.length > 0) {
432
463
  throw new DefinitionError(problems.join('\n'));
433
464
  }
@@ -0,0 +1,94 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FileProposalStore = void 0;
4
+ const crypto_1 = require("crypto");
5
+ const promises_1 = require("fs/promises");
6
+ const path_1 = require("path");
7
+ const zod_1 = require("zod");
8
+ const bundle_1 = require("../remote/bundle");
9
+ const identitySchema = zod_1.z.object({ iss: zod_1.z.string(), sub: zod_1.z.string() });
10
+ const timeSchema = zod_1.z.string().refine((value) => Number.isFinite(Date.parse(value)), 'expected a time');
11
+ // what is kept of a proposal: the fields of Proposal, checked before the server acts on them
12
+ const proposalSchema = zod_1.z.object({
13
+ hash: zod_1.z.string().regex(bundle_1.HASH_PATTERN, 'expected a hash of a build file'),
14
+ entry: zod_1.z.string(),
15
+ tasks: zod_1.z.array(zod_1.z.string()),
16
+ services: zod_1.z.array(zod_1.z.string()),
17
+ accounts: zod_1.z.array(zod_1.z.string()),
18
+ missing: zod_1.z.array(zod_1.z.string()),
19
+ plan: zod_1.z.record(zod_1.z.unknown()),
20
+ annotations: bundle_1.annotationsSchema.optional(),
21
+ proposedBy: identitySchema,
22
+ createdAt: timeSchema,
23
+ expiresAt: timeSchema.optional(),
24
+ state: zod_1.z.enum(['waiting', 'approved', 'rejected', 'expired']),
25
+ decidedBy: identitySchema.optional(),
26
+ decidedAt: timeSchema.optional(),
27
+ reason: zod_1.z.string().optional(),
28
+ });
29
+ const recordSchema = zod_1.z.object({ proposal: proposalSchema, bundle: bundle_1.bundleSchema.optional() });
30
+ const fileOf = (hash) => `${hash.replace(':', '-')}.json`;
31
+ // what a record that can not be read is skipped for, in a few words
32
+ const reasonOf = (e) => {
33
+ if (e instanceof zod_1.ZodError) {
34
+ const issue = e.issues[0];
35
+ return `${issue.path.join('.') || 'record'} ${issue.message}`;
36
+ }
37
+ return e instanceof Error ? e.message : String(e);
38
+ };
39
+ /**
40
+ * One file per proposal, written to a temporary file and renamed, as the run records are.
41
+ * Only the user of the server can read the files, they hold the files of the versions.
42
+ */
43
+ class FileProposalStore {
44
+ constructor(directory) {
45
+ this.directory = directory;
46
+ }
47
+ async save(record) {
48
+ await (0, promises_1.mkdir)(this.directory, { recursive: true, mode: 0o700 });
49
+ // also a directory that was made before, with other permissions
50
+ await (0, promises_1.chmod)(this.directory, 0o700);
51
+ const file = (0, path_1.join)(this.directory, fileOf(record.proposal.hash));
52
+ const temporary = `${file}.${(0, crypto_1.randomBytes)(8).toString('hex')}.tmp`;
53
+ await (0, promises_1.writeFile)(temporary, JSON.stringify(record), { mode: 0o600, flag: 'wx' });
54
+ await (0, promises_1.rename)(temporary, file);
55
+ }
56
+ async remove(hash) {
57
+ await (0, promises_1.rm)((0, path_1.join)(this.directory, fileOf(hash)), { force: true });
58
+ }
59
+ async load() {
60
+ const records = [];
61
+ const skipped = [];
62
+ let names;
63
+ try {
64
+ names = await (0, promises_1.readdir)(this.directory);
65
+ }
66
+ catch {
67
+ return { records, skipped };
68
+ }
69
+ for (const name of names) {
70
+ if (!name.endsWith('.json')) {
71
+ // a record that was being written when the server stopped
72
+ if (name.endsWith('.tmp')) {
73
+ await (0, promises_1.rm)((0, path_1.join)(this.directory, name), { force: true });
74
+ }
75
+ continue;
76
+ }
77
+ try {
78
+ const record = recordSchema.parse(JSON.parse(await (0, promises_1.readFile)((0, path_1.join)(this.directory, name), 'utf8')));
79
+ if (fileOf(record.proposal.hash) !== name) {
80
+ throw new Error('the name is not the hash of the record');
81
+ }
82
+ records.push(record);
83
+ }
84
+ catch (e) {
85
+ skipped.push(`${name}: ${reasonOf(e)}`);
86
+ }
87
+ }
88
+ // the times were checked, so this order is the order they were made in
89
+ records.sort((a, b) => Date.parse(a.proposal.createdAt) - Date.parse(b.proposal.createdAt));
90
+ return { records, skipped };
91
+ }
92
+ }
93
+ exports.FileProposalStore = FileProposalStore;
94
+ //# sourceMappingURL=proposal-store.js.map
@@ -121,6 +121,9 @@ async function handleProposals(config, store, proposals, log, principal, req, re
121
121
  case 'not-waiting':
122
122
  (0, http_1.send)(res, 409, { error: `the proposal is ${result.state}, it does not wait for an approval` });
123
123
  break;
124
+ case 'unreadable':
125
+ (0, http_1.send)(res, 503, { error: 'the files of this version can not be read right now, try again later' });
126
+ break;
124
127
  default:
125
128
  (0, http_1.send)(res, 404, { error: 'not found' });
126
129
  }
@@ -1,7 +1,24 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ProposalRegistry = exports.CooldownError = exports.ProposalError = void 0;
4
+ const bundle_1 = require("../remote/bundle");
5
+ const plan_1 = require("./plan");
6
+ const long_timer_1 = require("../utils/long-timer");
4
7
  const units_1 = require("../utils/units");
8
+ const errorText = (e) => (e instanceof Error ? e.message : String(e));
9
+ const sameWho = (a, b) => a.iss === b.iss && a.sub === b.sub;
10
+ // what the files say of a version, as a proposal keeps it; the annotations are the
11
+ // proposer's and not part of the hash, so a restart keeps them as they were. Every account
12
+ // the files use is missing: who proposed them is not known from the files, so whoever
13
+ // approves has to use all of them
14
+ const fieldsOf = (version) => ({
15
+ entry: version.entry,
16
+ tasks: version.tasks,
17
+ services: version.services,
18
+ accounts: version.accounts ?? [],
19
+ missing: version.accounts ?? [],
20
+ plan: version.plan ?? {},
21
+ });
5
22
  class ProposalError extends Error {
6
23
  constructor() {
7
24
  super(...arguments);
@@ -18,18 +35,79 @@ class CooldownError extends ProposalError {
18
35
  }
19
36
  }
20
37
  exports.CooldownError = CooldownError;
21
- // The proposals of the server, in memory: a restart forgets what waits, and
22
- // whoever proposed it proposes it again. Nothing in here is runnable.
38
+ // The proposals of the server. They are kept in the store when there is one, so a restart
39
+ // takes back what waits, with its expiry, and the rejections that still start a cooldown.
40
+ // Nothing in here is runnable.
23
41
  class ProposalRegistry {
24
42
  constructor(options = {}) {
43
+ this.options = options;
25
44
  this.entries = new Map();
26
45
  this.closed = false;
46
+ // the writes of the store, one after the other
47
+ this.writes = Promise.resolve();
27
48
  this.maxWaiting = options.maxWaiting ?? 100;
28
- this.timeout = options.timeout ?? 60 * 60 * 1000;
49
+ this.maxWaitingPerProposer = options.maxWaitingPerProposer ?? 10;
50
+ this.timeout = options.timeout;
29
51
  this.keep = options.keep ?? 100;
30
52
  this.cooldown = options.cooldown ?? 0;
31
53
  this.now = options.now ?? Date.now;
32
54
  }
55
+ /**
56
+ * Takes back the proposals of a previous start. What waited waits on until its expiry, the
57
+ * one it had. Its files are read again now; if that is refused it expires, and if it fails
58
+ * for now it waits and is read again before it is decided. One whose time ran out while the
59
+ * server was down expires now, and one whose expiry can not be read expires too, as a
60
+ * fail-safe.
61
+ */
62
+ async restore() {
63
+ const store = this.options.store;
64
+ if (!store) {
65
+ return;
66
+ }
67
+ const { records, skipped } = await store.load();
68
+ skipped.forEach((entry) => this.options.log?.(`skip proposal record ${entry}`));
69
+ // one reading of the clock for all of them
70
+ const now = this.now();
71
+ for (const { proposal, bundle } of records) {
72
+ const entry = { proposal: { ...proposal } };
73
+ this.entries.set(proposal.hash, entry);
74
+ if (proposal.state !== 'waiting') {
75
+ continue;
76
+ }
77
+ if (!bundle) {
78
+ // nothing to publish: it can not be approved, so it is over
79
+ this.settle(entry, 'expired', undefined, undefined, now);
80
+ continue;
81
+ }
82
+ if ((0, bundle_1.hashBundle)(bundle) !== proposal.hash) {
83
+ // not the version it names: nobody may approve these files as that one
84
+ this.entries.delete(proposal.hash);
85
+ this.options.log?.(`skip proposal ${proposal.hash}: its files are not that version`);
86
+ continue;
87
+ }
88
+ entry.bundle = bundle;
89
+ const reading = await this.reread(entry);
90
+ if (reading.state === 'refused') {
91
+ this.settle(entry, 'expired', undefined, `the build file does not load after a restart: ${reading.reason}`, now);
92
+ continue;
93
+ }
94
+ if (proposal.expiresAt === undefined) {
95
+ continue;
96
+ }
97
+ const expiresAt = Date.parse(proposal.expiresAt);
98
+ if (!Number.isFinite(expiresAt) || expiresAt <= now) {
99
+ this.settle(entry, 'expired', undefined, undefined, Number.isFinite(expiresAt) ? expiresAt : now);
100
+ }
101
+ else {
102
+ this.arm(entry, expiresAt - now);
103
+ }
104
+ }
105
+ this.evict();
106
+ }
107
+ // Resolves once what was written so far is on disk.
108
+ async flush() {
109
+ await this.writes;
110
+ }
33
111
  // Proposing what already waits is not an error and changes nothing.
34
112
  propose(version, bundle, proposer, missing = []) {
35
113
  if (this.closed) {
@@ -41,9 +119,14 @@ class ProposalRegistry {
41
119
  return { proposal: { ...existing.proposal }, created: false };
42
120
  }
43
121
  this.checkCooldown(version, proposer);
122
+ const own = this.waiting().filter((waiting) => sameWho(waiting.proposedBy, proposer)).length;
123
+ if (own >= this.maxWaitingPerProposer) {
124
+ throw new ProposalError(`you already have ${own} build file versions waiting for an approval, at most ${this.maxWaitingPerProposer} at a time`);
125
+ }
44
126
  if (this.waiting().length >= this.maxWaiting) {
45
127
  throw new ProposalError('too many build file versions are waiting for an approval');
46
128
  }
129
+ const createdAt = this.now();
47
130
  const proposal = {
48
131
  hash: version.hash,
49
132
  entry: version.entry,
@@ -54,15 +137,17 @@ class ProposalRegistry {
54
137
  plan: version.plan ?? {},
55
138
  ...(version.annotations ? { annotations: { ...version.annotations } } : {}),
56
139
  proposedBy: { iss: proposer.iss, sub: proposer.sub },
57
- createdAt: new Date(this.now()).toISOString(),
58
- expiresAt: new Date(this.now() + this.timeout).toISOString(),
140
+ createdAt: new Date(createdAt).toISOString(),
141
+ ...(this.timeout === undefined ? {} : { expiresAt: new Date(createdAt + this.timeout).toISOString() }),
59
142
  state: 'waiting',
60
143
  };
61
144
  const entry = { proposal, bundle };
62
- entry.timer = setTimeout(() => this.settle(entry, 'expired'), this.timeout);
63
- entry.timer.unref();
145
+ if (this.timeout !== undefined) {
146
+ this.arm(entry, this.timeout);
147
+ }
64
148
  this.entries.delete(key);
65
149
  this.entries.set(key, entry);
150
+ this.persist(entry);
66
151
  this.evict();
67
152
  return { proposal: { ...proposal }, created: true };
68
153
  }
@@ -81,9 +166,9 @@ class ProposalRegistry {
81
166
  bundle(hash) {
82
167
  return this.entries.get(hash)?.bundle;
83
168
  }
84
- // An approval publishes the files first (`publish`), and only then is the
85
- // proposal approved, so it never claims a version that is not there. Nobody
86
- // decides on their own proposal.
169
+ // An approval reads the files again when they could not be read before, then publishes
170
+ // them (`publish`), and only then is the proposal approved, so it never claims a version
171
+ // that is not there. Nobody decides on their own proposal.
87
172
  async decide(decider, hash, outcome, mayDecide, publish, reason) {
88
173
  const entry = this.entries.get(hash);
89
174
  if (!entry || !mayDecide(entry.proposal)) {
@@ -95,6 +180,24 @@ class ProposalRegistry {
95
180
  if (entry.proposal.state !== 'waiting' || !entry.bundle) {
96
181
  return { status: 'not-waiting', state: entry.proposal.state };
97
182
  }
183
+ if (entry.unread) {
184
+ const reading = await this.reread(entry);
185
+ if (reading.state === 'refused') {
186
+ this.settle(entry, 'expired', undefined, `the build file does not load: ${reading.reason}`);
187
+ return { status: 'not-waiting', state: 'expired' };
188
+ }
189
+ if (reading.state === 'unavailable') {
190
+ return { status: 'unreadable' };
191
+ }
192
+ if (entry.proposal.state !== 'waiting') {
193
+ return { status: 'not-waiting', state: entry.proposal.state };
194
+ }
195
+ this.persist(entry);
196
+ // the accounts it needs may have changed with the files
197
+ if (!mayDecide(entry.proposal)) {
198
+ return { status: 'not-found' };
199
+ }
200
+ }
98
201
  if (outcome === 'approved') {
99
202
  await publish(entry.bundle);
100
203
  if (entry.proposal.state !== 'waiting') {
@@ -107,22 +210,45 @@ class ProposalRegistry {
107
210
  close() {
108
211
  this.closed = true;
109
212
  for (const entry of this.entries.values()) {
110
- if (entry.timer) {
111
- clearTimeout(entry.timer);
112
- entry.timer = undefined;
213
+ this.disarm(entry);
214
+ }
215
+ }
216
+ // Reads the files of an entry again. A refusal (DefinitionError) is the files' own and does
217
+ // not change; any other failure may, so the entry stays unread and waiting.
218
+ async reread(entry) {
219
+ const prepare = this.options.prepare;
220
+ if (!prepare || !entry.bundle) {
221
+ return { state: 'ok' };
222
+ }
223
+ try {
224
+ entry.proposal = { ...entry.proposal, ...fieldsOf(await prepare(entry.bundle)) };
225
+ entry.unread = false;
226
+ return { state: 'ok' };
227
+ }
228
+ catch (e) {
229
+ if (e instanceof plan_1.DefinitionError) {
230
+ return { state: 'refused', reason: errorText(e) };
113
231
  }
232
+ entry.unread = true;
233
+ this.options.log?.(`the files of proposal ${entry.proposal.hash} can not be read now: ${errorText(e)}`);
234
+ return { state: 'unavailable' };
114
235
  }
115
236
  }
116
- settle(entry, state, by, reason) {
237
+ arm(entry, ms) {
238
+ entry.cancel = (0, long_timer_1.setLongTimeout)(() => this.settle(entry, 'expired'), ms);
239
+ }
240
+ disarm(entry) {
241
+ entry.cancel?.();
242
+ entry.cancel = undefined;
243
+ }
244
+ // `at` is when it was decided, the expiry for one that ran out while the server was down
245
+ settle(entry, state, by, reason, at = this.now()) {
117
246
  if (entry.proposal.state !== 'waiting') {
118
247
  return;
119
248
  }
120
- if (entry.timer) {
121
- clearTimeout(entry.timer);
122
- entry.timer = undefined;
123
- }
249
+ this.disarm(entry);
124
250
  entry.proposal.state = state;
125
- entry.proposal.decidedAt = new Date(this.now()).toISOString();
251
+ entry.proposal.decidedAt = new Date(at).toISOString();
126
252
  if (by) {
127
253
  entry.proposal.decidedBy = by;
128
254
  }
@@ -130,6 +256,20 @@ class ProposalRegistry {
130
256
  entry.proposal.reason = reason;
131
257
  }
132
258
  entry.bundle = undefined;
259
+ entry.unread = false;
260
+ this.persist(entry);
261
+ }
262
+ // Writes what the entry is now, after the writes before it. A write that fails is logged:
263
+ // the decision stands in memory, and the proposal is lost only by a restart.
264
+ persist(entry) {
265
+ const store = this.options.store;
266
+ if (!store) {
267
+ return;
268
+ }
269
+ const record = { proposal: { ...entry.proposal }, ...(entry.bundle ? { bundle: entry.bundle } : {}) };
270
+ this.writes = this.writes
271
+ .then(() => store.save(record))
272
+ .catch((e) => this.options.log?.(`the proposal ${record.proposal.hash} was not written: ${errorText(e)}`));
133
273
  }
134
274
  // A rejection is a no; a proposal that only ran out of time is not.
135
275
  checkCooldown(version, proposer) {
@@ -153,8 +293,17 @@ class ProposalRegistry {
153
293
  const decided = [...this.entries.entries()].filter(([, e]) => e.proposal.state !== 'waiting');
154
294
  for (const [key] of decided.slice(0, Math.max(0, decided.length - this.keep))) {
155
295
  this.entries.delete(key);
296
+ if (this.options.store) {
297
+ this.remove(key);
298
+ }
156
299
  }
157
300
  }
301
+ remove(hash) {
302
+ const store = this.options.store;
303
+ this.writes = this.writes
304
+ .then(() => store?.remove(hash))
305
+ .catch((e) => this.options.log?.(`the proposal ${hash} was not removed: ${errorText(e)}`));
306
+ }
158
307
  }
159
308
  exports.ProposalRegistry = ProposalRegistry;
160
309
  //# sourceMappingURL=proposals.js.map