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
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();
|
package/src/interface.ts
ADDED
|
@@ -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;
|
package/src/telemetry.ts
ADDED
|
@@ -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>>;
|