@kurvball/rehearse 1.2.1 → 1.3.0

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,14 +3,15 @@ import path from 'node:path';
3
3
  import { infoOf, overlay, topOf } from '../git/index.js';
4
4
  import { toPosix, refOf } from '../scenarios/index.js';
5
5
  import { RehearseError, errorText } from '../errors.js';
6
- import { broken, runnerOf } from '../kinds/index.js';
6
+ import { broken, runnerOf, } from '../kinds/index.js';
7
7
  import { fill } from '../manifest/index.js';
8
8
  import { signIn } from '../people/index.js';
9
- import { stateDir, bringDown, bringUp, liveServices, makeRoom, release, standinsFor, } from '../services/index.js';
9
+ import { stateDir, bringDown, bringUp, inUse, liveServices, makeRoom, release, standinsFor, } from '../services/index.js';
10
10
  import { VERSION } from '../version.js';
11
11
  import { applyWorld, chainOf } from '../worlds/index.js';
12
12
  export { applyWorld };
13
13
  import { cacheKeyOf, groupsOf } from './cache.js';
14
+ import { inTurn, slotsFor, unitsOf } from './parallel.js';
14
15
  import { baseVars } from './vars.js';
15
16
  const worldOf = (s, o) => o.world ?? s.world;
16
17
  const personOf = (s, o) => o.as ?? s.person;
@@ -66,193 +67,333 @@ function manifestFolderAsOnBothSides(m) {
66
67
  return '{{manifest}}';
67
68
  return inside ? `{{checkout}}/${toPosix(inside)}` : '{{checkout}}';
68
69
  }
