@infosupport/huddle-cli 0.0.0-experiment-109.66.1 → 0.0.0-experiment-56.68.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,174 +0,0 @@
1
- "use strict";
2
- // Does the gateway container ACTUALLY reach Huddle Node?
3
- //
4
- // control-address.ts derives an answer from what the engine says it is. That
5
- // derivation has one assumption in it — "engine in a VM ⇒ the host is reachable
6
- // on its loopback via host.docker.internal" — and it is false on Rancher
7
- // Desktop for Windows: the engine runs in a WSL distro, `host.docker.internal`
8
- // resolves to that distro's docker0 gateway (172.17.0.1), and Huddle Node is a
9
- // Windows process bound to the Windows loopback. The name resolves, nothing
10
- // listens, and the gateway fails closed: every devcontainer is denied all egress
11
- // and nothing is filed as `requested`, because a gateway with no policy is not
12
- // allowed to invent one.
13
- //
14
- // A derivation cannot tell that apart from a working setup. A connection can.
15
- // So init stops guessing: it starts Node, then opens the real connection from a
16
- // throwaway container, and only trusts an address that answered.
17
- //
18
- // Split from control-address.ts because everything here SPAWNS — the pure
19
- // decision stays testable without an engine, and the parsers below are exported
20
- // for the same reason.
21
- var __importDefault = (this && this.__importDefault) || function (mod) {
22
- return (mod && mod.__esModule) ? mod : { "default": mod };
23
- };
24
- Object.defineProperty(exports, "__esModule", { value: true });
25
- exports.parseProbeOutput = parseProbeOutput;
26
- exports.probeControlUrl = probeControlUrl;
27
- exports.parseDefaultGateway = parseDefaultGateway;
28
- exports.engineHostAddress = engineHostAddress;
29
- exports.hostCandidateUrls = hostCandidateUrls;
30
- exports.localIpv4Addresses = localIpv4Addresses;
31
- exports.pickBindAddress = pickBindAddress;
32
- const child_process_1 = require("child_process");
33
- const os_1 = __importDefault(require("os"));
34
- /** How long any single engine call may take before we call it a failure. */
35
- const PROBE_TIMEOUT_MS = 25_000;
36
- /**
37
- * Run the probe inside the gateway image itself.
38
- *
39
- * That image, not a stock one: it is already present (init just pulled or built
40
- * it), so this costs no download, and it is the exact runtime the real gateway
41
- * uses — same Node, same DNS resolution, same TLS stack.
42
- */
43
- function runInImage(rt, image, runArgs, entrypoint, cmdArgs = []) {
44
- try {
45
- return (0, child_process_1.execFileSync)(rt, ['run', '--rm', '--entrypoint', entrypoint, ...runArgs, image, ...cmdArgs], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: PROBE_TIMEOUT_MS });
46
- }
47
- catch {
48
- return null;
49
- }
50
- }
51
- // The script the probe container runs. One line, because it travels as an argv
52
- // entry through a shell on Windows. A 4s timeout of its own: an address that is
53
- // silently dropped (a host firewall) must come back as a result, not as a hang.
54
- const PROBE_SCRIPT = "fetch(process.env.PROBE_URL + '/control/health', { signal: AbortSignal.timeout(4000) })" +
55
- ".then(r => console.log('PROBE_HTTP ' + r.status))" +
56
- ".catch(e => console.log('PROBE_ERR ' + ((e.cause && e.cause.code) || e.name || e.message)))";
57
- /**
58
- * Read the probe container's single line of output.
59
- *
60
- * ANY HTTP status means reachable, and 401 is the expected one: /control/health
61
- * is behind the gateway token and the probe deliberately sends none. What is
62
- * being tested is whether the packets arrive, not whether we are authorised —
63
- * the token is checked separately, and conflating the two is how "unreachable"
64
- * ends up hiding a token mismatch.
65
- */
66
- function parseProbeOutput(out) {
67
- if (out === null)
68
- return { reachable: false, detail: 'the probe container could not be started' };
69
- const line = out.split('\n').map((l) => l.trim()).filter(Boolean).pop() ?? '';
70
- const http = /^PROBE_HTTP (\d+)$/.exec(line);
71
- if (http)
72
- return { reachable: true, detail: `HTTP ${http[1]}` };
73
- const err = /^PROBE_ERR (.+)$/.exec(line);
74
- if (err)
75
- return { reachable: false, detail: err[1] };
76
- return { reachable: false, detail: line || 'no output' };
77
- }
78
- /**
79
- * Open the control channel from where the gateway will open it: same image,
80
- * same network, same --add-host arguments. Anything less tests a different path
81
- * than the one that has to work.
82
- */
83
- function probeControlUrl(rt, image, url, network, runArgs) {
84
- const out = runInImage(rt, image, ['--network', network, ...runArgs, '-e', `PROBE_URL=${url}`], 'node', ['-e', PROBE_SCRIPT]);
85
- return parseProbeOutput(out);
86
- }
87
- /**
88
- * Pull the gateway out of `ip route show default`.
89
- *
90
- * Two shapes, since busybox and iproute2 order the fields differently:
91
- * default via 172.20.144.1 dev eth0 proto kernel
92
- * default dev eth0 scope link src 10.0.0.5 via 10.0.0.1
93
- * so match on `via <ip>` wherever it sits rather than on a field position.
94
- */
95
- function parseDefaultGateway(routeOutput) {
96
- if (!routeOutput)
97
- return null;
98
- for (const line of routeOutput.split('\n')) {
99
- if (!line.trim().startsWith('default'))
100
- continue;
101
- const via = /\bvia\s+(\d{1,3}(?:\.\d{1,3}){3})\b/.exec(line);
102
- if (via && via[1].split('.').every((o) => Number(o) <= 255))
103
- return via[1];
104
- }
105
- return null;
106
- }
107
- /**
108
- * The address of the machine the ENGINE runs on, seen from inside the engine.
109
- *
110
- * `--network host` puts the probe in the engine host's own network namespace —
111
- * the WSL distro on Rancher Desktop, the Linux VM elsewhere — so its default
112
- * route names the next hop out of that namespace. On WSL that next hop is the
113
- * Windows host, on the vEthernet adapter the two share, which is exactly the
114
- * address a container can reach and `host.docker.internal` failed to name.
115
- *
116
- * Only worth asking when the derived address did not answer: on Docker Desktop
117
- * this returns the VM's own internal gateway, which is not what anyone wants.
118
- */
119
- function engineHostAddress(rt, image) {
120
- return parseDefaultGateway(runInImage(rt, image, ['--network', 'host'], 'ip', ['-4', 'route', 'show', 'default']));
121
- }
122
- /**
123
- * The other names and addresses a container might reach this machine on, tried
124
- * only when the derived one did not answer.
125
- *
126
- * `host.docker.internal` is not a promise. Rancher Desktop points it at the
127
- * WSL distro's own docker0 gateway, which is the distro, not this machine —
128
- * measured, and it is what sent us here. So try the aliases other engines
129
- * publish, and then the one address that is not a guess at all:
130
- *
131
- * Rancher Desktop and `podman machine` both route the VM through
132
- * gvisor-tap-vsock, which serves 192.168.127.0/24 with the gateway on .1 and
133
- * THIS MACHINE on .254 — a userspace forwarder running here, so it reaches the
134
- * host loopback exactly like Docker Desktop's alias does. Derived from whatever
135
- * gateway the engine reported rather than hardcoded, because the subnet is
136
- * configurable.
137
- *
138
- * Every one of these is a candidate, not an answer: each is probed, and only an
139
- * address that replies is used.
140
- */
141
- function hostCandidateUrls(port, vmGateway) {
142
- const hosts = ['host.rancher-desktop.internal', 'host.containers.internal'];
143
- const octets = vmGateway ? /^(\d{1,3}\.\d{1,3}\.\d{1,3})\.\d{1,3}$/.exec(vmGateway) : null;
144
- if (octets)
145
- hosts.push(`${octets[1]}.254`);
146
- return hosts.map((h) => `http://${h}:${port}`);
147
- }
148
- /** Every IPv4 address this machine actually has, loopback excluded. */
149
- function localIpv4Addresses() {
150
- const out = [];
151
- for (const addrs of Object.values(os_1.default.networkInterfaces())) {
152
- for (const a of addrs ?? []) {
153
- if (a.family === 'IPv4' && !a.internal)
154
- out.push(a.address);
155
- }
156
- }
157
- return out;
158
- }
159
- /**
160
- * An address Huddle Node can BIND that the engine can also reach.
161
- *
162
- * Both halves matter, and the second one is the trap: the engine's default
163
- * gateway is not this machine. On Rancher Desktop it is 192.168.127.1, served by
164
- * a forwarder — binding it fails with EADDRNOTAVAIL and takes Huddle Node down
165
- * with it, which is exactly how a control-channel fix turned into no Huddle at
166
- * all. So only ever offer an address this machine really owns, on the same
167
- * subnet the engine routes through.
168
- */
169
- function pickBindAddress(local, vmGateway) {
170
- if (!vmGateway)
171
- return null;
172
- const prefix = vmGateway.replace(/\.\d+$/, '.');
173
- return local.find((a) => a.startsWith(prefix)) ?? null;
174
- }
package/dist/logs.js DELETED
@@ -1,213 +0,0 @@
1
- "use strict";
2
- // `huddle logs` — the two halves' output, from one command.
3
- //
4
- // Huddle runs as two processes (docs/ADR-huddle-node-split.md) and each keeps
5
- // its output somewhere else: Huddle Node appends stdout+stderr to
6
- // ~/.huddle/node.log, the gateway container has whatever `docker logs` holds.
7
- // Knowing that is not something an operator should have to look up, so this
8
- // command reads both and says which is which.
9
- //
10
- // Reading is deliberately local: the log of a Node that failed to start is
11
- // exactly the log you need, and asking the API for it would need the process
12
- // this command exists to diagnose.
13
- var __importDefault = (this && this.__importDefault) || function (mod) {
14
- return (mod && mod.__esModule) ? mod : { "default": mod };
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.parseLines = parseLines;
18
- exports.tailFile = tailFile;
19
- exports.runLogs = runLogs;
20
- const fs_1 = __importDefault(require("fs"));
21
- const child_process_1 = require("child_process");
22
- const node_1 = require("./node");
23
- const runtime_1 = require("./runtime");
24
- const utils_1 = require("./utils");
25
- const GATEWAY_CONTAINER = 'huddle';
26
- function parseLines(raw) {
27
- if (raw === undefined)
28
- return 200;
29
- const n = Number(raw);
30
- if (!Number.isInteger(n) || n < 1 || n > 100_000) {
31
- throw new Error(`Invalid --lines "${raw}": use a whole number between 1 and 100000.`);
32
- }
33
- return n;
34
- }
35
- /**
36
- * The last `lines` lines of a file, read from the END.
37
- *
38
- * node.log is append-only across restarts, so it grows without bound — reading
39
- * the whole thing into memory to throw away all but the tail is exactly the
40
- * wrong shape for the one file this command exists to read. Chunks are read
41
- * backwards until enough newlines have been seen.
42
- */
43
- function tailFile(file, lines) {
44
- let fd;
45
- try {
46
- fd = fs_1.default.openSync(file, 'r');
47
- }
48
- catch {
49
- return null; // never started, or the log was cleaned up
50
- }
51
- try {
52
- const size = fs_1.default.fstatSync(fd).size;
53
- const chunk = 64 * 1024;
54
- let pos = size;
55
- let found = 0;
56
- let text = '';
57
- while (pos > 0 && found <= lines) {
58
- const len = Math.min(chunk, pos);
59
- pos -= len;
60
- const buf = Buffer.alloc(len);
61
- fs_1.default.readSync(fd, buf, 0, len, pos);
62
- const part = buf.toString('utf8');
63
- found += (part.match(/\n/g) ?? []).length;
64
- text = part + text;
65
- }
66
- const all = text.split('\n');
67
- // A trailing newline makes the last element empty; drop it so `--lines 1`
68
- // shows the last real line rather than a blank.
69
- if (all[all.length - 1] === '')
70
- all.pop();
71
- return all.slice(-lines).join('\n');
72
- }
73
- finally {
74
- fs_1.default.closeSync(fd);
75
- }
76
- }
77
- function printNodeLog(lines) {
78
- const pid = (0, node_1.readNodePid)();
79
- const state = pid === null
80
- ? (0, utils_1.dim)('(no pid file — not started by `huddle init`)')
81
- : (0, node_1.isNodePidAlive)() ? (0, utils_1.dim)(`(pid ${pid}, running)`) : (0, utils_1.yellow)(`(pid ${pid}, NOT running)`);
82
- console.log((0, utils_1.bold)(`── Huddle Node — ${(0, utils_1.cyan)(node_1.NODE_LOG_FILE)} ${state}`));
83
- const tail = tailFile(node_1.NODE_LOG_FILE, lines);
84
- if (tail === null) {
85
- console.log((0, utils_1.dim)(' No log file yet. `huddle init` starts Node and creates it;'));
86
- console.log((0, utils_1.dim)(' `huddle node` runs it in the foreground and prints here instead.'));
87
- return;
88
- }
89
- console.log(tail.trim() ? tail : (0, utils_1.dim)(' (empty)'));
90
- }
91
- // The engine command, or null with a printed reason. Not being able to reach an
92
- // engine must not fail `huddle logs`: node.log is often the half that explains
93
- // why, and it has already been printed by the time this runs.
94
- function engineCommand() {
95
- try {
96
- return (0, runtime_1.resolveRuntime)().name;
97
- }
98
- catch (err) {
99
- console.log((0, utils_1.dim)(` No container runtime available: ${err.message.split('\n')[0]}`));
100
- return null;
101
- }
102
- }
103
- // `docker logs` and not the API: the gateway's own startup failures are the
104
- // interesting case, and those never reach an HTTP endpoint.
105
- async function printGatewayLog(lines) {
106
- console.log('');
107
- console.log((0, utils_1.bold)('── huddle-gateway'));
108
- const engine = engineCommand();
109
- if (!engine)
110
- return;
111
- console.log((0, utils_1.dim)(` ${engine} logs ${GATEWAY_CONTAINER}`));
112
- await new Promise((resolve) => {
113
- const child = (0, child_process_1.spawn)(engine, ['logs', '--tail', String(lines), GATEWAY_CONTAINER], {
114
- stdio: ['ignore', 'inherit', 'inherit'],
115
- });
116
- child.on('error', (err) => {
117
- console.log((0, utils_1.red)(` Could not run ${engine}: ${err.message}`));
118
- resolve();
119
- });
120
- child.on('close', () => resolve());
121
- });
122
- }
123
- /**
124
- * Follow both halves at once: `tail -f` on node.log, `docker logs -f` on the
125
- * gateway, each line prefixed so two interleaved streams stay readable. Ends on
126
- * Ctrl-C like every other follower.
127
- */
128
- async function followBoth(lines, wantNode, wantGateway) {
129
- const children = [];
130
- if (wantNode) {
131
- console.log((0, utils_1.dim)(`── following ${node_1.NODE_LOG_FILE}`));
132
- // Start at the END of the file and print the tail once, so following does
133
- // not replay a log that has been growing across every restart.
134
- let pos = 0;
135
- try {
136
- pos = fs_1.default.statSync(node_1.NODE_LOG_FILE).size;
137
- }
138
- catch { /* not created yet */ }
139
- const initial = tailFile(node_1.NODE_LOG_FILE, lines);
140
- if (initial?.trim())
141
- console.log(prefix('node', initial));
142
- // Polling, not fs.watch: on Windows a file appended to by a detached process
143
- // does not reliably raise watch events, and a 500ms poll on one file costs
144
- // nothing next to being silently stuck.
145
- const timer = setInterval(() => {
146
- let size;
147
- try {
148
- size = fs_1.default.statSync(node_1.NODE_LOG_FILE).size;
149
- }
150
- catch {
151
- return;
152
- }
153
- if (size <= pos) {
154
- pos = Math.min(pos, size);
155
- return;
156
- } // truncated or unchanged
157
- const buf = Buffer.alloc(size - pos);
158
- const fd = fs_1.default.openSync(node_1.NODE_LOG_FILE, 'r');
159
- try {
160
- fs_1.default.readSync(fd, buf, 0, buf.length, pos);
161
- }
162
- finally {
163
- fs_1.default.closeSync(fd);
164
- }
165
- pos = size;
166
- const text = buf.toString('utf8').replace(/\n$/, '');
167
- if (text)
168
- console.log(prefix('node', text));
169
- }, 500);
170
- process.on('SIGINT', () => clearInterval(timer));
171
- }
172
- const engine = wantGateway ? engineCommand() : null;
173
- if (engine) {
174
- console.log((0, utils_1.dim)(`── following ${engine} logs -f ${GATEWAY_CONTAINER}`));
175
- const child = (0, child_process_1.spawn)(engine, ['logs', '-f', '--tail', String(lines), GATEWAY_CONTAINER], {
176
- stdio: ['ignore', 'pipe', 'pipe'],
177
- });
178
- for (const stream of [child.stdout, child.stderr]) {
179
- stream?.on('data', (b) => {
180
- const text = b.toString('utf8').replace(/\n$/, '');
181
- if (text)
182
- console.log(prefix('gateway', text));
183
- });
184
- }
185
- child.on('error', (err) => console.log((0, utils_1.red)(` Could not run ${engine}: ${err.message}`)));
186
- children.push(child);
187
- }
188
- await new Promise((resolve) => {
189
- process.on('SIGINT', () => {
190
- for (const c of children)
191
- c.kill();
192
- resolve();
193
- });
194
- });
195
- }
196
- function prefix(who, text) {
197
- const tag = who === 'node' ? (0, utils_1.cyan)('[node] ') : (0, utils_1.dim)('[gateway]');
198
- return text.split('\n').map((l) => `${tag} ${l}`).join('\n');
199
- }
200
- async function runLogs(opts) {
201
- const lines = parseLines(opts.lines);
202
- // Neither flag means both halves; either flag means only that one.
203
- const wantNode = opts.node === true || opts.gateway !== true;
204
- const wantGateway = opts.gateway === true || opts.node !== true;
205
- if (opts.follow) {
206
- await followBoth(lines, wantNode, wantGateway);
207
- return;
208
- }
209
- if (wantNode)
210
- printNodeLog(lines);
211
- if (wantGateway)
212
- await printGatewayLog(lines);
213
- }