centralu 0.1.0-beta.4 → 0.1.0-beta.41
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.
- package/bin/centralu.mjs +466 -117
- package/bin/node-floor.mjs +42 -0
- package/bin/platform.mjs +380 -0
- package/bin/semver.mjs +37 -4
- package/bin/serve-args.mjs +116 -0
- package/bin/serve-autostart.mjs +489 -0
- package/bin/serve-detach.mjs +289 -0
- package/bin/serve-files.mjs +299 -0
- package/bin/serve-handover.mjs +152 -0
- package/bin/serve-host.mjs +395 -0
- package/bin/serve-install.mjs +204 -0
- package/bin/serve-port.mjs +79 -0
- package/bin/serve-run.mjs +197 -0
- package/bin/serve-util.mjs +127 -0
- package/bin/serve-window.mjs +112 -0
- package/bin/serve-windows.mjs +171 -0
- package/bin/serve.mjs +37 -0
- package/bin/swap.mjs +48 -0
- package/package.json +10 -6
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The two launchers and the install they reach: `<data>/bin/centralu` that `serve` keeps for an npm
|
|
3
|
+
* install, and the managed install the hub writes over ssh (`<data>/remote/`, docs/plans/remote-hub.md
|
|
4
|
+
* §10.1), with the launcher that never changes and the pointers it reads.
|
|
5
|
+
*/
|
|
6
|
+
import { chmodSync, mkdirSync, readFileSync, statSync } from 'node:fs'
|
|
7
|
+
import { dirname, join } from 'node:path'
|
|
8
|
+
import { replaceFile, say } from './serve-util.mjs'
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The launcher `serve` keeps at `<data folder>/bin/centralu` (`centralu.cmd` on Windows).
|
|
12
|
+
*
|
|
13
|
+
* The client runs `ssh -T -o BatchMode=yes <target> centralu …`, and a non-interactive SSH shell
|
|
14
|
+
* reads no profile: npm's global bin under nvm, fnm, volta or `~/.npm-global` is not on its PATH,
|
|
15
|
+
* and often neither is `node`. So the plain name fails with exit 127, and the person, who just ran
|
|
16
|
+
* `centralu serve` in their own shell, sees no reason why. This file names both by absolute path,
|
|
17
|
+
* so `~/.centralu/bin/centralu` works from any shell. It is rewritten whenever it differs from
|
|
18
|
+
* what this run would write, which follows a Node upgrade or a moved npm prefix on the next start.
|
|
19
|
+
*/
|
|
20
|
+
export function launcherScript(platform, execPath, cliPath) {
|
|
21
|
+
if (platform === 'win32') {
|
|
22
|
+
// A batch file reads every % as the start of a variable (`100% cli.mjs" %*` came out as `100*`); %% is a literal one
|
|
23
|
+
const lit = (v) => String(v).replaceAll('%', '%%')
|
|
24
|
+
/*
|
|
25
|
+
* The file is UTF-8, and cmd.exe reads each line of a batch file in the console's code page as it reaches it: 949
|
|
26
|
+
* on a Korean Windows, where a profile folder named in Korean came out as other characters and node found no
|
|
27
|
+
* centralu.mjs there (#849). So the lines before the paths, all ASCII, switch the console to UTF-8 (65001), and the
|
|
28
|
+
* code page it had is put back on the line with the paths, ahead of node: cmd.exe reads and decodes a whole line
|
|
29
|
+
* before it runs any of it, so the paths are already read as UTF-8 by then. The console is the shell's that ran
|
|
30
|
+
* this, and node runs on the page it had; a Ctrl+C answered at "Terminate batch job (Y/N)?" ends this file
|
|
31
|
+
* before any later line, and a restore there was skipped. chcp is named by its full path: the shell's PATH may
|
|
32
|
+
* not have System32 on it.
|
|
33
|
+
*/
|
|
34
|
+
return [
|
|
35
|
+
'@echo off',
|
|
36
|
+
"rem Written by `centralu serve`: reaches this install without npm's folder on PATH.",
|
|
37
|
+
'setlocal',
|
|
38
|
+
'set "CENTRALU_CP="',
|
|
39
|
+
`for /f "tokens=2 delims=:." %%c in ('%SystemRoot%\\System32\\chcp.com') do set /a "CENTRALU_CP=%%c" >nul 2>&1`,
|
|
40
|
+
'%SystemRoot%\\System32\\chcp.com 65001 >nul 2>&1',
|
|
41
|
+
`(if defined CENTRALU_CP %SystemRoot%\\System32\\chcp.com %CENTRALU_CP% >nul 2>&1) & "${lit(execPath)}" "${lit(cliPath)}" %*`,
|
|
42
|
+
'exit /b %ERRORLEVEL%',
|
|
43
|
+
'',
|
|
44
|
+
].join('\r\n')
|
|
45
|
+
}
|
|
46
|
+
const q = (v) => `'${String(v).replaceAll("'", "'\\''")}'`
|
|
47
|
+
return (
|
|
48
|
+
'#!/bin/sh\n' +
|
|
49
|
+
"# Written by `centralu serve`: reaches this install from a shell whose PATH has neither npm's global\n" +
|
|
50
|
+
'# folder nor node (a non-interactive SSH session). Rewritten when node or the package moves.\n' +
|
|
51
|
+
`exec ${q(execPath)} ${q(cliPath)} "$@"\n`
|
|
52
|
+
)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Writes the launcher if it is missing or out of date. Returns its path. Never fatal to the caller */
|
|
56
|
+
export function ensureLauncher(dataDir, { platform = process.platform, execPath = process.execPath, cliPath }) {
|
|
57
|
+
const file = join(dataDir, 'bin', platform === 'win32' ? 'centralu.cmd' : 'centralu')
|
|
58
|
+
const want = launcherScript(platform, execPath, cliPath)
|
|
59
|
+
let have = null
|
|
60
|
+
try {
|
|
61
|
+
have = readFileSync(file, 'utf8')
|
|
62
|
+
} catch {
|
|
63
|
+
// not there yet
|
|
64
|
+
}
|
|
65
|
+
if (have !== want) {
|
|
66
|
+
mkdirSync(dirname(file), { recursive: true })
|
|
67
|
+
replaceFile(file, want, { mode: 0o755 })
|
|
68
|
+
}
|
|
69
|
+
if (platform !== 'win32' && (statSync(file).mode & 0o777) !== 0o755) chmodSync(file, 0o755)
|
|
70
|
+
return file
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* ensureLauncher, with a failure said on stderr instead of thrown: the launcher is a convenience.
|
|
75
|
+
*
|
|
76
|
+
* Not under the managed launcher (`CENTRALU_MANAGED=1`, docs/plans/remote-hub.md §10.1): an install
|
|
77
|
+
* the hub made over ssh has its own launcher in `<data>/remote/bin/`, which reads `current`. Writing
|
|
78
|
+
* `<data>/bin/centralu` from there would point an npm install's launcher at one managed version, and
|
|
79
|
+
* the two would rewrite each other's file on every start.
|
|
80
|
+
*/
|
|
81
|
+
export function keepLauncher(dataDir, cliPath, env) {
|
|
82
|
+
if (!cliPath || env?.CENTRALU_MANAGED === '1') return
|
|
83
|
+
try {
|
|
84
|
+
ensureLauncher(dataDir, { cliPath })
|
|
85
|
+
} catch (e) {
|
|
86
|
+
say(`could not write the launcher in ${join(dataDir, 'bin')}: ${e.message}`)
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* The install the hub manages on this machine (docs/plans/remote-hub.md §10.1): side-by-side
|
|
92
|
+
* versions, the pinned Node they run on, and two pointer files naming what runs and what to roll
|
|
93
|
+
* back to. The hub's installer writes it; `serve` only reads it.
|
|
94
|
+
*/
|
|
95
|
+
export function remoteLayout(dataDir) {
|
|
96
|
+
const root = join(dataDir, 'remote')
|
|
97
|
+
return {
|
|
98
|
+
root,
|
|
99
|
+
current: join(root, 'current'),
|
|
100
|
+
previous: join(root, 'previous'),
|
|
101
|
+
versions: join(root, 'versions'),
|
|
102
|
+
node: join(root, 'node'),
|
|
103
|
+
bin: join(root, 'bin'),
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** A word a pointer file may hold: a folder name, nothing a path could escape with */
|
|
108
|
+
const POINTER_WORD = /^[0-9A-Za-z][0-9A-Za-z.+-]{0,63}$/
|
|
109
|
+
|
|
110
|
+
/** `current` / `previous`: one line, "<centralu version> <node version>". null for anything else */
|
|
111
|
+
export function parsePointer(text) {
|
|
112
|
+
const m = /^\s*(\S+)[ \t]+(\S+)\s*$/.exec(String(text ?? ''))
|
|
113
|
+
if (!m || !POINTER_WORD.test(m[1]) || !POINTER_WORD.test(m[2])) return null
|
|
114
|
+
return { version: m[1], node: m[2] }
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Where a managed version came from, from its `install.json`: `{ kind: 'dev', commit, dirty }` for a dev build put
|
|
119
|
+
* there from a git commit (`pnpm remote-dev`, #1036), null for a release (or anything unreadable). The hub shows it
|
|
120
|
+
* on the machine's row, so a build no release produced is never mistaken for one.
|
|
121
|
+
*/
|
|
122
|
+
export function installSource(versionDir) {
|
|
123
|
+
try {
|
|
124
|
+
const s = JSON.parse(readFileSync(join(versionDir, 'install.json'), 'utf8')).source
|
|
125
|
+
if (s?.kind === 'dev' && typeof s.commit === 'string' && /^[0-9a-f]{7,64}$/.test(s.commit)) return { kind: 'dev', commit: s.commit, dirty: s.dirty === true }
|
|
126
|
+
} catch {
|
|
127
|
+
// no install.json, or not one this reads
|
|
128
|
+
}
|
|
129
|
+
return null
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* The connection line's `install` field (docs/plans/remote-hub.md §10.5): whether this command was
|
|
134
|
+
* started by the managed launcher, the managed install's `current` and `previous`, and the Node
|
|
135
|
+
* running this command. Read from the machine at every ask, never kept by the hub (S12).
|
|
136
|
+
*/
|
|
137
|
+
export function installInfo(dataDir, env, nodeVersion = process.versions.node) {
|
|
138
|
+
const l = remoteLayout(dataDir)
|
|
139
|
+
const read = (file) => {
|
|
140
|
+
let p
|
|
141
|
+
try {
|
|
142
|
+
p = parsePointer(readFileSync(file, 'utf8'))
|
|
143
|
+
} catch {
|
|
144
|
+
return null
|
|
145
|
+
}
|
|
146
|
+
const source = p && installSource(join(l.versions, p.version))
|
|
147
|
+
return p && source ? { ...p, source } : p
|
|
148
|
+
}
|
|
149
|
+
return { managed: env.CENTRALU_MANAGED === '1', current: read(l.current), previous: read(l.previous), node: nodeVersion }
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* The managed launcher, `<data>/remote/bin/centralu` (`centralu.cmd` on Windows), as the installer
|
|
154
|
+
* writes it (docs/plans/remote-hub.md §10.1, S8).
|
|
155
|
+
*
|
|
156
|
+
* **Its text never changes.** It reads `current` at every start and runs that version's
|
|
157
|
+
* `centralu.mjs` on that version's Node, so switching versions is one file replaced by a rename,
|
|
158
|
+
* atomic on both systems. A launcher rewritten per version would be replaced while it may be
|
|
159
|
+
* running, and cmd.exe reads a batch file by offset as it runs. It sets `CENTRALU_MANAGED=1`, so
|
|
160
|
+
* the `serve` it starts leaves `<data>/bin/` to an npm install on the same machine.
|
|
161
|
+
*
|
|
162
|
+
* Both refuse a pointer that holds anything but plain version words, so an edited `current` cannot
|
|
163
|
+
* point it outside the install.
|
|
164
|
+
*/
|
|
165
|
+
export function managedLauncherScript(platform) {
|
|
166
|
+
if (platform === 'win32') {
|
|
167
|
+
return (
|
|
168
|
+
[
|
|
169
|
+
'@echo off',
|
|
170
|
+
'rem The Centralu launcher for the install the app manages over SSH. It never changes: it reads',
|
|
171
|
+
'rem "current" at every start, so switching versions replaces that file and never this one.',
|
|
172
|
+
'setlocal',
|
|
173
|
+
'set "CENTRALU_REMOTE=%~dp0.."',
|
|
174
|
+
'set "CENTRALU_LINE="',
|
|
175
|
+
'set "CENTRALU_V="',
|
|
176
|
+
'set "CENTRALU_N="',
|
|
177
|
+
'set /p CENTRALU_LINE=<"%CENTRALU_REMOTE%\\current"',
|
|
178
|
+
'for /f "tokens=1,2" %%a in ("%CENTRALU_LINE%") do (set "CENTRALU_V=%%a" & set "CENTRALU_N=%%b")',
|
|
179
|
+
'if not defined CENTRALU_N goto none',
|
|
180
|
+
'echo %CENTRALU_V% %CENTRALU_N%| findstr /r /c:"^[0-9A-Za-z][0-9A-Za-z.+-]* [0-9A-Za-z][0-9A-Za-z.+-]*$" >nul || goto none',
|
|
181
|
+
'set CENTRALU_MANAGED=1',
|
|
182
|
+
'"%CENTRALU_REMOTE%\\node\\v%CENTRALU_N%\\node.exe" "%CENTRALU_REMOTE%\\versions\\%CENTRALU_V%\\node_modules\\centralu\\bin\\centralu.mjs" %*',
|
|
183
|
+
'exit /b %ERRORLEVEL%',
|
|
184
|
+
':none',
|
|
185
|
+
'echo Centralu: no version is installed in %CENTRALU_REMOTE% 1>&2',
|
|
186
|
+
'exit /b 1',
|
|
187
|
+
].join('\r\n') + '\r\n'
|
|
188
|
+
)
|
|
189
|
+
}
|
|
190
|
+
return [
|
|
191
|
+
'#!/bin/sh',
|
|
192
|
+
'# The Centralu launcher for the install the app manages over SSH. It never changes: it reads',
|
|
193
|
+
'# `current` at every start, so switching versions replaces that file and never this one.',
|
|
194
|
+
'remote=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd -P) || exit 1',
|
|
195
|
+
'v= n=',
|
|
196
|
+
'read -r v n < "$remote/current" 2>/dev/null',
|
|
197
|
+
'case "$v" in ""|[!0-9A-Za-z]*|*[!0-9A-Za-z.+-]*) echo "Centralu: no version is installed in $remote" >&2; exit 1 ;; esac',
|
|
198
|
+
'case "$n" in ""|[!0-9A-Za-z]*|*[!0-9A-Za-z.+-]*) echo "Centralu: no version is installed in $remote" >&2; exit 1 ;; esac',
|
|
199
|
+
'CENTRALU_MANAGED=1',
|
|
200
|
+
'export CENTRALU_MANAGED',
|
|
201
|
+
'exec "$remote/node/v$n/bin/node" "$remote/versions/$v/node_modules/centralu/bin/centralu.mjs" "$@"',
|
|
202
|
+
'',
|
|
203
|
+
].join('\n')
|
|
204
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/** The port `centralu serve` listens on: the default, the recorded one, and the next free one (#482) */
|
|
2
|
+
import { createServer } from 'node:net'
|
|
3
|
+
import { runCaptured } from './serve-util.mjs'
|
|
4
|
+
import { detachHow, windowsTool } from './serve-windows.mjs'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The port `serve` listens on unless told otherwise, and keeps across restarts.
|
|
8
|
+
*
|
|
9
|
+
* Stable, because the client is told it once per connection and the person may write it into an
|
|
10
|
+
* SSH config or a systemd unit. Below 20000 on purpose: every OS lends ports from its ephemeral
|
|
11
|
+
* range to outgoing connections (Linux 32768–60999, macOS and Windows 49152–65535), and the host
|
|
12
|
+
* itself hands out per-app view origins from 20000–32767 (views/origin-ports.ts). A default inside
|
|
13
|
+
* either range could be taken by something transient the day the host restarts.
|
|
14
|
+
*/
|
|
15
|
+
export const DEFAULT_SERVE_PORT = 17175
|
|
16
|
+
|
|
17
|
+
/** How many ports from the recorded one `serve` tries when it is taken (#482); none at or above 20000 */
|
|
18
|
+
export const SERVE_PORT_TRIES = 20
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The port `serve` starts the host on (#482): `{ port, from }`, `from` being the port it moved away
|
|
22
|
+
* from (null when it did not), or null when every candidate is taken.
|
|
23
|
+
*
|
|
24
|
+
* A port the person gave (`--port`) is used as given: they asked for that one. Otherwise the recorded
|
|
25
|
+
* port (else the default) when it is free, and when another program listens there, the next free
|
|
26
|
+
* one above it, below 20000 (the ranges `DEFAULT_SERVE_PORT` keeps out of). The host's ready line
|
|
27
|
+
* then records the port it got, so `--connection` reports it and the hub forwards to it.
|
|
28
|
+
*
|
|
29
|
+
* The usual other program is the other half of one Windows laptop: WSL2 relays a distro's
|
|
30
|
+
* 127.0.0.1 ports to Windows (`wslrelay.exe`), so a Windows install and a WSL install linked as two
|
|
31
|
+
* machines both wanted 17175, and whichever started second could not start at all.
|
|
32
|
+
* `taken(port)` answers whether something listens there.
|
|
33
|
+
*/
|
|
34
|
+
export async function chooseServePort({ asked, recorded, taken }) {
|
|
35
|
+
if (asked !== null && asked !== undefined) return { port: asked, from: null }
|
|
36
|
+
const first = recorded ?? DEFAULT_SERVE_PORT
|
|
37
|
+
for (let p = first; p < first + SERVE_PORT_TRIES && p <= 65535; p++) {
|
|
38
|
+
if (p !== first && p >= 20000) break
|
|
39
|
+
if (!(await taken(p))) return { port: p, from: p === first ? null : first }
|
|
40
|
+
}
|
|
41
|
+
return null
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Whether something listens on 127.0.0.1:`port` here: a listen that fails with EADDRINUSE (or EACCES) */
|
|
45
|
+
export function listensHere(port) {
|
|
46
|
+
return new Promise((resolve) => {
|
|
47
|
+
const srv = createServer()
|
|
48
|
+
srv.once('error', (e) => resolve(e?.code === 'EADDRINUSE' || e?.code === 'EACCES'))
|
|
49
|
+
srv.listen({ host: '127.0.0.1', port, exclusive: true }, () => srv.close(() => resolve(false)))
|
|
50
|
+
})
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* The TCP ports Windows listens on, from `netstat.exe -an -p TCP` output: a listening socket is the
|
|
55
|
+
* row whose foreign address is `0.0.0.0:0` (or `[::]:0`). Read that way rather than by the state
|
|
56
|
+
* column, which Windows translates (a Korean Windows does not print LISTENING everywhere).
|
|
57
|
+
*/
|
|
58
|
+
export function parseNetstatListening(text) {
|
|
59
|
+
const ports = new Set()
|
|
60
|
+
for (const line of String(text).split(/\r?\n/)) {
|
|
61
|
+
const m = /^\s*TCP\s+(?:127\.0\.0\.1|0\.0\.0\.0|\[::1?\]):(\d+)\s+(?:0\.0\.0\.0:0|\[::\]:0)\s/i.exec(line)
|
|
62
|
+
if (m) ports.add(Number(m[1]))
|
|
63
|
+
}
|
|
64
|
+
return ports
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The ports the Windows side listens on, seen from inside a WSL distro (empty elsewhere, or when
|
|
69
|
+
* Windows cannot be asked). Inside the distro a port Windows holds looks free, yet a host there
|
|
70
|
+
* would be unreachable from the hub: the hub's forward ends on Windows' 127.0.0.1, where the
|
|
71
|
+
* Windows program answers instead (#482).
|
|
72
|
+
*/
|
|
73
|
+
export async function windowsListening(env, platform) {
|
|
74
|
+
if (detachHow(platform, env) !== 'wsl') return new Set()
|
|
75
|
+
const netstat = windowsTool('wsl', env, ['System32', 'netstat.exe'])
|
|
76
|
+
if (!netstat) return new Set()
|
|
77
|
+
const r = await runCaptured(netstat, ['-an', '-p', 'TCP'], env)
|
|
78
|
+
return r.code === 0 ? parseNetstatListening(r.stdout) : new Set()
|
|
79
|
+
}
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
/** `centralu serve` in the foreground, `--connection` and `--rotate-token` */
|
|
2
|
+
import { spawn } from 'node:child_process'
|
|
3
|
+
import { writeFileSync, writeSync } from 'node:fs'
|
|
4
|
+
import { dirname, join } from 'node:path'
|
|
5
|
+
import { createInterface } from 'node:readline'
|
|
6
|
+
import { isAlive, say } from './serve-util.mjs'
|
|
7
|
+
import { SERVE_STATE_FILE, SERVE_PID_FILE, readStopped, serveDataDir, ensureServeState, recordServePort, rotateServeToken, heldHere, lockHolder, lockHolderPid, removeServePid } from './serve-files.mjs'
|
|
8
|
+
import { DEFAULT_SERVE_PORT, SERVE_PORT_TRIES, chooseServePort, listensHere, windowsListening } from './serve-port.mjs'
|
|
9
|
+
import { keepLauncher, installInfo } from './serve-install.mjs'
|
|
10
|
+
import { protocolVersionOf, connectionLine, hostEnv, hostCommand, readyPort, hostProvesOf, probeHost, serveFrom, takesTokenOnStdin, tokenLine } from './serve-host.mjs'
|
|
11
|
+
import { autostartInfo } from './serve-autostart.mjs'
|
|
12
|
+
import { moveIntoSignIn } from './serve-handover.mjs'
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* The data folder a command that may start or describe a host works in: its state, created on first use, and the
|
|
16
|
+
* launcher serve keeps there brought up to date (`keepLauncher`).
|
|
17
|
+
*/
|
|
18
|
+
export function serveFolder({ env, home, cliPath, platform = process.platform }) {
|
|
19
|
+
const dataDir = serveDataDir(env, home)
|
|
20
|
+
const state = ensureServeState(dataDir, platform)
|
|
21
|
+
keepLauncher(dataDir, cliPath, env)
|
|
22
|
+
return { dataDir, state }
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** What `--connection` answers, as fields: the running host's versions when one answers, else the installed ones */
|
|
26
|
+
export async function describe({ env, dataDir, state, entry, version }) {
|
|
27
|
+
const port = state.port ?? DEFAULT_SERVE_PORT
|
|
28
|
+
const installed = protocolVersionOf(entry)
|
|
29
|
+
// Whether the installed host proves it holds the token (#838): asked of the running one before its hello, and said in the line
|
|
30
|
+
const proof = hostProvesOf(entry)
|
|
31
|
+
const probe = await probeHost({ port, token: state.token, protocolVersion: installed, prove: proof })
|
|
32
|
+
const protocolVersion = (probe.running ? probe.protocolVersion : undefined) ?? installed
|
|
33
|
+
if (protocolVersion === null) return null
|
|
34
|
+
const hostRunning = heldHere(probe, dataDir)
|
|
35
|
+
// The person stopped it here (#1143): said while no host runs, so a hub starts none by itself
|
|
36
|
+
const stopped = hostRunning ? null : readStopped(dataDir)
|
|
37
|
+
return {
|
|
38
|
+
proof,
|
|
39
|
+
port,
|
|
40
|
+
token: state.token,
|
|
41
|
+
version: (probe.running ? probe.version : undefined) ?? version,
|
|
42
|
+
protocolVersion,
|
|
43
|
+
dataDir,
|
|
44
|
+
hostRunning,
|
|
45
|
+
install: installInfo(dataDir, env),
|
|
46
|
+
autostart: autostartInfo(dataDir, process.platform, env),
|
|
47
|
+
...(stopped ? { stopped } : {}),
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* `centralu serve --connection`. stdout carries exactly one line, the JSON; everything else goes to
|
|
53
|
+
* stderr. Exit 1 when there is no host to describe.
|
|
54
|
+
*/
|
|
55
|
+
export async function printConnection({ env, home, entry, version, cliPath }) {
|
|
56
|
+
const { dataDir, state } = serveFolder({ env, home, cliPath })
|
|
57
|
+
const d = await describe({ env, dataDir, state, entry, version })
|
|
58
|
+
if (!d) {
|
|
59
|
+
say(`cannot read the protocol version of the host at ${entry}`)
|
|
60
|
+
return 1
|
|
61
|
+
}
|
|
62
|
+
process.stdout.write(`${connectionLine(d)}\n`)
|
|
63
|
+
return 0
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* `centralu serve`. Resolves with the exit code once the host has exited.
|
|
68
|
+
*
|
|
69
|
+
* The host's stdout is read here and never passed on: its ready line carries the token, which is
|
|
70
|
+
* printed nowhere but `--connection`. Every other line the host writes to stdout (a lock conflict,
|
|
71
|
+
* a store from a newer build) it also writes to stderr, which is passed through untouched.
|
|
72
|
+
*
|
|
73
|
+
* `logFd` is serve.log of a detached launcher (`runDetachedChild`): the host's stderr goes there
|
|
74
|
+
* until it is ready, so a host that dies while starting (a native module that does not load, a store
|
|
75
|
+
* from a newer build) says why in a file `--detach` can quote. From then on host.log has every line,
|
|
76
|
+
* and serve.log stops growing.
|
|
77
|
+
*/
|
|
78
|
+
export async function runServe({ env, home, entry, version, cliPath, port: askedPort, from = null, platform = process.platform, execPath = process.execPath, logFd = null, handOver = moveIntoSignIn }) {
|
|
79
|
+
const { dataDir, state } = serveFolder({ env, home, cliPath, platform })
|
|
80
|
+
const protocolVersion = protocolVersionOf(entry)
|
|
81
|
+
|
|
82
|
+
// A serve that is already up answers on the port it recorded; say so before starting a host that
|
|
83
|
+
// would only fail on the data folder's lock with a less specific message.
|
|
84
|
+
const recorded = state.port ?? DEFAULT_SERVE_PORT
|
|
85
|
+
const existing = await probeHost({ port: recorded, token: state.token, protocolVersion, prove: hostProvesOf(entry) })
|
|
86
|
+
// A host the hub's ssh started before anyone signed in moves into this sign-in, once idle (#1224, serve-handover.mjs)
|
|
87
|
+
if (heldHere(existing, dataDir) && !(await handOver({ dataDir, entry, env, existing, platform }))) {
|
|
88
|
+
const pid = lockHolderPid(dataDir)
|
|
89
|
+
say(`centralu serve is already running for ${dataDir} on 127.0.0.1:${recorded}${pid ? ` (pid ${pid})` : ''}. Not starting a second one.`)
|
|
90
|
+
return 1
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const onWindows = await windowsListening(env, platform)
|
|
94
|
+
const chosen = await chooseServePort({ asked: askedPort, recorded: state.port, taken: async (p) => onWindows.has(p) || (await listensHere(p)) })
|
|
95
|
+
if (chosen === null) {
|
|
96
|
+
say(`another program listens on 127.0.0.1:${recorded} and on the ${SERVE_PORT_TRIES - 1} ports above it. Give a free one with --port <n>.`)
|
|
97
|
+
return 1
|
|
98
|
+
}
|
|
99
|
+
const port = chosen.port
|
|
100
|
+
if (chosen.from !== null) {
|
|
101
|
+
const who = onWindows.has(chosen.from) ? 'Windows' : 'another program'
|
|
102
|
+
say(`127.0.0.1:${chosen.from} is in use by ${who}; starting on ${port} instead (kept for the next start)`)
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const plan = hostCommand(execPath, entry, { port, dataDir, platform })
|
|
106
|
+
const onStdin = takesTokenOnStdin(entry)
|
|
107
|
+
const child = spawn(plan.command, plan.args, {
|
|
108
|
+
stdio: ['pipe', 'pipe', logFd === null ? 'inherit' : 'pipe'],
|
|
109
|
+
env: hostEnv(env, { dataDir, version, hostDir: dirname(entry), from: serveFrom(env, from), ...(onStdin ? {} : { legacyToken: state.token }) }),
|
|
110
|
+
detached: plan.detached,
|
|
111
|
+
windowsHide: true,
|
|
112
|
+
})
|
|
113
|
+
// The token, before anything else on the pipe the host watches (#538); stdin stays open for --watch-parent
|
|
114
|
+
if (onStdin) child.stdin.write(tokenLine(state.token))
|
|
115
|
+
|
|
116
|
+
let ready = false
|
|
117
|
+
if (logFd !== null) {
|
|
118
|
+
// Read to the end in any case: a pipe nobody drains stops the host once its buffer is full
|
|
119
|
+
child.stderr.on('data', (b) => {
|
|
120
|
+
if (ready) return
|
|
121
|
+
try {
|
|
122
|
+
writeSync(logFd, b)
|
|
123
|
+
} catch {
|
|
124
|
+
// the log is a convenience
|
|
125
|
+
}
|
|
126
|
+
})
|
|
127
|
+
}
|
|
128
|
+
if (child.pid) {
|
|
129
|
+
try {
|
|
130
|
+
writeFileSync(join(dataDir, SERVE_PID_FILE), `${JSON.stringify({ pid: process.pid, hostPid: child.pid, port })}\n`)
|
|
131
|
+
} catch (e) {
|
|
132
|
+
say(`could not write ${SERVE_PID_FILE}: ${e.message}`)
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
createInterface({ input: child.stdout }).on('line', (line) => {
|
|
136
|
+
const p = readyPort(line)
|
|
137
|
+
if (p === null || ready) return
|
|
138
|
+
ready = true
|
|
139
|
+
try {
|
|
140
|
+
recordServePort(dataDir, p, platform)
|
|
141
|
+
} catch (e) {
|
|
142
|
+
say(`could not record the port in ${join(dataDir, SERVE_STATE_FILE)}: ${e.message}`)
|
|
143
|
+
}
|
|
144
|
+
say(`listening on 127.0.0.1:${p} (Centralu ${version}, protocol ${protocolVersion ?? 'unknown'}, data ${dataDir})`)
|
|
145
|
+
if (logFd === null) say(`from your computer: ssh -N -L ${p}:127.0.0.1:${p} <this machine>, or let the app connect over SSH`)
|
|
146
|
+
else say(`the host's own log continues in ${join(dataDir, 'host.log')}`)
|
|
147
|
+
})
|
|
148
|
+
|
|
149
|
+
/*
|
|
150
|
+
* One signal to the host alone, whatever reached this launcher. SIGHUP (the terminal closed) is
|
|
151
|
+
* passed as SIGTERM: the host has no SIGHUP handler, and Node's default for it is to exit on the
|
|
152
|
+
* spot, skipping the shutdown that stops the agents. A second signal changes nothing on the host
|
|
153
|
+
* side (its shutdown runs once), so forwarding every one is safe.
|
|
154
|
+
*/
|
|
155
|
+
const forward = (sig) => {
|
|
156
|
+
if (child.exitCode !== null || child.signalCode !== null) return
|
|
157
|
+
if (platform === 'win32') return // the host shares the console and received Ctrl+C itself
|
|
158
|
+
try {
|
|
159
|
+
child.kill(sig === 'SIGHUP' ? 'SIGTERM' : sig)
|
|
160
|
+
} catch {
|
|
161
|
+
// already gone
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
const signals = platform === 'win32' ? ['SIGINT'] : ['SIGINT', 'SIGTERM', 'SIGHUP']
|
|
165
|
+
for (const s of signals) process.on(s, forward)
|
|
166
|
+
|
|
167
|
+
return await new Promise((resolve) => {
|
|
168
|
+
child.on('error', (e) => {
|
|
169
|
+
removeServePid(dataDir, process.pid)
|
|
170
|
+
say(`could not start the host (${plan.command}): ${e.message}`)
|
|
171
|
+
resolve(1)
|
|
172
|
+
})
|
|
173
|
+
child.on('exit', (code, signal) => {
|
|
174
|
+
for (const s of signals) process.off(s, forward)
|
|
175
|
+
removeServePid(dataDir, process.pid)
|
|
176
|
+
if (!ready && code !== 0) {
|
|
177
|
+
const holder = lockHolder(dataDir)
|
|
178
|
+
if (holder && holder.pid !== child.pid && isAlive(holder.pid)) {
|
|
179
|
+
// Who it is, when its host.lock says (#1223)
|
|
180
|
+
const who = { app: 'the Centralu window on this machine', keeper: "Centralu's keeper on this machine", serve: 'another centralu serve' }[holder.by] ?? 'probably the Centralu app on this machine'
|
|
181
|
+
say(`the host did not start. ${dataDir} belongs to another Centralu host (pid ${holder.pid}), ${who}. Quit it, or point CC_DATA_DIR at another folder.`)
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
if (logFd !== null) say(`the host exited (${signal ?? code})`)
|
|
185
|
+
resolve(code ?? (signal ? 1 : 0))
|
|
186
|
+
})
|
|
187
|
+
})
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** `centralu serve --rotate-token` */
|
|
191
|
+
export function rotateToken({ env, home }) {
|
|
192
|
+
const dataDir = serveDataDir(env, home)
|
|
193
|
+
rotateServeToken(dataDir)
|
|
194
|
+
say(`replaced the token in ${join(dataDir, SERVE_STATE_FILE)}.`)
|
|
195
|
+
say('A serve that is running keeps the old one until it restarts; clients read the new one with --connection.')
|
|
196
|
+
return 0
|
|
197
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Small helpers every `centralu serve` command uses: the log line (`say`), running a program for its
|
|
3
|
+
* output, a process check, and waiting.
|
|
4
|
+
*/
|
|
5
|
+
import { spawn } from 'node:child_process'
|
|
6
|
+
import { closeSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
|
|
7
|
+
import { renameWaitsForReaders } from './platform.mjs'
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Where `say` writes: stderr, except in a detached launcher, which nobody reads the stderr of and
|
|
11
|
+
* which writes serve.log instead (`runDetachedChild`).
|
|
12
|
+
*/
|
|
13
|
+
let sink = (text) => process.stderr.write(text)
|
|
14
|
+
|
|
15
|
+
/** Writes a line to stderr, prefixed so it reads apart from the host's own log lines */
|
|
16
|
+
export function say(line) {
|
|
17
|
+
sink(`[centralu serve] ${line}\n`)
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The one line `--detach`, `--stop` and `--autostart` answer with on stdout, `{ v: 1, [key]: value }`, its `message` said
|
|
22
|
+
* on stderr as well. Returns the exit code: 0 when `value.ok`, else 1.
|
|
23
|
+
*/
|
|
24
|
+
export function answerLine(write, key, value) {
|
|
25
|
+
if (value.message) say(value.message)
|
|
26
|
+
write(`${JSON.stringify({ v: 1, [key]: value })}\n`)
|
|
27
|
+
return value.ok ? 0 : 1
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Points `say` at `write` from here on (a detached launcher's serve.log) */
|
|
31
|
+
export function sayTo(write) {
|
|
32
|
+
sink = write
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Blocks this thread for `ms`, for the synchronous callers that cannot await (a rename that is retried) */
|
|
36
|
+
export function sleepSync(ms) {
|
|
37
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** What a rename over a file says on Windows while another handle has the target open (a reader, a virus scanner) */
|
|
41
|
+
const BUSY_CODES = new Set(['EPERM', 'EBUSY', 'EACCES'])
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* `rename`, tried again for up to `budgetMs` while the system refuses it because someone has the target open (#1041;
|
|
45
|
+
* `retry`: Windows only, `renameWaitsForReaders`). With `retry` off, and for any other error, it is one try. Backs off 10, 20, 40 ... 200 ms between tries; the last
|
|
46
|
+
* error is thrown when the budget is spent.
|
|
47
|
+
*/
|
|
48
|
+
export function renameRetrying(from, to, { retry = renameWaitsForReaders(), rename = renameSync, sleep = sleepSync, budgetMs = 5_000, now = Date.now } = {}) {
|
|
49
|
+
const t0 = now()
|
|
50
|
+
for (let delay = 10; ; delay = Math.min(delay * 2, 200)) {
|
|
51
|
+
try {
|
|
52
|
+
return rename(from, to)
|
|
53
|
+
} catch (e) {
|
|
54
|
+
if (!retry || !BUSY_CODES.has(e?.code) || now() - t0 + delay > budgetMs) throw e
|
|
55
|
+
}
|
|
56
|
+
sleep(delay)
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Replaces `file` with `text` at once: written to a temporary file beside it, then renamed over it, so a reader finds
|
|
62
|
+
* the old file or the new one and never half of one. `mode` and `flag` are the temporary file's: a private file is
|
|
63
|
+
* created with its mode from the first byte, and with `wx`, never written into a file that is already there.
|
|
64
|
+
* On Windows a rename fails while a reader has the target open, so it is retried (`renameRetrying`); when it still
|
|
65
|
+
* fails, the temporary file is removed and the error thrown, the old file untouched.
|
|
66
|
+
*/
|
|
67
|
+
export function replaceFile(file, text, { mode = 0o666, flag = 'w', ...rename } = {}) {
|
|
68
|
+
const tmp = `${file}.${process.pid}.tmp`
|
|
69
|
+
const fd = openSync(tmp, flag, mode)
|
|
70
|
+
try {
|
|
71
|
+
writeFileSync(fd, text)
|
|
72
|
+
} finally {
|
|
73
|
+
closeSync(fd)
|
|
74
|
+
}
|
|
75
|
+
try {
|
|
76
|
+
renameRetrying(tmp, file, rename)
|
|
77
|
+
} catch (e) {
|
|
78
|
+
rmSync(tmp, { force: true })
|
|
79
|
+
throw e
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function runCaptured(command, args, env) {
|
|
84
|
+
return new Promise((resolve) => {
|
|
85
|
+
let stdout = ''
|
|
86
|
+
let stderr = ''
|
|
87
|
+
let child
|
|
88
|
+
try {
|
|
89
|
+
child = spawn(command, args, { env, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true })
|
|
90
|
+
} catch (e) {
|
|
91
|
+
return resolve({ code: null, stdout, stderr: e.message })
|
|
92
|
+
}
|
|
93
|
+
child.stdout.on('data', (b) => (stdout += String(b)))
|
|
94
|
+
child.stderr.on('data', (b) => (stderr += String(b)))
|
|
95
|
+
child.once('error', (e) => resolve({ code: null, stdout, stderr: e.message }))
|
|
96
|
+
child.once('close', (code) => resolve({ code, stdout, stderr }))
|
|
97
|
+
})
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** The last lines of a file, for a reason; empty when it cannot be read */
|
|
101
|
+
export function tail(file, n = 15) {
|
|
102
|
+
try {
|
|
103
|
+
return readFileSync(file, 'utf8').trimEnd().split(/\r?\n/).slice(-n).join('\n')
|
|
104
|
+
} catch {
|
|
105
|
+
return ''
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
|
|
110
|
+
|
|
111
|
+
export async function waitUntil(pred, ms) {
|
|
112
|
+
const t0 = Date.now()
|
|
113
|
+
while (Date.now() - t0 < ms) {
|
|
114
|
+
if (await pred()) return true
|
|
115
|
+
await sleep(200)
|
|
116
|
+
}
|
|
117
|
+
return pred()
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function isAlive(pid) {
|
|
121
|
+
try {
|
|
122
|
+
process.kill(pid, 0)
|
|
123
|
+
return true
|
|
124
|
+
} catch (e) {
|
|
125
|
+
return e?.code === 'EPERM'
|
|
126
|
+
}
|
|
127
|
+
}
|