import type { WireEventEntry } from "./eventRelayStore.ts"; /** * Pure aggregation over whatever events have reached the signed-event relay * (backend-expansion todo 5). This module never touches the relay store * itself, never writes/mutates anything, and never fabricates a number: a * field is only ever derived from an actual relayed `WireEventEntry`, and an * empty relay produces an honest empty summary (see `buildRelayAggregate`'s * `totalEvents === 0` case), never a placeholder figure. */ /** Which mini-app (by `miniappRegistry` id) a relayed event's payload `type` * belongs to, derived from the type's first dot-segment - the same prefix * convention every mini-app's event payloads already use (e.g. * `fairshare.need`, `housing.assignment`). `wallet` is not a * `miniappRegistry` tile (it is the shell's wallet/transfer surface, see * plan todo 3), but is tracked the same way since it is one of the relay's * genuine event sources. Admin/demo/test noise (`seed.*`, `local.*`, * `test.*`, `hollow.*`, `testimony.*`, `something.else`) is intentionally * unmapped - it is not mini-app activity. */ const MINIAPP_PREFIXES: ReadonlyArray<{ prefix: string; id: string; label: string }> = [ { prefix: "fairshare", id: "fair-share", label: "Fair Share" }, { prefix: "waterwatch", id: "water-watch", label: "Water Watch" }, { prefix: "tunnelsafety", id: "tunnel-safety", label: "Tunnel Safety" }, { prefix: "housing", id: "housing", label: "Housing" }, { prefix: "healthpost", id: "health-post", label: "Health Post" }, { prefix: "fairdraw", id: "fair-draw", label: "Fair Draw" }, { prefix: "mentor", id: "mentor", label: "Mentor" }, { prefix: "sky", id: "sky", label: "Sky" }, { prefix: "wallet", id: "wallet", label: "Wallet" }, ]; export interface MiniappActivitySummary { id: string; label: string; /** The payload `type` of that mini-app's most recent relayed event. */ lastEventType: string; /** The `lamportTs` of that most recent relayed event. */ lastLamportTs: number; } /** * A relayed event considered "tagged as an error": its payload `type` ends * in `.error`, or it carries an explicit `error: true` / `severity: "error"` * / `level: "error"` field. No mini-app in this repo currently emits such an * event (confirmed by inspection), so an honest relay will report zero of * these until one actually does - never a fabricated example. */ export interface ErrorTaggedEvent { type: string; lamportTs: number; detail?: string; } export interface RelayAggregateSummary { /** Total relayed events this summary was computed from. 0 means the relay * has nothing yet - the only honest "no data" signal; every other field * below is only ever populated from an entry actually present here. */ totalEvents: number; /** The latest `seed.population` value relayed, or `null` if none has been. */ population: number | null; /** The latest `seed.resource.` value per resource name relayed so far. */ resources: Record; miniapps: MiniappActivitySummary[]; errorEvents: ErrorTaggedEvent[]; } function payloadRecord(payload: unknown): Record | null { return typeof payload === "object" && payload !== null ? (payload as Record) : null; } function isErrorTagged(payload: Record, type: string): boolean { if (type.toLowerCase().endsWith(".error")) return true; if (payload.error === true) return true; if (typeof payload.severity === "string" && payload.severity.toLowerCase() === "error") { return true; } if (typeof payload.level === "string" && payload.level.toLowerCase() === "error") return true; return false; } function errorDetail(payload: Record): string | undefined { const message = payload.message ?? payload.detail ?? payload.reason; return typeof message === "string" ? message : undefined; } /** * Build the read-only aggregate summary from the relay's current entries * (caller passes `pullEvents(0).entries` - the live, uncached snapshot). * "Latest" seed.population/seed.resource.* values are the last one seen in * relay arrival order; per-mini-app last activity picks whichever relayed * event for that mini-app has the greatest `lamportTs`. */ export function buildRelayAggregate(entries: readonly WireEventEntry[]): RelayAggregateSummary { let population: number | null = null; const resources: Record = {}; const miniappActivity = new Map(); const errorEvents: ErrorTaggedEvent[] = []; for (const entry of entries) { const payload = payloadRecord(entry.payload); if (payload === null || typeof payload.type !== "string") continue; const type = payload.type; if (type === "seed.population" && typeof payload.value === "number") { population = payload.value; } else if (type.startsWith("seed.resource.") && typeof payload.value === "number") { resources[type.slice("seed.resource.".length)] = payload.value; } const prefix = type.slice(0, type.indexOf(".") === -1 ? type.length : type.indexOf(".")); const mapped = MINIAPP_PREFIXES.find((m) => m.prefix === prefix.toLowerCase()); if (mapped) { const existing = miniappActivity.get(mapped.id); if (!existing || entry.lamportTs >= existing.lastLamportTs) { miniappActivity.set(mapped.id, { id: mapped.id, label: mapped.label, lastEventType: type, lastLamportTs: entry.lamportTs, }); } } if (isErrorTagged(payload, type)) { errorEvents.push({ type, lamportTs: entry.lamportTs, detail: errorDetail(payload) }); } } return { totalEvents: entries.length, population, resources, miniapps: Array.from(miniappActivity.values()).sort((a, b) => a.label.localeCompare(b.label)), errorEvents, }; }