mapsource-node 0.0.0-stage → 0.1.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.
- package/README.md +33 -2
- package/bin/mapsource-node.mjs +41 -0
- package/package.json +51 -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,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
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import "./network-family-policy.mjs";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { execFileSync } from "node:child_process";
|
|
4
|
+
import net from "node:net";
|
|
5
|
+
|
|
6
|
+
export const RELEASE_SCHEMA = "mapsource-web-release.v1";
|
|
7
|
+
const minutes = count => count * 60_000;
|
|
8
|
+
// Source qualification is shared by web and native releases. Deployment
|
|
9
|
+
// compatibility is measured separately against the actual serving fleet.
|
|
10
|
+
export const QUALIFICATION_STEPS = Object.freeze([
|
|
11
|
+
{ name: "install", program: "pnpm", args: ["install", "--frozen-lockfile"], timeoutMs: minutes(20) },
|
|
12
|
+
{ name: "compiler", program: "pnpm", args: ["check:compiler"], timeoutMs: minutes(20) },
|
|
13
|
+
{ name: "check", program: "pnpm", args: ["check"], timeoutMs: minutes(60) },
|
|
14
|
+
{ name: "release-browser", program: "node", args: ["--import", "tsx", "scripts/release-browser-smoke.mjs"], timeoutMs: minutes(10) },
|
|
15
|
+
{ name: "account-security-browser", program: "node", args: ["--import", "tsx", "scripts/browser-account-security-smoke.mjs"], timeoutMs: minutes(10) },
|
|
16
|
+
{ name: "native-pdf", program: "node", args: ["--import", "tsx", "services/gateway/src/document-browser-smoke.ts"], timeoutMs: minutes(10) },
|
|
17
|
+
{ name: "desktop-indicator", program: "python3", args: ["-c", "from pathlib import Path; p=Path('scripts/mirror-desktop.py'); compile(p.read_text(),str(p),'exec')"], timeoutMs: minutes(1) },
|
|
18
|
+
{ name: "package", program: "node", args: ["scripts/release-artifact.mjs"], timeoutMs: minutes(5) },
|
|
19
|
+
]);
|
|
20
|
+
export function apiProbeRequest(publicOrigin,key) {
|
|
21
|
+
return {method:"POST",headers:{authorization:`Bearer ${key}`,"content-type":"text/plain",origin:new URL(publicOrigin).origin,referer:new URL("/docs/quickstart",publicOrigin).href},body:"[out:json][timeout:5];node(1);out;"};
|
|
22
|
+
}
|
|
23
|
+
export async function freeWebSlot(ports,reserved) {
|
|
24
|
+
assert.ok(ports.length===2&&new Set(ports).size===2&&ports.every(p=>Number.isInteger(p)&&p>=1024&&p<=65535),"Configure two distinct unprivileged web slot ports.");
|
|
25
|
+
for(const port of ports.filter(p=>!reserved.includes(p))) {
|
|
26
|
+
const free=await new Promise((resolve,reject)=>{const socket=net.createServer();socket.once("error",error=>error.code==="EADDRINUSE"?resolve(false):reject(error));socket.listen(port,"127.0.0.1",()=>socket.close(()=>resolve(true)));});
|
|
27
|
+
if(free)return port;
|
|
28
|
+
}
|
|
29
|
+
throw new Error("No unused web slot is available; serving and foreign processes were left intact.");
|
|
30
|
+
}
|
|
31
|
+
export async function waitForReadyFleet(read,check,{onSample=()=>{},timeoutMs=120_000,intervalMs=2000,now=Date.now,pause=ms=>new Promise(resolve=>setTimeout(resolve,ms))}={}) {
|
|
32
|
+
const until=now()+timeoutMs;
|
|
33
|
+
for(;;){const snapshot=await read();onSample(snapshot);try{check(snapshot);return snapshot;}catch(error){if(now()>=until)throw error;await pause(intervalMs);}}
|
|
34
|
+
}
|
|
35
|
+
// The controller owns jobs, fencing, native data and the account schema. Web
|
|
36
|
+
// CD must never silently turn a change to these into a controller restart.
|
|
37
|
+
export function statefulChange(file) {
|
|
38
|
+
if (/^scripts\/overpass-job-[a-z0-9-]+\.(?:mjs|d\.mts)$/.test(file)) return true;
|
|
39
|
+
if (file === "scripts/account-native-replication.mjs") return true;
|
|
40
|
+
if (file === "scripts/release-node-admin.mjs" || file.startsWith("apps/node-admin/")) return true;
|
|
41
|
+
if (["scripts/artifact-lifecycle.mjs", "scripts/network-family-policy.mjs", "scripts/network-family-policy.d.mts"].includes(file)) return true;
|
|
42
|
+
// This separately deployed public fallback Worker has no native account or
|
|
43
|
+
// controller state. Its publication/browser checks run in the edge deploy.
|
|
44
|
+
if (file.startsWith("infra/edge-fallback/")) return false;
|
|
45
|
+
// Telegram runs on Cloudflare and its source is not loaded by native hosts.
|
|
46
|
+
if (file.startsWith("infra/telegram-ops/")) return false;
|
|
47
|
+
return /^(services\/|packages\/|apps\/web\/public\/mediakit\/|infra\/(?!deploy\/)|pnpm-lock\.yaml$|pnpm-workspace\.yaml$|package\.json$)/.test(file)
|
|
48
|
+
|| /^scripts\/(?:mirror-[a-z0-9-]+\.(?:mjs|py)|dev(?:-state)?\.mjs)$/.test(file);
|
|
49
|
+
}
|
|
50
|
+
export function deploymentKind(changed) {
|
|
51
|
+
// The web release store is used by staging and supervised retention. It
|
|
52
|
+
// does not run in either serving router or the native account controller.
|
|
53
|
+
const liveServing = file => file.startsWith("infra/edge-fallback/") || /^scripts\/release-(?:router|ingress-router|web-start|control-install)\.mjs$/.test(file);
|
|
54
|
+
return changed.some(file => statefulChange(file) || liveServing(file)) ? "native" : "web";
|
|
55
|
+
}
|
|
56
|
+
export function canSkipOptionalWebFirst(changed) {
|
|
57
|
+
const tooling = new Set(["scripts/mirror-authority.mjs", "scripts/mirror-service-health.mjs", "scripts/mirror-storage.mjs", "scripts/mirror-connector-health.mjs", "scripts/mirror-checkpoint.mjs", "scripts/release-native-node.mjs", "scripts/release-node-admin.mjs", "scripts/release-native-policy.mjs",
|
|
58
|
+
"scripts/mirror-state.mjs", "scripts/mirror-transfer.mjs", "scripts/mirror-scratch-transfer.mjs", "scripts/mirror-recover.mjs", "infra/mirror/checkpoint-limits.js", "docs/specs/mirror-authority.md",
|
|
59
|
+
"scripts/release-native-rollout.mjs", "scripts/release-rollout.mjs", "scripts/release-fleet.mjs", "scripts/release-control-rpc.mjs", "scripts/release-node.mjs",
|
|
60
|
+
"scripts/release-policy.mjs", "scripts/release-install-coordinator.mjs", "scripts/release-control-install.mjs", "scripts/release-edge-install.mjs", "scripts/artifact-lifecycle.mjs", "infra/mirror/authority.js", "infra/mirror/witness.mjs",
|
|
61
|
+
"infra/edge-fallback/serving.js", "scripts/release-serving.test.ts", "scripts/account-native-replication.mjs"]);
|
|
62
|
+
return changed.every(file => file === "AGENTS.md" || /^docs\/(?:runbooks|work-orders)\//.test(file)
|
|
63
|
+
|| file.startsWith("apps/node-admin/") || tooling.has(file) || tooling.has(file.replace(/\.test\.ts$/, ".mjs")));
|
|
64
|
+
}
|
|
65
|
+
export function assertCompatible(repository, runtimeCommit, commit) {
|
|
66
|
+
for (const sha of [runtimeCommit, commit]) assert.match(sha, /^[a-f0-9]{40}$/);
|
|
67
|
+
const changed = execFileSync("git", ["-C", repository, "diff", "--name-only", runtimeCommit, commit], { encoding: "utf8" }).trim().split("\n").filter(Boolean);
|
|
68
|
+
const blocked = changed.filter(statefulChange);
|
|
69
|
+
assert.equal(blocked.length, 0, `Stateful runtime changes require a separately tested migration; the healthy runtime is retained: ${blocked.join(", ")}`);
|
|
70
|
+
return changed;
|
|
71
|
+
}
|
|
72
|
+
// A release is qualified only by a passing local record for this exact commit
|
|
73
|
+
// and source tree in which every required step ran, in order, and passed.
|
|
74
|
+
export function qualifiedRelease(record, sha, sourceTree, steps = QUALIFICATION_STEPS) {
|
|
75
|
+
return record?.schema === "mapsource-local-qualification.v2" && record.commit === sha
|
|
76
|
+
&& record.sourceTree === sourceTree && record.passed === true && /^[a-f0-9]{64}$/.test(record.artifactSha256 ?? "")
|
|
77
|
+
&& Array.isArray(record.steps) && record.steps.length === steps.length
|
|
78
|
+
&& steps.every((step, index) => record.steps[index]?.name === step.name && record.steps[index].passed === true);
|
|
79
|
+
}
|
|
80
|
+
export function deploymentOrder(nodes, statuses, { independentWeb = false } = {}) {
|
|
81
|
+
assert.ok(nodes.length >= 2, "Staggered production CD requires at least two full serving hosts.");
|
|
82
|
+
assert.equal(new Set(nodes.map(n => n.node)).size, nodes.length, "Duplicate fleet host.");
|
|
83
|
+
const cloud = statuses.find(status => status?.accountAuthority?.kind === "cloudflare")?.accountAuthority;
|
|
84
|
+
if (cloud) {
|
|
85
|
+
assert.ok(Number.isSafeInteger(cloud.epoch) && cloud.epoch > 0 && Number.isSafeInteger(cloud.revision) && cloud.revision >= 0,
|
|
86
|
+
"Cloudflare account authority lacks a witnessed cutover revision");
|
|
87
|
+
for (const [index, node] of nodes.entries()) {
|
|
88
|
+
const status = statuses[index], authority = status?.accountAuthority, reader = status?.accountReader;
|
|
89
|
+
assert.ok(status?.node === node.node && authority?.kind === "cloudflare" && authority.epoch === cloud.epoch
|
|
90
|
+
&& authority.revision === cloud.revision && status.qualified && status.storageReady === true
|
|
91
|
+
&& status.connectivity?.witness && status.connectivity?.edge && status.role !== "primary",
|
|
92
|
+
`Host ${node.node} has not verified the Cloudflare account epoch.`);
|
|
93
|
+
assert.ok(reader?.ready === true && reader.feedFresh === true && reader.localRevision >= cloud.revision && reader.signedRevision >= cloud.revision,
|
|
94
|
+
`The signed account reader on ${node.node} is unavailable or behind the cutover revision.`);
|
|
95
|
+
assert.ok(Object.values(status.localServices ?? {}).every(value => ["ready", "relay"].includes(value) || String(value).includes("optional")),
|
|
96
|
+
`Mandatory services are unhealthy on ${node.node}.`);
|
|
97
|
+
}
|
|
98
|
+
return [...nodes];
|
|
99
|
+
}
|
|
100
|
+
const owner = statuses[0]?.owner;
|
|
101
|
+
assert.ok(owner && nodes.some(n => n.node === owner), "The live authority must be in the fleet.");
|
|
102
|
+
const writer = statuses.find(status => status?.node === owner && status.role === "primary");
|
|
103
|
+
assert.ok(writer, "The witnessed writer must be serving before web deployment.");
|
|
104
|
+
// Native rollouts and legacy ingress need a peer that can take over writes.
|
|
105
|
+
// An independent web slot switch leaves the native controllers running.
|
|
106
|
+
if (!independentWeb) assert.ok(statuses.some(status => status?.node !== owner && status?.role === "standby" && status.synchronized && status.takeoverReady),
|
|
107
|
+
"A current, synchronized failover peer must remain available during deployment.");
|
|
108
|
+
const followingMaps = status => status?.role === "standby" && status.synchronized
|
|
109
|
+
&& Number.isSafeInteger(status.overpassSequence) && Number.isSafeInteger(writer.overpassSequence)
|
|
110
|
+
&& Number.isFinite(Date.parse(status.overpassVersion)) && Number.isFinite(Date.parse(writer.overpassVersion))
|
|
111
|
+
&& Number.isFinite(Date.parse(status.areaVersion)) && Number.isFinite(Date.parse(writer.areaVersion)) && status.areaVersion >= writer.areaVersion
|
|
112
|
+
&& (status.overpassSequence < writer.overpassSequence || status.overpassVersion < writer.overpassVersion);
|
|
113
|
+
for (let i = 0; i < nodes.length; i++) {
|
|
114
|
+
const status = statuses[i];
|
|
115
|
+
const healthyStandby = independentWeb ? ["standby", "syncing"].includes(status?.role)
|
|
116
|
+
: status?.synchronized && (status.takeoverReady || followingMaps(status));
|
|
117
|
+
assert.ok(status?.node === nodes[i].node && status.owner === owner && status.qualified
|
|
118
|
+
&& status.connectivity?.witness && status.connectivity?.edge && status.storageReady !== false
|
|
119
|
+
&& (status.role === "primary" || healthyStandby), `Host ${nodes[i].node} is not ready for a rollout: role=${status?.role}, synchronized=${status?.synchronized}, takeover=${status?.takeoverDetail??status?.takeoverReady}.`);
|
|
120
|
+
assert.ok(Object.entries(status.localServices ?? {}).filter(([, state]) => !String(state).includes("optional")).every(([, state]) => ["ready", "relay"].includes(state)), `Mandatory services are unhealthy on ${nodes[i].node}.`);
|
|
121
|
+
}
|
|
122
|
+
assert.equal(statuses.filter(s => s.role === "primary").length, 1);
|
|
123
|
+
const tier = node => node.node === owner ? 2 : statuses.find(status => status.node === node.node)?.takeoverReady ? 1 : 0;
|
|
124
|
+
return [...nodes].sort((a,b) => tier(a) - tier(b));
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export function webDeploymentOrder(nodes, reports) {
|
|
128
|
+
const independentWeb = reports.length === nodes.length && reports.every(({ router }) => router?.ingress?.ingressProtocol === 1
|
|
129
|
+
&& router.ingress.draining !== true && router.active && router.slots?.some(slot => slot.commit === router.active && slot.origin));
|
|
130
|
+
return deploymentOrder(nodes, reports.map(report => report.controller), { independentWeb });
|
|
131
|
+
}
|