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,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
|
+
}
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
// Independent of the fenced database controller. Switching this web pointer
|
|
2
|
+
// never kills an application process or interrupts an in-flight response.
|
|
3
|
+
import "./network-family-policy.mjs";
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import { createIngressPlane, streamingRequest } from "./release-ingress-router.mjs";
|
|
6
|
+
import http from "node:http";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import { createReadStream } from "node:fs";
|
|
9
|
+
import { readFile, open, rename, stat, realpath } from "node:fs/promises";
|
|
10
|
+
import { timingSafeEqual,createHash } from "node:crypto";
|
|
11
|
+
import { RELEASE_SCHEMA } from "./release-policy.mjs";
|
|
12
|
+
|
|
13
|
+
export async function atomicJson(file, value) {
|
|
14
|
+
const pending = `${file}.pending`;
|
|
15
|
+
const handle = await open(pending, "w", 0o600);
|
|
16
|
+
try { await handle.writeFile(JSON.stringify(value) + "\n"); await handle.sync(); } finally { await handle.close(); }
|
|
17
|
+
await rename(pending, file);
|
|
18
|
+
const directory = await open(path.dirname(file), "r"); try { await directory.sync(); } finally { await directory.close(); }
|
|
19
|
+
}
|
|
20
|
+
const json = (response, code, value) => response.writeHead(code, { "content-type": "application/json", "cache-control": "no-store" }).end(JSON.stringify(value));
|
|
21
|
+
const safeHost = value => ["mapsource.io", "api.mapsource.io", "app.mapsource.io", "127.0.0.1", "localhost"].includes(String(value).split(":")[0]);
|
|
22
|
+
const mime = name => ({ ".js":"application/javascript", ".css":"text/css", ".woff2":"font/woff2", ".woff":"font/woff", ".png":"image/png", ".svg":"image/svg+xml", ".json":"application/json", ".map":"application/json" })[path.extname(name)] || "application/octet-stream";
|
|
23
|
+
export async function probeWeb(origin, { paths = [["/",200],["/account?intent=sign_in",200],["/status",200],["/authentication-station",200],["/admin",404],["/mediakit",200]] } = {}) {
|
|
24
|
+
let assetChecked = false;
|
|
25
|
+
for (const [route, expected] of paths) {
|
|
26
|
+
const started = performance.now();
|
|
27
|
+
const response = await fetch(origin + route, { redirect:"manual", headers:{host:"mapsource.io"}, signal:AbortSignal.timeout(10_000) });
|
|
28
|
+
assert.equal(response.status, expected, `Candidate ${route}: HTTP ${response.status}, expected ${expected}`);
|
|
29
|
+
const body = await response.text();
|
|
30
|
+
assert.ok(body.length > 100 && !body.includes("Application error: a server-side exception"), `Candidate ${route} did not render.`);
|
|
31
|
+
assert.ok(performance.now() - started < 5000, `Candidate ${route} exceeded the 5s readiness limit.`);
|
|
32
|
+
if (route === "/") {
|
|
33
|
+
const assets = [...new Set([...body.matchAll(/(?:src|href)="([^"?]*\/_next\/static\/[^"?]+)"/g)].map(match=>match[1]))];
|
|
34
|
+
assert.ok(assets.length > 0, "Candidate page has no JavaScript/style assets.");
|
|
35
|
+
for (const asset of assets) { const reply = await fetch(new URL(asset,origin), {signal:AbortSignal.timeout(10_000)}); assert.ok(reply.ok, `Missing candidate asset ${asset}`); await reply.body?.cancel(); }
|
|
36
|
+
assetChecked = true;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return { passed:true, assetChecked, routes:paths.length };
|
|
40
|
+
}
|
|
41
|
+
export async function probeWebBuild(root,origin) {
|
|
42
|
+
const buildId=(await readFile(path.join(root,"apps/web/.next/BUILD_ID"),"utf8")).trim();assert.match(buildId,/^[A-Za-z0-9_-]{1,100}$/);
|
|
43
|
+
const relative=`/_next/static/${buildId}/_buildManifest.js`,expected=await readFile(path.join(root,"apps/web/.next/static",buildId,"_buildManifest.js"));
|
|
44
|
+
const response=await fetch(origin+relative,{signal:AbortSignal.timeout(5000)});assert.equal(response.status,200,"Candidate is not serving its staged build ID.");
|
|
45
|
+
assert.equal(createHash("sha256").update(Buffer.from(await response.arrayBuffer())).digest("hex"),createHash("sha256").update(expected).digest("hex"),"Candidate's served build differs from the immutable CI artifact.");
|
|
46
|
+
}
|
|
47
|
+
function forward(request, response, origin, fallback, release, streaming = false) {
|
|
48
|
+
const address = new URL(origin);
|
|
49
|
+
const headers = { ...request.headers, host:request.headers.host || "mapsource.io" };
|
|
50
|
+
for (const name of ["connection", "keep-alive", "x-mapsource-origin-token", "x-mapsource-ha-target", "x-mapsource-public-host"]) delete headers[name];
|
|
51
|
+
const upstream = http.request({ hostname:address.hostname, port:address.port, path:request.url, method:request.method, headers }, result => {
|
|
52
|
+
if (streaming) upstream.setTimeout(0);
|
|
53
|
+
if (fallback && result.statusCode >= 500) { result.resume(); forward(request,response,fallback,null,"legacy"); return; }
|
|
54
|
+
const outgoing = { ...result.headers, "x-mapsource-web-release":release }; delete outgoing.connection;
|
|
55
|
+
// Keep-alive lifetime belongs to this socket. Forwarding Fastify's 72s
|
|
56
|
+
// hint through this 5s server makes clients reuse a socket we have closed.
|
|
57
|
+
delete outgoing["keep-alive"];
|
|
58
|
+
response.writeHead(result.statusCode,outgoing); result.pipe(response);
|
|
59
|
+
});
|
|
60
|
+
upstream.once("error",()=>{if(!response.headersSent && fallback)forward(request,response,fallback,null,"legacy");else if(!response.headersSent)json(response,502,{error:"Web origin unavailable"});else response.destroy();});
|
|
61
|
+
upstream.setTimeout(185_000,()=>upstream.destroy(new Error("Web origin timeout")));
|
|
62
|
+
request.once("aborted",()=>upstream.destroy());
|
|
63
|
+
response.once("close",()=>{if(!response.writableFinished)upstream.destroy();});
|
|
64
|
+
// Retry is restricted to bodyless document reads. Mutations and API reads
|
|
65
|
+
// are streamed once to the existing authority, never replayed here.
|
|
66
|
+
if (fallback) upstream.end(); else request.pipe(upstream);
|
|
67
|
+
}
|
|
68
|
+
export async function startReleaseRouter(config) {
|
|
69
|
+
const ingress = await createIngressPlane(config);
|
|
70
|
+
assert.ok(config.stateFile && config.releaseRoot && config.controlTokenFile);
|
|
71
|
+
const token = Buffer.from((await readFile(config.controlTokenFile,"utf8")).trim()); assert.ok(token.length >= 32);
|
|
72
|
+
const legacy = config.legacyOrigin || "http://127.0.0.1:3210", gateway = config.gatewayOrigin || "http://127.0.0.1:8787";
|
|
73
|
+
for (const origin of [legacy,gateway]) { const url=new URL(origin); assert.equal(url.protocol,"http:"); assert.equal(url.hostname,"127.0.0.1"); }
|
|
74
|
+
let state; try { state=JSON.parse(await readFile(config.stateFile,"utf8")); } catch(error) { if(error.code!=="ENOENT")throw error; state={active:null,previous:null,slots:[]}; }
|
|
75
|
+
let mutation = false, stopped = false;
|
|
76
|
+
const slot = commit => state.slots.find(s=>s.commit===commit);
|
|
77
|
+
const persist = async next => { await atomicJson(config.stateFile,next); state=next; };
|
|
78
|
+
const rollback = async () => {const previous=slot(state.previous);await persist({...state,active:previous?.commit??null,previous:null,activatedAt:Date.now()});};
|
|
79
|
+
const serve = async (request,response) => {
|
|
80
|
+
if (!safeHost(request.headers.host)) return json(response,400,{error:"Invalid host"});
|
|
81
|
+
const url = new URL(request.url,"http://localhost");
|
|
82
|
+
if (String(request.headers.host).split(":")[0] === "app.mapsource.io") return forward(request,response,config.appOrigin ?? "http://127.0.0.1:3220",null,"application");
|
|
83
|
+
if (String(request.headers.host).split(":")[0] === "api.mapsource.io") return forward(request,response,gateway,null,"authority",streamingRequest(request,config.ingress?.streamingResponses));
|
|
84
|
+
// The authority and its existing relay continue handling every API,
|
|
85
|
+
// metering and account mutation throughout the web rollout.
|
|
86
|
+
if (/^\/(?:api(?:\/|$)|health\/|mcp(?:\.json|\/|$)|llms?(?:-full)?\.txt$|\.well-known\/mcp\/)/.test(url.pathname)
|
|
87
|
+
|| ["/docs/quickstart.md","/docs/agents.md","/docs/compatibility.md"].includes(url.pathname)) return forward(request,response,gateway,null,"authority",streamingRequest(request,config.ingress?.streamingResponses));
|
|
88
|
+
if (["GET","HEAD"].includes(request.method) && url.pathname.startsWith("/_next/static/")) {
|
|
89
|
+
let relative; try { relative=decodeURIComponent(url.pathname.slice("/_next/static/".length)); } catch { return json(response,400,{error:"Invalid asset path"}); }
|
|
90
|
+
if (!relative || relative.split(/[\\/]/).some(p=>p===".."||p==="."||!p)) return json(response,404,{error:"Unknown asset"});
|
|
91
|
+
// Stage on ALL hosts before the first pointer switch. New HTML can then
|
|
92
|
+
// retrieve its chunks from any host during the staggered rollout.
|
|
93
|
+
for (const candidate of [...state.slots].reverse()) {
|
|
94
|
+
const root=path.join(candidate.root,"apps/web/.next/static"), file=path.join(root,relative);
|
|
95
|
+
try { const canonical=await realpath(file); if(!canonical.startsWith(root+path.sep))continue; const info=await stat(canonical); if(!info.isFile())continue;
|
|
96
|
+
response.writeHead(200,{"content-type":mime(file),"content-length":info.size,"cache-control":"public, max-age=31536000, immutable","x-content-type-options":"nosniff","x-mapsource-web-release":candidate.commit});
|
|
97
|
+
if(request.method==="HEAD")response.end();else {const stream=createReadStream(canonical);stream.once("error",()=>response.destroy());response.once("close",()=>stream.destroy());stream.pipe(response);} return;
|
|
98
|
+
} catch(error) { if(!["ENOENT","ENOTDIR"].includes(error.code))throw error; }
|
|
99
|
+
}
|
|
100
|
+
return forward(request,response,legacy,null,"legacy");
|
|
101
|
+
}
|
|
102
|
+
const active=slot(state.active);
|
|
103
|
+
const documentRead=["GET","HEAD"].includes(request.method) && !url.searchParams.has("_rsc") && !request.headers.rsc;
|
|
104
|
+
forward(request,response,active?.origin??legacy,active&&documentRead?slot(state.previous)?.origin??legacy:null,active?.commit??"legacy");
|
|
105
|
+
};
|
|
106
|
+
const web=http.createServer((req,res)=>{void (ingress ? ingress.serve(req,res,serve,state.active) : serve(req,res)).catch(()=>{if(!res.headersSent)json(res,502,{error:"Web router unavailable"});else res.destroy();});});
|
|
107
|
+
const control=http.createServer((req,res)=>{void (async()=>{
|
|
108
|
+
const received=Buffer.from(req.headers.authorization??""), expected=Buffer.concat([Buffer.from("Bearer "),token]);
|
|
109
|
+
if(received.length!==expected.length||!timingSafeEqual(received,expected))return json(res,404,{});
|
|
110
|
+
if(req.method==="GET"&&req.url==="/status")return json(res,200,{...state,node:config.node,routerRevision:config.routerRevision,ingress:ingress?.state()});
|
|
111
|
+
if(req.method!=="POST"||!["/stage","/activate","/rollback","/retire","/forget",...(ingress?["/maintenance/drain","/maintenance/hold","/maintenance/resume","/maintenance/quiesce"]:[])].includes(req.url))return json(res,404,{});
|
|
112
|
+
if(mutation)return json(res,409,{error:"Another deployment operation is running"}); mutation=true;
|
|
113
|
+
try {
|
|
114
|
+
let text="";for await(const chunk of req){text+=chunk;assert.ok(Buffer.byteLength(text)<=4096);}const body=JSON.parse(text||"{}");
|
|
115
|
+
if(req.url==="/maintenance/quiesce") { assert.equal(config.socketActivation,true,"A retained systemd socket is required for ingress restart"); assert.equal(ingress.state().commit,body.commit); ingress.quiesce(); web.close(()=>{}); web.closeIdleConnections(); return json(res,200,ingress.state()); }
|
|
116
|
+
if(req.url.startsWith("/maintenance/"))return json(res,200,ingress.maintenanceControl(req.url,body));
|
|
117
|
+
if(req.url==="/stage") {
|
|
118
|
+
assert.match(body.commit??"",/^[a-f0-9]{40}$/);assert.ok((config.slotPorts??[3310,3311]).includes(body.port),"Use a reserved web slot.");
|
|
119
|
+
const root=await realpath(path.join(config.releaseRoot,body.commit));assert.equal(root,path.join(await realpath(config.releaseRoot),body.commit));
|
|
120
|
+
const manifest=JSON.parse(await readFile(path.join(root,"release.json"),"utf8"));assert.equal(manifest.schema,RELEASE_SCHEMA);assert.equal(manifest.commit,body.commit);
|
|
121
|
+
const buildId=(await readFile(path.join(root,"apps/web/.next/BUILD_ID"),"utf8")).trim();assert.equal((await readFile(path.join(root,"apps/web/.next/MAPSOURCE_BUILD_COMPLETE"),"utf8")).trim(),buildId);assert.equal(manifest.buildId,buildId);
|
|
122
|
+
assert.ok(!state.slots.some(s=>s.commit!==body.commit&&s.port===body.port),"Forget and drain the old slot before reuse.");
|
|
123
|
+
const candidate={commit:body.commit,root,port:body.port,origin:`http://127.0.0.1:${body.port}`,buildId};await probeWebBuild(candidate.root,candidate.origin);await probeWeb(candidate.origin);
|
|
124
|
+
await persist({...state,slots:[...state.slots.filter(s=>s.commit!==body.commit),candidate]});
|
|
125
|
+
} else if(req.url==="/activate") {
|
|
126
|
+
const candidate=slot(body.commit);assert.ok(candidate,"Candidate was not staged.");await probeWebBuild(candidate.root,candidate.origin);await probeWeb(candidate.origin);
|
|
127
|
+
if(state.active!==candidate.commit)await persist({...state,previous:state.active,active:candidate.commit,activatedAt:Date.now()});
|
|
128
|
+
} else if(req.url==="/rollback") {if(!body.commit||state.active===body.commit)await rollback();}
|
|
129
|
+
else if(req.url==="/retire") {
|
|
130
|
+
assert.ok(Date.now()-(state.activatedAt??0)>=185_000,"The former web process has not drained.");
|
|
131
|
+
await persist({...state,previous:null,slots:state.slots.map(s=>s.commit!==state.active?{...s,origin:null,port:null}:s)});
|
|
132
|
+
}
|
|
133
|
+
else {assert.ok(body.commit!==state.active&&body.commit!==state.previous,"Cannot forget serving or rollback releases.");await persist({...state,slots:state.slots.filter(s=>s.commit!==body.commit)});}
|
|
134
|
+
json(res,200,{active:state.active,previous:state.previous});
|
|
135
|
+
} finally {mutation=false;}
|
|
136
|
+
})().catch(error=>{if(!res.headersSent)json(res,422,{error:error.message});else res.destroy();});});
|
|
137
|
+
for(const server of [web,control]){server.headersTimeout=15_000;server.requestTimeout=185_000;}
|
|
138
|
+
await Promise.all([new Promise((resolve,reject)=>{web.once("error",reject);if(config.socketActivation){assert.equal(Number(process.env.LISTEN_PID),process.pid);assert.equal(Number(process.env.LISTEN_FDS),1);web.listen({fd:3},resolve);}else web.listen(config.port??18992,"127.0.0.1",resolve);}),new Promise((resolve,reject)=>{control.once("error",reject);control.listen(config.controlPort??18993,"127.0.0.1",resolve);})]);
|
|
139
|
+
// A single failing route is enough to withdraw the candidate. Keep every
|
|
140
|
+
// former process alive until fleet-wide soak AND the drain interval finish.
|
|
141
|
+
const monitor=setInterval(()=>{if(stopped||mutation||!state.active)return;mutation=true;const active=slot(state.active);void probeWebBuild(active.root,active.origin).then(()=>probeWeb(active.origin)).catch(async error=>{await rollback();console.error(JSON.stringify({event:"automatic-web-rollback",commit:active.commit,error:error.message}));}).finally(()=>{mutation=false;});},config.monitorMs??15_000); monitor.unref();
|
|
142
|
+
return {web,control,close:async()=>{stopped=true;clearInterval(monitor);await Promise.all([web,control].map(server=>new Promise(resolve=>{server.close(resolve);server.closeIdleConnections();})));}};
|
|
143
|
+
}
|
|
144
|
+
if(process.argv[1]===import.meta.filename){
|
|
145
|
+
const config=JSON.parse(await readFile(process.argv[2],"utf8"));assert.equal((await readFile("/etc/machine-id","utf8")).trim(),config.machineId);
|
|
146
|
+
const router=await startReleaseRouter(config);const stop=()=>void router.close().then(()=>process.exit(0));process.once("SIGTERM",stop);process.once("SIGINT",stop);
|
|
147
|
+
console.log(JSON.stringify({event:"web-router-ready",node:config.node,port:config.port??18992}));
|
|
148
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { access, readFile, realpath, stat, statfs } from "node:fs/promises";
|
|
2
|
+
import { availableParallelism, totalmem } from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
|
|
5
|
+
const GiB = 1024 ** 3;
|
|
6
|
+
const idPattern = /^[a-z][a-z0-9-]{0,31}$/;
|
|
7
|
+
const bytes = value => Number.isSafeInteger(value) && value >= 0;
|
|
8
|
+
const requireValue = (condition, message) => { if (!condition) throw new Error(message); };
|
|
9
|
+
const indexed = (rows, kind, validate) => {
|
|
10
|
+
requireValue(Array.isArray(rows) && rows.length <= 128, `Invalid ${kind} list.`);
|
|
11
|
+
const result = new Map();
|
|
12
|
+
for (const row of rows) {
|
|
13
|
+
requireValue(row && idPattern.test(row.id) && !result.has(row.id) && validate(row), `Invalid or duplicate ${kind}.`);
|
|
14
|
+
result.set(row.id, row);
|
|
15
|
+
}
|
|
16
|
+
return result;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export function validateCatalog(catalog) {
|
|
20
|
+
requireValue(catalog?.schema === "mapsource-node-catalog.v1" && /^[a-f0-9]{40}$/.test(catalog.commit), "This service catalog requires a compatible Mapsource Node release.");
|
|
21
|
+
const volumes = indexed(catalog.volumes, "volume", volume => bytes(volume.reserveBytes));
|
|
22
|
+
const resources = indexed(catalog.resources, "resource", resource => volumes.has(resource.volume)
|
|
23
|
+
&& bytes(resource.peakBytes) && bytes(resource.finalBytes) && resource.peakBytes >= resource.finalBytes
|
|
24
|
+
&& Number.isSafeInteger(resource.inodes) && resource.inodes >= 0);
|
|
25
|
+
const services = indexed(catalog.services, "service", service =>
|
|
26
|
+
typeof service.label === "string" && service.label.length > 0 && service.label.length <= 80
|
|
27
|
+
&& Array.isArray(service.resources) && service.resources.every(id => resources.has(id))
|
|
28
|
+
&& Array.isArray(service.architectures) && service.architectures.every(arch => ["x64", "arm64"].includes(arch))
|
|
29
|
+
&& Array.isArray(service.tools) && service.tools.every(tool => idPattern.test(tool))
|
|
30
|
+
&& bytes(service.memoryBytes) && Number.isSafeInteger(service.cpu) && service.cpu > 0);
|
|
31
|
+
return { volumes, resources, services };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function nearestMount(target) {
|
|
35
|
+
requireValue(path.isAbsolute(target), "Deployment volumes must be absolute paths.");
|
|
36
|
+
return realpath(target).catch(error => {
|
|
37
|
+
if (error.code !== "ENOENT" || target === "/") throw error;
|
|
38
|
+
return nearestMount(path.dirname(target));
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export async function measureHost(targets) {
|
|
43
|
+
const tools = [];
|
|
44
|
+
await Promise.all(["docker", "ssh", "sshd", "rsync", "systemctl", "sudo", "python3", "java"].map(async tool => {
|
|
45
|
+
for (const directory of [...(process.env.PATH ?? "").split(":").filter(path.isAbsolute), "/usr/sbin", "/usr/bin"]) {
|
|
46
|
+
try { await access(path.join(directory, tool), 1); tools.push(tool); break; }
|
|
47
|
+
catch { /* Check the remaining executable paths. */ }
|
|
48
|
+
}
|
|
49
|
+
}));
|
|
50
|
+
const mounts = {};
|
|
51
|
+
for (const [id, target] of Object.entries(targets)) {
|
|
52
|
+
const directory = await nearestMount(target);
|
|
53
|
+
const [volume, metadata] = await Promise.all([statfs(directory), stat(directory)]);
|
|
54
|
+
mounts[id] = { path: target, device: metadata.dev, bytes: volume.bavail * volume.bsize, inodes: volume.ffree };
|
|
55
|
+
}
|
|
56
|
+
const memory = /^MemAvailable:\s+(\d+) kB$/m.exec(await readFile("/proc/meminfo", "utf8").catch(() => ""));
|
|
57
|
+
const os = /^ID="?([a-z0-9-]+)"?$/m.exec(await readFile("/etc/os-release", "utf8").catch(() => ""))?.[1] ?? "unknown";
|
|
58
|
+
const cuda = await access("/dev/nvidiactl").then(() => true, () => access("/dev/nvhost-gpu").then(() => true, () => false));
|
|
59
|
+
return { platform: process.platform, os, architecture: process.arch, cpu: availableParallelism(), memoryBytes: memory ? Number(memory[1]) * 1024 : totalmem(), cuda, tools: tools.sort(), mounts };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function planServices(catalog, host, selections) {
|
|
63
|
+
const { volumes, resources, services } = validateCatalog(catalog);
|
|
64
|
+
requireValue(Array.isArray(selections) && selections.length > 0 && selections.length <= services.size, "Select at least one service.");
|
|
65
|
+
const requested = [...new Set(selections)].map(id => {
|
|
66
|
+
requireValue(services.has(id), `Unknown service: ${id}`);
|
|
67
|
+
return services.get(id);
|
|
68
|
+
});
|
|
69
|
+
const errors = [];
|
|
70
|
+
if (host.platform !== "linux" || !["ubuntu", "debian"].includes(host.os)) errors.push("Select a supported Ubuntu or Debian host.");
|
|
71
|
+
for (const service of requested) {
|
|
72
|
+
if (!service.architectures.includes(host.architecture)) errors.push(`${service.label} does not support this architecture.`);
|
|
73
|
+
const missing = service.tools.filter(tool => !host.tools.includes(tool));
|
|
74
|
+
if (missing.length) errors.push(`${service.label} requires ${missing.join(", ")}.`);
|
|
75
|
+
}
|
|
76
|
+
const requiredCpu = requested.reduce((sum, service) => sum + service.cpu, 0);
|
|
77
|
+
const requiredMemory = requested.reduce((sum, service) => sum + service.memoryBytes, GiB);
|
|
78
|
+
if (requiredCpu > host.cpu) errors.push(`Selected services require ${requiredCpu} available CPU threads.`);
|
|
79
|
+
if (requiredMemory > host.memoryBytes) errors.push(`Selected services require ${(requiredMemory / GiB).toFixed(1)} GiB of available memory including reserve.`);
|
|
80
|
+
const disks = new Map();
|
|
81
|
+
for (const id of new Set(requested.flatMap(service => service.resources))) {
|
|
82
|
+
const resource = resources.get(id);
|
|
83
|
+
const policy = volumes.get(resource.volume);
|
|
84
|
+
const mount = host.mounts[resource.volume];
|
|
85
|
+
if (!mount) { errors.push(`Choose a filesystem for ${resource.volume}.`); continue; }
|
|
86
|
+
const disk = disks.get(mount.device) ?? { paths: [], peakBytes: 0, finalBytes: 0, reserveBytes: 0, inodes: 0, availableBytes: mount.bytes, availableInodes: mount.inodes };
|
|
87
|
+
if (!disk.paths.includes(mount.path)) disk.paths.push(mount.path);
|
|
88
|
+
disk.peakBytes += resource.peakBytes;
|
|
89
|
+
disk.finalBytes += resource.finalBytes;
|
|
90
|
+
disk.reserveBytes = Math.max(disk.reserveBytes, policy.reserveBytes);
|
|
91
|
+
disk.inodes += resource.inodes;
|
|
92
|
+
disk.availableBytes = Math.min(disk.availableBytes, mount.bytes);
|
|
93
|
+
disk.availableInodes = Math.min(disk.availableInodes, mount.inodes);
|
|
94
|
+
disks.set(mount.device, disk);
|
|
95
|
+
}
|
|
96
|
+
for (const disk of disks.values()) {
|
|
97
|
+
if (disk.peakBytes + disk.reserveBytes > disk.availableBytes) errors.push(`Insufficient staging and reserve space on ${disk.paths.join(", ")}.`);
|
|
98
|
+
if (disk.inodes > disk.availableInodes) errors.push(`Insufficient free inodes on ${disk.paths.join(", ")}.`);
|
|
99
|
+
}
|
|
100
|
+
return { eligible: errors.length === 0, services: requested.map(({ id, label }) => ({ id, label })), requiredCpu, requiredMemory, disks: [...disks.values()], errors };
|
|
101
|
+
}
|
package/src/commands.mjs
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { access, mkdir, open, rm } from "node:fs/promises";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { createInterface } from "node:readline/promises";
|
|
6
|
+
import { parseArgs } from "node:util";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
import { measureHost, planServices, validateCatalog } from "./capability.mjs";
|
|
9
|
+
import { catalogDigest, enrollmentRequest, localIdentity, operatorRequest, readEnrollment, readInvitation, saveEnrollment, secretInput } from "./enrollment.mjs";
|
|
10
|
+
|
|
11
|
+
const mirrorRoot = "/srv/mapsource-mirror";
|
|
12
|
+
const bootstrap = fileURLToPath(new URL("../protocol/bootstrap/scripts/mirror-mesh-install.mjs", import.meta.url));
|
|
13
|
+
const targets = { system: "/usr/local", data: mirrorRoot };
|
|
14
|
+
const sshKey = /^ssh-ed25519 [A-Za-z0-9+/=]+(?: [a-zA-Z0-9-]+)?$/;
|
|
15
|
+
const printable = value => String(value).replace(/[\p{Cc}\p{Cf}]/gu, "");
|
|
16
|
+
const gib = value => (value / 1024 ** 3).toFixed(1) + " GiB";
|
|
17
|
+
const show = value => console.log(JSON.stringify(value, null, 2));
|
|
18
|
+
const servicesOption = { services: { type: "string" } };
|
|
19
|
+
const flags = (args, options) => parseArgs({ args, options }).values;
|
|
20
|
+
const ids = value => value.split(",").map(item => item.trim()).filter(Boolean);
|
|
21
|
+
const usage = `Mapsource Node
|
|
22
|
+
|
|
23
|
+
mapsource-node Open the terminal dashboard
|
|
24
|
+
mapsource-node --json Read current fleet telemetry
|
|
25
|
+
mapsource-node services List profiles offered by the local authority
|
|
26
|
+
mapsource-node invite --node NAME --services ID[,ID] [--out FILE]
|
|
27
|
+
mapsource-node revoke --node NAME Revoke an unused sync key
|
|
28
|
+
mapsource-node setup [--key-file FILE | --key-stdin] [--services ID[,ID]] [--apply]
|
|
29
|
+
mapsource-node resume Resume an authorized enrollment and deploy
|
|
30
|
+
mapsource-node status Read enrollment and service progress
|
|
31
|
+
mapsource-node disable [--services ID[,ID]] [--apply]
|
|
32
|
+
mapsource-node retire [--services ID[,ID]] [--apply]
|
|
33
|
+
`;
|
|
34
|
+
|
|
35
|
+
async function input(prompt) {
|
|
36
|
+
if (!process.stdin.isTTY) throw new Error("This choice requires a terminal or an explicit option.");
|
|
37
|
+
const reader = createInterface({ input: process.stdin, output: process.stderr });
|
|
38
|
+
try { return (await reader.question(prompt)).trim(); }
|
|
39
|
+
finally { reader.close(); }
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function showPlan(plan) {
|
|
43
|
+
console.log(plan.services.map(service => printable(service.label)).join(", "));
|
|
44
|
+
console.log(`Needs ${plan.requiredCpu} CPU threads and ${gib(plan.requiredMemory)} of available memory.`);
|
|
45
|
+
for (const disk of plan.disks) {
|
|
46
|
+
console.log(`${disk.paths.join(", ")} · ${gib(disk.peakBytes)} peak · ${gib(disk.reserveBytes)} reserve · ${gib(disk.availableBytes)} free · ${disk.inodes.toLocaleString()} inodes`);
|
|
47
|
+
}
|
|
48
|
+
for (const issue of plan.errors) console.log(printable(issue));
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function localMesh(configuration) {
|
|
52
|
+
const { operatorPublicKey, ...payload } = configuration;
|
|
53
|
+
if (!sshKey.test(operatorPublicKey ?? "")) throw new Error("Invalid scoped peer operator key.");
|
|
54
|
+
const sshDirectory = path.join(homedir(), ".ssh");
|
|
55
|
+
const authorized = path.join(sshDirectory, "authorized_keys");
|
|
56
|
+
await mkdir(sshDirectory, { recursive: true, mode: 0o700 });
|
|
57
|
+
const file = await open(authorized, "a+", 0o600);
|
|
58
|
+
try {
|
|
59
|
+
const info = await file.stat();
|
|
60
|
+
if (!info.isFile() || info.uid !== process.getuid() || info.mode & 0o022) throw new Error("Use a private authorized_keys file.");
|
|
61
|
+
const before = await file.readFile("utf8");
|
|
62
|
+
const line = `restrict ${operatorPublicKey}`;
|
|
63
|
+
if (!before.split("\n").includes(line)) await file.appendFile("\n" + line + "\n");
|
|
64
|
+
await file.sync();
|
|
65
|
+
} finally { await file.close(); }
|
|
66
|
+
// Only the reviewed, npm-pinned bootstrap code is executable. The authority
|
|
67
|
+
// supplies the scoped connector credential and node identity as data.
|
|
68
|
+
const text = execFileSync(process.execPath, [bootstrap, "--execute"], {
|
|
69
|
+
input: JSON.stringify(payload), encoding: "utf8", stdio: ["pipe", "pipe", "pipe"], timeout: 180_000,
|
|
70
|
+
});
|
|
71
|
+
const installed = JSON.parse(text.trim().split("\n").at(-1));
|
|
72
|
+
if (installed.installed !== true || installed.node !== payload.node || installed.machineId !== payload.machineId) {
|
|
73
|
+
throw new Error("The local peer transport did not return the expected identity.");
|
|
74
|
+
}
|
|
75
|
+
return { publicKeys: { host: installed.hostPublicKey, peer: installed.peerPublicKey }, root: installed.root };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async function localPrivileges(services, catalog) {
|
|
79
|
+
execFileSync("/usr/bin/sudo", ["-n", "true"], { stdio: "ignore", timeout: 5000 });
|
|
80
|
+
if (catalog.services.some(service => services.includes(service.id) && service.tools.includes("docker"))) {
|
|
81
|
+
execFileSync("docker", ["info", "--format", "{{.ServerVersion}}"], { stdio: "ignore", timeout: 8000 });
|
|
82
|
+
execFileSync("docker", ["compose", "version", "--short"], { stdio: "ignore", timeout: 8000 });
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
async function resume() {
|
|
87
|
+
const saved = await readEnrollment();
|
|
88
|
+
if (saved.pendingClaim) throw new Error("Re-enter the same sync key with setup to resume the authorized selection.");
|
|
89
|
+
const identity = await localIdentity();
|
|
90
|
+
const call = (operation, value = {}) => enrollmentRequest(saved.endpoint, operation, { node: saved.node, ...value }, { identity });
|
|
91
|
+
let result = await call("status");
|
|
92
|
+
if (["authorized", "tunnel-issued"].includes(result.phase)) {
|
|
93
|
+
const peer = await call("bootstrap");
|
|
94
|
+
const identityProof = await localMesh(peer);
|
|
95
|
+
result = await call("register", identityProof);
|
|
96
|
+
}
|
|
97
|
+
if (["registered", "failed"].includes(result.phase)) {
|
|
98
|
+
const host = await measureHost(targets);
|
|
99
|
+
const plan = planServices(saved.catalog, host, saved.services);
|
|
100
|
+
if (!plan.eligible) { showPlan(plan); throw new Error("This host no longer meets the selected service requirements."); }
|
|
101
|
+
await localPrivileges(saved.services, saved.catalog);
|
|
102
|
+
result = await call("deploy");
|
|
103
|
+
}
|
|
104
|
+
return result;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async function setup(args) {
|
|
108
|
+
const options = flags(args, { ...servicesOption, "key-file": { type: "string" }, "key-stdin": { type: "boolean" }, apply: { type: "boolean" } });
|
|
109
|
+
if (options["key-file"] && options["key-stdin"]) throw new Error("Choose one sync key input.");
|
|
110
|
+
let saved = await readEnrollment().catch(error => { if (error.code !== "ENOENT") throw error; });
|
|
111
|
+
if (saved && !saved.pendingClaim) { show(await resume()); return; }
|
|
112
|
+
const invitation = readInvitation(await secretInput({ fromFile: options["key-file"], fromStdin: options["key-stdin"] }));
|
|
113
|
+
if (saved && saved.endpoint !== invitation.endpoint) throw new Error("Resume with the original sync key.");
|
|
114
|
+
if (!saved) {
|
|
115
|
+
const grant = await enrollmentRequest(invitation.endpoint, "catalog", {}, { invitation });
|
|
116
|
+
const catalog = grant.catalog;
|
|
117
|
+
validateCatalog(catalog);
|
|
118
|
+
const host = await measureHost(targets);
|
|
119
|
+
console.log(`${host.os} ${host.architecture} · ${host.cpu} threads · ${gib(host.memoryBytes)} available · CUDA device ${host.cuda ? "detected" : "absent"}`);
|
|
120
|
+
for (const service of catalog.services.filter(item => grant.allowed.includes(item.id))) {
|
|
121
|
+
const { errors, eligible } = planServices(catalog, host, [service.id]);
|
|
122
|
+
console.log(` ${service.id} ${printable(service.label)} · ${eligible ? "compatible" : printable(errors[0])}`);
|
|
123
|
+
}
|
|
124
|
+
const selection = ids(options.services ?? await input("Select service IDs separated by commas: "));
|
|
125
|
+
if (!selection.every(id => grant.allowed.includes(id))) throw new Error("The sync key does not permit one or more selected services.");
|
|
126
|
+
const plan = planServices(catalog, host, selection);
|
|
127
|
+
showPlan(plan);
|
|
128
|
+
if (!plan.eligible) throw new Error("The selection exceeds this host’s capacity.");
|
|
129
|
+
if (!options.apply && (!process.stdin.isTTY || (await input("Apply this plan? [y/N] ")).toLowerCase() !== "y")) return;
|
|
130
|
+
await localPrivileges(selection, catalog);
|
|
131
|
+
saved = { node: grant.node, endpoint: invitation.endpoint, services: [...new Set(selection)].sort(), catalog, pendingClaim: true };
|
|
132
|
+
await saveEnrollment(saved);
|
|
133
|
+
}
|
|
134
|
+
const identity = await localIdentity();
|
|
135
|
+
const receipt = await enrollmentRequest(saved.endpoint, "claim", {
|
|
136
|
+
machineId: identity.machineId, username: identity.username, services: saved.services, catalogDigest: catalogDigest(saved.catalog),
|
|
137
|
+
}, { invitation, identity });
|
|
138
|
+
if (receipt.node !== saved.node) throw new Error("The claimed identity does not match the enrollment.");
|
|
139
|
+
await saveEnrollment({ ...saved, pendingClaim: false });
|
|
140
|
+
show(await resume());
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export async function main(command, args) {
|
|
144
|
+
if (command === "--help" && !args.length) { process.stdout.write(usage); return; }
|
|
145
|
+
if (command === "setup") { await setup(args); return; }
|
|
146
|
+
if (command === "resume" && !args.length) { show(await resume()); return; }
|
|
147
|
+
if (command === "services" && !args.length) { show((await operatorRequest("catalog", {})).catalog.services); return; }
|
|
148
|
+
if (command === "invite" || command === "revoke") {
|
|
149
|
+
const options = flags(args, command === "invite" ? { node: { type: "string" }, out: { type: "string" }, ...servicesOption } : { node: { type: "string" } });
|
|
150
|
+
if (!options.node) throw new Error("Pass --node NAME.");
|
|
151
|
+
if (command === "revoke") { show(await operatorRequest(command, { node: options.node })); return; }
|
|
152
|
+
if (!options.services) throw new Error("Pass --services with at least one service ID.");
|
|
153
|
+
if (options.out) {
|
|
154
|
+
const fd = await open(options.out, "wx", 0o600);
|
|
155
|
+
let complete = false;
|
|
156
|
+
try {
|
|
157
|
+
const result = await operatorRequest(command, { node: options.node, services: ids(options.services) });
|
|
158
|
+
await fd.writeFile(result.key + "\n"); await fd.sync();
|
|
159
|
+
complete = true;
|
|
160
|
+
show({ node: result.node, expiresAt: result.expiresAt, keyFile: options.out });
|
|
161
|
+
} finally { await fd.close(); if (!complete) await rm(options.out); }
|
|
162
|
+
} else {
|
|
163
|
+
if (!process.stdout.isTTY) throw new Error("Use --out FILE to avoid printing a key into logs or a pipeline.");
|
|
164
|
+
const result = await operatorRequest(command, { node: options.node, services: ids(options.services) });
|
|
165
|
+
console.log(result.key);
|
|
166
|
+
console.log("Expires " + new Date(result.expiresAt).toISOString());
|
|
167
|
+
}
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
if (["status", "disable", "retire"].includes(command)) {
|
|
171
|
+
const options = flags(args, command === "status" ? {} : { ...servicesOption, apply: { type: "boolean" } });
|
|
172
|
+
const saved = await readEnrollment();
|
|
173
|
+
if (saved.pendingClaim) throw new Error("Waiting for sync key confirmation. Run mapsource-node setup.");
|
|
174
|
+
show(await enrollmentRequest(saved.endpoint, command, { node: saved.node, preview: !options.apply,
|
|
175
|
+
...(options.services && { services: ids(options.services) }) }, { identity: await localIdentity() }));
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
throw new Error("Unknown command. Run mapsource-node --help.");
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export async function firstRun() {
|
|
182
|
+
const enrolled = await Promise.all(["/etc/mapsource-cd/node-v5.json", "/etc/systemd/system/mapsource-mesh-tunnel.service"]
|
|
183
|
+
.map(file => access(file).then(() => true, () => false)));
|
|
184
|
+
if (enrolled.some(Boolean)) return false;
|
|
185
|
+
const state = await readEnrollment().catch(error => { if (error.code !== "ENOENT") throw error; });
|
|
186
|
+
if (state && !state.pendingClaim) return false;
|
|
187
|
+
if (!process.stdin.isTTY) return false;
|
|
188
|
+
console.log("Mapsource Node · First-time setup");
|
|
189
|
+
console.log("Create a sync key on an enrolled host with mapsource-node invite.");
|
|
190
|
+
await setup([]);
|
|
191
|
+
return true;
|
|
192
|
+
}
|