architecture-harness 0.27.0 → 0.28.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/package.json +3 -2
- package/src/cli/cli.test.mjs +8 -0
- package/src/cli/fleet-assign.mjs +12 -0
- package/src/cli/fleet-assign.test.mjs +24 -1
- package/src/cli/fleet-discover.mjs +137 -0
- package/src/cli/fleet-discover.test.mjs +213 -0
- package/src/cli/fleet-github.mjs +6 -0
- package/src/cli/fleet-github.test.mjs +17 -0
- package/src/cli/fleet-load.mjs +18 -0
- package/src/cli/fleet-load.test.mjs +13 -0
- package/src/cli/fleet-node.mjs +52 -10
- package/src/cli/fleet-node.test.mjs +113 -11
- package/src/cli/fleet.mjs +27 -12
- package/src/cli/fleet.test.mjs +78 -12
- package/src/cli/statusline.test.mjs +155 -0
- package/user-config/claude/statusline.js +47 -8
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "architecture-harness",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.28.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Architecture gates, lint rules and scaffolding for the bounded-vertical-slice architecture",
|
|
6
6
|
"license": "MIT",
|
|
@@ -32,7 +32,8 @@
|
|
|
32
32
|
"access": "public"
|
|
33
33
|
},
|
|
34
34
|
"bin": {
|
|
35
|
-
"qc": "./src/cli/qc.mjs"
|
|
35
|
+
"qc": "./src/cli/qc.mjs",
|
|
36
|
+
"architecture-harness": "./src/cli/qc.mjs"
|
|
36
37
|
},
|
|
37
38
|
"exports": {
|
|
38
39
|
".": "./src/index.mjs",
|
package/src/cli/cli.test.mjs
CHANGED
|
@@ -11,6 +11,14 @@ import { runInit } from "./init.mjs";
|
|
|
11
11
|
import { installHooks } from "./install-hooks.mjs";
|
|
12
12
|
import { runCheck } from "./check.mjs";
|
|
13
13
|
|
|
14
|
+
test("both package bin names point to the existing CLI file", () => {
|
|
15
|
+
const packageUrl = new URL("../../package.json", import.meta.url);
|
|
16
|
+
const { bin } = JSON.parse(readFileSync(packageUrl, "utf8"));
|
|
17
|
+
assert.equal(bin.qc, "./src/cli/qc.mjs");
|
|
18
|
+
assert.equal(bin["architecture-harness"], bin.qc);
|
|
19
|
+
assert.ok(existsSync(new URL(bin.qc, packageUrl)));
|
|
20
|
+
});
|
|
21
|
+
|
|
14
22
|
function repo() {
|
|
15
23
|
const dir = mkdtempSync(path.join(tmpdir(), "qc-cli-"));
|
|
16
24
|
execFileSync("git", ["init", "-q"], { cwd: dir });
|
package/src/cli/fleet-assign.mjs
CHANGED
|
@@ -1,11 +1,23 @@
|
|
|
1
1
|
import { ownerOf } from "./fleet.mjs";
|
|
2
2
|
|
|
3
|
+
/** Human-readable reasons for withholding new work; unknown metrics never count. */
|
|
4
|
+
export function overloaded(load) {
|
|
5
|
+
const reasons = [];
|
|
6
|
+
if (load?.cpu != null && load.cpu >= 0.9) reasons.push(`cpu ${Math.round(load.cpu * 100)}%`);
|
|
7
|
+
if (load?.mem != null && load.mem >= 0.9) reasons.push(`mem ${Math.round(load.mem * 100)}%`);
|
|
8
|
+
if (load?.rtt != null && load.rtt >= 2000) reasons.push(`rtt ${load.rtt}ms`);
|
|
9
|
+
return reasons;
|
|
10
|
+
}
|
|
11
|
+
|
|
3
12
|
/** Keep open work stable and give each idle, compatible live node one issue. */
|
|
4
13
|
export function assignTick({ fleet, repo, open, free, assignments, peers, kit, now }) {
|
|
5
14
|
const kept = Object.fromEntries(Object.entries(assignments).filter(([, row]) => row.repo !== repo || open.has(row.issue)));
|
|
6
15
|
const messages = [], warnings = [];
|
|
7
16
|
const busy = new Set(Object.values(kept).map(row => row.node));
|
|
8
17
|
const idle = fleet.nodes.filter(node => {
|
|
18
|
+
const reasons = overloaded(peers[node.id]?.load);
|
|
19
|
+
if (reasons.length) warnings.push(`node ${node.id} is overloaded: ${reasons.join(", ")}`);
|
|
20
|
+
if (reasons.length) return false;
|
|
9
21
|
if (node.id === fleet.self) return !busy.has(node.id);
|
|
10
22
|
const peer = peers[node.id];
|
|
11
23
|
if (peer && peer.kit !== kit) warnings.push(`node ${node.id} runs kit ${peer.kit}, leader runs ${kit}`);
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { strict as assert } from "node:assert";
|
|
2
2
|
import { test } from "node:test";
|
|
3
|
-
import { assignTick } from "./fleet-assign.mjs";
|
|
3
|
+
import { assignTick, overloaded } from "./fleet-assign.mjs";
|
|
4
4
|
import { ownerOf } from "./fleet.mjs";
|
|
5
5
|
|
|
6
6
|
const now = 100_000;
|
|
@@ -112,3 +112,26 @@ test("takeover uses ownerOf, excludes stale candidates, and retains size for tak
|
|
|
112
112
|
const first = assignTick({ ...base, open: new Set([1]), free: [row(1, [], "L")] });
|
|
113
113
|
assert.equal(first.assignments["o/r#1"].size, "L");
|
|
114
114
|
});
|
|
115
|
+
|
|
116
|
+
test("overload limits are inclusive and unknown values do not count", () => {
|
|
117
|
+
assert.deepEqual(overloaded(), []);
|
|
118
|
+
assert.deepEqual(overloaded({ cpu: null, mem: null, rtt: null }), []);
|
|
119
|
+
assert.deepEqual(overloaded({ cpu: 0.89, mem: 0.89, rtt: 1999 }), []);
|
|
120
|
+
for (const [field, value, reason] of [["cpu", 0.9, "cpu 90%"], ["mem", 0.9, "mem 90%"], ["rtt", 2000, "rtt 2000ms"]]) {
|
|
121
|
+
assert.deepEqual(overloaded({ [field]: value }), [reason]);
|
|
122
|
+
}
|
|
123
|
+
assert.deepEqual(overloaded({ cpu: 0.95, mem: 0.91, rtt: 2100 }), ["cpu 95%", "mem 91%", "rtt 2100ms"]);
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
test("overloaded peers and Leader get no new work or takeover and keep held work", () => {
|
|
127
|
+
for (const id of ["a", "b"]) for (const load of [{ cpu: 0.95 }, { mem: 0.9 }, { rtt: 2000 }]) {
|
|
128
|
+
const input = { ...base, fleet: { self: "a", nodes: [node(id)] }, peers: { [id]: { time: now, kit: "kit", load } } };
|
|
129
|
+
const fresh = assignTick(input);
|
|
130
|
+
assert.deepEqual(fresh.assignments, {});
|
|
131
|
+
assert.deepEqual(fresh.warnings, [`node ${id} is overloaded: ${overloaded(load).join(", ")}`]);
|
|
132
|
+
const held = { "o/r#1": saved(1, id) };
|
|
133
|
+
assert.deepEqual(assignTick({ ...input, assignments: held }).assignments, held);
|
|
134
|
+
const dead = { "o/r#1": saved(1, "dead") };
|
|
135
|
+
assert.deepEqual(assignTick({ ...input, assignments: dead }).assignments, dead);
|
|
136
|
+
}
|
|
137
|
+
});
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { createSocket as udpSocket } from "node:dgram";
|
|
3
|
+
import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { isIP } from "node:net";
|
|
5
|
+
import os from "node:os";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { canonical } from "./fleet-message.mjs";
|
|
8
|
+
import { stateDir } from "./fleet-state.mjs";
|
|
9
|
+
|
|
10
|
+
const validId = id => typeof id === "string" && /^[a-z0-9-]{1,32}$/.test(id);
|
|
11
|
+
const validPort = port => Number.isInteger(port) && port >= 1024 && port <= 65535;
|
|
12
|
+
const validCapacity = node => Number.isFinite(node.weight) && node.weight > 0 && node.weight <= 100 && ["S", "M", "L"].includes(node.maxSize);
|
|
13
|
+
const localIPv4 = interfaces => Object.values(interfaces()).flat().filter(row =>
|
|
14
|
+
row && !row.internal && row.family === "IPv4" && isIP(row.address) === 4);
|
|
15
|
+
const mac = (fields, secret) => createHmac("sha256", Buffer.from(secret, "utf8")).update(canonical(fields)).digest("hex");
|
|
16
|
+
|
|
17
|
+
const fingerprint = secret => createHash("sha256").update(secret, "utf8").digest("hex").slice(0, 16);
|
|
18
|
+
|
|
19
|
+
/** Discovery state shares the fleet's private git state directory and secret identity. */
|
|
20
|
+
export function readDiscovered(root, secret) {
|
|
21
|
+
try {
|
|
22
|
+
const saved = JSON.parse(readFileSync(path.join(stateDir(root), "discovered.json"), "utf8"));
|
|
23
|
+
return typeof secret === "string" && saved?.fleet === fingerprint(secret) &&
|
|
24
|
+
saved.nodes && typeof saved.nodes === "object" && !Array.isArray(saved.nodes) ? saved.nodes : {};
|
|
25
|
+
}
|
|
26
|
+
catch (error) { if (error.code === "ENOENT") return {}; throw error; }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function saveDiscovered(root, secret, nodes) {
|
|
30
|
+
const discovered = { fleet: fingerprint(secret), nodes };
|
|
31
|
+
const file = path.join(stateDir(root), "discovered.json");
|
|
32
|
+
const temporary = `${file}.${randomBytes(8).toString("hex")}.tmp`;
|
|
33
|
+
mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
34
|
+
try {
|
|
35
|
+
writeFileSync(temporary, `${JSON.stringify(discovered, null, 2)}\n`, { flag: "wx", mode: 0o600 });
|
|
36
|
+
renameSync(temporary, file);
|
|
37
|
+
} finally { rmSync(temporary, { force: true, maxRetries: 10, retryDelay: 100 }); }
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** A fresh, signed announcement always fits a single small UDP datagram. */
|
|
41
|
+
export function createBeacon({ fleet, address, clock = Date.now }) {
|
|
42
|
+
const self = fleet.nodes.find(node => node.id === fleet.self);
|
|
43
|
+
if (isIP(address ?? "") !== 4) throw new Error("fleet discovery needs an IPv4 node address");
|
|
44
|
+
const fields = { v: 1, id: fleet.self, port: self.port ?? 8080, addresses: [address], weight: self.weight ?? 1,
|
|
45
|
+
maxSize: self.maxSize ?? "L", time: clock(), nonce: randomBytes(16).toString("hex") };
|
|
46
|
+
return { ...fields, sig: mac(fields, fleet.secret) };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Static files keep their identity; discovery adds only recent, unconfigured peers. */
|
|
50
|
+
export function effectiveFleet(fleet, discovered, now = Date.now(), interfaces = os.networkInterfaces) {
|
|
51
|
+
if (!fleet.discover) return fleet;
|
|
52
|
+
const nodes = fleet.nodes.map(node => node.id === fleet.self && !node.address
|
|
53
|
+
? { ...node, address: localIPv4(interfaces)[0]?.address } : node);
|
|
54
|
+
const named = new Set(nodes.map(node => node.id));
|
|
55
|
+
for (const [id, row] of Object.entries(discovered)) {
|
|
56
|
+
if (named.has(id) || !validId(id) || !row || !Number.isFinite(row.seen) || now - row.seen < 0 || now - row.seen > 300_000) continue;
|
|
57
|
+
if (isIP(row.address) !== 4 || !validPort(row.port) || !validCapacity(row)) continue;
|
|
58
|
+
nodes.push({ id, address: row.address, port: row.port, weight: row.weight, maxSize: row.maxSize, active: true });
|
|
59
|
+
}
|
|
60
|
+
return { ...fleet, nodes, leaders: nodes.map(node => node.id).sort() };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function broadcastAddresses(interfaces, address) {
|
|
64
|
+
const targets = new Set(["255.255.255.255"]);
|
|
65
|
+
for (const row of localIPv4(interfaces).filter(row => row.address === address)) {
|
|
66
|
+
if (isIP(row.netmask) !== 4) continue;
|
|
67
|
+
const mask = row.netmask.split(".").map(Number);
|
|
68
|
+
targets.add(row.address.split(".").map((byte, i) => (Number(byte) | (~mask[i] & 255))).join("."));
|
|
69
|
+
}
|
|
70
|
+
return targets;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Authenticated LAN discovery with injectable transport, interfaces, timer and clock. */
|
|
74
|
+
export async function startDiscovery({ root, fleet, address, clock = Date.now, interfaces = os.networkInterfaces,
|
|
75
|
+
createSocket = udpSocket, timer = setInterval, clearTimer = clearInterval, warn = console.error }) {
|
|
76
|
+
if (!fleet.secret) throw new Error("fleet secret is required for discovery");
|
|
77
|
+
const ipv4 = isIP(address ?? "") === 4;
|
|
78
|
+
const socket = createSocket({ type: "udp4", reuseAddr: true });
|
|
79
|
+
const nonces = new Map();
|
|
80
|
+
let collisionAt, interval, closed = false;
|
|
81
|
+
const port = fleet.discoveryPort ?? 47913;
|
|
82
|
+
const close = () => { if (closed) return; closed = true; if (interval !== undefined) clearTimer(interval); socket.close(); };
|
|
83
|
+
const announce = () => {
|
|
84
|
+
if (closed || !ipv4) return;
|
|
85
|
+
try {
|
|
86
|
+
const beacon = createBeacon({ fleet, address, clock });
|
|
87
|
+
const data = Buffer.from(JSON.stringify(beacon));
|
|
88
|
+
for (const address of broadcastAddresses(interfaces, beacon.addresses[0])) socket.send(data, port, address, error => {
|
|
89
|
+
if (error) warn(`fleet discovery: ${error.message}`);
|
|
90
|
+
});
|
|
91
|
+
} catch (error) { warn(`fleet discovery: ${error.message}`); }
|
|
92
|
+
};
|
|
93
|
+
socket.on("message", (data, sender) => {
|
|
94
|
+
if (closed || data.length >= 1024) return;
|
|
95
|
+
try {
|
|
96
|
+
const { sig, ...fields } = JSON.parse(data.toString("utf8"));
|
|
97
|
+
if (typeof sig !== "string" || !/^[0-9a-f]{64}$/i.test(sig) ||
|
|
98
|
+
!timingSafeEqual(Buffer.from(sig, "hex"), Buffer.from(mac(fields, fleet.secret), "hex"))) return;
|
|
99
|
+
const now = clock();
|
|
100
|
+
if (fields.v !== 1 || !validId(fields.id) || !validPort(fields.port) || !validCapacity(fields) ||
|
|
101
|
+
!Number.isFinite(fields.time) || Math.abs(now - fields.time) > 60_000 ||
|
|
102
|
+
typeof fields.nonce !== "string" || !fields.nonce || fields.nonce.length > 128 ||
|
|
103
|
+
!Array.isArray(fields.addresses) || fields.addresses.length !== 1 || !fields.addresses.every(address => isIP(address) === 4) ||
|
|
104
|
+
!fields.addresses.includes(sender.address)) return;
|
|
105
|
+
for (const [nonce, seen] of nonces) if (now - seen > 120_000) nonces.delete(nonce);
|
|
106
|
+
if (nonces.has(fields.nonce)) return;
|
|
107
|
+
nonces.set(fields.nonce, now);
|
|
108
|
+
if (fields.id === fleet.self) {
|
|
109
|
+
if (!localIPv4(interfaces).some(row => row.address === sender.address) &&
|
|
110
|
+
(collisionAt === undefined || now - collisionAt >= 600_000)) {
|
|
111
|
+
collisionAt = now;
|
|
112
|
+
warn(`fleet name ${fleet.self} is used by ${sender.address}`);
|
|
113
|
+
}
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
const discovered = readDiscovered(root, fleet.secret);
|
|
117
|
+
Object.defineProperty(discovered, fields.id, { enumerable: true, configurable: true, writable: true,
|
|
118
|
+
value: { address: sender.address, port: fields.port, weight: fields.weight, maxSize: fields.maxSize, seen: now } });
|
|
119
|
+
saveDiscovered(root, fleet.secret, discovered);
|
|
120
|
+
} catch (error) {
|
|
121
|
+
// Malformed datagrams are ignored; disk failures remain visible to the operator.
|
|
122
|
+
if (error.code) warn(`fleet discovery: ${error.message}`);
|
|
123
|
+
}
|
|
124
|
+
});
|
|
125
|
+
try {
|
|
126
|
+
await new Promise((resolve, reject) => {
|
|
127
|
+
socket.once("error", reject);
|
|
128
|
+
socket.bind(port, "0.0.0.0", () => { socket.off("error", reject); resolve(); });
|
|
129
|
+
});
|
|
130
|
+
socket.on("error", error => warn(`fleet discovery: ${error.message}`));
|
|
131
|
+
socket.setBroadcast(true);
|
|
132
|
+
if (!ipv4) warn("fleet discovery needs an IPv4 node address");
|
|
133
|
+
announce();
|
|
134
|
+
interval = timer(announce, 15_000);
|
|
135
|
+
return { close };
|
|
136
|
+
} catch (error) { close(); throw error; }
|
|
137
|
+
}
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import { strict as assert } from "node:assert";
|
|
2
|
+
import { createHash, createHmac } from "node:crypto";
|
|
3
|
+
import { EventEmitter } from "node:events";
|
|
4
|
+
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
5
|
+
import os from "node:os";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { test } from "node:test";
|
|
8
|
+
import { canonical } from "./fleet-message.mjs";
|
|
9
|
+
import { stateDir } from "./fleet-state.mjs";
|
|
10
|
+
import { createBeacon, effectiveFleet, readDiscovered, startDiscovery } from "./fleet-discover.mjs";
|
|
11
|
+
|
|
12
|
+
const secret = "ab".repeat(32);
|
|
13
|
+
const now = 1_800_000_000_000;
|
|
14
|
+
const interfaces = () => ({ eth0: [{ family: "IPv4", internal: false, address: "192.168.1.10", netmask: "255.255.255.0" }],
|
|
15
|
+
eth1: [{ family: "IPv4", internal: false, address: "10.0.0.2", netmask: "255.255.0.0" }],
|
|
16
|
+
lo: [{ family: "IPv4", internal: true, address: "127.0.0.1", netmask: "255.0.0.0" }],
|
|
17
|
+
v6: [{ family: "IPv6", internal: false, address: "::1" }] });
|
|
18
|
+
const fleet = { self: "a", secret, discover: true, nodes: [{ id: "a", port: 8080, weight: 1, maxSize: "L" }] };
|
|
19
|
+
const fingerprint = key => createHash("sha256").update(key, "utf8").digest("hex").slice(0, 16);
|
|
20
|
+
const sign = (fields, key = secret) => ({ ...fields, sig: createHmac("sha256", Buffer.from(key, "utf8")).update(canonical(fields)).digest("hex") });
|
|
21
|
+
const beacon = (changes = {}, key = secret) => sign({ v: 1, id: "b", port: 8081, addresses: ["192.168.1.20"], weight: 2,
|
|
22
|
+
maxSize: "M", time: now, nonce: "new-nonce", ...changes }, key);
|
|
23
|
+
|
|
24
|
+
export class FakeSocket extends EventEmitter {
|
|
25
|
+
sent = [];
|
|
26
|
+
closed = false;
|
|
27
|
+
bind(port, host, ready) { this.bound = { port, host }; ready(); }
|
|
28
|
+
setBroadcast(value) { this.broadcast = value; }
|
|
29
|
+
send(data, port, address, callback) { this.sent.push({ data, port, address }); callback?.(); }
|
|
30
|
+
close() { this.closed = true; }
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function fixture(t) {
|
|
34
|
+
const root = mkdtempSync(path.join(os.tmpdir(), "qc-discover-"));
|
|
35
|
+
mkdirSync(path.join(root, ".git"));
|
|
36
|
+
t.after(() => rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }));
|
|
37
|
+
return root;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async function listener(t, changes = {}, root = fixture(t), address = changes.nodes?.find(node => node.id === (changes.self ?? fleet.self))?.address ?? "192.168.1.10") {
|
|
41
|
+
const socket = new FakeSocket(), warnings = [], timers = [], cleared = [];
|
|
42
|
+
let time = now;
|
|
43
|
+
const discovery = await startDiscovery({ root, fleet: { ...fleet, ...changes }, address, interfaces, clock: () => time,
|
|
44
|
+
createSocket: options => { assert.deepEqual(options, { type: "udp4", reuseAddr: true }); return socket; },
|
|
45
|
+
timer: (fn, ms) => { const timer = { fn, ms }; timers.push(timer); return timer; }, clearTimer: timer => cleared.push(timer),
|
|
46
|
+
warn: text => warnings.push(text) });
|
|
47
|
+
t.after(() => discovery.close());
|
|
48
|
+
const receive = (message, address = "192.168.1.20") => socket.emit("message", Buffer.from(JSON.stringify(message)), { address });
|
|
49
|
+
return { root, secret: changes.secret ?? secret, socket, warnings, timers, cleared, discovery, receive, setTime: value => { time = value; } };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
test("beacons sign canonical data, advertise only the HTTP bind address and stay below 1 KB", () => {
|
|
53
|
+
const value = createBeacon({ fleet, address: "192.168.1.10", clock: () => now });
|
|
54
|
+
const { sig, ...fields } = value;
|
|
55
|
+
assert.deepEqual(Object.keys(fields).sort(), ["v", "id", "port", "addresses", "weight", "maxSize", "time", "nonce"].sort());
|
|
56
|
+
assert.deepEqual(fields.addresses, ["192.168.1.10"]);
|
|
57
|
+
assert.equal(fields.id, "a");
|
|
58
|
+
assert.equal(fields.port, 8080);
|
|
59
|
+
assert.equal(fields.time, now);
|
|
60
|
+
assert.equal(sig, sign(fields).sig);
|
|
61
|
+
assert.notEqual(value.nonce, createBeacon({ fleet, address: "192.168.1.10", clock: () => now }).nonce);
|
|
62
|
+
assert.ok(Buffer.byteLength(JSON.stringify(value)) < 1024);
|
|
63
|
+
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
test("discovery binds UDP, broadcasts at start and every 15 seconds, and saves a good beacon", async t => {
|
|
67
|
+
const f = await listener(t);
|
|
68
|
+
assert.deepEqual(f.socket.bound, { port: 47913, host: "0.0.0.0" });
|
|
69
|
+
assert.equal(f.socket.broadcast, true);
|
|
70
|
+
assert.deepEqual(f.socket.sent.map(row => row.address), ["255.255.255.255", "192.168.1.255"]);
|
|
71
|
+
assert.ok(f.socket.sent.every(row => row.port === 47913 && row.data.length < 1024));
|
|
72
|
+
assert.equal(f.timers[0].ms, 15_000);
|
|
73
|
+
const first = JSON.parse(f.socket.sent[0].data).nonce;
|
|
74
|
+
f.timers[0].fn();
|
|
75
|
+
assert.equal(f.socket.sent.length, 4);
|
|
76
|
+
assert.notEqual(JSON.parse(f.socket.sent[2].data).nonce, first);
|
|
77
|
+
f.receive(beacon());
|
|
78
|
+
const saved = { b: { address: "192.168.1.20", port: 8081, weight: 2, maxSize: "M", seen: now } };
|
|
79
|
+
assert.deepEqual(readDiscovered(f.root, f.secret), saved);
|
|
80
|
+
assert.deepEqual(JSON.parse(readFileSync(path.join(stateDir(f.root), "discovered.json"), "utf8")), { fleet: fingerprint(secret), nodes: saved });
|
|
81
|
+
f.discovery.close();
|
|
82
|
+
assert.equal(f.socket.closed, true);
|
|
83
|
+
assert.deepEqual(f.cleared, f.timers);
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
test("non-IPv4 bound addresses send no beacon and warn once", async t => {
|
|
87
|
+
for (const address of ["::1", "::ffff:127.0.0.1", "localhost", undefined]) {
|
|
88
|
+
const f = await listener(t, {}, fixture(t), address === undefined ? null : address);
|
|
89
|
+
f.timers[0].fn();
|
|
90
|
+
f.timers[0].fn();
|
|
91
|
+
assert.deepEqual(f.socket.sent, []);
|
|
92
|
+
assert.deepEqual(f.warnings, ["fleet discovery needs an IPv4 node address"]);
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
test("an explicit self address advertises and broadcasts only on its interface", async t => {
|
|
97
|
+
const f = await listener(t, { nodes: [{ ...fleet.nodes[0], address: "10.0.0.2" }] });
|
|
98
|
+
assert.deepEqual(f.socket.sent.map(row => row.address), ["255.255.255.255", "10.0.255.255"]);
|
|
99
|
+
for (const row of f.socket.sent) assert.deepEqual(JSON.parse(row.data).addresses, ["10.0.0.2"]);
|
|
100
|
+
const implicit = await listener(t);
|
|
101
|
+
const remote = { ...fleet, self: "b", nodes: [{ ...fleet.nodes[0], id: "b", address: "10.0.0.2" }] };
|
|
102
|
+
const message = createBeacon({ fleet: remote, address: remote.nodes[0].address, clock: () => now });
|
|
103
|
+
implicit.receive(message, "192.168.1.20");
|
|
104
|
+
assert.deepEqual(readDiscovered(implicit.root, implicit.secret), {});
|
|
105
|
+
implicit.receive(message, "10.0.0.2");
|
|
106
|
+
assert.equal(readDiscovered(implicit.root, implicit.secret).b.address, "10.0.0.2");
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
test("secrets differing only in their final odd character refuse each other's beacons", async t => {
|
|
110
|
+
const secrets = [`${secret}c`, `${secret}d`];
|
|
111
|
+
for (const [own, other] of [secrets, [...secrets].reverse()]) {
|
|
112
|
+
const f = await listener(t, { secret: own });
|
|
113
|
+
const remote = { ...fleet, self: "b", secret: other,
|
|
114
|
+
nodes: [{ id: "b", address: "192.168.1.20", port: 8081, weight: 2, maxSize: "M" }] };
|
|
115
|
+
f.receive(createBeacon({ fleet: remote, address: remote.nodes[0].address, clock: () => now }));
|
|
116
|
+
assert.deepEqual(readDiscovered(f.root, f.secret), {});
|
|
117
|
+
f.receive(createBeacon({ fleet: { ...remote, secret: own }, address: remote.nodes[0].address, clock: () => now }));
|
|
118
|
+
assert.equal(readDiscovered(f.root, f.secret).b.address, "192.168.1.20");
|
|
119
|
+
}
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
test("a secret change ignores the previous fleet and replaces its cache on the next beacon", async t => {
|
|
123
|
+
const first = await listener(t);
|
|
124
|
+
first.receive(beacon());
|
|
125
|
+
assert.ok(readDiscovered(first.root, secret).b);
|
|
126
|
+
first.discovery.close();
|
|
127
|
+
const changed = `${secret}e`;
|
|
128
|
+
const second = await listener(t, { secret: changed }, first.root);
|
|
129
|
+
assert.deepEqual(readDiscovered(second.root, changed), {});
|
|
130
|
+
second.receive(beacon({ id: "c" }, changed));
|
|
131
|
+
const saved = JSON.parse(readFileSync(path.join(stateDir(first.root), "discovered.json"), "utf8"));
|
|
132
|
+
assert.equal(saved.fleet, fingerprint(changed));
|
|
133
|
+
assert.deepEqual(Object.keys(saved.nodes), ["c"]);
|
|
134
|
+
assert.deepEqual(readDiscovered(second.root, secret), {});
|
|
135
|
+
assert.equal(readDiscovered(second.root, changed).c.address, "192.168.1.20");
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
test("legacy unscoped discoveries count as empty and the next save replaces them", async t => {
|
|
139
|
+
const f = await listener(t);
|
|
140
|
+
mkdirSync(stateDir(f.root), { recursive: true });
|
|
141
|
+
const file = path.join(stateDir(f.root), "discovered.json");
|
|
142
|
+
writeFileSync(file, JSON.stringify({ old: { address: "192.168.1.99", port: 8080, weight: 1, maxSize: "L", seen: now } }));
|
|
143
|
+
assert.deepEqual(readDiscovered(f.root, secret), {});
|
|
144
|
+
f.receive(beacon());
|
|
145
|
+
const saved = JSON.parse(readFileSync(file, "utf8"));
|
|
146
|
+
assert.equal(saved.fleet, fingerprint(secret));
|
|
147
|
+
assert.deepEqual(Object.keys(saved.nodes), ["b"]);
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
test("discovery rejects bad MAC, old/future time, address mismatch and malformed signed fields", async t => {
|
|
151
|
+
const f = await listener(t, { discoveryPort: 49000 });
|
|
152
|
+
assert.equal(f.socket.bound.port, 49000);
|
|
153
|
+
const invalid = [
|
|
154
|
+
{ ...beacon(), sig: "00".repeat(32) }, { ...beacon(), sig: "bad" },
|
|
155
|
+
beacon({ time: now - 60_001 }), beacon({ time: now + 60_001 }), beacon({ time: "bad" }),
|
|
156
|
+
beacon({ addresses: ["192.168.1.99"] }), beacon({ addresses: ["192.168.1.20", "10.0.0.2"] }), beacon({ addresses: "192.168.1.20" }),
|
|
157
|
+
...["A", "", "a".repeat(33), "a/b"].map(id => beacon({ id })),
|
|
158
|
+
...[1023, 65536, 8080.5, "8080"].map(port => beacon({ port })),
|
|
159
|
+
...[0, -1, 101, "2"].map(weight => beacon({ weight })),
|
|
160
|
+
beacon({ maxSize: "XL" }), beacon({ v: 2 }), beacon({ nonce: "" }),
|
|
161
|
+
beacon({ extra: "x".repeat(1024) }),
|
|
162
|
+
];
|
|
163
|
+
for (const value of invalid) f.receive(value);
|
|
164
|
+
f.socket.emit("message", Buffer.from("{"), { address: "192.168.1.20" });
|
|
165
|
+
assert.deepEqual(readDiscovered(f.root, f.secret), {});
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
test("a nonce is rejected for 120 seconds and old entries can be received with a fresh nonce", async t => {
|
|
169
|
+
const f = await listener(t);
|
|
170
|
+
f.receive(beacon());
|
|
171
|
+
f.setTime(now + 1000);
|
|
172
|
+
f.receive(beacon());
|
|
173
|
+
assert.equal(readDiscovered(f.root, f.secret).b.seen, now);
|
|
174
|
+
f.receive(beacon({ time: now + 1000, port: 9000 }));
|
|
175
|
+
assert.equal(readDiscovered(f.root, f.secret).b.port, 8081);
|
|
176
|
+
f.setTime(now + 120_001);
|
|
177
|
+
f.receive(beacon({ time: now + 120_001 }));
|
|
178
|
+
assert.equal(readDiscovered(f.root, f.secret).b.seen, now + 120_001);
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
test("name collisions are dropped and reported at most once per ten minutes", async t => {
|
|
182
|
+
const f = await listener(t);
|
|
183
|
+
const remote = { ...fleet, nodes: [{ ...fleet.nodes[0], address: "192.168.1.20" }] };
|
|
184
|
+
f.receive(createBeacon({ fleet: remote, address: remote.nodes[0].address, clock: () => now }));
|
|
185
|
+
f.setTime(now + 60_000);
|
|
186
|
+
f.receive(beacon({ id: "a", nonce: "another", time: now + 60_000 }));
|
|
187
|
+
assert.deepEqual(f.warnings, ["fleet name a is used by 192.168.1.20"]);
|
|
188
|
+
f.setTime(now + 600_000);
|
|
189
|
+
f.receive(beacon({ id: "a", nonce: "third", time: now + 600_000 }));
|
|
190
|
+
assert.equal(f.warnings.length, 2);
|
|
191
|
+
f.receive(beacon({ id: "a", nonce: "local", time: now + 600_000, addresses: ["192.168.1.10"] }), "192.168.1.10");
|
|
192
|
+
assert.equal(f.warnings.length, 2);
|
|
193
|
+
assert.deepEqual(readDiscovered(f.root, f.secret), {});
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
test("effectiveFleet expires discoveries after 300 seconds, keeps configured nodes and sorts leaders", () => {
|
|
197
|
+
const staticFleet = { ...fleet, discover: false };
|
|
198
|
+
assert.equal(effectiveFleet(staticFleet, {}, now, interfaces), staticFleet);
|
|
199
|
+
const configured = { ...fleet, leaders: ["z"], nodes: [...fleet.nodes, { id: "z", address: "fixed", port: 9000 }] };
|
|
200
|
+
const discovered = {
|
|
201
|
+
b: { address: "192.168.1.20", port: 8081, weight: 2, maxSize: "M", seen: now - 299_999 },
|
|
202
|
+
c: { address: "192.168.1.21", port: 8082, weight: 1, maxSize: "S", seen: now - 300_000 },
|
|
203
|
+
old: { address: "192.168.1.22", port: 8083, weight: 1, maxSize: "L", seen: now - 300_001 },
|
|
204
|
+
z: { address: "changed", port: 1234, weight: 10, maxSize: "S", seen: now },
|
|
205
|
+
};
|
|
206
|
+
const current = effectiveFleet(configured, discovered, now, interfaces);
|
|
207
|
+
assert.equal(current.nodes[0].address, "192.168.1.10");
|
|
208
|
+
assert.equal(current.nodes[1], configured.nodes[1]);
|
|
209
|
+
assert.deepEqual(current.leaders, ["a", "b", "c", "z"]);
|
|
210
|
+
assert.deepEqual(current.nodes.find(node => node.id === "b"), { id: "b", address: "192.168.1.20", port: 8081, weight: 2, maxSize: "M", active: true });
|
|
211
|
+
assert.deepEqual(effectiveFleet(configured, discovered, now + 300_001, interfaces).leaders, ["a", "z"]);
|
|
212
|
+
assert.equal(configured.nodes[0].address, undefined);
|
|
213
|
+
});
|
package/src/cli/fleet-github.mjs
CHANGED
|
@@ -8,7 +8,12 @@ const assignmentRef = row => row && typeof row.repo === "string" && /^[a-z0-9][a
|
|
|
8
8
|
export const validBranch = value => value === undefined || value === null || (typeof value === "string" && value.length > 0 && !/[\s\x00-\x1f\x7f]/.test(value));
|
|
9
9
|
export const validHead = value => value === undefined || value === null || (typeof value === "string" && /^[0-9a-f]{40}$/i.test(value));
|
|
10
10
|
export const validWork = row => assignmentRef(row) && [null, "plan", "code", "review", "merge"].includes(row.step) && validBranch(row.branch) && validHead(row.head);
|
|
11
|
+
const validLoad = load => load !== null && typeof load === "object" && !Array.isArray(load) &&
|
|
12
|
+
Object.entries({ cpu: 1, mem: 1, rtt: 600_000 }).every(([key, limit]) =>
|
|
13
|
+
load[key] === null || (Number.isFinite(load[key]) && load[key] >= 0 && load[key] <= limit)) &&
|
|
14
|
+
Object.keys(load).every(key => ["cpu", "mem", "rtt"].includes(key));
|
|
11
15
|
const validHeartbeat = body => validTerm(body.term) && typeof body.leader === "boolean" && (body.kit === null || typeof body.kit === "string") &&
|
|
16
|
+
(body.load === undefined || validLoad(body.load)) &&
|
|
12
17
|
(body.work === undefined || (Array.isArray(body.work) && body.work.every(validWork))) &&
|
|
13
18
|
(body.assigned === undefined || (Array.isArray(body.assigned) && body.assigned.every(assignmentRef)));
|
|
14
19
|
|
|
@@ -44,6 +49,7 @@ export function receiveMessage({ root, fleet, message, clock = Date.now }) {
|
|
|
44
49
|
Date.parse(message.time) <= Date.parse(previous?.messageTime))) {
|
|
45
50
|
peers[message.from].time = time;
|
|
46
51
|
} else Object.defineProperty(peers, message.from, { value: { time, messageTime: message.time, kit: message.body.kit, term: message.body.term, leader: accepted,
|
|
52
|
+
...(message.body.load === undefined ? {} : { load: message.body.load }),
|
|
47
53
|
...(message.body.os === undefined ? {} : { os: message.body.os }),
|
|
48
54
|
...(message.body.work === undefined ? {} : { work: message.body.work }),
|
|
49
55
|
...(message.body.assigned === undefined ? {} : { assigned: message.body.assigned }) }, enumerable: true, configurable: true, writable: true });
|
|
@@ -241,3 +241,20 @@ test("paginated comments are read and gh errors or invalid responses preserve ea
|
|
|
241
241
|
readGithub({ root, fleet, clock: () => now + 120_000, gh: () => { throw new Error("user read failed"); } });
|
|
242
242
|
assert.deepEqual(readState(root, "github"), saved);
|
|
243
243
|
});
|
|
244
|
+
|
|
245
|
+
test("heartbeat load validation accepts missing and bounded values, refuses bad values, and saves load", t => {
|
|
246
|
+
const root = fixture(t);
|
|
247
|
+
const body = { kit: null, term: 1, leader: false };
|
|
248
|
+
for (const load of [undefined, { cpu: null, mem: null, rtt: null }, { cpu: 0, mem: 1, rtt: 600000 }]) {
|
|
249
|
+
const fields = load === undefined ? body : { ...body, load };
|
|
250
|
+
assert.equal(receiveMessage({ root, fleet, clock: () => now, message: message({ kind: "heartbeat", body: fields }) }).ok, true);
|
|
251
|
+
assert.deepEqual(readState(root, "peers").b.load, load);
|
|
252
|
+
// A later snapshot must be eligible to replace the previous one.
|
|
253
|
+
writeState(root, "peers", {});
|
|
254
|
+
}
|
|
255
|
+
for (const load of [null, [], "bad", {}, { cpu: -0.01, mem: 0, rtt: 0 }, { cpu: 1.01, mem: 0, rtt: 0 },
|
|
256
|
+
{ cpu: 0, mem: 1.01, rtt: 0 }, { cpu: 0, mem: 0, rtt: -1 }, { cpu: 0, mem: 0, rtt: 600001 },
|
|
257
|
+
{ cpu: "0", mem: 0, rtt: 0 }, { cpu: 0, mem: 0, rtt: true }]) {
|
|
258
|
+
assert.deepEqual(receiveMessage({ root, fleet, clock: () => now, message: message({ kind: "heartbeat", body: { ...body, load } }) }), { ok: false, reason: "bad-heartbeat" });
|
|
259
|
+
}
|
|
260
|
+
});
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import os from "node:os";
|
|
2
|
+
|
|
3
|
+
const round = value => Math.round(value * 100) / 100;
|
|
4
|
+
|
|
5
|
+
/** CPU counter deltas work across operating systems, including Windows. */
|
|
6
|
+
export function sampleLoad({ os: host = os, previous } = {}) {
|
|
7
|
+
const sample = host.cpus().map(({ times }) => ({ idle: times.idle,
|
|
8
|
+
total: Object.values(times).reduce((sum, value) => sum + value, 0) }));
|
|
9
|
+
let cpu = null;
|
|
10
|
+
if (previous?.length === sample.length && sample.length) {
|
|
11
|
+
const total = sample.reduce((sum, value, index) => sum + value.total - previous[index].total, 0);
|
|
12
|
+
const idle = sample.reduce((sum, value, index) => sum + value.idle - previous[index].idle, 0);
|
|
13
|
+
if (total > 0 && idle >= 0 && idle <= total && sample.every((value, index) => value.total >= previous[index].total && value.idle >= previous[index].idle)) {
|
|
14
|
+
cpu = round(1 - idle / total);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
return { cpu, mem: round(1 - host.freemem() / host.totalmem()), sample };
|
|
18
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { strict as assert } from "node:assert";
|
|
2
|
+
import { test } from "node:test";
|
|
3
|
+
import { sampleLoad } from "./fleet-load.mjs";
|
|
4
|
+
|
|
5
|
+
const fakeOS = times => ({ cpus: () => times.map(times => ({ times })), freemem: () => 247, totalmem: () => 1000 });
|
|
6
|
+
test("first CPU sample is unknown; memory and CPU deltas round to two decimals", () => {
|
|
7
|
+
const first = sampleLoad({ os: fakeOS([{ user: 20, nice: 0, sys: 10, idle: 70, irq: 0 }, { user: 10, idle: 90 }]) });
|
|
8
|
+
assert.equal(first.cpu, null);
|
|
9
|
+
assert.equal(first.mem, 0.75);
|
|
10
|
+
const second = sampleLoad({ os: fakeOS([{ user: 50, nice: 0, sys: 20, idle: 130, irq: 0 }, { user: 20, idle: 180 }]), previous: first.sample });
|
|
11
|
+
assert.equal(second.cpu, 0.25);
|
|
12
|
+
assert.equal(sampleLoad({ os: fakeOS([{ user: 20, nice: 0, sys: 10, idle: 70, irq: 0 }, { user: 10, idle: 90 }]), previous: first.sample }).cpu, null);
|
|
13
|
+
});
|