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.
@@ -0,0 +1,153 @@
1
+ import { createHash, createPrivateKey, generateKeyPairSync, randomUUID, sign } from "node:crypto";
2
+ import { mkdir, open, readFile, realpath, rename, rm, stat } from "node:fs/promises";
3
+ import { homedir, userInfo } from "node:os";
4
+ import path from "node:path";
5
+ import { createInterface } from "node:readline/promises";
6
+ import { Writable } from "node:stream";
7
+ import { request } from "node:http";
8
+
9
+ const enrollmentHost = /^mapsource-enroll-[a-z][a-z0-9-]{0,31}\.mapsource\.io$/;
10
+ const stateRoot = () => path.join(process.env.XDG_STATE_HOME || path.join(homedir(), ".local/state"), "mapsource-node");
11
+ const maximumReply = 1024 ** 2;
12
+
13
+ export function readInvitation(input, { allowLoopback = false } = {}) {
14
+ const match = /^mps-sync1:([a-z0-9.-]+(?::[0-9]+)?):([a-f0-9]{32}):([A-Za-z0-9_-]{43})$/.exec(input.trim());
15
+ if (!match) throw new Error("Enter a valid Mapsource sync key.");
16
+ const [, host, id, secret] = match;
17
+ const loopback = allowLoopback && /^127\.0\.0\.1:[1-9][0-9]{1,4}$/.test(host);
18
+ if (!loopback && !enrollmentHost.test(host)) throw new Error("The sync key must use a registered Mapsource enrollment host.");
19
+ return { endpoint: `${loopback ? "http" : "https"}://${host}`, id, secret };
20
+ }
21
+
22
+ async function privateRead(file) {
23
+ const resolved = await realpath(file);
24
+ const info = await stat(resolved);
25
+ if (!info.isFile() || info.uid !== process.getuid() || (info.mode & 0o077)) throw new Error("Enrollment credentials must belong to you and have mode 0600.");
26
+ if (info.size > 256 * 1024) throw new Error("Enrollment state exceeds its size budget.");
27
+ return readFile(resolved, "utf8");
28
+ }
29
+
30
+ async function privateWrite(name, data, { exclusive = false } = {}) {
31
+ const root = stateRoot();
32
+ await mkdir(root, { recursive: true, mode: 0o700 });
33
+ const directory = await stat(root);
34
+ if (!directory.isDirectory() || directory.uid !== process.getuid() || (directory.mode & 0o077)) throw new Error("Enrollment state must be a private directory.");
35
+ const destination = path.join(root, name);
36
+ const pending = exclusive ? destination : path.join(root, ".pending-" + randomUUID());
37
+ const file = await open(pending, "wx", 0o600);
38
+ try {
39
+ try { await file.writeFile(JSON.stringify(data) + "\n"); await file.sync(); }
40
+ finally { await file.close(); }
41
+ if (!exclusive) await rename(pending, destination);
42
+ const directoryFD = await open(root, "r");
43
+ try { await directoryFD.sync(); } finally { await directoryFD.close(); }
44
+ } finally {
45
+ if (!exclusive) await rm(pending, { force: true });
46
+ }
47
+ }
48
+
49
+ export async function localIdentity() {
50
+ const file = path.join(stateRoot(), "identity.json");
51
+ try { return JSON.parse(await privateRead(file)); }
52
+ catch (error) { if (error.code !== "ENOENT") throw error; }
53
+ const { privateKey, publicKey } = generateKeyPairSync("ed25519");
54
+ const machineId = (await readFile("/etc/machine-id", "utf8")).trim();
55
+ if (!/^[a-f0-9]{32}$/.test(machineId)) throw new Error("The machine needs a valid Linux machine ID.");
56
+ const username = userInfo().username;
57
+ if (!/^[a-z_][a-z0-9_-]{0,31}$/.test(username) || username === "root") throw new Error("Run setup as the local Mapsource service user with sudo access.");
58
+ const identity = {
59
+ machineId, username,
60
+ publicKey: publicKey.export({ type: "spki", format: "der" }).toString("base64url"),
61
+ privateKey: privateKey.export({ type: "pkcs8", format: "pem" }).toString(),
62
+ };
63
+ try { await privateWrite("identity.json", identity, { exclusive: true }); }
64
+ catch (error) { if (error.code === "EEXIST") return JSON.parse(await privateRead(file)); throw error; }
65
+ return identity;
66
+ }
67
+
68
+ export const readEnrollment = () => privateRead(path.join(stateRoot(), "enrollment.json")).then(JSON.parse);
69
+ export const saveEnrollment = data => privateWrite("enrollment.json", data);
70
+
71
+ export async function secretInput({ fromStdin, fromFile } = {}) {
72
+ if (fromFile) return (await privateRead(fromFile)).trim();
73
+ if (fromStdin) {
74
+ let data = "";
75
+ for await (const chunk of process.stdin) {
76
+ data += chunk;
77
+ if (data.length > 4096) throw new Error("Sync key input is too long.");
78
+ }
79
+ return data.trim();
80
+ }
81
+ if (!process.stdin.isTTY) throw new Error("Use --key-stdin or --key-file for a noninteractive enrollment.");
82
+ const discard = new Writable({ write(_chunk, _encoding, callback) { callback(); } });
83
+ const reader = createInterface({ input: process.stdin, output: discard, terminal: true });
84
+ try {
85
+ process.stderr.write("Paste the sync key, then press Enter: ");
86
+ return (await new Promise((resolve, reject) => {
87
+ reader.once("close", () => reject(new Error("Input canceled.")));
88
+ reader.once("SIGINT", () => reader.close());
89
+ reader.question("").then(resolve, reject);
90
+ })).trim();
91
+ } finally { reader.close(); process.stderr.write("\n"); }
92
+ }
93
+
94
+ export function signOperation(identity, operation, payload, timestamp = Date.now(), requestId = randomUUID()) {
95
+ const body = { ...payload, publicKey: identity.publicKey, timestamp, requestId };
96
+ const encoded = Buffer.from(JSON.stringify([operation, body]));
97
+ return { body, proof: sign(null, encoded, createPrivateKey(identity.privateKey)).toString("base64url") };
98
+ }
99
+
100
+ export async function enrollmentRequest(endpoint, operation, payload, { invitation, identity, fetcher = fetch } = {}) {
101
+ const value = identity ? signOperation(identity, operation, payload) : { body: payload };
102
+ const response = await fetcher(new URL("/v1/" + operation, endpoint), {
103
+ method: "POST", redirect: "error", signal: AbortSignal.timeout(25_000),
104
+ headers: { "content-type": "application/json", ...(invitation && { authorization: `Bearer ${invitation.id}.${invitation.secret}` }) },
105
+ body: JSON.stringify(value),
106
+ });
107
+ const reader = response.body?.getReader();
108
+ if (!reader) throw new Error("Enrollment authority did not return a response.");
109
+ const chunks = [];
110
+ let bytes = 0;
111
+ try {
112
+ for (;;) {
113
+ const { done, value } = await reader.read();
114
+ if (done) break;
115
+ bytes += value.length;
116
+ if (bytes > maximumReply) throw new Error("Enrollment response exceeded its size budget.");
117
+ chunks.push(value);
118
+ }
119
+ } finally { await reader.cancel().catch(() => {}); }
120
+ const body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
121
+ if (!response.ok) {
122
+ const reason = /^[a-z][a-z0-9-]{0,60}$/.test(body.error ?? "") ? ` (${body.error})` : "";
123
+ throw new Error(`Enrollment request failed with HTTP ${response.status}${reason}.`);
124
+ }
125
+ return body;
126
+ }
127
+
128
+ export function catalogDigest(catalog) {
129
+ return createHash("sha256").update(JSON.stringify(catalog)).digest("hex");
130
+ }
131
+
132
+ export function operatorRequest(operation, input, socketPath = path.join(homedir(), ".local/share/mapsource/node-enrollment/operator.sock")) {
133
+ return new Promise((resolve, reject) => {
134
+ const body = JSON.stringify(input);
135
+ const req = request({ socketPath, path: "/v1/" + operation, method: "POST",
136
+ headers: { "content-type": "application/json", "content-length": Buffer.byteLength(body) } }, async response => {
137
+ try {
138
+ let reply = "";
139
+ for await (const chunk of response) {
140
+ reply += chunk;
141
+ if (Buffer.byteLength(reply) > maximumReply) throw new Error("Operator response exceeds its budget.");
142
+ }
143
+ const value = JSON.parse(reply);
144
+ if (response.statusCode !== 200) throw new Error("Operator request failed (" + (value.error ?? response.statusCode) + ").");
145
+ resolve(value);
146
+ } catch (error) { reject(error); }
147
+ });
148
+ req.setTimeout(15_000, () => req.destroy(new Error("Enrollment authority did not respond.")));
149
+ req.on("error", cause => reject(cause.code === "ENOENT" || cause.code === "ECONNREFUSED"
150
+ ? new Error("This host does not have an active Mapsource enrollment authority.") : cause));
151
+ req.end(body);
152
+ });
153
+ }
package/src/index.ts ADDED
@@ -0,0 +1,70 @@
1
+ import { createCliRenderer } from "@opentui/core";
2
+ import type { CliRenderer } from "@opentui/core";
3
+ import { mapsourcePalette } from "./palette.ts";
4
+ import { nodeInterface } from "./interface.ts";
5
+ import { readTelemetry } from "./telemetry.ts";
6
+
7
+ const version = process.env.MAPSOURCE_NODE_BUILD ?? "development";
8
+ const usage = "Mapsource Admin\n\n mapsource-node Open the terminal dashboard\n mapsource-node --json Print one read-only telemetry snapshot\n mapsource-node --version Print the installed release\n";
9
+ const [arg, ...remaining] = process.argv.slice(2);
10
+
11
+ function bindKeys(renderer: CliRenderer, ui: ReturnType<typeof nodeInterface>, refresh: () => void) {
12
+ renderer.keyInput.on("keypress", key => {
13
+ if (key.name === "q" || key.name === "escape") renderer.destroy();
14
+ else if (key.name === "r") refresh();
15
+ else if (key.name === "left") ui.navigate(ui.tab() - 1);
16
+ else if (key.name === "right" || key.name === "tab") ui.navigate(ui.tab() + 1);
17
+ else if (key.name === "up") ui.scroll(-1);
18
+ else if (key.name === "down") ui.scroll(1);
19
+ else if (key.name === "pageup") ui.scroll(-10);
20
+ else if (key.name === "pagedown") ui.scroll(10);
21
+ else if (["1", "2", "3"].includes(key.name)) ui.navigate(Number(key.name) - 1);
22
+ });
23
+ }
24
+
25
+ async function launch() {
26
+ const renderer = await createCliRenderer({
27
+ screenMode: "alternate-screen", backgroundColor: mapsourcePalette.ink, consoleMode: "disabled",
28
+ useMouse: true, exitOnCtrlC: true, exitSignals: ["SIGINT", "SIGTERM", "SIGHUP"],
29
+ });
30
+ const ui = nodeInterface(renderer, version);
31
+ let closed = false, sampling = false;
32
+ async function refresh() {
33
+ if (closed || sampling) return;
34
+ sampling = true;
35
+ try {
36
+ const data = await readTelemetry();
37
+ if (!closed) ui.update(data);
38
+ } finally { sampling = false; }
39
+ }
40
+ renderer.on("resize", ui.paint);
41
+ bindKeys(renderer, ui, () => void refresh());
42
+ const timer = setInterval(() => void refresh(), 5000);
43
+ renderer.once("destroy", () => { closed = true; clearInterval(timer); });
44
+ ui.paint();
45
+ void refresh();
46
+ }
47
+
48
+ if (arg === "--help" && !remaining.length) process.stdout.write(usage);
49
+ else if (arg === "--version" && !remaining.length) console.log("mapsource-node " + version);
50
+ else if (arg === "--json" && !remaining.length) console.log(JSON.stringify(await readTelemetry(), null, 2));
51
+ else if (arg === "--self-test" && !remaining.length) {
52
+ const { createTestRenderer } = await import("@opentui/core/testing");
53
+ const { renderer, mockInput, renderOnce, captureCharFrame } = await createTestRenderer({ width: 80, height: 24 });
54
+ try {
55
+ const view = nodeInterface(renderer, version);
56
+ bindKeys(renderer, view, () => {});
57
+ view.paint();
58
+ await renderOnce();
59
+ const frame = captureCharFrame();
60
+ if (!frame.includes("MAPSOURCE ADMIN") || !frame.includes("3 Services")) throw new Error("OpenTUI verification frame incomplete");
61
+ mockInput.pressArrow("right");
62
+ mockInput.pressArrow("right");
63
+ await renderOnce();
64
+ if (view.tab() !== 2 || !captureCharFrame().includes("Q Quit")) throw new Error("OpenTUI navigation verification failed");
65
+ console.log("mapsource-node self-test " + version);
66
+ } finally { renderer.destroy(); }
67
+ } else if (arg !== undefined || !process.stdin.isTTY || !process.stdout.isTTY) {
68
+ process.stderr.write(arg === undefined ? "A terminal is required. SSH with -t or use mapsource-node --json.\n" : usage);
69
+ process.exitCode = 2;
70
+ } else await launch();
@@ -0,0 +1,181 @@
1
+ import { BoxRenderable, ScrollBoxRenderable, TextAttributes, TextRenderable } from "@opentui/core";
2
+ import type { CliRenderer, RenderContext } from "@opentui/core";
3
+ import { mapsourcePalette as palette } from "./palette.ts";
4
+ import type { Telemetry } from "./telemetry.ts";
5
+
6
+ const tabs = ["Overview", "Fleet", "Services"] as const;
7
+ const compactTabs = ["Node", "Fleet", "Svc"] as const;
8
+ const good = palette.focus, muted = palette.muted, amber = "#eac684", red = "#ef9990";
9
+ const dash = "—";
10
+ const percent = (value: number | null | undefined) => value == null ? dash : value.toFixed(1) + "%";
11
+ const rate = (value: number | null) => value == null ? dash : value.toFixed(1) + "/s";
12
+ const count = (value: number | null) => value == null ? dash : String(value);
13
+ const bars = "▁▂▃▄▅▆▇█";
14
+ function sparkline(values: readonly (number | null)[]) {
15
+ const peak = Math.max(1, ...values.map(value => value ?? 0));
16
+ return values.map(value => value == null ? " " : bars[Math.round(7 * value / peak)]).join("");
17
+ }
18
+ const utc = (value: string | number | null | undefined) => {
19
+ const date = value == null ? null : new Date(value);
20
+ return date && Number.isFinite(date.valueOf()) ? date.toISOString().slice(5, 16).replace("T", " ") + " UTC" : dash;
21
+ };
22
+ const stateColor = (state: string) => {
23
+ const value = state.toLowerCase();
24
+ if (["ready", "relay", "operational", "connected", "serving", "current"].includes(value)) return good;
25
+ if (value === "unknown" || value.includes("optional")) return muted;
26
+ return value.includes("unavailable") ? red : amber;
27
+ };
28
+
29
+ export function nodeInterface(renderer: CliRenderer, version: string) {
30
+ let selected = 0, snapshot: Telemetry | null = null;
31
+ const history = new Map<string, { latency: (number | null)[]; queued: (number | null)[] }>();
32
+ // OpenTUI's renderer getter types omit undefined on optional context fields.
33
+ const context = renderer as unknown as RenderContext;
34
+ const box = (options: ConstructorParameters<typeof BoxRenderable>[1] = {}) =>
35
+ new BoxRenderable(context, { flexDirection: "column", ...options });
36
+ const text = (content: string, fg: string = palette.paper, bold = false, extra: ConstructorParameters<typeof TextRenderable>[1] = {}) =>
37
+ new TextRenderable(context, { content, fg, height: 1, flexShrink: 0, wrapMode: "none", truncate: true,
38
+ attributes: bold ? TextAttributes.BOLD : 0, ...extra });
39
+ const frame = box({ width: "100%", height: "100%", backgroundColor: palette.ink, paddingX: 1 });
40
+ const header = box({ height: 3, flexShrink: 0, border: ["bottom"], borderColor: palette.moss, paddingX: 1, justifyContent: "center" });
41
+ const heading = text("MAPSOURCE ADMIN", good, true);
42
+ header.add(heading);
43
+ const navigation = box({ flexDirection: "row", height: 2, flexShrink: 0, gap: 1, paddingX: 1 });
44
+ const navText = tabs.map((tab, index) => text(` ${index + 1} ${tab} `, muted, false, { width: tab.length + 4 }));
45
+ navText.forEach(item => navigation.add(item));
46
+ const viewport = new ScrollBoxRenderable(context, {
47
+ flexGrow: 1, flexShrink: 1, minHeight: 0, scrollX: false, scrollY: true, viewportCulling: true,
48
+ contentOptions: { paddingX: 1, paddingBottom: 1 },
49
+ verticalScrollbarOptions: { showArrows: false },
50
+ });
51
+ const footer = box({ height: 2, flexShrink: 0, paddingX: 1, border: ["top"], borderColor: palette.moss });
52
+ const keys = text("1–3 / ← → View ↑ ↓ Scroll R Refresh Q Quit", muted);
53
+ footer.add(keys);
54
+ for (const section of [header, navigation, viewport, footer]) frame.add(section);
55
+ renderer.root.add(frame);
56
+
57
+ function panel(title: string) {
58
+ const section = box({ border: true, borderStyle: "single", borderColor: palette.moss,
59
+ backgroundColor: palette.slate, paddingX: 1, flexShrink: 0, marginBottom: 1 });
60
+ section.add(text(title, good, true));
61
+ return section;
62
+ }
63
+
64
+ function row(section: BoxRenderable, name: string, detail: string, color: string = palette.paper) {
65
+ const line = box({ flexDirection: "row", height: 1, flexShrink: 0 });
66
+ line.add(text(name, muted, false, { width: renderer.width < 55 ? "43%" : "36%" }));
67
+ line.add(text(detail, color, false, { flexGrow: 1, flexShrink: 1, minWidth: 0 }));
68
+ section.add(line);
69
+ }
70
+
71
+ function overview(data: Telemetry) {
72
+ const cards = box({ flexDirection: renderer.width >= 56 ? "row" : "column", gap: 1, flexShrink: 0 });
73
+ const indicators = [
74
+ ["PUBLIC OVERPASS", data.public.verifiedOverpass, "Checked " + utc(data.public.checkedAt)],
75
+ ["ACCOUNT WRITER", data.authority, data.feedFresh ? "Signed feed current" : "Signed feed unverified"],
76
+ ["LOCAL ENGINE ROUTING", data.admitted ? "Serving" : data.controllerAvailable ? "Not admitted" : "Unavailable",
77
+ data.controllerAvailable ? `Role · ${data.role}` : "Controller unreachable"],
78
+ ] as const;
79
+ for (const [title, value, detail] of indicators) {
80
+ const card = panel(title);
81
+ card.flexGrow = 1;
82
+ if (renderer.width >= 56) card.width = "32%";
83
+ card.add(text(value, title === "ACCOUNT WRITER" && value !== "Unknown" ? good : stateColor(value), true));
84
+ card.add(text(detail, muted));
85
+ cards.add(card);
86
+ }
87
+ viewport.add(cards);
88
+ const node = panel("NODE HEALTH");
89
+ row(node, "CPU / memory", [percent(data.host.cpuPercent), percent(data.host.memoryPercent)].join(" / "));
90
+ row(node, "Dataset volume", data.host.storageAvailableBytes === null ? dash :
91
+ `${(data.host.storageAvailableBytes / 1024 ** 3).toFixed(0)} GiB available · ${data.storageReady ? "ready" : "unverified"}`);
92
+ row(node, "Node uptime", `${Math.floor(data.host.uptimeSeconds / 3600)}h ${Math.floor(data.host.uptimeSeconds % 3600 / 60)}m`);
93
+ row(node, "Authority link", data.witnessLink ? "Connected" : "Unverified", data.witnessLink ? good : amber);
94
+ row(node, "Cloudflare tunnel", data.cloudLink ? "Connected" : "Unverified", data.cloudLink ? good : amber);
95
+ viewport.add(node);
96
+ const datasets = panel("DATA FRESHNESS");
97
+ row(datasets, "Overpass applied through", utc(data.overpassVersion));
98
+ row(datasets, "Area index generation", utc(data.areaVersion));
99
+ row(datasets, "Account checkpoint", utc(data.checkpointAt));
100
+ viewport.add(datasets);
101
+ }
102
+
103
+ function fleet(data: Telemetry) {
104
+ for (const host of data.fleet.nodes) {
105
+ const section = panel(host.name.toUpperCase() + (host.name === data.node ? " · LOCAL" : ""));
106
+ const health = host.recent ? (host.serving ? "Serving" : "Not admitted") : host.at ? "Stale" : "Unreachable";
107
+ row(section, "Engine routing", `${health} · ${host.role}`, stateColor(health));
108
+ row(section, "CPU / memory", `${percent(host.cpuPercent)} / ${percent(host.memoryPercent)}`);
109
+ row(section, "Requests / errors", `${rate(host.requestRate)} / ${rate(host.errorRate)}`);
110
+ row(section, "Overpass applied", utc(host.overpassAt));
111
+ row(section, "Observed", utc(host.at));
112
+ viewport.add(section);
113
+ }
114
+ if (data.fleet.note) viewport.add(text(data.fleet.note, amber));
115
+ }
116
+
117
+ function services(data: Telemetry) {
118
+ const engines = panel("ENGINE QUEUES");
119
+ for (const engine of data.engines) {
120
+ const slots = engine.slots == null ? dash : `${count(engine.active)}/${engine.slots}`;
121
+ const latency = engine.latencyMs == null ? dash : engine.latencyMs.toFixed(0) + " ms";
122
+ const pressure = `${slots} active · ${count(engine.queued)} queued · ${latency}`;
123
+ row(engines, engine.name, pressure + " · " + engine.state, stateColor(engine.state));
124
+ const samples = history.get(engine.name);
125
+ if (samples?.latency.some(value => value != null)) row(engines, " Latency", sparkline(samples.latency), good);
126
+ if (samples?.queued.some(value => value != null)) row(engines, " Queue depth", sparkline(samples.queued), amber);
127
+ }
128
+ viewport.add(engines);
129
+ const local = panel("LOCAL SERVICES");
130
+ for (const service of data.services) row(local, service.name, service.state, stateColor(service.state));
131
+ if (!data.services.length) local.add(text("Controller telemetry unavailable.", amber));
132
+ viewport.add(local);
133
+ const tools = panel("ENROLLMENT");
134
+ tools.add(text("Run mapsource-node services to list profiles.", muted));
135
+ tools.add(text("Run mapsource-node invite to create a sync key.", muted));
136
+ tools.add(text("Run mapsource-node status for enrollment progress.", muted));
137
+ viewport.add(tools);
138
+ }
139
+
140
+ function paint() {
141
+ const oldOffset = viewport.scrollTop;
142
+ for (const child of viewport.getChildren()) child.destroyRecursively();
143
+ heading.content = snapshot ? `MAPSOURCE ADMIN / ${snapshot.node.toUpperCase()}` : "MAPSOURCE ADMIN";
144
+ navText.forEach((item, index) => {
145
+ const name = (renderer.width < 42 ? compactTabs : tabs)[index] ?? "";
146
+ item.content = ` ${index + 1} ${name} `;
147
+ item.width = name.length + 4;
148
+ item.fg = index === selected ? palette.ink : muted;
149
+ item.bg = index === selected ? good : palette.ink;
150
+ });
151
+ keys.content = renderer.width < 65 ? "1–3 View · ↑↓ Scroll · R Refresh · Q Quit" :
152
+ `1–3 / ← → View ↑ ↓ Scroll R Refresh Q Quit · ${version.slice(0, 12)}`;
153
+ if (!snapshot) viewport.add(text("Reading node, fleet, and public status…", muted));
154
+ else if (selected === 0) overview(snapshot);
155
+ else if (selected === 1) fleet(snapshot);
156
+ else services(snapshot);
157
+ viewport.scrollTop = oldOffset;
158
+ }
159
+
160
+ return {
161
+ paint,
162
+ update(data: Telemetry) {
163
+ snapshot = data;
164
+ for (const engine of data.engines) {
165
+ const series = history.get(engine.name) ?? { latency: [], queued: [] };
166
+ series.latency.push(engine.latencyMs);
167
+ series.queued.push(engine.queued);
168
+ if (series.latency.length > 30) { series.latency.shift(); series.queued.shift(); }
169
+ history.set(engine.name, series);
170
+ }
171
+ paint();
172
+ },
173
+ navigate(next: number) {
174
+ selected = (next + tabs.length) % tabs.length;
175
+ viewport.scrollTop = 0;
176
+ paint();
177
+ },
178
+ tab: () => selected,
179
+ scroll(lines: number) { viewport.scrollBy(lines); },
180
+ };
181
+ }
package/src/palette.ts ADDED
@@ -0,0 +1,11 @@
1
+ /** Shared website and Mapsource basemap colors. Safe to import in the browser. */
2
+ export const mapsourcePalette = {
3
+ slate: "#232d31",
4
+ ink: "#101310",
5
+ paper: "#f3f2ec",
6
+ moss: "#506a55",
7
+ ground: "#d4d1c3",
8
+ line: "#91aa93",
9
+ muted: "#b8bcb5",
10
+ focus: "#d8ed9d",
11
+ } as const;
@@ -0,0 +1,158 @@
1
+ import { readFile, statfs } from "node:fs/promises";
2
+ import { cpus, hostname, totalmem, uptime } from "node:os";
3
+
4
+ type RecordValue = Record<string, unknown>;
5
+ const object = (value: unknown): RecordValue =>
6
+ value && typeof value === "object" && !Array.isArray(value) ? value as RecordValue : {};
7
+ const items = (value: unknown): unknown[] => Array.isArray(value) ? value : [];
8
+ const number = (value: unknown): number | null => typeof value === "number" && Number.isFinite(value) ? value : null;
9
+ const label = (value: unknown, fallback = "Unknown"): string =>
10
+ typeof value === "string" && value.trim() ? value.replace(/[\p{Cc}\p{Cf}]/gu, "").slice(0, 120) || fallback : fallback;
11
+
12
+ const controllerUrl = "http://127.0.0.1:18989/status";
13
+ const fleetUrl = "http://127.0.0.1:19390/fleet";
14
+ const publicUrl = "https://api.mapsource.io/status";
15
+ const configFile = "/etc/mapsource-cd/node-v5.json";
16
+ const fleetEngines = ["overpass", "search", "routing", "tiles", "contours"] as const;
17
+
18
+ async function readJson(response: Response, limit: number): Promise<RecordValue> {
19
+ if (!response.ok) {
20
+ await response.body?.cancel();
21
+ throw new Error("HTTP " + response.status);
22
+ }
23
+ const reader = response.body?.getReader();
24
+ if (!reader) throw new Error("Empty response");
25
+ const chunks: Uint8Array[] = [];
26
+ let bytes = 0;
27
+ try {
28
+ for (;;) {
29
+ const chunk = await reader.read();
30
+ if (chunk.done) break;
31
+ bytes += chunk.value.byteLength;
32
+ if (bytes > limit) throw new Error("Response exceeds telemetry budget");
33
+ chunks.push(chunk.value);
34
+ }
35
+ return object(JSON.parse(Buffer.concat(chunks).toString("utf8")));
36
+ } finally {
37
+ await reader.cancel().catch(() => {});
38
+ }
39
+ }
40
+
41
+ async function fetchStatus(url: string, headers: HeadersInit = {}) {
42
+ const response = await fetch(url, { headers, redirect: "error", signal: AbortSignal.timeout(3500) });
43
+ return readJson(response, 512 * 1024);
44
+ }
45
+
46
+ function cpuCounters() {
47
+ return cpus().reduce(({ idle, total }, { times }) => ({
48
+ idle: idle + times.idle,
49
+ total: total + times.user + times.nice + times.sys + times.idle + times.irq,
50
+ }), { idle: 0, total: 0 });
51
+ }
52
+ let previousCpu = cpuCounters();
53
+
54
+ async function hostMetrics() {
55
+ const current = cpuCounters();
56
+ const span = current.total - previousCpu.total;
57
+ const idle = current.idle - previousCpu.idle;
58
+ previousCpu = current;
59
+ const [memory, disk] = await Promise.all([
60
+ readFile("/proc/meminfo", "utf8").catch(() => ""),
61
+ statfs("/srv/geo").catch(() => null),
62
+ ]);
63
+ const memoryAvailable = /^(?:MemAvailable):\s+(\d+) kB$/m.exec(memory);
64
+ return {
65
+ cpuPercent: span > 0 ? 100 * (1 - idle / span) : null,
66
+ memoryPercent: memoryAvailable ? 100 * (1 - Number(memoryAvailable[1]) * 1024 / totalmem()) : null,
67
+ totalMemoryBytes: totalmem(),
68
+ storageAvailableBytes: disk ? disk.bavail * disk.bsize : null,
69
+ uptimeSeconds: uptime(),
70
+ };
71
+ }
72
+
73
+ async function readFleet() {
74
+ let token: string;
75
+ try {
76
+ const config = object(JSON.parse(await readFile(configFile, "utf8")));
77
+ if (typeof config.haConfig !== "string") throw new Error("Missing HA configuration");
78
+ const ha = object(JSON.parse(await readFile(config.haConfig, "utf8")));
79
+ if (typeof ha.originTokenFile !== "string") throw new Error("Missing fleet credential");
80
+ token = (await readFile(ha.originTokenFile, "utf8")).trim();
81
+ if (token.length < 32) throw new Error("Missing fleet credential");
82
+ } catch {
83
+ return { nodes: [], note: "Fleet view requires the node operator’s access." };
84
+ }
85
+ try {
86
+ const data = await fetchStatus(fleetUrl + "?after=" + Date.now(), { "x-mapsource-capacity-token": token });
87
+ const now = Date.now();
88
+ const nodes = items(data.nodes).slice(0, 64).map(value => {
89
+ const node = object(value);
90
+ const sample = object(node.latest);
91
+ const host = object(sample.host), state = object(sample.status), rates = object(sample.rates);
92
+ const at = number(sample.at);
93
+ const recent = at !== null && at <= now + 5_000 && now - at < 8_000;
94
+ return {
95
+ name: label(node.node),
96
+ profile: label(node.profile, "full"),
97
+ at,
98
+ recent,
99
+ serving: recent && state.engineQualified === true,
100
+ role: label(state.role),
101
+ cpuPercent: number(host.cpuPercent),
102
+ memoryPercent: number(host.memoryPercent),
103
+ requestRate: number(rates.requests),
104
+ errorRate: number(rates.errors),
105
+ overpassAt: typeof state.overpassVersion === "string" ? state.overpassVersion : null,
106
+ };
107
+ });
108
+ return { nodes, note: nodes.length ? null : "No node samples are available." };
109
+ } catch {
110
+ return { nodes: [], note: "Local fleet telemetry is unavailable." };
111
+ }
112
+ }
113
+
114
+ export async function readTelemetry() {
115
+ const [controller, publicStatus, fleet, host] = await Promise.all([
116
+ fetchStatus(controllerUrl).catch(() => null),
117
+ fetchStatus(publicUrl).catch(() => null),
118
+ readFleet(),
119
+ hostMetrics(),
120
+ ]);
121
+ const status = object(controller), authority = object(status.accountAuthority);
122
+ const links = object(status.connectivity), accountReader = object(status.accountReader);
123
+ const localServices = object(status.localServices), engineLoad = object(status.engineLoad);
124
+ const publicApi = object(publicStatus?.publicApi);
125
+ const observed = label(publicApi.checkedAt, "");
126
+ const observationAt = Date.parse(observed);
127
+ const freshPublic = Number.isFinite(observationAt) && Date.now() - observationAt < 180_000 && observationAt <= Date.now() + 5000;
128
+ return {
129
+ at: Date.now(),
130
+ node: label(status.node, label(hostname())),
131
+ controllerAvailable: controller !== null,
132
+ admitted: status.engineQualified === true,
133
+ role: label(status.role),
134
+ authority: label(authority.kind === "native" ? status.owner : authority.kind ?? status.owner),
135
+ cloudLink: links.edge === true,
136
+ witnessLink: links.witness === true,
137
+ feedFresh: accountReader.feedFresh === true,
138
+ checkpointAt: number(status.checkpointAt),
139
+ overpassVersion: label(status.overpassVersion),
140
+ areaVersion: label(status.areaVersion),
141
+ storageReady: status.storageReady === true,
142
+ host,
143
+ fleet,
144
+ public: {
145
+ state: label(publicStatus?.status),
146
+ verifiedOverpass: freshPublic ? label(publicApi.overpass) : "Unknown",
147
+ checkedAt: observed || null,
148
+ },
149
+ engines: fleetEngines.map(name => {
150
+ const load = object(engineLoad[name]);
151
+ return { name, state: label(localServices[name]), active: number(load.inflight), slots: number(load.slots),
152
+ queued: number(load.queued), latencyMs: number(load.latencyMs) };
153
+ }),
154
+ services: Object.entries(localServices).slice(0, 40).map(([name, state]) => ({ name: label(name), state: label(state) })),
155
+ };
156
+ }
157
+
158
+ export type Telemetry = Awaited<ReturnType<typeof readTelemetry>>;