Files
patriothacks/api/admin.integration.test.ts
T
OmO Orchestrator d22361a613 feat: persist synced event-log history across server runs (SQLite relay)
The event relay was an in-memory array that started empty on every process, so
synced history vanished on every API-server restart. Persist it to a gitignored
.data/events.sqlite3 via node:sqlite like the blob store (EVENT_DB_PATH override;
seq rowid pull cursor; UNIQUE(authorPubkey,signature) push idempotency), keeping
the exact exported API. Synced history now survives restarts and keeps growing,
and a fresh device pulls the whole lived-in history on load; ShellLayout adds a
light 6s poll for live cross-device reflection. Adds a dev:all script, isolates
the two integration tests to a temp EVENT_DB_PATH, documents EVENT_DB_PATH.
2026-11-20 02:30:03 -05:00

162 lines
5.4 KiB
TypeScript

import type { AddressInfo } from "node:net";
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import * as ed from "@noble/ed25519";
import { createApiServer } from "./_lib/devServer.ts";
import { resetEventRelayStore } from "./_lib/eventRelayStore.ts";
import type { RelayAggregateSummary } from "./_lib/relayAggregate.ts";
function hex(bytes: Uint8Array): string {
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
}
function canonical(payload: unknown, lamportTs: number): Uint8Array {
return new TextEncoder().encode(JSON.stringify({ payload, lamportTs }));
}
interface Device {
publicKey: Uint8Array;
secretKey: Uint8Array;
}
async function newDevice(): Promise<Device> {
const { secretKey, publicKey } = await ed.keygenAsync();
return { publicKey, secretKey };
}
async function signEvent(device: Device, payload: unknown, lamportTs: number) {
const signature = await ed.signAsync(canonical(payload, lamportTs), device.secretKey);
return {
payload,
authorPubkey: hex(device.publicKey),
signature: hex(signature),
lamportTs,
};
}
async function pushRaw(baseUrl: string, events: unknown[]): Promise<Response> {
return fetch(`${baseUrl}/api/sync`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ push: events, pullCursor: 0 }),
});
}
describe("admin aggregate endpoint integration (todo 5)", () => {
let server: ReturnType<typeof createApiServer>;
let baseUrl: string;
let storeDir: string;
beforeAll(async () => {
storeDir = await mkdtemp(join(tmpdir(), "commons-admin-test-"));
process.env.EVENT_DB_PATH = join(storeDir, "events.sqlite3");
server = createApiServer();
await new Promise<void>((resolve) => server.listen(0, resolve));
const { port } = server.address() as AddressInfo;
baseUrl = `http://127.0.0.1:${port}`;
});
afterAll(async () => {
await new Promise<void>((resolve) => server.close(() => resolve()));
delete process.env.EVENT_DB_PATH;
await rm(storeDir, { recursive: true, force: true });
});
beforeEach(() => {
resetEventRelayStore();
});
it("reflects a real combined aggregate across two simulated devices relayed through the real /api/sync endpoint", async () => {
const deviceA = await newDevice();
const deviceB = await newDevice();
const eventsFromA = [
await signEvent(deviceA, { type: "seed.population", value: 4200 }, 0),
await signEvent(deviceA, { type: "seed.resource.water", resource: "water", value: 620 }, 1),
await signEvent(
deviceA,
{ type: "fairshare.need", agent: "townA", resource: "water", value: 10 },
2,
),
];
const eventsFromB = [
await signEvent(
deviceB,
{ type: "housing.assignment", residentId: "townB", slotId: "slot-1" },
5,
),
await signEvent(
deviceB,
{ type: "tunnelsafety.hazard.error", message: "sensor offline" },
6,
),
];
const pushA = await pushRaw(baseUrl, eventsFromA);
expect(pushA.status).toBe(200);
const pushB = await pushRaw(baseUrl, eventsFromB);
expect(pushB.status).toBe(200);
const res = await fetch(`${baseUrl}/api/admin/aggregate`);
expect(res.status).toBe(200);
const summary = (await res.json()) as RelayAggregateSummary;
expect(summary.totalEvents).toBe(5);
expect(summary.population).toBe(4200);
expect(summary.resources).toEqual({ water: 620 });
const fairshare = summary.miniapps.find((m) => m.id === "fair-share");
expect(fairshare).toBeDefined();
expect(fairshare!.lastEventType).toBe("fairshare.need");
expect(fairshare!.lastLamportTs).toBe(2);
const housing = summary.miniapps.find((m) => m.id === "housing");
expect(housing).toBeDefined();
expect(housing!.lastLamportTs).toBe(5);
expect(summary.errorEvents).toHaveLength(1);
expect(summary.errorEvents[0]).toMatchObject({
type: "tunnelsafety.hazard.error",
lamportTs: 6,
detail: "sensor offline",
});
});
it("stays live, not cached: a request after new events land reflects them, a request before does not", async () => {
const before = await fetch(`${baseUrl}/api/admin/aggregate`);
const beforeSummary = (await before.json()) as RelayAggregateSummary;
expect(beforeSummary.totalEvents).toBe(0);
const device = await newDevice();
await pushRaw(baseUrl, [
await signEvent(device, { type: "seed.population", value: 99 }, 0),
]);
const after = await fetch(`${baseUrl}/api/admin/aggregate`);
const afterSummary = (await after.json()) as RelayAggregateSummary;
expect(afterSummary.totalEvents).toBe(1);
expect(afterSummary.population).toBe(99);
});
it("honest empty state: zero relayed events renders zero counts, no fabricated figures", async () => {
const res = await fetch(`${baseUrl}/api/admin/aggregate`);
expect(res.status).toBe(200);
const summary = (await res.json()) as RelayAggregateSummary;
expect(summary).toEqual({
totalEvents: 0,
population: null,
resources: {},
miniapps: [],
errorEvents: [],
});
});
it("rejects a non-GET method with 405 rather than performing any mutation", async () => {
const res = await fetch(`${baseUrl}/api/admin/aggregate`, { method: "POST" });
expect(res.status).toBe(405);
});
});