import { describe, expect, test } from "bun:test"; import { Hono } from "hono"; import type { HeartbeatPayload } from "@bbbug/shared/protocol"; import { nodeHeartbeatHandler } from "../src/node_heartbeat"; const heartbeat: HeartbeatPayload = { nodeId: "test-android", evalInFlight: 0, evalCapacity: 3, fixInFlight: 0, fixCapacity: 1, ttkbPackages: [{ id: "lemon8/lemon8-knowledge", version: "1", commitId: "abc", description: null, skills: [], }], }; function request(app: Hono) { return app.request("/heartbeat", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(heartbeat), }); } describe("node heartbeat registration contract", () => { test("a pruned node receives 404, with no capability publication or broadcast", async () => { const events: string[] = []; const app = new Hono().post("/heartbeat", nodeHeartbeatHandler({ touchNode: async (payload) => { expect(payload).toEqual(heartbeat); events.push("touch"); return false; }, publishHeartbeat: async () => { events.push("publish"); }, })); const res = await request(app); expect(res.status).toBe(404); expect(res.ok).toBe(false); // Old satellite clients re-register on non-2xx. expect(await res.json()).toEqual({ error: "node_not_registered" }); expect(events).toEqual(["touch"]); }); test("registered nodes refresh before their full heartbeat is published", async () => { const events: string[] = []; const app = new Hono().post("/heartbeat", nodeHeartbeatHandler({ touchNode: async () => { events.push("touch"); return true; }, publishHeartbeat: async (payload) => { expect(payload).toEqual(heartbeat); events.push("publish"); }, })); const res = await request(app); expect(res.status).toBe(200); expect(await res.json()).toEqual({ ok: true }); expect(events).toEqual(["touch", "publish"]); }); test("after re-registration the same heartbeat republishes package availability", async () => { let registered = false; const published: HeartbeatPayload[] = []; const app = new Hono().post("/heartbeat", nodeHeartbeatHandler({ touchNode: async () => registered, publishHeartbeat: async (payload) => { published.push(payload); }, })); expect((await request(app)).status).toBe(404); registered = true; // The register endpoint restores the complete node row. expect((await request(app)).status).toBe(200); expect(published).toEqual([heartbeat]); expect((await request(app)).status).toBe(200); expect(published).toHaveLength(2); }); test("database failures do not acknowledge or publish a heartbeat", async () => { let published = false; const app = new Hono().post("/heartbeat", nodeHeartbeatHandler({ touchNode: async () => { throw new Error("database unavailable"); }, publishHeartbeat: async () => { published = true; }, })); app.onError((_err, c) => c.json({ error: "internal_error" }, 500)); expect((await request(app)).status).toBe(500); expect(published).toBe(false); }); });