69
- export async function runSide(m, checkout, scenarios, o) {
70
- const side = {
71
- checkout: infoOf(m, checkout, o.ref),
72
- observations: new Map(),
73
- broke: null,
74
- notRun: [],
70
+ async function planOf(m, world, group) {
71
+ const runners = new Map();
72
+ for (const s of group)
73
+ if (!runners.has(s.kind))
74
+ runners.set(s.kind, await runnerOf(s.kind));
75
+ const forEveryScenario = [
76
+ ...everyServiceWhenTheWorldAdds(m, world),
77
+ ...(m.signIn?.service ? [m.signIn.service] : []),
78
+ ];
79
+ const needed = new Set([
80
+ ...group.flatMap((s) => runners.get(s.kind).services(s, m)),
81
+ ...everyServiceWhenTheWorldAdds(m, world),
82
+ ]);
83
+ if (m.signIn?.service)
84
+ needed.add(m.signIn.service);
85
+ return {
86
+ world,
87
+ group,
88
+ runners,
89
+ needed,
90
+ servicesOf: (s) => [...new Set([...runners.get(s.kind).services(s, m), ...forEveryScenario])],
75
91
  };
76
- if (scenarios.length === 0)
77
- return side;
92
+ }
93
+ function undeclaredIn(m, needed) {
94
+ const undeclared = [...needed].filter((name) => !m.services[name]);
95
+ return undeclared.length
96
+ ? {
97
+ step: 'up',
98
+ says: `It needs the service ${undeclared.join(', ')}, which the manifest doesn't declare.`,
99
+ }
100
+ : null;
101
+ }
102
+ function upInAnotherWorld(checkout, world, leftUp) {
103
+ const other = leftUp.find((r) => (r.world ?? null) !== world);
104
+ return other
105
+ ? {
106
+ step: 'world',
107
+ says: `${other.name} is already up in ${checkout} with ${other.world ? `the world ${other.world}` : 'no world Rehearse built'}, not ${world ?? 'no world'}: run with --world ${other.world ?? '…'}, or stop it with \`rehearse down\`.`,
108
+ }
109
+ : null;
110
+ }
111
+ const everyOneOf = (group, why) => group.map((s) => ({ scenario: s, ...why, byItsRunner: false }));
112
+ async function runGroup(side, world, group, runners, needed, upAlready, rehearseCanVouchForTheirState) {
113
+ const { m, checkout, o } = side;
114
+ const out = { observations: new Map(), notRun: [], broke: null };
115
+ const started = [];
116
+ let running = upAlready;
117
+ const vars = () => baseVars(m, checkout, running);
118
+ let bringingUp = null;
78
119
  try {
79
- overlay(m, checkout);
120
+ const fresh = [...needed].filter((name) => !running.some((r) => r.name === name));
121
+ if (fresh.length)
122
+ await makeRoom(m, checkout, o.progress);
123
+ if (world && fresh.length)
124
+ await applyWorld(m, world, 'before', checkout, vars());
125
+ for (const name of Object.keys(m.services).filter((n) => fresh.includes(n))) {
126
+ bringingUp = name;
127
+ const r = await bringUp(m, m.services[name], checkout, {
128
+ world,
129
+ real: o.real,
130
+ vars: vars(),
131
+ progress: o.progress,
132
+ });
133
+ started.push(r);
134
+ running = [...running, r];
135
+ }
80
136
  }
81
137
  catch (error) {
82
- side.broke = { step: 'overlay', says: errorText(error) };
83
- return side;
138
+ for (const r of started)
139
+ await bringDown(m, r, o.progress);
140
+ out.broke = {
141
+ step: error instanceof RehearseError && error.code === 'world' ? 'world' : 'up',
142
+ says: errorText(error),
143
+ bringingUp,
144
+ };
145
+ return out;
84
146
  }
85
- side.checkout = infoOf(m, checkout, o.ref);
86
- const groups = o.groups ?? (await groupsOf(m, scenarios, o.world));
87
- const manifestAs = manifestFolderAsOnBothSides(m);
88
- const placed = (v) => placedIn(v, [
89
- [path.resolve(checkout), '{{checkout}}'],
90
- [path.resolve(m.dir), manifestAs],
91
- ]);
92
- const keepDir = path.join(stateDir(m.dir), 'runs', `${Date.now().toString(36)}-${path.basename(checkout)}`);
93
- mkdirSync(keepDir, { recursive: true });
94
- const worlds = new Map();
95
- for (const s of scenarios)
96
- worlds.set(worldOf(s, o), [...(worlds.get(worldOf(s, o)) ?? []), s]);
97
- for (const [world, group] of worlds) {
98
- const runners = new Map();
99
- for (const s of group)
100
- if (!runners.has(s.kind))
101
- runners.set(s.kind, await runnerOf(s.kind));
102
- const needed = new Set([
103
- ...group.flatMap((s) => runners.get(s.kind).services(s, m)),
104
- ...everyServiceWhenTheWorldAdds(m, world),
105
- ]);
106
- if (m.signIn?.service)
107
- needed.add(m.signIn.service);
108
- const undeclared = [...needed].filter((name) => !m.services[name]);
109
- if (undeclared.length) {
110
- for (const s of group)
111
- side.notRun.push({
112
- scenario: s,
113
- step: 'up',
114
- says: `It needs the service ${undeclared.join(', ')}, which the manifest doesn't declare.`,
115
- });
116
- continue;
117
- }
118
- const started = [];
119
- let running = await liveServices(m, checkout);
120
- const vars = () => baseVars(m, checkout, running);
121
- const leftUp = running.filter((r) => needed.has(r.name));
122
- const rehearseCanVouchForTheirState = leftUp.length === 0;
123
- const leftUpInAnotherWorld = leftUp.find((r) => (r.world ?? null) !== world);
124
- if (leftUpInAnotherWorld) {
125
- for (const s of group)
126
- side.notRun.push({
127
- scenario: s,
128
- step: 'world',
129
- says: `${leftUpInAnotherWorld.name} is already up in ${checkout} with ${leftUpInAnotherWorld.world ? `the world ${leftUpInAnotherWorld.world}` : 'no world Rehearse built'}, not ${world ?? 'no world'}: run with --world ${leftUpInAnotherWorld.world ?? '…'}, or stop it with \`rehearse down\`.`,
130
- });
131
- continue;
132
- }
133
- try {
134
- const fresh = [...needed].filter((name) => !running.some((r) => r.name === name));
135
- if (fresh.length)
136
- await makeRoom(m, checkout, o.progress);
137
- if (world && fresh.length)
138
- await applyWorld(m, world, 'before', checkout, vars());
139
- for (const name of Object.keys(m.services).filter((n) => fresh.includes(n))) {
140
- const r = await bringUp(m, m.services[name], checkout, {
147
+ try {
148
+ if (world && started.length)
149
+ await applyWorld(m, world, 'add', checkout, vars());
150
+ const someoneSignsIn = Boolean(m.signIn) || Object.values(m.people).some((p) => p.token);
151
+ const signedIn = async () => {
152
+ if (!someoneSignsIn)
153
+ return { tokens: {}, variables: {} };
154
+ const v = vars();
155
+ const signed = await signIn(m, {
156
+ cwd: checkout,
157
+ env: {},
158
+ fill: (t) => fill(t, { ...v, ...(world && { world }) }),
159
+ });
160
+ return { tokens: signed.tokens, variables: signed.variables };
161
+ };
162
+ let people = await signedIn();
163
+ const variables = () => ({ ...vars(), ...people.variables, ...(world && { world }) });
164
+ const signInAgain = async () => {
165
+ people = await signedIn();
166
+ return { tokens: people.tokens, variables: variables() };
167
+ };
168
+ const broughtUpAndUnused = new Set(started.map((r) => r.name));
169
+ for (const [kind, runner] of runners) {
170
+ const these = group.filter((s) => s.kind === kind);
171
+ const begun = Date.now();
172
+ let ran;
173
+ try {
174
+ ran = await runner.run(these, {
175
+ manifest: m,
176
+ checkout,
141
177
  world,
142
- real: o.real,
143
- vars: vars(),
178
+ as: o.as,
179
+ tokens: people.tokens,
180
+ variables: variables(),
181
+ running,
182
+ broughtUpAndUnused: new Set(broughtUpAndUnused),
183
+ signInAgain,
184
+ keep: side.keepDir,
144
185
  progress: o.progress,
145
186
  });
146
- started.push(r);
147
- running = [...running, r];
148
187
  }
149
- }
150
- catch (error) {
151
- for (const r of started)
152
- await bringDown(m, r, o.progress);
153
- side.broke = {
154
- step: error instanceof RehearseError && error.code === 'world' ? 'world' : 'up',
155
- says: errorText(error),
156
- };
157
- return side;
158
- }
159
- const notRun = (step, says) => group.forEach((s) => side.notRun.push({ scenario: s, step, says }));
160
- try {
161
- if (world && started.length)
162
- await applyWorld(m, world, 'add', checkout, vars());
163
- let tokens = {};
164
- let signedVars = {};
165
- if (m.signIn || Object.values(m.people).some((p) => p.token)) {
166
- const v = vars();
167
- const signed = await signIn(m, {
168
- cwd: checkout,
169
- env: {},
170
- fill: (t) => fill(t, { ...v, ...(world && { world }) }),
171
- });
172
- tokens = signed.tokens;
173
- signedVars = signed.variables;
188
+ catch (error) {
189
+ ran = new Map(these.map((s) => [s.id, broken('runner', errorText(error))]));
174
190
  }
175
- for (const [kind, runner] of runners) {
176
- const these = group.filter((s) => s.kind === kind);
177
- const begun = Date.now();
178
- let ran;
179
- try {
180
- ran = await runner.run(these, {
181
- manifest: m,
182
- checkout,
183
- world,
184
- as: o.as,
185
- tokens,
186
- variables: { ...vars(), ...signedVars, ...(world && { world }) },
187
- running,
188
- keep: keepDir,
189
- progress: o.progress,
190
- });
191
- }
192
- catch (error) {
193
- ran = new Map(these.map((s) => [s.id, broken('runner', errorText(error))]));
194
- }
195
- const ms = Math.round((Date.now() - begun) / Math.max(1, these.length));
196
- for (const s of these) {
197
- const r = ran.get(s.id);
198
- if (!r)
199
- continue;
200
- if (r.broke &&
201
- ['world', 'signIn', 'runner', 'driver', 'up'].includes(r.broke.step) &&
202
- r.observed === null) {
203
- side.notRun.push({ scenario: s, step: r.broke.step, says: r.broke.says });
204
- continue;
205
- }
206
- const services = runner.services(s, m);
207
- const person = personOf(s, o);
208
- side.observations.set(s.id, {
209
- v: 1,
210
- ok: r.ok,
211
- scenario: refOf(s),
212
- checkout: side.checkout,
213
- world,
214
- person,
215
- standins: standinUses(m, services, o.real),
216
- failures: placed(r.failures),
217
- broke: placed(r.broke),
218
- observed: placed(r.observed),
219
- artifacts: r.artifacts,
220
- ms,
221
- at: new Date().toISOString(),
222
- rehearse: VERSION,
223
- runner: runner.version,
224
- cacheKey: side.checkout.commit && !side.checkout.dirty && rehearseCanVouchForTheirState
225
- ? cacheKeyOf({
226
- group: groups.get(s.id) ?? null,
227
- commit: side.checkout.commit,
228
- scenario: s,
229
- world,
230
- person,
231
- real: [...o.real],
232
- runner,
233
- manifest: m,
234
- })
235
- : null,
236
- cached: false,
237
- });
191
+ for (const s of these)
192
+ for (const name of runner.services(s, m))
193
+ broughtUpAndUnused.delete(name);
194
+ const ms = Math.round((Date.now() - begun) / Math.max(1, these.length));
195
+ for (const s of these) {
196
+ const r = ran.get(s.id);
197
+ if (!r)
198
+ continue;
199
+ if (r.broke &&
200
+ ['world', 'signIn', 'runner', 'driver', 'up'].includes(r.broke.step) &&
201
+ r.observed === null) {
202
+ out.notRun.push({ scenario: s, step: r.broke.step, says: r.broke.says, byItsRunner: true });
203
+ continue;
238
204
  }
205
+ const services = runner.services(s, m);
206
+ const person = personOf(s, o);
207
+ out.observations.set(s.id, {
208
+ v: 1,
209
+ ok: r.ok,
210
+ scenario: refOf(s),
211
+ checkout: side.info,
212
+ world,
213
+ person,
214
+ standins: standinUses(m, services, o.real),
215
+ failures: side.placed(r.failures),
216
+ broke: side.placed(r.broke),
217
+ observed: side.placed(r.observed),
218
+ artifacts: r.artifacts,
219
+ ms,
220
+ at: new Date().toISOString(),
221
+ rehearse: VERSION,
222
+ runner: runner.version,
223
+ cacheKey: side.info.commit && !side.info.dirty && rehearseCanVouchForTheirState
224
+ ? cacheKeyOf({
225
+ group: side.groups.get(s.id) ?? null,
226
+ commit: side.info.commit,
227
+ scenario: s,
228
+ world,
229
+ person,
230
+ real: [...o.real],
231
+ runner,
232
+ manifest: m,
233
+ })
234
+ : null,
235
+ cached: false,
236
+ });
239
237
  }
240
238
  }
241
- catch (error) {
242
- notRun(error instanceof RehearseError && error.code === 'sign_in'
239
+ }
240
+ catch (error) {
241
+ out.notRun.push(...everyOneOf(group, {
242
+ step: error instanceof RehearseError && error.code === 'sign_in'
243
243
  ? 'signIn'
244
244
  : error instanceof RehearseError && error.code === 'world'
245
245
  ? 'world'
246
- : 'runner', errorText(error));
246
+ : 'runner',
247
+ says: errorText(error),
248
+ }));
249
+ }
250
+ finally {
251
+ if (o.keepUp)
252
+ for (const r of started)
253
+ release(r);
254
+ else
255
+ for (const r of started.toReversed())
256
+ await bringDown(m, r, o.progress);
257
+ }
258
+ return out;
259
+ }
260
+ const asNotRun = ({ byItsRunner: _byItsRunner, ...n }) => n;
261
+ function takeIn(side, ran) {
262
+ for (const [id, ob] of ran.observations)
263
+ side.observations.set(id, ob);
264
+ side.notRun.push(...ran.notRun.map(asNotRun));
265
+ }
266
+ async function oneWorldAfterAnother(scope, worlds, side) {
267
+ const { m, checkout } = scope;
268
+ for (const [world, group] of worlds) {
269
+ const plan = await planOf(m, world, group);
270
+ const undeclared = undeclaredIn(m, plan.needed);
271
+ if (undeclared) {
272
+ side.notRun.push(...everyOneOf(group, undeclared).map(asNotRun));
273
+ continue;
247
274
  }
248
- finally {
249
- if (o.keepUp)
250
- for (const r of started)
251
- release(r);
252
- else
253
- for (const r of started.toReversed())
254
- await bringDown(m, r, o.progress);
275
+ const running = await liveServices(m, checkout);
276
+ const leftUp = running.filter((r) => plan.needed.has(r.name));
277
+ const elsewhere = upInAnotherWorld(checkout, world, leftUp);
278
+ if (elsewhere) {
279
+ side.notRun.push(...everyOneOf(group, elsewhere).map(asNotRun));
280
+ continue;
255
281
  }
282
+ const ran = await runGroup(scope, world, group, plan.runners, plan.needed, running, leftUp.length === 0);
283
+ if (ran.broke) {
284
+ side.broke = { step: ran.broke.step, says: ran.broke.says };
285
+ return side;
286
+ }
287
+ takeIn(side, ran);
256
288
  }
257
289
  return side;
258
290
  }
291
+ function inTheOrderOneAfterAnotherWouldGive(plan, ran) {
292
+ const kinds = [...plan.runners.keys()];
293
+ const at = new Map(plan.group.map((s, i) => [s.id, i]));
294
+ const rank = (s, byItsRunner) => byItsRunner ? [0, kinds.indexOf(s.kind), at.get(s.id) ?? 0] : [1, 0, at.get(s.id) ?? 0];
295
+ const byRank = (a, b) => {
296
+ for (let i = 0; i < a.length; i += 1)
297
+ if (a[i] !== b[i])
298
+ return a[i] - b[i];
299
+ return 0;
300
+ };
301
+ const observations = ran
302
+ .flatMap((r) => [...r.observations])
303
+ .sort(([a], [b]) => byRank(rank(plan.group[at.get(a)], true), rank(plan.group[at.get(b)], true)));
304
+ const notRun = ran
305
+ .flatMap((r) => r.notRun)
306
+ .sort((a, b) => byRank(rank(a.scenario, a.byItsRunner), rank(b.scenario, b.byItsRunner)));
307
+ return { observations: new Map(observations), notRun, broke: null };
308
+ }
309
+ function brokeFirstOneAfterAnother(m, ran) {
310
+ const order = Object.keys(m.services);
311
+ const broke = ran.flatMap((r) => (r.broke ? [r.broke] : []));
312
+ const at = (b) => b.bringingUp === null ? -1 : order.indexOf(b.bringingUp);
313
+ return broke.sort((a, b) => at(a) - at(b))[0] ?? null;
314
+ }
315
+ async function inTurns(scope, worlds, side, slots) {
316
+ const { m, checkout } = scope;
317
+ const upAtFirst = await liveServices(m, checkout);
318
+ const upAtFirstNames = new Set(upAtFirst.map((r) => r.name));
319
+ const planned = [];
320
+ const units = [];
321
+ for (const [world, group] of worlds) {
322
+ const plan = await planOf(m, world, group);
323
+ const leftUp = upAtFirst.filter((r) => plan.needed.has(r.name));
324
+ const refused = undeclaredIn(m, plan.needed) ?? upInAnotherWorld(checkout, world, leftUp);
325
+ if (refused) {
326
+ planned.push({ refused: everyOneOf(group, refused) });
327
+ continue;
328
+ }
329
+ const these = unitsOf(m, { ...plan, at: planned.length, vouched: leftUp.length === 0 });
330
+ planned.push({ plan, units: these });
331
+ units.push(...these);
332
+ }
333
+ let firstWorldThatBroke = Infinity;
334
+ const results = await inTurn(units, slots, async (u) => {
335
+ const running = (await liveServices(m, checkout)).filter((r) => u.needed.has(r.name) || upAtFirstNames.has(r.name));
336
+ const ran = await runGroup(scope, u.world, u.members, u.runners, u.needed, running, u.vouched);
337
+ if (ran.broke)
338
+ firstWorldThatBroke = Math.min(firstWorldThatBroke, u.at);
339
+ return ran;
340
+ }, (u) => u.at >= firstWorldThatBroke);
341
+ for (const p of planned) {
342
+ if ('refused' in p) {
343
+ side.notRun.push(...p.refused.map(asNotRun));
344
+ continue;
345
+ }
346
+ const ran = p.units.flatMap((u) => results[units.indexOf(u)] ?? []);
347
+ const broke = brokeFirstOneAfterAnother(m, ran);
348
+ if (broke) {
349
+ side.broke = { step: broke.step, says: broke.says };
350
+ return side;
351
+ }
352
+ takeIn(side, inTheOrderOneAfterAnotherWouldGive(p.plan, ran));
353
+ }
354
+ return side;
355
+ }
356
+ export function runSide(m, checkout, scenarios, o) {
357
+ return runSideSharing(m, checkout, scenarios, o, slotsFor(o.parallel ?? 1));
358
+ }
359
+ export function runSideSharing(m, checkout, scenarios, o, slots) {
360
+ return inUse(checkout, async () => {
361
+ const side = {
362
+ checkout: infoOf(m, checkout, o.ref),
363
+ observations: new Map(),
364
+ broke: null,
365
+ notRun: [],
366
+ };
367
+ if (scenarios.length === 0)
368
+ return side;
369
+ try {
370
+ overlay(m, checkout);
371
+ }
372
+ catch (error) {
373
+ side.broke = { step: 'overlay', says: errorText(error) };
374
+ return side;
375
+ }
376
+ side.checkout = infoOf(m, checkout, o.ref);
377
+ const manifestAs = manifestFolderAsOnBothSides(m);
378
+ const keepDir = path.join(stateDir(m.dir), 'runs', `${Date.now().toString(36)}-${path.basename(checkout)}`);
379
+ mkdirSync(keepDir, { recursive: true });
380
+ const scope = {
381
+ m,
382
+ checkout,
383
+ o,
384
+ info: side.checkout,
385
+ groups: o.groups ?? (await groupsOf(m, scenarios, o.world)),
386
+ keepDir,
387
+ placed: (v) => placedIn(v, [
388
+ [path.resolve(checkout), '{{checkout}}'],
389
+ [path.resolve(m.dir), manifestAs],
390
+ ]),
391
+ };
392
+ const worlds = new Map();
393
+ for (const s of scenarios)
394
+ worlds.set(worldOf(s, o), [...(worlds.get(worldOf(s, o)) ?? []), s]);
395
+ return (o.parallel ?? 1) > 1 && !o.keepUp
396
+ ? inTurns(scope, worlds, side, slots)
397
+ : oneWorldAfterAnother(scope, worlds, side);
398
+ });
399
+ }
@@ -1,2 +1,2 @@
1
1
  export { alive, runningServices, stateDir, type Running } from './registry.ts';
2
- export { bringDown, bringUp, downStartedHere, freePort, liveServices, makeRoom, release, restart, restartable, standinsFor, } from './service.ts';
2
+ export { bringDown, bringUp, downStartedHere, freePort, inUse, liveServices, makeRoom, release, restart, restartable, standinsFor, } from './service.ts';
@@ -1,2 +1,2 @@
1
1
  export { alive, runningServices, stateDir } from './registry.js';
2
- export { bringDown, bringUp, downStartedHere, freePort, liveServices, makeRoom, release, restart, restartable, standinsFor, } from './service.js';
2
+ export { bringDown, bringUp, downStartedHere, freePort, inUse, liveServices, makeRoom, release, restart, restartable, standinsFor, } from './service.js';
@@ -1,6 +1,7 @@
1
1
  import { type Manifest, type Service, type Standin } from '../manifest/index.ts';
2
2
  import { type Running } from './registry.ts';
3
3
  export declare function freePort(): Promise<number>;
4
+ export declare function inUse<T>(checkout: string, work: () => Promise<T>): Promise<T>;
4
5
  export declare function standinsFor(m: Manifest, service: string, real: ReadonlySet<string>): {
5
6
  standin: Standin;
6
7
  real: boolean;
@@ -14,7 +15,7 @@ export interface UpOptions {
14
15
  export declare const logOf: (m: Manifest, name: string, checkout: string) => string;
15
16
  export declare function liveServices(m: Manifest, checkout?: string | null): Promise<Running[]>;
16
17
  export declare const restartable: (r: Running) => boolean;
17
- export declare function restart(m: Manifest, r: Running): Promise<string | null>;
18
+ export declare function restart(m: Manifest, r: Running, whileDown?: () => Promise<void>): Promise<string | null>;
18
19
  export declare const release: (r: Running) => boolean;
19
20
  export declare function downStartedHere(): Promise<void>;
20
21
  export declare function bringUp(m: Manifest, s: Service, checkout: string, options: UpOptions): Promise<Running>;
@@ -8,17 +8,44 @@ import { fill, fillEnv } from '../manifest/index.js';
8
8
  import { alive, checkoutKey, forget, remember, runningServices, stateDir } from './registry.js';
9
9
  const POLL_MS = 250;
10
10
  const STOP_MS = 5_000;
11
- export function freePort() {
12
- return new Promise((resolve, reject) => {
13
- const server = createServer();
14
- server.unref();
15
- server.once('error', reject);
16
- server.listen(0, '127.0.0.1', () => {
17
- const address = server.address();
18
- const port = typeof address === 'object' && address ? address.port : 0;
19
- server.close(() => resolve(port));
20
- });
11
+ const TRIES_FOR_A_PORT_NOT_YET_HANDED_OUT = 20;
12
+ const anyFreePort = () => new Promise((resolve, reject) => {
13
+ const server = createServer();
14
+ server.unref();
15
+ server.once('error', reject);
16
+ server.listen(0, '127.0.0.1', () => {
17
+ const address = server.address();
18
+ const port = typeof address === 'object' && address ? address.port : 0;
19
+ server.close(() => resolve(port));
21
20
  });
21
+ });
22
+ const LONG_ENOUGH_FOR_ITS_SERVICE_TO_LISTEN_MS = 120_000;
23
+ const handedOutAt = new Map();
24
+ export async function freePort() {
25
+ const now = Date.now();
26
+ for (const [port, at] of handedOutAt)
27
+ if (now - at > LONG_ENOUGH_FOR_ITS_SERVICE_TO_LISTEN_MS)
28
+ handedOutAt.delete(port);
29
+ let port = await anyFreePort();
30
+ for (let i = 0; i < TRIES_FOR_A_PORT_NOT_YET_HANDED_OUT && handedOutAt.has(port); i += 1)
31
+ port = await anyFreePort();
32
+ handedOutAt.set(port, now);
33
+ return port;
34
+ }
35
+ const checkoutsInUseHere = new Map();
36
+ export async function inUse(checkout, work) {
37
+ const key = path.resolve(checkout);
38
+ checkoutsInUseHere.set(key, (checkoutsInUseHere.get(key) ?? 0) + 1);
39
+ try {
40
+ return await work();
41
+ }
42
+ finally {
43
+ const left = (checkoutsInUseHere.get(key) ?? 1) - 1;
44
+ if (left > 0)
45
+ checkoutsInUseHere.set(key, left);
46
+ else
47
+ checkoutsInUseHere.delete(key);
48
+ }
22
49
  }
23
50
  const portTaken = (port) => new Promise((resolve) => {
24
51
  const socket = connect({ port, host: '127.0.0.1' });
@@ -117,13 +144,14 @@ function readyVarsOf(m, r) {
117
144
  ...(r.url && { url: r.url }),
118
145
  };
119
146
  }
120
- export async function restart(m, r) {
147
+ export async function restart(m, r, whileDown = async () => undefined) {
121
148
  const s = m.services[r.name];
122
149
  if (!s || !restartable(r))
123
150
  return null;
124
151
  const cwd = s.cwd ? path.resolve(r.checkout, s.cwd) : r.checkout;
125
152
  const env = r.env ?? {};
126
153
  await sh(r.down, { cwd, env, timeoutMs: 60_000 });
154
+ await whileDown();
127
155
  const up = await sh(r.up, { cwd, env, timeoutMs: s.timeoutMs });
128
156
  const upSaidThisTime = logOf(m, s.name, r.checkout);
129
157
  writeFileSync(upSaidThisTime, `${up.stdout}${up.stderr}`);
@@ -276,7 +304,8 @@ export async function makeRoom(m, checkout, progress) {
276
304
  const over = sets.length + 1 - m.budget.services;
277
305
  if (over <= 0)
278
306
  return;
279
- for (const set of sets.slice(0, over)) {
307
+ const notInUseHere = sets.filter((set) => !checkoutsInUseHere.has(set));
308
+ for (const set of notInUseHere.slice(0, over)) {
280
309
  progress?.(`The budget allows ${m.budget.services} set${m.budget.services === 1 ? '' : 's'} of services at once: stopping those in ${set}.`);
281
310
  for (const r of others.filter((x) => path.resolve(x.checkout) === set))
282
311
  await bringDown(m, r, progress);
@@ -11,6 +11,8 @@ export interface StageScope {
11
11
  cwd: string;
12
12
  head: string | null;
13
13
  base: string | null;
14
+ announce: string | null;
15
+ said: readonly string[];
14
16
  progress: (line: string) => void;
15
17
  };
16
18
  head: {
package/dist/stage/api.js CHANGED
@@ -155,8 +155,8 @@ export function apiOf(s) {
155
155
  base: s.asked.base,
156
156
  ids: [id],
157
157
  affected: false,
158
- announce: null,
159
- said: [],
158
+ announce: s.asked.announce,
159
+ said: [...s.asked.said],
160
160
  fresh: false,
161
161
  world,
162
162
  as,
@@ -13,6 +13,8 @@ export interface StageOptions {
13
13
  base: string | null;
14
14
  port: number;
15
15
  anyPort?: boolean;
16
+ announce?: string | null;
17
+ said?: readonly string[];
16
18
  progress: (line: string) => void;
17
19
  }
18
20
  export interface Stage {