hammerkit 2.2.0-next.2 → 2.2.0-next.4

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,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.setUserPermissions = exports.prepareMounts = exports.prepareVolume = exports.pullImage = exports.refuseHostLinks = exports.hostedRoot = void 0;
3
+ exports.setUserPermissions = exports.innermostMount = exports.prepareMounts = exports.prepareVolume = exports.pullImage = exports.refuseHostLinks = exports.hostedRoot = void 0;
4
4
  const pull_1 = require("../docker/pull");
5
5
  const get_docker_executor_1 = require("./get-docker-executor");
6
6
  const path_1 = require("path");
@@ -92,6 +92,7 @@ async function prepareMounts(item, environment) {
92
92
  }
93
93
  }
94
94
  if ((0, work_task_1.isContainerWorkTask)(item.data)) {
95
+ await createOutputFoldersUnderMounts(item.data, environment);
95
96
  for (const gen of item.data.generates) {
96
97
  if (!gen.isFile) {
97
98
  continue;
@@ -108,6 +109,40 @@ async function prepareMounts(item, environment) {
108
109
  }
109
110
  }
110
111
  exports.prepareMounts = prepareMounts;
112
+ // The mount that holds a path, the innermost one when several do (`.` and `./app`
113
+ // for `app/node_modules`: `./app`), or undefined when none does.
114
+ function innermostMount(mounts, path) {
115
+ let found;
116
+ for (const mount of mounts) {
117
+ const holds = mount.containerPath === path || (0, get_container_binds_1.isInside)(path, mount.containerPath);
118
+ if (holds && (!found || mount.containerPath.length > found.containerPath.length)) {
119
+ found = mount;
120
+ }
121
+ }
122
+ return found;
123
+ }
124
+ exports.innermostMount = innermostMount;
125
+ // Docker creates the folder of a volume nested under a bind mount on the host, as root and
126
+ // empty, when the container starts. Its outputs could not be exported into it, so the folder
127
+ // is created here, as the user, before the container starts.
128
+ async function createOutputFoldersUnderMounts(task, environment) {
129
+ for (const gen of task.generates) {
130
+ if (gen.isFile) {
131
+ continue;
132
+ }
133
+ const mount = innermostMount(task.mounts, gen.path);
134
+ // the mount is the output's folder itself: created with the mount above
135
+ if (!mount || mount.containerPath === gen.path) {
136
+ continue;
137
+ }
138
+ const target = (0, path_1.join)(mount.localPath, (0, path_1.relative)(mount.containerPath, gen.path));
139
+ // never outside the mount on the host
140
+ if (target !== mount.localPath && !(0, get_container_binds_1.isInside)(target, mount.localPath)) {
141
+ continue;
142
+ }
143
+ await environment.file.createDirectory(target);
144
+ }
145
+ }
111
146
  async function setUserPermissions(item, container, environment) {
112
147
  if (item.data.user) {
113
148
  // On a server only the volumes: a chown as the container's root on a path of the host
@@ -1,12 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getContainerBinds = void 0;
3
+ exports.getContainerBinds = exports.isInside = void 0;
4
4
  const path_1 = require("path");
5
5
  const dependency_outputs_1 = require("../planner/utils/dependency-outputs");
6
6
  function isInside(path, parent) {
7
7
  const rel = (0, path_1.relative)(parent, path);
8
8
  return rel !== '' && !rel.startsWith('..') && !(0, path_1.isAbsolute)(rel);
9
9
  }
10
+ exports.isInside = isInside;
10
11
  function getContainerBinds(item) {
11
12
  const sources = item.data.src.map((s) => s.absolutePath);
12
13
  const items = [
@@ -67,9 +67,8 @@ function describeOverview(server, overview, now = Date.now()) {
67
67
  const accounts = (run.approvals ?? [])
68
68
  .filter((approval) => !approval.approvedBy)
69
69
  .map((approval) => approval.account);
70
- lines.push(` ${(0, server_client_1.printable)(run.id)} ${describeWork(run)}${ownerOf(run)} needs ${accounts
71
- .map(server_client_1.printable)
72
- .join(', ')} until ${(0, server_client_1.printable)(run.approvals?.[0]?.expiresAt ?? '-')}`);
70
+ const expiresAt = run.approvals?.[0]?.expiresAt;
71
+ lines.push(` ${(0, server_client_1.printable)(run.id)} ${describeWork(run)}${ownerOf(run)} needs ${accounts.map(server_client_1.printable).join(', ')}${expiresAt ? ` until ${(0, server_client_1.printable)(expiresAt)}` : ' with no time limit'}`);
73
72
  }
74
73
  lines.push(`service runs: ${overview.services.open}${overview.services.max !== undefined ? ` of ${overview.services.max}` : ''} places taken on the server`);
75
74
  for (const run of overview.services.runs) {
@@ -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,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
@@ -6,6 +6,7 @@ const oauth_1 = require("./oauth");
6
6
  const runner_commands_1 = require("../executer/runner-commands");
7
7
  const run_logs_1 = require("./run-logs");
8
8
  const units_1 = require("../utils/units");
9
+ const long_timer_1 = require("../utils/long-timer");
9
10
  const FINAL_STATES = ['succeeded', 'failed', 'cancelled', 'rejected'];
10
11
  function isFinal(state) {
11
12
  return FINAL_STATES.includes(state);
@@ -306,7 +307,7 @@ class RunRegistry {
306
307
  this.keep = options.keep ?? 200;
307
308
  this.maxEvents = options.maxEvents ?? 5000;
308
309
  this.maxWaiting = options.maxWaiting ?? 100;
309
- this.approvalTimeout = options.approvalTimeout ?? 60 * 60 * 1000;
310
+ this.approvalTimeout = options.approvalTimeout;
310
311
  this.now = options.now ?? Date.now;
311
312
  this.maxLogBytes = options.maxLogBytes ?? Infinity;
312
313
  }
@@ -344,13 +345,18 @@ class RunRegistry {
344
345
  };
345
346
  this.entries.set(run.id, entry);
346
347
  if (run.state === 'awaiting-approval') {
347
- const left = Date.parse(run.approvals?.[0]?.expiresAt ?? '') - this.now();
348
- if (Number.isFinite(left) && left > 0) {
349
- entry.timer = setTimeout(() => this.expire(entry), left);
350
- entry.timer.unref();
351
- }
352
- else {
353
- this.finish(entry, 'rejected', 'nobody approved it in time');
348
+ // no expiry means no time limit: it waits until somebody decides. An expiry that can not
349
+ // be read rejects it, as a fail-safe; one that is past rejects it too
350
+ const expiresAt = run.approvals?.[0]?.expiresAt;
351
+ if (expiresAt !== undefined) {
352
+ const at = Date.parse(expiresAt);
353
+ const now = this.now();
354
+ if (!Number.isFinite(at) || at <= now) {
355
+ this.finish(entry, 'rejected', 'nobody approved it in time');
356
+ }
357
+ else {
358
+ entry.timer = (0, long_timer_1.setLongTimeout)(() => this.expire(entry), at - now);
359
+ }
354
360
  }
355
361
  }
356
362
  else if (run.state === 'asleep') {
@@ -503,13 +509,14 @@ class RunRegistry {
503
509
  this.entries.set(run.id, entry);
504
510
  if (waiting) {
505
511
  // before the first event, which is written down with the run
506
- const expiresAt = new Date(this.now() + this.approvalTimeout).toISOString();
507
- run.approvals = approvalAccounts.map((account) => ({ account, expiresAt }));
512
+ const expiresAt = this.approvalTimeout === undefined ? undefined : new Date(this.now() + this.approvalTimeout).toISOString();
513
+ run.approvals = approvalAccounts.map((account) => ({ account, ...(expiresAt ? { expiresAt } : {}) }));
508
514
  }
509
515
  this.record(entry, { type: 'state', state: run.state });
510
516
  if (waiting) {
511
- entry.timer = setTimeout(() => this.expire(entry), this.approvalTimeout);
512
- entry.timer.unref();
517
+ if (this.approvalTimeout !== undefined) {
518
+ entry.timer = (0, long_timer_1.setLongTimeout)(() => this.expire(entry), this.approvalTimeout);
519
+ }
513
520
  }
514
521
  else {
515
522
  this.queue.push(entry);
@@ -993,7 +1000,7 @@ class RunRegistry {
993
1000
  }
994
1001
  clearTimer(entry) {
995
1002
  if (entry.timer) {
996
- clearTimeout(entry.timer);
1003
+ entry.timer();
997
1004
  entry.timer = undefined;
998
1005
  }
999
1006
  }
@@ -1702,14 +1709,13 @@ class RunRegistry {
1702
1709
  this.queue.push(entry);
1703
1710
  this.dispatch();
1704
1711
  }
1705
- // Stops a service run at its expiry, and puts one that is up to sleep at its sleepsAt. A
1706
- // timer can't wait longer than about 24 days, so a longer one looks again then.
1712
+ // Stops a service run at its expiry, and puts one that is up to sleep at its sleepsAt.
1707
1713
  expireLater(entry) {
1708
1714
  this.clearTimer(entry);
1709
1715
  const expiresAt = Date.parse(entry.run.expiresAt ?? '');
1710
1716
  const sleepsAt = entry.run.state === 'up' ? Date.parse(entry.run.sleepsAt ?? '') : NaN;
1711
1717
  const next = Number.isFinite(sleepsAt) ? Math.min(expiresAt, sleepsAt) : expiresAt;
1712
- entry.timer = setTimeout(() => {
1718
+ entry.timer = (0, long_timer_1.setLongTimeout)(() => {
1713
1719
  var _a;
1714
1720
  if (isFinal(entry.run.state)) {
1715
1721
  return;
@@ -1740,8 +1746,7 @@ class RunRegistry {
1740
1746
  return;
1741
1747
  }
1742
1748
  this.expireLater(entry);
1743
- }, Math.max(0, Math.min(next - this.now(), 2 ** 31 - 1)));
1744
- entry.timer.unref();
1749
+ }, Math.max(0, next - this.now()));
1745
1750
  }
1746
1751
  keepsVolumes() {
1747
1752
  return this.options.up?.keepVolumes !== false;
@@ -493,10 +493,14 @@ exports.serverConfigSchema = zod_1.z
493
493
  entitlements: zod_1.z.array(exports.entitlementSchema).default([]),
494
494
  approvals: zod_1.z
495
495
  .object({
496
- // how long a run waits for its approval before it is rejected
497
- timeout: duration.default('1h'),
496
+ // how long a run waits for its approval before it is rejected, and a proposed version
497
+ // for its decision; unset, they wait until somebody decides
498
+ timeout: duration.optional(),
498
499
  // runs waiting at the same time, more are refused
499
500
  maxWaiting: zod_1.z.number().int().min(1).default(100),
501
+ // proposed build file versions one proposer may have waiting at the same time, more are
502
+ // refused: without a time limit they wait until somebody decides
503
+ maxWaitingPerProposer: zod_1.z.number().int().min(1).default(10),
500
504
  // after a version was rejected, who proposed it can not propose that build
501
505
  // file again, and nobody that version, for this long
502
506
  cooldown: duration.default('10m'),