mapsource-node 0.0.0-stage → 0.1.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.
- package/README.md +33 -2
- package/bin/mapsource-node.mjs +44 -0
- package/package.json +32 -4
- package/protocol/bootstrap/infra/mirror/runtime.json +28 -0
- package/protocol/bootstrap/scripts/artifact-lifecycle.mjs +531 -0
- package/protocol/bootstrap/scripts/mirror-mesh-agent.mjs +58 -0
- package/protocol/bootstrap/scripts/mirror-mesh-config.mjs +39 -0
- package/protocol/bootstrap/scripts/mirror-mesh-install.mjs +91 -0
- package/protocol/bootstrap/scripts/mirror-mesh-membership.mjs +71 -0
- package/protocol/bootstrap/scripts/mirror-peer-health.mjs +41 -0
- package/protocol/bootstrap/scripts/mirror-peer-path.mjs +98 -0
- package/protocol/bootstrap/scripts/mirror-transport-install.mjs +237 -0
- package/protocol/bootstrap/scripts/mirror-transport-reconcile.mjs +121 -0
- package/protocol/bootstrap/scripts/network-family-policy.mjs +13 -0
- package/protocol/bootstrap/scripts/release-ingress-router.mjs +212 -0
- package/protocol/bootstrap/scripts/release-policy.mjs +131 -0
- package/protocol/bootstrap/scripts/release-router.mjs +148 -0
- package/src/capability.mjs +101 -0
- package/src/commands.mjs +192 -0
- package/src/enrollment.mjs +153 -0
- package/src/index.ts +70 -0
- package/src/interface.ts +181 -0
- package/src/palette.ts +11 -0
- package/src/telemetry.ts +158 -0
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Install transport-only recovery without changing native controller bytes.
|
|
3
|
+
// New SYNs use a qualified shadow while established requests drain normally.
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import { execFileSync } from "node:child_process";
|
|
6
|
+
import { createHash } from "node:crypto";
|
|
7
|
+
import { lstat, mkdir, readFile, readdir, realpath, writeFile } from "node:fs/promises";
|
|
8
|
+
import os from "node:os";
|
|
9
|
+
import path from "node:path";
|
|
10
|
+
import { parseArgs } from "node:util";
|
|
11
|
+
import { pathToFileURL } from "node:url";
|
|
12
|
+
import { freeSpacePreflight, withProjectLock, withProjectTempDirectory, writeRetainedArtifact } from "./artifact-lifecycle.mjs";
|
|
13
|
+
import { probePeerHttp } from "./mirror-peer-health.mjs";
|
|
14
|
+
import { meshSshBudget } from "./mirror-mesh-config.mjs";
|
|
15
|
+
|
|
16
|
+
const capture = (command, args) => execFileSync(command, args, { encoding: "utf8", timeout: 30_000, maxBuffer: 1024 ** 2 }).trim();
|
|
17
|
+
const privileged = (command, args) => capture("sudo", ["-n", command, ...args]);
|
|
18
|
+
export const transportRuntimeFiles = Object.freeze(["network-family-policy.mjs", "mirror-peer-path.mjs", "mirror-peer-health.mjs", "mirror-transport-reconcile.mjs"]);
|
|
19
|
+
// This directory is writable inside the coordinator's ProtectSystem sandbox.
|
|
20
|
+
// Keep atomic configuration replacement out of the read-only /etc parent.
|
|
21
|
+
export const transportRecoveryConfiguration = "/etc/mapsource-cd/transport/recovery.json";
|
|
22
|
+
export function verifyTransportRuntime(runtime) {
|
|
23
|
+
const imports = ["mirror-peer-path.mjs", "mirror-transport-reconcile.mjs"].map(name => `await import(${JSON.stringify(pathToFileURL(path.join(runtime, name)).href)});`).join("\n");
|
|
24
|
+
capture(process.execPath, ["--input-type=module", "-e", imports]);
|
|
25
|
+
return true;
|
|
26
|
+
}
|
|
27
|
+
const show = (unit, property) => capture("systemctl", ["show", unit, `--property=${property}`, "--value"]);
|
|
28
|
+
const argv = unit => {
|
|
29
|
+
const match = /argv\[\]=([^;]+);/.exec(show(unit, "ExecStart"));
|
|
30
|
+
assert.ok(match, `No command for ${unit}`); return match[1].trim().split(/\s+/);
|
|
31
|
+
};
|
|
32
|
+
const accepted = port => privileged("ss", ["-Hnt", "state", "established", `( sport = :${port} )`]).split("\n").filter(Boolean).length;
|
|
33
|
+
export function cloudflareOnly(config) {
|
|
34
|
+
const edge = config.upstreams?.filter(item => item.name === "edge");
|
|
35
|
+
assert.equal(edge?.length, 1, "Exactly one registered Cloudflare peer link is required");
|
|
36
|
+
assert.ok(Number.isInteger(edge[0].port) && edge[0].port >= 1024 && edge[0].port <= 65535);
|
|
37
|
+
return { ...config, host: "127.0.0.1", upstreams: [{ name: "edge", port: edge[0].port }] };
|
|
38
|
+
}
|
|
39
|
+
export function capacityProbeOrigin(node, generator, localPort, links) {
|
|
40
|
+
const link = links.find(item => item.unit === `mapsource-capacity-peer-${generator}.service`);
|
|
41
|
+
const port = generator === node ? localPort : link?.port;
|
|
42
|
+
assert.ok(Number.isInteger(port) && port >= 1024 && port <= 65535, `No registered capacity transport for ${generator}`);
|
|
43
|
+
return new URL("/run", `http://127.0.0.1:${port}`);
|
|
44
|
+
}
|
|
45
|
+
export function transportNatBackend(run) {
|
|
46
|
+
// Jetson's nftables works even when the xt_owner compatibility module does
|
|
47
|
+
// not. Listing iptables rules alone does not prove owner matches can work.
|
|
48
|
+
try { run("nft", ["-j", "-a", "list", "chain", "ip", "nat", "OUTPUT"]); return "nft"; }
|
|
49
|
+
catch { run("iptables", ["-t", "nat", "-S", "OUTPUT"]); return "iptables"; }
|
|
50
|
+
}
|
|
51
|
+
export function transportRuntimeMatches({ command, directory, user, live }, expected) {
|
|
52
|
+
const actual = /argv\[\]=([^;]+);/.exec(command)?.[1].trim().split(/\s+/);
|
|
53
|
+
return actual?.length === 3 && actual[0] === expected.binary && actual[1] === expected.program && actual[2] === expected.configuration
|
|
54
|
+
&& directory === expected.runtime && [String(expected.uid), expected.user].includes(user)
|
|
55
|
+
&& live?.command.length === 3 && live.command[0] === expected.binary && live.command[1] === expected.program && live.command[2] === expected.configuration
|
|
56
|
+
&& live.directory === expected.runtime && live.uid === expected.uid;
|
|
57
|
+
}
|
|
58
|
+
async function waitFor(check, message, timeout = 30_000) {
|
|
59
|
+
const deadline = Date.now() + timeout;
|
|
60
|
+
while (!await check()) { assert.ok(Date.now() < deadline, message); await new Promise(resolve => setTimeout(resolve, 500)); }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export async function installTransport(root, { execute = false, recoveryOnly = false } = {}) {
|
|
64
|
+
root = await realpath(root);
|
|
65
|
+
const identity = JSON.parse(await readFile(path.join(root, "enrollment.json"), "utf8"));
|
|
66
|
+
assert.equal(identity.machineId, (await readFile("/etc/machine-id", "utf8")).trim());
|
|
67
|
+
assert.equal((await lstat(root)).uid, process.getuid());
|
|
68
|
+
assert.ok(root.startsWith(os.homedir() + "/"));
|
|
69
|
+
const units = capture("systemctl", ["list-units", "--all", "--plain", "--no-legend", "--no-pager", "--type=service"]).split("\n").map(line => line.trim().split(/\s+/)[0]);
|
|
70
|
+
const selectors = [], links = [];
|
|
71
|
+
for (const unit of units) {
|
|
72
|
+
if (/^mapsource-peer-path-[a-z][a-z0-9-]*\.service$/.test(unit)) {
|
|
73
|
+
const command = argv(unit); assert.equal(path.basename(command[1]), "mirror-peer-path.mjs");
|
|
74
|
+
const configuration = path.resolve(command[2]);
|
|
75
|
+
assert.ok(!/[\r\n%"\\]/.test(configuration));
|
|
76
|
+
const config = cloudflareOnly(JSON.parse(await readFile(configuration, "utf8")));
|
|
77
|
+
assert.ok(config.listen >= 1024 && config.listen <= 53535);
|
|
78
|
+
selectors.push({ unit, configuration, config, shadowPort: config.listen + 12000 });
|
|
79
|
+
} else if (/^mapsource-(?:mirror-peer|capacity-peer|read-link)-[a-z][a-z0-9-]*\.service$/.test(unit) && !unit.endsWith("-lan.service")) {
|
|
80
|
+
const command = argv(unit);
|
|
81
|
+
assert.equal(command[0], "/usr/bin/ssh");
|
|
82
|
+
const forward = command[command.indexOf("-L") + 1], match = /^127\.0\.0\.1:(\d+):127\.0\.0\.1:(8989|8990|19390)$/.exec(forward);
|
|
83
|
+
assert.ok(command.includes("-F") && !command.includes("-R") && match, "Only existing one-way private peer links can be reconciled");
|
|
84
|
+
links.push({ unit, port: Number(match[1]) });
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
assert.ok(selectors.length <= 16 && links.length <= 32);
|
|
88
|
+
const result = { node: identity.node, transport: recoveryOnly ? "unchanged" : "registered-cloudflare-only", recoveryOnly, selectors: selectors.map(item => item.unit), links, execute, accountControllerRestarted: false };
|
|
89
|
+
if (!execute) return result;
|
|
90
|
+
await freeSpacePreflight({ target: root, projectedBytes: 2 * 1024 ** 2 });
|
|
91
|
+
const source = import.meta.dirname, files = {};
|
|
92
|
+
for (const name of transportRuntimeFiles) {
|
|
93
|
+
const bytes = await readFile(path.join(source, name)); assert.ok(bytes.length < 256 * 1024); files[name] = bytes;
|
|
94
|
+
}
|
|
95
|
+
const hash = createHash("sha256").update(await readFile(import.meta.filename)).update(JSON.stringify(meshSshBudget)); for (const [name, bytes] of Object.entries(files)) hash.update(name).update(bytes);
|
|
96
|
+
const version = hash.digest("hex"), base = path.join(root, "runtime/transport"), runtime = path.join(base, version);
|
|
97
|
+
await mkdir(base, { recursive: true, mode: 0o700 }); assert.equal(await realpath(base), base);
|
|
98
|
+
assert.ok((await readdir(base)).length < 16 || (await readdir(base)).includes(version), "Installed transport version limit reached");
|
|
99
|
+
await mkdir(runtime, { recursive: true, mode: 0o700 }); assert.equal(await realpath(runtime), runtime);
|
|
100
|
+
for (const [name, bytes] of Object.entries(files)) {
|
|
101
|
+
const file = path.join(runtime, name);
|
|
102
|
+
try { assert.ok((await readFile(file)).equals(bytes), "Installed transport bytes differ"); }
|
|
103
|
+
catch (error) { if (error.code !== "ENOENT") throw error; await writeFile(file, bytes, { flag: "wx", mode: 0o600 }); }
|
|
104
|
+
}
|
|
105
|
+
// Prove the copied dependency closure in isolation before changing any
|
|
106
|
+
// service definition, timer or resource setting.
|
|
107
|
+
verifyTransportRuntime(runtime);
|
|
108
|
+
const policy = { id: "portable-transport-install", root: path.join(root, "transport-evidence"), maxFileBytes: 1024 ** 2, maxBytes: 8 * 1024 ** 2, maxCount: 16, maxAgeMs: 30 * 86400000, freeSpaceFloorBytes: 10 * 1024 ** 3 };
|
|
109
|
+
const installFile = async (target, bytes) => withProjectTempDirectory("mapsource-transport-install-", async temporary => {
|
|
110
|
+
const file = path.join(temporary, path.basename(target)); await writeFile(file, bytes, { mode: 0o600 });
|
|
111
|
+
privileged("install", ["-d", "-m", "0755", path.dirname(target)]);
|
|
112
|
+
privileged("install", ["-m", "0644", file, target]);
|
|
113
|
+
});
|
|
114
|
+
await withProjectLock("portable-transport", async () => {
|
|
115
|
+
const before = [];
|
|
116
|
+
for (const item of selectors) before.push({ unit: item.unit, loadedCommand: show(item.unit, "ExecStart"), loadedDirectory: show(item.unit, "WorkingDirectory") });
|
|
117
|
+
await writeRetainedArtifact(policy, `before-${version}.json`, JSON.stringify({ ...result, before, version, at: new Date().toISOString() }, null, 2));
|
|
118
|
+
assert.ok(show("mapsource-mesh-sshd.service", "Description").startsWith("Mapsource "), "Refusing an unrelated SSH service");
|
|
119
|
+
// Apply the canonical budget live and persist it across reboot, without
|
|
120
|
+
// interrupting peer sessions or the account writer.
|
|
121
|
+
privileged("systemctl", ["set-property", "mapsource-mesh-sshd.service", `MemoryHigh=${meshSshBudget.highMiB}M`, `MemoryMax=${meshSshBudget.maxMiB}M`]);
|
|
122
|
+
// Origin recovery must not depend on every remote service already being
|
|
123
|
+
// available: it is needed precisely when a connector/origin has failed.
|
|
124
|
+
const configuration = transportRecoveryConfiguration;
|
|
125
|
+
await installFile(configuration, JSON.stringify({ machineId: identity.machineId, sshPort: identity.sshPort ?? 22991, stateFile: "/run/mapsource-mesh-recovery/status.json", links }));
|
|
126
|
+
await installFile("/etc/systemd/system/mapsource-mesh-recovery.service", `[Unit]\nDescription=Mapsource registered transport readiness and recovery\nAfter=network-online.target\n[Service]\nType=oneshot\nExecStart="${process.execPath}" "${runtime}/mirror-transport-reconcile.mjs" "${configuration}"\nRuntimeDirectory=mapsource-mesh-recovery\nRuntimeDirectoryPreserve=yes\nUMask=0077\nTimeoutStartSec=90\nMemoryMax=128M\nTasksMax=32\nNoNewPrivileges=true\nProtectSystem=full\nPrivateTmp=true\nLimitCORE=0\nLogNamespace=mapsource-mirror\n`);
|
|
127
|
+
await installFile("/etc/systemd/system/mapsource-mesh-recovery.timer", "[Unit]\nDescription=Check Mapsource portable transports every 15 seconds\n[Timer]\nOnBootSec=20\nOnUnitInactiveSec=15\nAccuracySec=1\n[Install]\nWantedBy=timers.target\n");
|
|
128
|
+
privileged("systemctl", ["daemon-reload"]);
|
|
129
|
+
privileged("systemctl", ["enable", "--now", "mapsource-mesh-sshd.service", "mapsource-mesh-tunnel.service", "mapsource-mesh-agent.service", "mapsource-mesh-recovery.timer"]);
|
|
130
|
+
privileged("systemctl", ["start", "mapsource-mesh-recovery.service"]);
|
|
131
|
+
if (recoveryOnly) {
|
|
132
|
+
await writeRetainedArtifact(policy, `recovery-${version}.json`, JSON.stringify({ ...result, version, runtime, passed: true, at: new Date().toISOString() }));
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
const backend = selectors.length ? transportNatBackend(privileged) : "nft";
|
|
136
|
+
let pausedCapacity = false;
|
|
137
|
+
try {
|
|
138
|
+
// Capacity's sampler owns persistent read-only HTTP connections. Prove no
|
|
139
|
+
// generator is running a lab before briefly pausing this independent
|
|
140
|
+
// collector; preserve all native controllers and restore it in finally.
|
|
141
|
+
if (selectors.length && units.includes("mapsource-capacity-fleet.service") && show("mapsource-capacity-fleet.service", "ActiveState") === "active") {
|
|
142
|
+
const configFile = argv("mapsource-capacity-fleet.service").at(-1);
|
|
143
|
+
const capacity = JSON.parse(await readFile(configFile, "utf8"));
|
|
144
|
+
const native = JSON.parse(await readFile(capacity.nativeConfig, "utf8"));
|
|
145
|
+
const token = (await readFile(native.originTokenFile, "utf8")).trim();
|
|
146
|
+
for (const generator of [native.node, ...Object.keys(native.peerOrigins ?? {})]) {
|
|
147
|
+
// Inspect each generator over its registered link directly. Routing
|
|
148
|
+
// through the selector being repaired creates a maintenance deadlock.
|
|
149
|
+
const url = capacityProbeOrigin(native.node, generator, capacity.port ?? 19390, links);
|
|
150
|
+
const response = await fetch(url, { headers: { "x-mapsource-capacity-token": token }, signal: AbortSignal.timeout(6000) });
|
|
151
|
+
assert.ok(response.ok, `Cannot establish the capacity lab state for ${generator}`);
|
|
152
|
+
const current = await response.json();
|
|
153
|
+
assert.ok(!["running", "stopping"].includes(current.snapshot?.state) && !current.lab?.draining, "An active capacity run must finish before transport maintenance");
|
|
154
|
+
}
|
|
155
|
+
privileged("systemctl", ["stop", "mapsource-capacity-fleet.service"]); pausedCapacity = true;
|
|
156
|
+
}
|
|
157
|
+
for (const item of selectors) {
|
|
158
|
+
const program = path.join(runtime, "mirror-peer-path.mjs"), shadowConfig = path.join(runtime, item.unit + ".shadow.json");
|
|
159
|
+
const configuration = path.join(runtime, item.unit + ".cloudflare.json");
|
|
160
|
+
const bytes = JSON.stringify(item.config);
|
|
161
|
+
try { assert.equal(await readFile(configuration, "utf8"), bytes, "Installed Cloudflare configuration differs"); }
|
|
162
|
+
catch (error) { if (error.code !== "ENOENT") throw error; await writeFile(configuration, bytes, { flag: "wx", mode: 0o600 }); }
|
|
163
|
+
// Preserve older overrides, but sort after their healthy-root pin. An
|
|
164
|
+
// earlier drop-in can be installed successfully while systemd continues
|
|
165
|
+
// to run that older command and its LAN-first configuration.
|
|
166
|
+
const dropIn = `/etc/systemd/system/${item.unit}.d/99-registered-cloudflare.conf`;
|
|
167
|
+
const desired = `[Unit]\nDescription=Mapsource registered Cloudflare transport (${item.unit})\n[Service]\nUser=${os.userInfo().username}\nWorkingDirectory=${runtime}\nExecStart=\nExecStart="${process.execPath}" "${program}" "${configuration}"\nTimeoutStopSec=210\n`;
|
|
168
|
+
const runtimeMatches = async () => {
|
|
169
|
+
const pid = show(item.unit, "MainPID"); if (!/^[1-9][0-9]*$/.test(pid)) return false;
|
|
170
|
+
try {
|
|
171
|
+
const live = { command: (await readFile(`/proc/${pid}/cmdline`, "utf8")).split("\0").filter(Boolean),
|
|
172
|
+
directory: await realpath(`/proc/${pid}/cwd`), uid: Number((await readFile(`/proc/${pid}/status`, "utf8")).match(/^Uid:\s+\d+\s+(\d+)/m)?.[1]) };
|
|
173
|
+
return transportRuntimeMatches({ command: show(item.unit, "ExecStart"), directory: show(item.unit, "WorkingDirectory"), user: show(item.unit, "User"), live },
|
|
174
|
+
{ binary: process.execPath, program, configuration, runtime, uid: process.getuid(), user: os.userInfo().username });
|
|
175
|
+
} catch { return false; }
|
|
176
|
+
};
|
|
177
|
+
let current; try { current = await readFile(dropIn, "utf8"); } catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
178
|
+
if (current === desired && await runtimeMatches()) continue;
|
|
179
|
+
await writeRetainedArtifact(policy, item.unit + ".rollback.json", JSON.stringify({ dropIn, previous: current ?? null, command: show(item.unit, "ExecStart"), at: new Date().toISOString() }));
|
|
180
|
+
const shadow = `mapsource-peer-ready-shadow-cf-${item.config.listen}.service`;
|
|
181
|
+
await writeFile(shadowConfig, JSON.stringify({ ...item.config, listen: item.shadowPort }), { mode: 0o600 });
|
|
182
|
+
let active = false; try { active = show(shadow, "ActiveState") === "active"; } catch { /* New shadow. */ }
|
|
183
|
+
if (active && !(show(shadow, "ExecStart").includes(program) && show(shadow, "ExecStart").includes(shadowConfig))) {
|
|
184
|
+
const previous = argv(shadow);
|
|
185
|
+
assert.ok([String(process.getuid()), os.userInfo().username].includes(show(shadow, "User")), "Shadow belongs to another operating user");
|
|
186
|
+
assert.equal(path.basename(previous[1]), "mirror-peer-path.mjs", "Shadow belongs to another workload");
|
|
187
|
+
assert.equal(JSON.parse(await readFile(previous[2], "utf8")).listen, item.shadowPort);
|
|
188
|
+
if (accepted(item.shadowPort) === 0) { privileged("systemctl", ["stop", shadow]); active = false; }
|
|
189
|
+
else {
|
|
190
|
+
assert.ok((await readFile(previous[1])).equals(files["mirror-peer-path.mjs"]), "Busy shadow runs different transport code; preserve it for drain");
|
|
191
|
+
assert.deepEqual(JSON.parse(await readFile(previous[2], "utf8")), { ...item.config, listen: item.shadowPort }, "Busy shadow has different upstreams");
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
if (!active) privileged("systemd-run", ["--collect", `--unit=${shadow}`, `--uid=${process.getuid()}`, "--property=Restart=always", "--property=RestartSec=2", "--property=MemoryMax=128M", "--property=TasksMax=32", process.execPath, program, shadowConfig]);
|
|
195
|
+
await waitFor(() => probePeerHttp({ port: item.shadowPort, timeoutMs: 4000 }), "Shadow transport did not reach a remote HTTP origin");
|
|
196
|
+
const tag = `mapsource-peer-readiness-${item.config.listen}-${item.shadowPort}`;
|
|
197
|
+
const rule = ["OUTPUT", "-p", "tcp", "--syn", "-d", "127.0.0.1", "--dport", String(item.config.listen), "-m", "owner", "--uid-owner", String(process.getuid()), "-m", "comment", "--comment", tag, "-j", "REDIRECT", "--to-ports", String(item.shadowPort)];
|
|
198
|
+
const nftRule = () => JSON.parse(privileged("nft", ["-j", "-a", "list", "chain", "ip", "nat", "OUTPUT"])).nftables.map(item => item.rule).find(item => item?.comment === tag);
|
|
199
|
+
let present;
|
|
200
|
+
if (backend === "nft") present = Boolean(nftRule());
|
|
201
|
+
else { try { privileged("iptables", ["-t", "nat", "-C", ...rule]); present = true; } catch (error) { if (error.status !== 1) throw error; present = false; } }
|
|
202
|
+
if (!present) {
|
|
203
|
+
if (backend === "nft") privileged("nft", ["insert", "rule", "ip", "nat", "OUTPUT", `ip daddr 127.0.0.1 tcp dport ${item.config.listen} tcp flags & (syn | ack) == syn meta skuid ${process.getuid()} dnat to 127.0.0.1:${item.shadowPort} comment "${tag}"`]);
|
|
204
|
+
else privileged("iptables", ["-t", "nat", "-I", ...rule]);
|
|
205
|
+
}
|
|
206
|
+
console.log(JSON.stringify({ event: "transport-shadow-ready", node: identity.node, unit: item.unit }));
|
|
207
|
+
// If draining is interrupted, leave the qualified shadow and exact rule
|
|
208
|
+
// serving. A rerun resumes instead of killing customer connections.
|
|
209
|
+
await waitFor(() => accepted(item.config.listen) === 0, "Existing peer connections remain; retain the shadow and rerun", 210_000);
|
|
210
|
+
await installFile(dropIn, desired); privileged("systemctl", ["daemon-reload"]);
|
|
211
|
+
privileged("systemctl", ["restart", item.unit]);
|
|
212
|
+
await waitFor(async () => {
|
|
213
|
+
if (!await runtimeMatches()) return false;
|
|
214
|
+
// The service user's new SYNs still use the shadow during validation.
|
|
215
|
+
// Probe as root to bypass that exact UID rule and measure the real
|
|
216
|
+
// permanent listener rather than accidentally validating the shadow.
|
|
217
|
+
const pid = show(item.unit, "MainPID");
|
|
218
|
+
if (!/^[1-9][0-9]*$/.test(pid) || !privileged("ss", ["-Hlntp", `( sport = :${item.config.listen} )`]).includes(`pid=${pid},`)) return false;
|
|
219
|
+
try { return /^[234][0-9]{2}$/.test(privileged("curl", ["--noproxy", "*", "--head", "-sS", "--max-time", "4", "-o", "/dev/null", "-w", "%{http_code}", `http://127.0.0.1:${item.config.listen}/health/live`])); }
|
|
220
|
+
catch { return false; }
|
|
221
|
+
}, "Permanent transport did not recover; retain the shadow");
|
|
222
|
+
if (backend === "nft") privileged("nft", ["delete", "rule", "ip", "nat", "OUTPUT", "handle", String(nftRule().handle)]);
|
|
223
|
+
else privileged("iptables", ["-t", "nat", "-D", ...rule]);
|
|
224
|
+
if (accepted(item.shadowPort) === 0) privileged("systemctl", ["stop", shadow]);
|
|
225
|
+
console.log(JSON.stringify({ event: "transport-path-installed", node: identity.node, unit: item.unit }));
|
|
226
|
+
}
|
|
227
|
+
} finally { if (pausedCapacity) privileged("systemctl", ["start", "mapsource-capacity-fleet.service"]); }
|
|
228
|
+
await writeRetainedArtifact(policy, `after-${version}.json`, JSON.stringify({ ...result, version, runtime, passed: true, at: new Date().toISOString() }, null, 2));
|
|
229
|
+
}, { root: path.join(root, "locks") });
|
|
230
|
+
return { ...result, version, runtime, verified: true };
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
if (process.argv[1] === import.meta.filename) {
|
|
234
|
+
const { values } = parseArgs({ options: { root: { type: "string" }, execute: { type: "boolean" }, "recovery-only": { type: "boolean" } } });
|
|
235
|
+
assert.ok(values.root, "Use --root ENROLLED_MESH_ROOT [--execute]");
|
|
236
|
+
console.log(JSON.stringify(await installTransport(values.root, { execute: Boolean(values.execute), recoveryOnly: Boolean(values["recovery-only"]) })));
|
|
237
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Transport repair is independent of authority. This timer never changes a
|
|
3
|
+
// controller, qualification ticket, dataset, or elected writer.
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import { execFileSync } from "node:child_process";
|
|
6
|
+
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import { probePeerHttp, probePeerSsh, PEER_HEALTH_TIMEOUT_MS } from "./mirror-peer-health.mjs";
|
|
9
|
+
|
|
10
|
+
export const linkActivityLimits = Object.freeze({ sampleBytes: 512 * 1024, sockets: 256, statusBytes: 1024 * 1024 });
|
|
11
|
+
|
|
12
|
+
/** Response bytes on the SSH forward's accepted sockets, not SSH keepalives or
|
|
13
|
+
* uploaded request bytes. Socket inode and PID fence counters across reconnects. */
|
|
14
|
+
export function parseLinkActivity(text, pid) {
|
|
15
|
+
assert.ok(Number.isSafeInteger(pid) && pid > 0);
|
|
16
|
+
assert.ok(Buffer.byteLength(text) <= linkActivityLimits.sampleBytes, "Link activity sample exceeds its bound");
|
|
17
|
+
const sockets = {};
|
|
18
|
+
const lines = text.split("\n");
|
|
19
|
+
for (let index = 0; index < lines.length; index++) {
|
|
20
|
+
const line = lines[index], fields = line.trim().split(/\s+/);
|
|
21
|
+
if (fields[0] !== "ESTAB" || !line.includes(`pid=${pid},`)) continue;
|
|
22
|
+
const inode = /\bino:(\d+)\b/.exec(line)?.[1];
|
|
23
|
+
assert.ok(inode, "Established link socket has no identity");
|
|
24
|
+
const bytes = Number(/\bbytes_sent:(\d+)\b/.exec(lines[index + 1] ?? "")?.[1] ?? 0);
|
|
25
|
+
assert.ok(Number.isSafeInteger(bytes) && bytes >= 0);
|
|
26
|
+
const key = `${fields[3]}|${fields[4]}|${inode}`;
|
|
27
|
+
assert.ok(key.length <= 160);
|
|
28
|
+
sockets[key] = bytes;
|
|
29
|
+
assert.ok(Object.keys(sockets).length <= linkActivityLimits.sockets, "Link socket count exceeds its bound");
|
|
30
|
+
}
|
|
31
|
+
return { pid, sockets };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function linkResponseProgress(previous, current) {
|
|
35
|
+
if (!current) return false;
|
|
36
|
+
const before = previous?.pid === current.pid ? previous.sockets : {};
|
|
37
|
+
return Object.entries(current.sockets).some(([socket, bytes]) => bytes > (before?.[socket] ?? 0));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function recoveryDecision(previous, healthy, now, { failures = 2, cooldownMs = 60_000 } = {}) {
|
|
41
|
+
const consecutive = healthy ? 0 : (previous?.failures ?? 0) + 1;
|
|
42
|
+
const restart = !healthy && consecutive >= failures && now - (previous?.restartedAt ?? 0) >= cooldownMs;
|
|
43
|
+
return { failures: consecutive, healthy, checkedAt: now, restartedAt: restart ? now : previous?.restartedAt ?? 0, restart };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function linkRecoveryDecision(previous, probeHealthy, now, activity) {
|
|
47
|
+
const responseProgress = linkResponseProgress(previous?.activity, activity);
|
|
48
|
+
return { ...recoveryDecision(previous, probeHealthy || responseProgress, now), probeHealthy, responseProgress, activity };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export async function reconcileTransport(configuration, { run = (command, args) => execFileSync(command, args, { encoding: "utf8", timeout: 15_000 }).trim(), probe = probePeerHttp, sshProbe = probePeerSsh, now = Date.now(), activity } = {}) {
|
|
52
|
+
assert.equal(configuration.machineId, (await readFile("/etc/machine-id", "utf8")).trim());
|
|
53
|
+
assert.ok(Array.isArray(configuration.links) && configuration.links.length <= 32);
|
|
54
|
+
assert.equal(configuration.stateFile, "/run/mapsource-mesh-recovery/status.json");
|
|
55
|
+
let previous = {};
|
|
56
|
+
try { previous = JSON.parse(await readFile(configuration.stateFile, "utf8")); } catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
57
|
+
const result = {};
|
|
58
|
+
const sshPort = configuration.sshPort ?? 22991;
|
|
59
|
+
assert.ok(Number.isInteger(sshPort) && sshPort >= 1024 && sshPort <= 65535);
|
|
60
|
+
const sshUnit = "mapsource-mesh-sshd.service", sshReady = await sshProbe({ port: sshPort, timeoutMs: 2000 });
|
|
61
|
+
const sshDecision = recoveryDecision(previous[sshUnit], sshReady, now);
|
|
62
|
+
if (sshDecision.restart) {
|
|
63
|
+
assert.ok(run("systemctl", ["show", sshUnit, "--property=Description", "--value"]).startsWith("Mapsource "), "Refusing an unrelated SSH service");
|
|
64
|
+
run("systemctl", ["restart", "--no-block", sshUnit]);
|
|
65
|
+
console.log(JSON.stringify({ event: "local-peer-ssh-recovering" }));
|
|
66
|
+
}
|
|
67
|
+
result[sshUnit] = sshDecision;
|
|
68
|
+
const health = await Promise.all(configuration.links.map(async link => {
|
|
69
|
+
assert.match(link.unit, /^mapsource-(?:mirror-peer|capacity-peer|read-link)-[a-z][a-z0-9-]*\.service$/);
|
|
70
|
+
assert.ok(Number.isInteger(link.port) && link.port >= 1024 && link.port <= 65535);
|
|
71
|
+
return probe({ port: link.port, timeoutMs: PEER_HEALTH_TIMEOUT_MS });
|
|
72
|
+
}));
|
|
73
|
+
for (const [index, link] of configuration.links.entries()) {
|
|
74
|
+
const healthy = health[index];
|
|
75
|
+
let observed = null, activityError = null;
|
|
76
|
+
try {
|
|
77
|
+
if (activity) observed = await activity(link);
|
|
78
|
+
else {
|
|
79
|
+
const pid = Number(run("systemctl", ["show", link.unit, "--property=MainPID", "--value"]));
|
|
80
|
+
if (Number.isSafeInteger(pid) && pid > 0) observed = parseLinkActivity(run("ss", ["-Htienp", `( sport = :${link.port} )`]), pid);
|
|
81
|
+
else activityError = "The peer forward has no running process";
|
|
82
|
+
}
|
|
83
|
+
} catch (error) {
|
|
84
|
+
// Missing counters grant no liveness; ordinary bounded recovery remains.
|
|
85
|
+
activityError = String(error.message).slice(0, 200);
|
|
86
|
+
}
|
|
87
|
+
// A delayed side-channel HEAD must not restart a link carrying replies.
|
|
88
|
+
// Keep probe readiness separate from measured transport liveness.
|
|
89
|
+
const decision = linkRecoveryDecision(previous[link.unit], healthy, now, observed);
|
|
90
|
+
if (decision.restart) {
|
|
91
|
+
const description = run("systemctl", ["show", link.unit, "--property=Description", "--value"]);
|
|
92
|
+
assert.ok(description.startsWith("Mapsource "), "Refusing an unrelated unit");
|
|
93
|
+
run("systemctl", ["restart", "--no-block", link.unit]);
|
|
94
|
+
console.log(JSON.stringify({ event: "peer-transport-recovering", unit: link.unit }));
|
|
95
|
+
}
|
|
96
|
+
result[link.unit] = { ...decision, ...(activityError ? { activityError } : {}) };
|
|
97
|
+
}
|
|
98
|
+
// Keep automatic QUIC -> TCP fallback time intact. A connector still
|
|
99
|
+
// starting on a restrictive network must not be restarted every timer tick.
|
|
100
|
+
const unit = "mapsource-mesh-tunnel.service";
|
|
101
|
+
let connectorReady = false;
|
|
102
|
+
try { const response = await fetch("http://127.0.0.1:20849/ready", { signal: AbortSignal.timeout(2000) }); connectorReady = response.ok; await response.body?.cancel(); } catch { /* Reconciled below. */ }
|
|
103
|
+
const started = Number(run("systemctl", ["show", unit, "--property=ActiveEnterTimestampMonotonic", "--value"])) / 1000;
|
|
104
|
+
const uptime = Number((await readFile("/proc/uptime", "utf8")).split(" ")[0]) * 1000;
|
|
105
|
+
const connector = recoveryDecision(previous[unit], connectorReady, now, { failures: 12, cooldownMs: 240_000 });
|
|
106
|
+
if (connector.restart && uptime - started >= 240_000) {
|
|
107
|
+
run("systemctl", ["restart", "--no-block", unit]);
|
|
108
|
+
console.log(JSON.stringify({ event: "registered-tunnel-recovering" }));
|
|
109
|
+
} else if (connector.restart) connector.restartedAt = previous[unit]?.restartedAt ?? 0;
|
|
110
|
+
result[unit] = connector;
|
|
111
|
+
const bytes = JSON.stringify(result); assert.ok(Buffer.byteLength(bytes) <= linkActivityLimits.statusBytes);
|
|
112
|
+
await mkdir(path.dirname(configuration.stateFile), { recursive: true, mode: 0o700 });
|
|
113
|
+
await writeFile(configuration.stateFile + ".pending", bytes, { mode: 0o600 });
|
|
114
|
+
await rename(configuration.stateFile + ".pending", configuration.stateFile);
|
|
115
|
+
return { checked: configuration.links.length, unhealthy: configuration.links.filter(link => !result[link.unit].healthy).map(link => link.unit), sshReady, connectorReady, accountAuthorityChanged: false };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
if (process.argv[1] === import.meta.filename) {
|
|
119
|
+
assert.ok(process.argv[2], "Use CONFIG_JSON");
|
|
120
|
+
console.log(JSON.stringify(await reconcileTransport(JSON.parse(await readFile(process.argv[2], "utf8")))));
|
|
121
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { getDefaultAutoSelectFamilyAttemptTimeout, setDefaultAutoSelectFamilyAttemptTimeout } from "node:net";
|
|
2
|
+
|
|
3
|
+
export const minimumNetworkFamilyAttemptMs = 2000;
|
|
4
|
+
|
|
5
|
+
/** One address-family attempt must survive a working remote connection's RTT.
|
|
6
|
+
* This does not alter family selection, DNS order or any request deadline. */
|
|
7
|
+
export function ensureNetworkFamilyAttemptTimeout() {
|
|
8
|
+
const current = getDefaultAutoSelectFamilyAttemptTimeout();
|
|
9
|
+
if (current < minimumNetworkFamilyAttemptMs) setDefaultAutoSelectFamilyAttemptTimeout(minimumNetworkFamilyAttemptMs);
|
|
10
|
+
return getDefaultAutoSelectFamilyAttemptTimeout();
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
ensureNetworkFamilyAttemptTimeout();
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
// Stable ingress lives outside the fenced account controller. Maintenance is
|
|
2
|
+
// temporary and instance-independent at this HTTP plane; a restart clears it.
|
|
3
|
+
import "./network-family-policy.mjs";
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import http from "node:http";
|
|
6
|
+
import https from "node:https";
|
|
7
|
+
import { readFile } from "node:fs/promises";
|
|
8
|
+
import { timingSafeEqual } from "node:crypto";
|
|
9
|
+
export const cutoverReplicaHeader = "x-mapsource-cutover-replica";
|
|
10
|
+
const portalRequestIdHeader = "x-mapsource-portal-request-id";
|
|
11
|
+
const portalResumeHeader = "x-mapsource-portal-resume";
|
|
12
|
+
const publicHosts = new Set(["mapsource.io", "api.mapsource.io", "app.mapsource.io"]);
|
|
13
|
+
const equal = (a, b) => { const x = Buffer.from(a ?? ""), y = Buffer.from(b ?? ""); return x.length === y.length && timingSafeEqual(x, y); };
|
|
14
|
+
const pause = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
15
|
+
export function streamingRequest(request, rules = []) {
|
|
16
|
+
const host = String(request.headers.host ?? "").split(":")[0];
|
|
17
|
+
let pathname = new URL(request.url, "http://localhost").pathname;
|
|
18
|
+
if (host === "api.mapsource.io" && !pathname.startsWith("/api/")) pathname = `/api${pathname}`;
|
|
19
|
+
const method = request.method === "HEAD" ? "GET" : request.method;
|
|
20
|
+
return request.method === "POST" && ["/mcp", "/api/mcp"].includes(pathname)
|
|
21
|
+
|| rules.some(rule => rule.method === method && new RegExp(rule.pattern).test(pathname));
|
|
22
|
+
}
|
|
23
|
+
function independentRequest(request, safeReads = []) {
|
|
24
|
+
const pathname = new URL(request.url, "http://localhost").pathname;
|
|
25
|
+
const host = String(request.headers?.host ?? "").split(":")[0], site = host === "mapsource.io";
|
|
26
|
+
const capabilityPath = host === "api.mapsource.io" && !pathname.startsWith("/api/") ? `/api${pathname}` : pathname;
|
|
27
|
+
return /^\/_next\/static\//.test(pathname) || pathname === "/health/live"
|
|
28
|
+
|| site && ["GET", "HEAD"].includes(request.method) && ["/authentication-station", "/status"].includes(pathname)
|
|
29
|
+
|| safeReads.some(({ method, pattern, accountIndependent }) => accountIndependent === true && method === request.method && new RegExp(pattern).test(capabilityPath));
|
|
30
|
+
}
|
|
31
|
+
function paymentRequest(request) {
|
|
32
|
+
return Object.hasOwn(request.headers ?? {}, "payment-signature") || Object.hasOwn(request.headers ?? {}, "x-payment");
|
|
33
|
+
}
|
|
34
|
+
function acceptsReplicaRead(request, pathname, apiHost, safeReads = []) {
|
|
35
|
+
const capabilityPath = apiHost && !pathname.startsWith("/api/") ? `/api${pathname}` : pathname;
|
|
36
|
+
return !paymentRequest(request) && safeReads.some(({ method, pattern }) => method === request.method && new RegExp(pattern).test(capabilityPath));
|
|
37
|
+
}
|
|
38
|
+
export function requiresWriter(request, safeReads = []) {
|
|
39
|
+
const pathname = new URL(request.url, "http://localhost").pathname;
|
|
40
|
+
if (independentRequest(request, safeReads)) return false;
|
|
41
|
+
if (paymentRequest(request)) return true;
|
|
42
|
+
const apiHost = String(request.headers?.host ?? "").split(":")[0] === "api.mapsource.io";
|
|
43
|
+
if (acceptsReplicaRead(request, pathname, apiHost, safeReads)) return false;
|
|
44
|
+
if (!["GET", "HEAD"].includes(request.method)) return true;
|
|
45
|
+
if (apiHost) return true;
|
|
46
|
+
return /^\/(?:api(?:\/|$)|account(?:\/|$)|admin(?:\/|$)|checkout(?:\/|$)|authentication-station(?:\/|$)|mcp(?:\/|$))/.test(pathname);
|
|
47
|
+
}
|
|
48
|
+
export async function createIngressPlane(config, { fetchImpl = fetch, now = Date.now,
|
|
49
|
+
peerRequest = (address, options, callback) => (address.protocol === "https:" ? https : http).request(address, options, callback) } = {}) {
|
|
50
|
+
if (!config.ingress?.enabled) return null;
|
|
51
|
+
const ha = JSON.parse(await readFile(config.haConfig, "utf8"));
|
|
52
|
+
const originToken = (await readFile(ha.originTokenFile, "utf8")).trim(), controlToken = (await readFile(ha.tokenFile, "utf8")).trim();
|
|
53
|
+
assert.ok(originToken.length >= 32 && controlToken.length >= 32);
|
|
54
|
+
const hostname = `mapsource-serve-${config.node}.${config.ingress.domain ?? "mapsource.io"}`;
|
|
55
|
+
let maintenance = null, holding = null, localInflight = 0, writerInflight = 0, totalInflight = 0, proxyInflight = 0, quiesced = false, queued = 0, routing, routingAt = 0, routePending;
|
|
56
|
+
const state = () => {
|
|
57
|
+
if (maintenance?.expiresAt <= now()) maintenance = null;
|
|
58
|
+
if (holding?.expiresAt <= now()) holding = null;
|
|
59
|
+
return { ingressProtocol: 1, draining: !!maintenance, holdingWrites: !!holding, holdingAllRequests: holding?.allRequests === true,
|
|
60
|
+
replicaReadsOnly: holding?.replicaReadsOnly === true, localInflight, writerInflight, acceptedBeforeHold: holding?.acceptedBeforeHold ?? localInflight, totalInflight, proxyInflight, quiesced, queued,
|
|
61
|
+
commit: maintenance?.commit ?? holding?.commit ?? null, expiresAt: Math.max(maintenance?.expiresAt ?? 0, holding?.expiresAt ?? 0) };
|
|
62
|
+
};
|
|
63
|
+
async function route(forceRefresh = false) {
|
|
64
|
+
if (!forceRefresh && routing && now() - routingAt < 500) return routing;
|
|
65
|
+
if (routePending) return routePending;
|
|
66
|
+
routePending = (async () => {
|
|
67
|
+
try {
|
|
68
|
+
const r = await fetchImpl(new URL("/route", ha.endpoint), { headers: { authorization: `Bearer ${controlToken}` }, signal: AbortSignal.timeout(5000) });
|
|
69
|
+
assert.ok(r.ok, "Serving discovery unavailable");
|
|
70
|
+
const next = await r.json(); assert.ok(Array.isArray(next?.nodes), "Invalid serving discovery");
|
|
71
|
+
routing = next; routingAt = now(); return routing;
|
|
72
|
+
} catch (error) {
|
|
73
|
+
// A failed refresh must not erase a still-current verified report.
|
|
74
|
+
// Retain its original timestamps; peer admission below is rechecked
|
|
75
|
+
// after this wait, and a newer successful empty route always wins.
|
|
76
|
+
if (routing && now() - routingAt >= 0 && now() - routingAt < 20_000) return routing;
|
|
77
|
+
throw error;
|
|
78
|
+
}
|
|
79
|
+
})().finally(() => { routePending = null; });
|
|
80
|
+
return routePending;
|
|
81
|
+
}
|
|
82
|
+
function maintenanceControl(action, body) {
|
|
83
|
+
assert.match(body.commit ?? "", /^[a-f0-9]{40}$/);
|
|
84
|
+
if (action === "/maintenance/resume") {
|
|
85
|
+
if (maintenance?.commit === body.commit) maintenance = null;
|
|
86
|
+
if (holding?.commit === body.commit) holding = null;
|
|
87
|
+
} else {
|
|
88
|
+
assert.ok(!maintenance || maintenance.expiresAt <= now() || maintenance.commit === body.commit, "Another deployment is draining ingress");
|
|
89
|
+
assert.ok(!holding || holding.expiresAt <= now() || holding.commit === body.commit, "Another deployment is holding admission");
|
|
90
|
+
const ttl = body.ttlMs ?? 900_000; assert.ok(Number.isSafeInteger(ttl) && ttl >= 1000 && ttl <= 900_000);
|
|
91
|
+
const at = now();
|
|
92
|
+
if (body.expiresAt !== undefined) assert.ok(action === "/maintenance/hold" && body.hold === true
|
|
93
|
+
&& Number.isSafeInteger(body.expiresAt) && body.expiresAt > at && body.expiresAt <= at + ttl, "Account admission deadline expired or changed");
|
|
94
|
+
const value = { commit: body.commit, expiresAt: body.expiresAt ?? at + ttl };
|
|
95
|
+
if (action === "/maintenance/drain") { assert.equal(body.automatic, true); maintenance = value; }
|
|
96
|
+
else {
|
|
97
|
+
assert.equal(action, "/maintenance/hold"); assert.ok(body.allRequests === undefined || typeof body.allRequests === "boolean");
|
|
98
|
+
assert.ok(body.replicaReadsOnly === undefined || body.replicaReadsOnly === true && body.hold === true && !body.allRequests);
|
|
99
|
+
if (holding?.expiresAt > at && body.hold && holding.replicaReadsOnly) {
|
|
100
|
+
// A retried hold shares the existing drain snapshot and deadline.
|
|
101
|
+
assert.ok(holding.replicaReadsOnly === body.replicaReadsOnly && holding.expiresAt === value.expiresAt, "Account cutover hold changed");
|
|
102
|
+
} else {
|
|
103
|
+
holding = body.hold ? { ...value, allRequests: body.allRequests === true,
|
|
104
|
+
replicaReadsOnly: body.replicaReadsOnly === true, acceptedBeforeHold: localInflight } : null;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return state();
|
|
109
|
+
}
|
|
110
|
+
function countLocal(response, writerDependent = false) {
|
|
111
|
+
const holdAtAdmission = holding;
|
|
112
|
+
localInflight++;
|
|
113
|
+
if (writerDependent) writerInflight++;
|
|
114
|
+
let complete = false;
|
|
115
|
+
const finish = () => {
|
|
116
|
+
if (complete) return;
|
|
117
|
+
complete = true;
|
|
118
|
+
localInflight--;
|
|
119
|
+
if (writerDependent) writerInflight--;
|
|
120
|
+
if (holding && holding !== holdAtAdmission) holding.acceptedBeforeHold--;
|
|
121
|
+
};
|
|
122
|
+
response.once("finish", finish);
|
|
123
|
+
response.once("close", finish);
|
|
124
|
+
}
|
|
125
|
+
async function peer(request, response) {
|
|
126
|
+
proxyInflight++; let finished = false; const done = () => { if (!finished) { finished = true; proxyInflight--; } }; response.once("finish", done); response.once("close", done);
|
|
127
|
+
const discovered = await route();
|
|
128
|
+
const host = String(request.headers.host ?? "").split(":")[0];
|
|
129
|
+
const pathname = new URL(request.url, "http://localhost").pathname;
|
|
130
|
+
const replicaRead = publicHosts.has(host) && host !== "app.mapsource.io"
|
|
131
|
+
&& acceptsReplicaRead(request, pathname, host === "api.mapsource.io", config.ingress.safeReads);
|
|
132
|
+
const choices = discovered.nodes.filter(n => /^[a-z][a-z0-9-]{0,31}$/.test(n.node ?? "") && n.node !== config.node
|
|
133
|
+
&& n.enabled !== false && !n.ingressDraining && (n.qualified === true && n.frontHealthy === true
|
|
134
|
+
|| replicaRead && n.engineQualified === true && n.readGateway?.ready === true)
|
|
135
|
+
&& Number.isFinite(n.at) && now() - n.at >= -5000 && now() - n.at < 20_000);
|
|
136
|
+
assert.ok(choices.length, "No qualified peer is available for ingress drain");
|
|
137
|
+
const hop = Number(request.headers["x-mapsource-ingress-hop"] ?? 0);
|
|
138
|
+
assert.ok(Number.isInteger(hop) && hop >= 0 && hop < 2, "Ingress drain loop prevented");
|
|
139
|
+
const target = choices.sort((a, b) => (b.weight ?? 1) - (a.weight ?? 1))[0];
|
|
140
|
+
const address = new URL(`https://mapsource-serve-${target.node}.${config.ingress.domain ?? "mapsource.io"}`), split = request.url.indexOf("?");
|
|
141
|
+
address.pathname = split < 0 ? request.url : request.url.slice(0, split);
|
|
142
|
+
address.search = split < 0 ? "" : request.url.slice(split);
|
|
143
|
+
assert.equal(address.hostname, `mapsource-serve-${target.node}.${config.ingress.domain ?? "mapsource.io"}`);
|
|
144
|
+
const headers = { ...request.headers, host: address.host, "x-mapsource-origin-token": originToken,
|
|
145
|
+
"x-mapsource-public-host": request.headers.host, "x-mapsource-ingress-hop": String(hop + 1) };
|
|
146
|
+
delete headers.connection;
|
|
147
|
+
const upstream = peerRequest(address, { method: request.method, headers }, result => {
|
|
148
|
+
if (streamingRequest(request, config.ingress.streamingResponses)) upstream.setTimeout(0);
|
|
149
|
+
const outgoing = { ...result.headers }; delete outgoing.connection; response.writeHead(result.statusCode, outgoing); result.pipe(response);
|
|
150
|
+
result.once("error", () => response.destroy());
|
|
151
|
+
});
|
|
152
|
+
upstream.once("error", () => { if (!response.headersSent) response.writeHead(502, { "cache-control": "no-store" }).end(); else response.destroy(); });
|
|
153
|
+
upstream.setTimeout(185_000, () => upstream.destroy()); request.once("aborted", () => upstream.destroy());
|
|
154
|
+
response.once("close", () => { if (!response.writableFinished) upstream.destroy(); }); request.pipe(upstream);
|
|
155
|
+
}
|
|
156
|
+
async function serve(request, response, local, activeCommit) {
|
|
157
|
+
totalInflight++; let finished = false; const totalDone = () => { if (!finished) { finished = true; totalInflight--; } }; response.once("finish", totalDone); response.once("close", totalDone);
|
|
158
|
+
delete request.headers[cutoverReplicaHeader];
|
|
159
|
+
const receivedHost = String(request.headers.host ?? "").split(":")[0];
|
|
160
|
+
if (receivedHost === hostname) {
|
|
161
|
+
const customerHost = request.headers["x-mapsource-public-host"];
|
|
162
|
+
if (!equal(request.headers["x-mapsource-origin-token"], originToken) || !publicHosts.has(customerHost)) { response.writeHead(404).end(); return; }
|
|
163
|
+
request.headers.host = customerHost;
|
|
164
|
+
} else if (request.url.startsWith("/_mapsource/") && !equal(request.headers["x-mapsource-origin-token"], originToken)) { response.writeHead(404).end(); return; }
|
|
165
|
+
if (new URL(request.url, "http://localhost").pathname === "/_mapsource/hosting") {
|
|
166
|
+
response.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" }).end(JSON.stringify({ schema: "mapsource-serving-host.v1", node: config.node,
|
|
167
|
+
machineId: config.machineId, port: config.port, originAuthentication: true, ingressProtocol: 1, webCommit: activeCommit })); return;
|
|
168
|
+
}
|
|
169
|
+
if (new URL(request.url, "http://localhost").pathname.startsWith("/_mapsource/overpass-jobs/")) {
|
|
170
|
+
// This independent private plane survives public ingress withdrawal and
|
|
171
|
+
// account handoffs. Public API credentials never authorize worker access.
|
|
172
|
+
if (receivedHost !== hostname || !equal(request.headers["x-mapsource-origin-token"], originToken)
|
|
173
|
+
|| !equal(request.headers.authorization, "Bearer " + originToken)) { response.writeHead(404).end(); return; }
|
|
174
|
+
const port = config.ingress.jobPort ?? 18994; assert.ok(Number.isInteger(port) && port >= 1024 && port <= 65535);
|
|
175
|
+
countLocal(response);
|
|
176
|
+
const upstream = http.request({ host: "127.0.0.1", port, path: request.url, method: request.method, headers: { ...request.headers, host: "127.0.0.1:" + port, connection: "close" } }, result => { if (/^\/_mapsource\/overpass-jobs\/blobs\/[a-f0-9]{64}(?:\/chunks\/\d+)?$/.test(new URL(request.url, "http://localhost").pathname)) upstream.setTimeout(0); const headers = { ...result.headers }; delete headers.connection; response.writeHead(result.statusCode, headers); result.pipe(response); result.once("error", () => response.destroy()); });
|
|
177
|
+
upstream.setTimeout(120000, () => upstream.destroy()); upstream.once("error", () => { if (!response.headersSent) response.writeHead(503, { "x-mapsource-origin": "overpass-jobs-proxy", "x-mapsource-not-started": "1" }).end(); else response.destroy(); });
|
|
178
|
+
request.once("aborted", () => upstream.destroy()); response.once("close", () => { if (!response.writableFinished) upstream.destroy(); }); request.pipe(upstream); return;
|
|
179
|
+
}
|
|
180
|
+
const writerDependent = requiresWriter(request, config.ingress.safeReads);
|
|
181
|
+
const portalRequest = receivedHost === hostname && /^[a-zA-Z0-9_-]{16,64}$/.test(request.headers[portalRequestIdHeader] ?? "");
|
|
182
|
+
delete request.headers[portalRequestIdHeader];
|
|
183
|
+
const held = () => state().holdingWrites && (writerDependent || holding?.allRequests === true && !independentRequest(request, config.ingress.safeReads));
|
|
184
|
+
if (held()) {
|
|
185
|
+
const queuedForCloud = writerDependent && portalRequest && holding.replicaReadsOnly;
|
|
186
|
+
assert.ok(queued < 256, "Deployment admission queue is full"); queued++;
|
|
187
|
+
request.pause();
|
|
188
|
+
try { const until = now() + 100_000; while (held() && !response.destroyed) { assert.ok(now() < until, "Deployment admission exceeded its deadline"); await pause(25); } }
|
|
189
|
+
finally { queued--; }
|
|
190
|
+
if (response.destroyed) return;
|
|
191
|
+
if (queuedForCloud) {
|
|
192
|
+
let native = false;
|
|
193
|
+
try { native = (await route(true)).accountAuthority?.kind !== "cloudflare"; } catch { /* Ask the edge to revalidate. */ }
|
|
194
|
+
if (!native) {
|
|
195
|
+
response.writeHead(503, { "cache-control": "no-store", "x-mapsource-not-started": "1", [portalResumeHeader]: "1" }).end();
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
const admission = state();
|
|
201
|
+
if (admission.draining) return peer(request, response);
|
|
202
|
+
if (admission.replicaReadsOnly) {
|
|
203
|
+
const host = String(request.headers.host ?? "").split(":")[0];
|
|
204
|
+
const pathname = new URL(request.url, "http://localhost").pathname;
|
|
205
|
+
if (publicHosts.has(host) && host !== "app.mapsource.io" && acceptsReplicaRead(request, pathname, host === "api.mapsource.io", config.ingress.safeReads))
|
|
206
|
+
request.headers[cutoverReplicaHeader] = "1";
|
|
207
|
+
}
|
|
208
|
+
countLocal(response, writerDependent);
|
|
209
|
+
await local(request, response); request.resume();
|
|
210
|
+
}
|
|
211
|
+
return { state, maintenanceControl, serve, quiesce: () => { assert.ok(state().draining, "Withdraw ingress before closing its acceptor"); quiesced = true; } };
|
|
212
|
+
}
|