centralu 0.1.0-beta.7 → 0.1.0-beta.71

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.
@@ -0,0 +1,635 @@
1
+ /**
2
+ * `centralu serve --switch`: the machine runs a version switch of the install the hub manages (docs/plans/remote-hub.md
3
+ * §10.5a, #1903). The hub places the new version beside the running one, then hands this one command over ssh, and from
4
+ * then on only reads the outcome (`--switch-status`). Whatever happens to the hub or the link after the handover, the
5
+ * switcher, detached here the way `--detach` detaches a host, stops the old host, switches the pointers, starts and
6
+ * checks the new version, and puts the old one back when it does not answer.
7
+ *
8
+ * The switcher is the launcher of the newer of the two versions. It drives the other one only through the CLI every
9
+ * managed version has (`serve --stop`, `serve --detach`, `serve --connection`), run on its own Node from its folder under
10
+ * `<data>/remote/versions/`, as the managed launcher runs it: nothing is imported across versions.
11
+ *
12
+ * What it does is in `<data>/remote/switch.json`, each step written before it is taken, and `switch.lock` names the live
13
+ * process at work. A switcher that died is finished by the next reader (`reconcile`): `--switch-status`, any `serve` or
14
+ * `--detach` there, or the next `--switch`.
15
+ */
16
+ import { spawn } from 'node:child_process'
17
+ import { closeSync, cpSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from 'node:fs'
18
+ import { randomBytes } from 'node:crypto'
19
+ import { join } from 'node:path'
20
+ import { answerLine, replaceFile, runCaptured, say, sleep, tail, waitUntil } from './serve-util.mjs'
21
+ import { isWriter, isWriterWithin, processStartTime, serveDataDir } from './serve-files.mjs'
22
+ import { POINTER_WORD, managedLauncherScript, parsePointer, remoteLayout } from './serve-install.mjs'
23
+ import { detachHow } from './serve-windows.mjs'
24
+
25
+ export const SWITCH_FILE = 'switch.json'
26
+ export const SWITCH_LOCK = 'switch.lock'
27
+ /**
28
+ * The version whose launcher ran the last switch, as a pointer line, written by the hub's handover command before it runs
29
+ * it: the one that reads its status (`--switch-status`), whatever `current` is by then, and that a prune keeps
30
+ */
31
+ export const SWITCH_RUNNER = 'switch.runner'
32
+
33
+ /** How long the started version has to say hello as itself (plan §10.5 step 4) */
34
+ const CHECK_MS = 30_000
35
+ const NO_ANSWER = `it did not answer within ${CHECK_MS / 1000} s`
36
+ /** How long the handover waits for the detached switcher to write its pid before it runs the switch itself */
37
+ const HANDOVER_MS = 10_000
38
+ /**
39
+ * A live pid whose creation time Windows cannot read (another logon's process) counts as the switcher while its record
40
+ * is younger than this: past the longest switch (a stop of 30 s, a start and check of 60 s, a put-back of 60 s), so a
41
+ * pid reused later is not believed for long
42
+ */
43
+ const UNREADABLE_ALIVE_MS = 10 * 60_000
44
+ /** The steps between a stop and the start that follows it: no other host may start then */
45
+ const QUIET_STEPS = new Set(['stop', 'backup', 'switch', 'restore_store', 'roll_back'])
46
+
47
+ const LOCAL_BUILD = /\.local\.\d+$/
48
+ const pointer = (v) => (v && POINTER_WORD.test(String(v.version)) && POINTER_WORD.test(String(v.node)) ? { version: v.version, node: v.node } : null)
49
+ const line = (p) => `${p.version} ${p.node}\n`
50
+
51
+ /**
52
+ * The switch the hub asked for, from `--switch`'s argument (base64url of the hub's JSON, update.ts `switchCommand`),
53
+ * which `--switch-run` is handed unchanged; null when it is not one
54
+ */
55
+ export function decodeSwitch(raw) {
56
+ try {
57
+ const p = JSON.parse(Buffer.from(String(raw), 'base64url').toString('utf8'))
58
+ const to = pointer(p?.to)
59
+ if (!to || typeof p.id !== 'string' || !/^[0-9A-Za-z-]{8,64}$/.test(p.id)) return null
60
+ const by = typeof p.by === 'string' ? p.by.replace(/[^\w .()@-]/g, '').slice(0, 80) : 'another computer'
61
+ const was = { current: pointer(p.was?.current), previous: pointer(p.was?.previous) }
62
+ return { id: p.id, by, to, keep: pointer(p.keep), was, saveStore: p.saveStore === true }
63
+ } catch {
64
+ return null
65
+ }
66
+ }
67
+
68
+ /** `--switch-run`'s second argument: the data folder, which a process WMI creates does not inherit (base64url) */
69
+ const dataDirArg = (env) => (env.CC_DATA_DIR ? [Buffer.from(env.CC_DATA_DIR, 'utf8').toString('base64url')] : [])
70
+ const withDataDir = (env, arg) => (arg ? { ...env, CC_DATA_DIR: Buffer.from(arg, 'base64url').toString('utf8') } : env)
71
+
72
+ /** A time as `--detach`, `serve` and the hub's refusal say it: HH:MM, local */
73
+ export const clockOf = (at) => (typeof at === 'number' ? new Date(at).toTimeString().slice(0, 5) : 'an unknown time')
74
+
75
+ function readJson(file) {
76
+ try {
77
+ return JSON.parse(readFileSync(file, 'utf8'))
78
+ } catch {
79
+ return null
80
+ }
81
+ }
82
+
83
+ /** `switch.json`, or null when there is none */
84
+ export function readSwitch(dataDir) {
85
+ const s = readJson(join(remoteLayout(dataDir).root, SWITCH_FILE))
86
+ return s && typeof s.id === 'string' ? s : null
87
+ }
88
+
89
+ function readPointerFile(file) {
90
+ try {
91
+ return parsePointer(readFileSync(file, 'utf8'))
92
+ } catch {
93
+ return null
94
+ }
95
+ }
96
+
97
+ /** Whether `switch.lock` names a live switcher (`isWriter`), a Windows pid of another logon counting for a while */
98
+ export function lockIsLive(holder, writer = isWriter) {
99
+ if (!holder || !Number.isInteger(holder.pid)) return false
100
+ return isWriterWithin(holder, UNREADABLE_ALIVE_MS, writer)
101
+ }
102
+
103
+ /**
104
+ * Takes `switch.lock` for `id`: an exclusive create naming this process, so of two switchers only one runs. A lock whose
105
+ * process is not alive is stale and is taken over, moved aside first so of two takers only one removes it. Null when a
106
+ * live process holds it. The function it returns releases it, only while it is still this one's
107
+ */
108
+ function takeLock(root, id) {
109
+ const file = join(root, SWITCH_LOCK)
110
+ const own = { id, pid: process.pid, started: processStartTime(process.pid), at: Date.now() }
111
+ for (let i = 0; i < 3; i++) {
112
+ try {
113
+ const fd = openSync(file, 'wx')
114
+ try {
115
+ writeSync(fd, JSON.stringify(own))
116
+ } finally {
117
+ closeSync(fd)
118
+ }
119
+ return () => {
120
+ const now = readJson(file)
121
+ if (now?.pid === own.pid && now.at === own.at) rmSync(file, { force: true })
122
+ }
123
+ } catch (e) {
124
+ if (e?.code !== 'EEXIST') throw e
125
+ }
126
+ const holder = readJson(file)
127
+ if (holder ? lockIsLive(holder) : youngerThan(file, 5_000)) return null
128
+ const aside = `${file}.${process.pid}-${randomBytes(4).toString('hex')}.stale`
129
+ try {
130
+ renameSync(file, aside)
131
+ rmSync(aside, { force: true })
132
+ } catch {
133
+ // moved by another taker first
134
+ }
135
+ }
136
+ return null
137
+ }
138
+
139
+ function youngerThan(file, ms) {
140
+ try {
141
+ return Date.now() - statSync(file).mtimeMs < ms
142
+ } catch {
143
+ return false
144
+ }
145
+ }
146
+
147
+ /** One managed version's Node and `centralu.mjs`, as the managed launcher finds them */
148
+ function versionPaths(l, v, platform) {
149
+ return {
150
+ node: platform === 'win32' ? join(l.node, `v${v.node}`, 'node.exe') : join(l.node, `v${v.node}`, 'bin', 'node'),
151
+ cli: join(l.versions, v.version, 'node_modules', 'centralu', 'bin', 'centralu.mjs'),
152
+ }
153
+ }
154
+
155
+ /** One version's `centralu serve <args>`, on its own Node, as the managed launcher runs it */
156
+ function serveOf(l, v, args, env, platform) {
157
+ const { node, cli } = versionPaths(l, v, platform)
158
+ return runCaptured(node, [cli, 'serve', ...args], { ...env, CENTRALU_MANAGED: '1' })
159
+ }
160
+
161
+ /** The last `{ v: 1, … }` line of `stdout` that `pick` finds something in */
162
+ function lastLine(stdout, pick) {
163
+ for (const l of String(stdout).split(/\r?\n/).reverse()) {
164
+ if (!l.trim().startsWith('{')) continue
165
+ try {
166
+ const o = JSON.parse(l)
167
+ if (o?.v === 1 && pick(o) !== undefined) return pick(o)
168
+ } catch {
169
+ // not a line of serve's
170
+ }
171
+ }
172
+ return undefined
173
+ }
174
+
175
+ /** The end of `host.log`, in one line for a sentence ("" when there is none) */
176
+ export function hostLogTail(dataDir) {
177
+ const text = tail(join(dataDir, 'host.log'), 12)
178
+ .split(/\r?\n/)
179
+ .map((s) => s.trim())
180
+ .filter(Boolean)
181
+ .slice(-4)
182
+ .join(' / ')
183
+ return text.length > 600 ? `…${text.slice(-600)}` : text
184
+ }
185
+
186
+ /**
187
+ * Writes both pointers (`previous` first, then `current`, each by rename) and the managed launcher when it is not there
188
+ * yet (an update over an npm install). A null `current` gives the machine back the Centralu it ran before: the pointers
189
+ * and the launcher go, so the lookup finds that one again
190
+ */
191
+ export function setPointers(dataDir, current, previous, platform = process.platform) {
192
+ const l = remoteLayout(dataDir)
193
+ const launcher = join(l.bin, platform === 'win32' ? 'centralu.cmd' : 'centralu')
194
+ if (!current) {
195
+ for (const f of [l.previous, l.current, launcher]) rmSync(f, { force: true })
196
+ return
197
+ }
198
+ for (const v of [current, previous].filter(Boolean)) {
199
+ if (!existsSync(join(l.versions, v.version, 'install.json')) || !existsSync(join(l.node, `v${v.node}`))) throw new Error(`Centralu ${v.version} on Node ${v.node} is not there`)
200
+ }
201
+ if (!existsSync(launcher)) {
202
+ mkdirSync(l.bin, { recursive: true })
203
+ replaceFile(launcher, managedLauncherScript(platform), { mode: 0o755 })
204
+ }
205
+ if (previous) replaceFile(l.previous, line(previous))
206
+ else rmSync(l.previous, { force: true })
207
+ replaceFile(l.current, line(current))
208
+ }
209
+
210
+ /**
211
+ * Removes every version that is neither `current` nor `previous` nor the switch's runner (which reads its outcome), every
212
+ * Node none of them uses, and the store copies of versions that are gone (plan §10.5 step 6). A folder that cannot go (a Windows program still running from it) stays
213
+ * and is named, never fatal
214
+ */
215
+ export function prune(dataDir) {
216
+ const l = remoteLayout(dataDir)
217
+ const keep = [readPointerFile(l.current), readPointerFile(l.previous), readPointerFile(join(l.root, SWITCH_RUNNER))].filter(Boolean)
218
+ const removed = []
219
+ const left = []
220
+ const sweep = (dir, kept, named = true) => {
221
+ let names = []
222
+ try {
223
+ names = readdirSync(dir)
224
+ } catch {
225
+ return
226
+ }
227
+ for (const name of names) {
228
+ if (kept(name) || (name.startsWith('.') && !name.startsWith('.replaced-'))) continue
229
+ try {
230
+ rmSync(join(dir, name), { recursive: true, force: true })
231
+ if (named && !name.startsWith('.')) removed.push(name)
232
+ } catch {
233
+ if (named) left.push(name)
234
+ }
235
+ }
236
+ }
237
+ sweep(l.versions, (n) => keep.some((p) => p.version === n))
238
+ // What the installer moved aside and could not remove then
239
+ sweep(l.root, (n) => !n.startsWith('.replaced-'))
240
+ sweep(l.node, (n) => keep.some((p) => `v${p.node}` === n))
241
+ sweep(join(l.root, 'store-backup'), (n) => keep.some((p) => p.version === n), false)
242
+ return { removed, left }
243
+ }
244
+
245
+ /** The files of the host's store in the data folder: the database and SQLite's write-ahead log beside it */
246
+ const STORE_FILES = ['store.db', 'store.db-wal', 'store.db-shm']
247
+
248
+ /**
249
+ * A copy of the store taken while no host runs, before a dev build first opens it (#1036): a dev build may migrate the
250
+ * store past what the version before it reads, which would then refuse to start. Kept per `owner`, the version that left
251
+ * the store so (`store-backup/<owner>/`), replaced whole
252
+ */
253
+ export function storeBackup(dataDir, owner, before) {
254
+ const dir = join(remoteLayout(dataDir).root, 'store-backup')
255
+ const partial = join(dir, `.partial-${process.pid}`)
256
+ mkdirSync(dir, { recursive: true })
257
+ rmSync(partial, { recursive: true, force: true })
258
+ try {
259
+ mkdirSync(partial, { recursive: true })
260
+ const files = STORE_FILES.filter((f) => existsSync(join(dataDir, f)))
261
+ for (const f of files) cpSync(join(dataDir, f), join(partial, f))
262
+ writeFileSync(join(partial, 'backup.json'), JSON.stringify({ owner, before, files, at: new Date().toISOString() }, null, 2) + '\n')
263
+ rmSync(join(dir, owner), { recursive: true, force: true })
264
+ renameSync(partial, join(dir, owner))
265
+ } finally {
266
+ rmSync(partial, { recursive: true, force: true })
267
+ }
268
+ }
269
+
270
+ /**
271
+ * Puts back the copy `storeBackup` took for `owner`, no host running; false when there is none. A write-ahead log the
272
+ * copy did not have is removed, so SQLite does not replay the dev build's changes onto it. The copy stays
273
+ */
274
+ export function storeRestore(dataDir, owner) {
275
+ const dir = join(remoteLayout(dataDir).root, 'store-backup', owner)
276
+ const meta = readJson(join(dir, 'backup.json'))
277
+ if (meta?.owner !== owner || !Array.isArray(meta.files)) return false
278
+ for (const f of STORE_FILES) rmSync(join(dataDir, f), { force: true })
279
+ for (const f of meta.files.filter((f) => STORE_FILES.includes(f))) cpSync(join(dir, f), join(dataDir, f))
280
+ return true
281
+ }
282
+
283
+ /**
284
+ * The work of one switch, in a data folder, with the steps written to `switch.json` as they are taken. `state` is the
285
+ * file's content; `finish` writes the outcome
286
+ */
287
+ function switchWork(dataDir, state, { env, platform }) {
288
+ const l = remoteLayout(dataDir)
289
+ const file = join(l.root, SWITCH_FILE)
290
+ /** Answers the switch as written, which `runSwitcher` and `reconcile` answer in turn (a status read prints it) */
291
+ const write = (patch) => {
292
+ Object.assign(state, patch, { at: Date.now() })
293
+ replaceFile(file, `${JSON.stringify(state)}\n`)
294
+ return state
295
+ }
296
+ const step = (s) => write({ step: s })
297
+ const from = state.was.current
298
+ const to = state.to
299
+
300
+ /** `serve --stop` of `v` (for an update: the stopping host lists the turns it ends, #1618) */
301
+ const stopWith = async (v) => {
302
+ const r = await serveOf(l, v, ['--stop'], { ...env, CENTRALU_STOP_BY: 'hub', CENTRALU_STOP_FOR: 'update' }, platform)
303
+ const stop = lastLine(r.stdout, (o) => o.stop)
304
+ if (!stop) return { ok: false, wasRunning: false, message: r.stderr.trim().split(/\r?\n/).at(-1) || `serve --stop gave no answer (exit ${r.code})` }
305
+ return { ok: stop.ok === true, wasRunning: stop.wasRunning === true, message: typeof stop.message === 'string' ? stop.message : null }
306
+ }
307
+
308
+ /**
309
+ * What answers within `ms`, by the connection line of the version `asker`: `{ ok: true }` once a host answers as
310
+ * `version` (null: any), `{ ok: false, other }` at once when one answers as another version, `{ ok: false }` when none
311
+ * did. Asked at least once
312
+ */
313
+ const hear = async (asker, version, ms = CHECK_MS) => {
314
+ const until = Date.now() + ms
315
+ for (;;) {
316
+ const r = await serveOf(l, asker, ['--connection'], env, platform)
317
+ const said = lastLine(r.stdout, (o) => (typeof o.port === 'number' ? o : undefined))
318
+ if (said?.hostRunning === true && (version === null || said.version === version)) return { ok: true }
319
+ if (said?.hostRunning === true && typeof said.version === 'string') return { ok: false, other: said.version }
320
+ if (Date.now() >= until) return { ok: false }
321
+ await sleep(1_000)
322
+ }
323
+ }
324
+
325
+ /**
326
+ * `v` started and answering as itself; otherwise why not. A start refused for WMI is left to the hub's link
327
+ * (`unchecked`). A host of another version found there instead was started meanwhile by something that does not ask
328
+ * the switch (a version from before it, through the sign-in task, the person or another hub): it is stopped and `v`
329
+ * started again, twice at most (#1907)
330
+ */
331
+ const startAndCheck = async (v, [startStep, checkStep] = ['start', 'check']) => {
332
+ for (let stopped = 0; ; stopped++) {
333
+ step(startStep)
334
+ const r = await serveOf(l, v, ['--detach'], env, platform)
335
+ const detach = lastLine(r.stdout, (o) => o.detach)
336
+ if (detach?.ok === false && detach.reason === 'wmi_blocked') return { why: null, unchecked: detach.message ?? 'WMI is blocked' }
337
+ const failed = detach?.ok === false ? (detach.message ?? 'it did not start') : !detach ? r.stderr.trim().split(/\r?\n/).at(-1) || `serve --detach gave no answer (exit ${r.code})` : null
338
+ if (checkStep) step(checkStep)
339
+ // A start that failed may have met a host starting meanwhile: a few seconds tell
340
+ const heard = await hear(v, v.version, failed ? 5_000 : CHECK_MS)
341
+ if (heard.ok) return { why: null }
342
+ if (!heard.other) return { why: failed ?? NO_ANSWER }
343
+ if (stopped === 2) return { why: `Centralu ${heard.other} answered there instead; something started it again during the switch` }
344
+ write({ startedMeanwhile: heard.other })
345
+ await stopWith(from && heard.other === from.version ? from : v)
346
+ }
347
+ }
348
+
349
+ /** The old version back after `why`: the new host stopped, the pointers as they were, the old host started and heard */
350
+ const putBack = async (why, extra = {}) => {
351
+ // `why` is kept from here, so a reader that finishes this put-back can still say it
352
+ write({ step: 'roll_back', why })
353
+ const log = hostLogTail(dataDir)
354
+ const stop = await stopWith(readPointerFile(l.current) ?? to)
355
+ const stopFailed = stop.ok ? null : stop.message
356
+ try {
357
+ setPointers(dataDir, from, state.was.previous, platform)
358
+ if (state.saveStore && from) storeRestore(dataDir, from.version)
359
+ if (state.wasRunning !== false) {
360
+ if (from) {
361
+ const back = await startAndCheck(from, ['restart', null])
362
+ if (back.why) throw new Error(back.why === NO_ANSWER ? `${NO_ANSWER} either` : back.why)
363
+ } else {
364
+ await startNpm(dataDir, env, platform)
365
+ if (!(await hear(to, null)).ok) throw new Error(`${NO_ANSWER} either`)
366
+ }
367
+ }
368
+ } catch (err) {
369
+ return write({ outcome: 'failed', stage: 'put_back', why, putBackWhy: err.message, stopFailed, log, ...extra })
370
+ }
371
+ return write({ outcome: 'put_back', why, log, ...extra })
372
+ }
373
+
374
+ return { step, write, stopWith, hear, startAndCheck, putBack, from, to }
375
+ }
376
+
377
+ /** The Centralu an npm install keeps its launcher for (`<data>/bin/centralu`), started again after a failed first switch */
378
+ function startNpm(dataDir, env, platform) {
379
+ const win = platform === 'win32'
380
+ const launcher = join(dataDir, 'bin', win ? 'centralu.cmd' : 'centralu')
381
+ if (!existsSync(launcher)) throw new Error('the Centralu that ran before has no launcher in the data folder')
382
+ return new Promise((resolve, reject) => {
383
+ const child = spawn(win ? `"${launcher}"` : launcher, ['serve', '--detach'], { env, stdio: 'ignore', shell: win, windowsHide: true })
384
+ child.once('error', reject)
385
+ child.once('close', () => resolve())
386
+ })
387
+ }
388
+
389
+ /**
390
+ * The switch itself (plan §10.5 steps 2 to 6): stop the running host, switch the pointers, start and check the new
391
+ * version, then prune; or put the old version back. `onLocked` runs once the lock is this one's. Returns the outcome
392
+ * written, or null when a live switcher holds the lock
393
+ */
394
+ export async function runSwitcher({ dataDir, params, env, platform = process.platform, onLocked = () => {} }) {
395
+ const l = remoteLayout(dataDir)
396
+ mkdirSync(l.root, { recursive: true })
397
+ const release = takeLock(l.root, params.id)
398
+ if (!release) return null
399
+ try {
400
+ const state = { v: 1, ...params, from: params.was.current, step: 'stop', startedAt: Date.now(), pid: process.pid, started: processStartTime(process.pid) }
401
+ const w = switchWork(dataDir, state, { env, platform })
402
+ w.write({})
403
+ onLocked(state)
404
+ const { from, to } = w
405
+ const stop = await w.stopWith(from ?? to)
406
+ if (!stop.ok) return w.write({ outcome: 'failed', stage: 'stop', why: stop.message ?? 'no reason given' })
407
+ w.write({ wasRunning: stop.wasRunning })
408
+ if (params.saveStore && from) {
409
+ w.step('backup')
410
+ try {
411
+ storeBackup(dataDir, from.version, to.version)
412
+ } catch (err) {
413
+ // Nothing was switched: the old version starts again as it was
414
+ if (stop.wasRunning) await w.startAndCheck(from, ['restart', null])
415
+ return w.write({ outcome: 'failed', stage: 'backup', why: err.message })
416
+ }
417
+ }
418
+ w.step('switch')
419
+ try {
420
+ setPointers(dataDir, to, params.keep, platform)
421
+ } catch (err) {
422
+ // `await`: the lock is released in `finally` only once the put-back is done
423
+ return await w.putBack(err.message)
424
+ }
425
+ let started = await w.startAndCheck(to)
426
+ let restored = false
427
+ // Leaving a dev build for a release that refuses the store the dev build left: the copy taken for it, and one more start (#1036)
428
+ if (started.why && !params.saveStore && LOCAL_BUILD.test(from?.version ?? '') && !LOCAL_BUILD.test(to.version)) {
429
+ w.step('restore_store')
430
+ await w.stopWith(to)
431
+ if (storeRestore(dataDir, to.version)) {
432
+ restored = true
433
+ started = await w.startAndCheck(to)
434
+ }
435
+ }
436
+ if (started.why) return await w.putBack(started.why)
437
+ return finishDone(dataDir, w, { ...(restored ? { restored } : {}), ...(started.unchecked ? { unchecked: started.unchecked } : {}) })
438
+ } finally {
439
+ release()
440
+ }
441
+ }
442
+
443
+ /** The new version answered: what no pointer, nor the switch's runner, names is removed, and the switch is `done` */
444
+ function finishDone(dataDir, w, extra = {}) {
445
+ w.step('prune')
446
+ let pruned = { removed: [], left: [] }
447
+ try {
448
+ pruned = prune(dataDir)
449
+ } catch {
450
+ // the next switch prunes again
451
+ }
452
+ return w.write({ outcome: 'done', ...pruned, ...extra })
453
+ }
454
+
455
+ /**
456
+ * A switch with no outcome whose switcher is not alive, finished by whoever read it, by the last step written: before
457
+ * the switch nothing changed (`failed`); from the switch until the check passed the old version is put back
458
+ * (`put_back`); after it (`prune`), `done`.
459
+ *
460
+ * What answers there decides first, and a reader never stops a host the switch did not start (#1907):
461
+ * - the version this part of the switch starts (the new one from the switch to the check, the old one in the
462
+ * put-back) answering as itself is taken as it is: `done`, or `put_back`; asked within the time the switcher would
463
+ * have given it, or once when that is past;
464
+ * - any other version answering, except the new one in the put-back (which the switch started and is ending), was
465
+ * started by someone else meanwhile (a version from before this switch asks none). It keeps serving: the old one
466
+ * with the pointers back as they were (`put_back`, `kept`), another with nothing changed (`failed`, stage `kept`).
467
+ * `start`: a host is started too (the old one, or the one that runs when nothing was switched); a caller that starts
468
+ * one itself next passes false. Answers the switch as it is now
469
+ */
470
+ export async function reconcile(dataDir, { env, platform = process.platform, start }) {
471
+ const s = readSwitch(dataDir)
472
+ if (!s || s.outcome) return s
473
+ const l = remoteLayout(dataDir)
474
+ if (lockIsLive(readJson(join(l.root, SWITCH_LOCK)))) return s
475
+ const release = takeLock(l.root, s.id)
476
+ if (!release) return readSwitch(dataDir)
477
+ try {
478
+ const again = readSwitch(dataDir)
479
+ if (!again || again.outcome) return again
480
+ const w = switchWork(dataDir, again, { env, platform })
481
+ if (again.step === 'prune') return finishDone(dataDir, w, { interrupted: true })
482
+ const now = readPointerFile(l.current)
483
+ const back = ['roll_back', 'restart'].includes(again.step)
484
+ const old = again.was.current
485
+ if (now && (back || ['switch', 'start', 'check'].includes(again.step))) {
486
+ // What this part of the switch starts; only it is waited for, and only when the pointers name it
487
+ const own = back ? old?.version : again.to.version
488
+ const left = (typeof again.at === 'number' ? again.at : 0) + (again.step === 'start' || again.step === 'restart' ? 2 : 1) * CHECK_MS - Date.now()
489
+ const heard = own ? await w.hear(now, own, now.version === own ? Math.max(0, left) : 0) : { ok: false }
490
+ if (heard.ok && now.version === own) {
491
+ return back ? w.write({ outcome: 'put_back', why: again.why ?? 'interrupted', interrupted: true }) : finishDone(dataDir, w, { interrupted: true })
492
+ }
493
+ const other = heard.ok ? own : heard.other
494
+ if (other && !(back && other === again.to.version)) {
495
+ const why = `Centralu ${other} was started there during the switch`
496
+ if (old && other === old.version) {
497
+ setPointers(dataDir, old, again.was.previous, platform)
498
+ return w.write({ outcome: 'put_back', why, kept: other, interrupted: true })
499
+ }
500
+ return w.write({ outcome: 'failed', stage: 'kept', why, kept: other, interrupted: true })
501
+ }
502
+ }
503
+ if (again.step === 'stop' || again.step === 'backup') {
504
+ w.write({ outcome: 'failed', stage: 'interrupted', why: 'interrupted before the switch', interrupted: true })
505
+ const now = readPointerFile(l.current)
506
+ if (start && now) await w.startAndCheck(now, ['restart', null])
507
+ return again
508
+ }
509
+ if (!start) again.wasRunning = false
510
+ return await w.putBack(again.why ?? 'interrupted', { interrupted: true })
511
+ } finally {
512
+ release()
513
+ }
514
+ }
515
+
516
+ /**
517
+ * Before `serve` or `--detach` starts a host (§10.5a "No host starts beside a switch"): `{ go: true }`; `{ go: false,
518
+ * by, startedAt }` while a live switcher is between a stop and its start; `{ go: false, rerun }` when a switcher that died
519
+ * was finished here and `current` now names another version than this one (`version`), which then serves instead
520
+ */
521
+ export async function beforeHostStart({ dataDir, env, version, platform = process.platform }) {
522
+ const s = readSwitch(dataDir)
523
+ if (!s || s.outcome) return { go: true }
524
+ const l = remoteLayout(dataDir)
525
+ if (lockIsLive(readJson(join(l.root, SWITCH_LOCK)))) return QUIET_STEPS.has(s.step) ? { go: false, by: s.by, startedAt: s.startedAt } : { go: true }
526
+ await reconcile(dataDir, { env, platform, start: false })
527
+ const now = readPointerFile(l.current)
528
+ if (env.CENTRALU_MANAGED === '1' && now && now.version !== version) return { go: false, rerun: now }
529
+ return { go: true }
530
+ }
531
+
532
+ /** What `--detach` and `serve` say while a switch is under way there */
533
+ export function switchingMessage(gate) {
534
+ return `an update from ${gate.by} started at ${clockOf(gate.startedAt)} is switching versions here; no host starts until it ends`
535
+ }
536
+
537
+ /**
538
+ * `serve`, `--detach` and `--window` ask this before anything else (centralu.mjs), so a switcher that died is finished
539
+ * whatever this version would refuse next: a host already answering, a missing host entry, a Node below the floor (#1907).
540
+ * Null: go on. Otherwise the exit code, having said why or run the version `current` names now
541
+ */
542
+ export async function gateHostStart({ env, home, version, detach, platform = process.platform, write = (s) => process.stdout.write(s) }) {
543
+ const dataDir = serveDataDir(env, home)
544
+ const gate = await beforeHostStart({ dataDir, env, version, platform })
545
+ if (gate.go) return null
546
+ if (gate.rerun) return rerunAs(dataDir, gate.rerun, process.argv.slice(2), env, platform)
547
+ const message = switchingMessage(gate)
548
+ if (detach) return answerLine(write, 'detach', { ok: false, how: detachHow(platform, env), reason: 'switching', by: gate.by, startedAt: gate.startedAt, message })
549
+ say(message)
550
+ return 1
551
+ }
552
+
553
+ /** Runs `centralu serve <args>` of the version `current` names, in this terminal; answers its exit code */
554
+ export function rerunAs(dataDir, v, args, env, platform = process.platform) {
555
+ const { node, cli } = versionPaths(remoteLayout(dataDir), v, platform)
556
+ return new Promise((resolve) => {
557
+ const child = spawn(node, [cli, ...args], { env: { ...env, CENTRALU_MANAGED: '1' }, stdio: 'inherit', windowsHide: true })
558
+ child.once('error', () => resolve(1))
559
+ child.once('close', (code) => resolve(code ?? 1))
560
+ })
561
+ }
562
+
563
+ /** The variable the hub's handover names the running version in (`<version> <node>`), written to `switch.runner` */
564
+ export const RUNNER_ENV = 'CENTRALU_SWITCH_RUNNER'
565
+
566
+ /**
567
+ * `centralu serve --switch <arg>`, the handover: starts the switcher outside this ssh session (`detachHow`, as
568
+ * `--detach` starts a host), waits until it wrote its pid, prints `{ v: 1, switch: { ok: true, id, pid } }` and exits.
569
+ * When nothing can be started outside the session (WMI blocked, a `wsl.exe` that never ran), or the one started never
570
+ * wrote its pid, the switch runs here in the session: a link drop then ends it, and the next reader finishes it
571
+ * (`reconcile`). `{ ok: false, reason: 'busy', by, startedAt }` while another switch runs there, having changed
572
+ * nothing: `switch.runner` is written only once this one may run
573
+ */
574
+ export async function runSwitch({ env, home, raw, cliPath, execPath = process.execPath, platform = process.platform, start, write = (s) => process.stdout.write(s) }) {
575
+ const params = decodeSwitch(raw)
576
+ if (!params) return answerLine(write, 'switch', { ok: false, reason: 'params', message: 'this is not a switch serve --switch can read' })
577
+ const dataDir = serveDataDir(env, home)
578
+ const l = remoteLayout(dataDir)
579
+ mkdirSync(l.root, { recursive: true })
580
+ await reconcile(dataDir, { env, platform, start: false })
581
+ const busy = () => {
582
+ const s = readSwitch(dataDir)
583
+ return answerLine(write, 'switch', { ok: false, reason: 'busy', by: s?.by ?? null, startedAt: s?.startedAt ?? null, message: `another switch runs there${s ? `, from ${s.by} since ${clockOf(s.startedAt)}` : ''}` })
584
+ }
585
+ if (lockIsLive(readJson(join(l.root, SWITCH_LOCK)))) return busy()
586
+ const runner = parsePointer(env[RUNNER_ENV])
587
+ if (runner) replaceFile(join(l.root, SWITCH_RUNNER), line(runner))
588
+ const startOutside = start ?? (await import('./serve-detach.mjs')).startDetached
589
+ const created = await startOutside({ how: detachHow(platform, env), execPath, args: [cliPath, 'serve', '--switch-run', raw, ...dataDirArg(env)], env: { ...env, CENTRALU_MANAGED: '1' }, cwd: dataDir })
590
+ if (created.ok && (await waitUntil(() => readSwitch(dataDir)?.id === params.id, HANDOVER_MS))) {
591
+ return answerLine(write, 'switch', { ok: true, id: params.id, pid: readSwitch(dataDir).pid })
592
+ }
593
+ // Never ran, or not yet: what was created is ended (WSL's `wsl.exe` that hangs, §10.4), and the switch runs here
594
+ if (created.ok && readSwitch(dataDir)?.id !== params.id) await created.stop?.()
595
+ let said = false
596
+ const done = await runSwitcher({
597
+ dataDir,
598
+ params,
599
+ env,
600
+ platform,
601
+ onLocked: () => {
602
+ said = true
603
+ answerLine(write, 'switch', { ok: true, id: params.id, pid: process.pid, inSession: true })
604
+ },
605
+ })
606
+ if (said) return 0
607
+ // The detached one took the lock after all
608
+ const s = readSwitch(dataDir)
609
+ return s?.id === params.id ? answerLine(write, 'switch', { ok: true, id: params.id, pid: s.pid }) : done === null ? busy() : 1
610
+ }
611
+
612
+ /** `centralu serve --switch-run <arg> [<data folder>]`: the detached switcher `runSwitch` started */
613
+ export async function runSwitchRun({ env, home, raw, dataDir: dataArg = null, platform = process.platform }) {
614
+ const params = decodeSwitch(raw)
615
+ if (!params) return 2
616
+ const runEnv = withDataDir(env, dataArg)
617
+ const done = await runSwitcher({ dataDir: serveDataDir(runEnv, home), params, env: runEnv, platform })
618
+ return done ? 0 : 1
619
+ }
620
+
621
+ /**
622
+ * `centralu serve --switch-status [--seen <id>]`: `{ v: 1, switchStatus: <switch.json> | null }`. A switch whose
623
+ * switcher died is finished first, its old version started (`reconcile`). `--seen <id>`: that switch's outcome was
624
+ * reported to the person, so a hub that links later does not report it again
625
+ */
626
+ export async function runSwitchStatus({ env, home, seen = null, platform = process.platform, write = (s) => process.stdout.write(s) }) {
627
+ const dataDir = serveDataDir(env, home)
628
+ let s = await reconcile(dataDir, { env, platform, start: true })
629
+ if (s && seen && s.id === seen && s.outcome && !s.seen) {
630
+ s = { ...s, seen: true }
631
+ replaceFile(join(remoteLayout(dataDir).root, SWITCH_FILE), `${JSON.stringify(s)}\n`)
632
+ }
633
+ write(`${JSON.stringify({ v: 1, switchStatus: s })}\n`)
634
+ return 0
635
+ }