import { REALTIME_EVENT_NAMES, assertNotificationEventInAppScope, normalizeNotificationStreamScope, redactNotificationGuardDiagnostic, serializeRealtimeComment, serializeRealtimeEvent, } from "@toolctrl/realtime"; import { Hono, type Context } from "hono"; import { getApiAppDependencies } from "../app-dependencies.js"; import type { ApiEnv } from "../api-types.js"; import { authenticateServiceRequest } from "../auth.js"; import { getApiRuntimeConfig } from "../config.js"; import { apiError } from "../middleware/error-envelope.js"; import { handleWorkspaceContextRevalidationError } from "./shared.js"; export function registerNotificationRoutes(app: Hono) { app.get("/v1/notifications/stream", getNotificationStreamRequest); } async function getNotificationStreamRequest(c: Context) { const principal = authenticateServiceRequest(c.req.raw, getApiRuntimeConfig()); if (!principal) { return apiError(c, 401, "unauthorized", "A valid bearer token is required."); } const requestId: string = c.get("requestId"); const scopeResult: | { ok: true; scope: ReturnType } | { ok: false; error: string } = (() => { try { return { ok: true, scope: normalizeNotificationStreamScope({ tenantId: c.req.header("x-toolctrl-tenant-id") ?? c.req.query("tenantId"), userId: c.req.header("x-toolctrl-user-id") ?? c.req.query("userId"), afterCursor: c.req.header("last-event-id") ?? c.req.query("afterCursor"), }), }; } catch (error) { return { ok: false, error: redactNotificationGuardDiagnostic(error) }; } })(); if (!scopeResult.ok) { return apiError(c, 400, "invalid_request", scopeResult.error); } const { scope } = scopeResult; const dependencies = getApiAppDependencies(); try { await dependencies.revalidateWorkspaceContext({ tenantId: scope.tenantId, userId: scope.userId }); } catch (error) { return handleWorkspaceContextRevalidationError(c, error); } const afterCursor = scope.afterCursor ?? null; const stream = new ReadableStream({ async start(controller) { const encoder = new TextEncoder(); const write = (chunk: string) => controller.enqueue(encoder.encode(chunk)); const writeRealtimeEvent = (event: Parameters[0]) => { assertNotificationEventInAppScope(event, scope); write(serializeRealtimeEvent(event)); }; try { const snapshot = await dependencies.getNotificationStreamSnapshot({ tenantId: scope.tenantId, userId: scope.userId, afterCursor }); const cursor = snapshot.cursor ?? afterCursor ?? "initial"; writeRealtimeEvent({ event: REALTIME_EVENT_NAMES.notificationSnapshot, requestId, tenantId: scope.tenantId, userId: scope.userId, cursor, items: snapshot.items, }); write(serializeRealtimeComment(`keepalive ${JSON.stringify({ requestId, cursor })}`)); writeRealtimeEvent({ event: REALTIME_EVENT_NAMES.keepalive, requestId, tenantId: scope.tenantId, userId: scope.userId, cursor }); } catch { const cursor = afterCursor ?? "error"; write( serializeRealtimeEvent({ event: REALTIME_EVENT_NAMES.error, requestId, tenantId: scope.tenantId, userId: scope.userId, cursor, code: "notification_stream_failed", message: "Notification stream snapshot failed.", }) ); } finally { controller.close(); } }, }); return new Response(stream, { status: 200, headers: { "content-type": "text/event-stream; charset=utf-8", "cache-control": "no-cache", connection: "keep-alive", "x-request-id": requestId, "x-content-type-options": "nosniff", "referrer-policy": "no-referrer", "x-frame-options": "DENY", "permissions-policy": "camera=(), microphone=(), geolocation=(), payment=()", "cross-origin-opener-policy": "same-origin", "cross-origin-resource-policy": "same-origin", }, }); }