OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
ralph(M6-007): realtime module into core + wave checkpoint
ralph4242e89a5b3f
diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 99e9f7ea4..4c5b00df5 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -490,6 +490,24 @@ export {scheduleProjectDeletion,updateProjectForOrganization,} from './modules/project/project.service';+// The six ClickHouse queries moved from packages/trpc/src/routers/realtime.ts+// (M6-007) — packages/trpc's realtime router calls these directly, the same+// way V1 reaches every other dissolved service here. The `/live` websocket+// glue in the same file stays internal to core/realtime.routes.ts; V1's own+// Fastify `/live` controller is untouched (see realtime.service.ts's header)+// so nothing else needs it from this barrel.+export type {+ RealtimeBadgeDetailScope,+ RealtimeLocation,+} from './modules/realtime/realtime.service';+export {+ getRealtimeActiveSessions,+ getRealtimeCoordinates,+ getRealtimeGeo,+ getRealtimeMapBadgeDetails,+ getRealtimePaths,+ getRealtimeReferrals,+} from './modules/realtime/realtime.service';// Moved from packages/db/src/services/reference.service.ts, plus the// query/mutation bodies packages/trpc/src/routers/reference.ts held inline// (M6-004) — packages/trpc's reference router calls these directly, the samediff --git a/packages/core/src/modules/realtime/realtime.routes.test.ts b/packages/core/src/modules/realtime/realtime.routes.test.tsnew file mode 100644index 000000000..b33d5cbf5--- /dev/null+++ b/packages/core/src/modules/realtime/realtime.routes.test.ts@@ -0,0 +1,319 @@+// The runnable ws proof this task's notes require: `app.handle()` cannot+// exercise a websocket upgrade (no real HTTP connection to upgrade), so this+// boots the actual Elysia app with `.listen()` (== `Bun.serve` under the+// hood, same as main.ts) on an ephemeral port and drives it with a real+// `WebSocket` client — the same shape `apps/api/e2e/boot-proof.sh` uses for+// the plain-HTTP ops surface, extended to a ws handshake.+//+// The harness buffers messages/close events from the moment the socket is+// constructed: the server can send its "No active session" / "No access"+// frame and close the connection before the test ever gets to `await` a+// listener, and a listener attached after the fact misses an event that+// already fired.+//+// `./realtime.service` and `./src/access` are mocked (not a real Postgres/+// ClickHouse/Redis), and `../../http/session` for the same reason+// http/auth.test.ts mocks it: `resolveSession` is still a P6 stub. Every+// mock is registered before the subject's first (dynamic, per-connection)+// call — see AGENTS.md's `mock.module` idiom.++import {+ afterAll,+ afterEach,+ beforeAll,+ beforeEach,+ expect,+ mock,+ test,+} from 'bun:test';+import { stubAppDeps } from '../../../test/http-fixtures';+import { getSuperJson } from '../../shared/json';++let visitorActivityCallback: (() => void) | undefined;+const unsubscribeVisitorActivity = mock(() => undefined);+const subscribeToVisitorActivity = mock(+ async (_projectId: string, onActivity: () => void) => {+ visitorActivityCallback = onActivity;+ return unsubscribeVisitorActivity;+ }+);++let eventBatchCallback: ((event: { count: number }) => void) | undefined;+const unsubscribeEventBatches = mock(() => undefined);+const subscribeToProjectEventBatches = mock(+ async (_projectId: string, onBatch: (event: { count: number }) => void) => {+ eventBatchCallback = onBatch;+ return unsubscribeEventBatches;+ }+);++const subscribeToProjectNotifications = mock(async () => () => undefined);+const subscribeToOrganizationSubscriptionUpdates = mock(+ async () => () => undefined+);++let activeVisitorCount = 0;+const getActiveVisitorCount = mock(async () => activeVisitorCount);++// Spread the real module rather than hand-listing every export:+// `mock.module` replaces this specifier process-wide (bun shares one module+// registry across files without `--isolate` — see AGENTS.md), and+// realtime.service.test.ts's own `beforeAll` does `await+// import('./realtime.service')` expecting the real implementation. A plain+// snapshot, not the live import binding — see gsc.service.test.ts's+// clickhouse/client mock for why the live binding would make a+// same-binding "restore" a no-op.+const actualService = await import('./realtime.service');+const realService = { ...actualService };+mock.module('./realtime.service', () => ({+ ...realService,+ getActiveVisitorCount,+ subscribeToVisitorActivity,+ subscribeToProjectEventBatches,+ subscribeToProjectNotifications,+ subscribeToOrganizationSubscriptionUpdates,+}));++afterAll(() => {+ mock.module('./realtime.service', () => realService);+});++let projectAccess: { level: string } | null = null;+let organizationAccess: { role: string } | null = null;+const getProjectAccess = mock(async () => projectAccess);+const getOrganizationAccess = mock(async () => organizationAccess);+mock.module('./src/access', () => ({+ getProjectAccess,+ getOrganizationAccess,+}));++let session: { userId: string } | null = null;+const resolveSession = mock(() => Promise.resolve(session));+mock.module('../../http/session', () => ({+ SESSION_COOKIE_NAME: 'session',+ resolveSession,+}));++let realtimeRoutes: typeof import('./realtime.routes').realtimeRoutes;+beforeAll(async () => {+ ({ realtimeRoutes } = await import('./realtime.routes'));+});++let app: ReturnType<typeof realtimeRoutes>;+let port: number;++beforeEach(async () => {+ const { deps } = stubAppDeps();+ app = realtimeRoutes(deps);+ await new Promise<void>((resolve) => {+ app.listen(0, () => resolve());+ });+ port = app.server?.port ?? 0;++ session = null;+ projectAccess = null;+ organizationAccess = null;+ activeVisitorCount = 0;+ visitorActivityCallback = undefined;+ eventBatchCallback = undefined;+ for (const m of [+ subscribeToVisitorActivity,+ subscribeToProjectEventBatches,+ subscribeToProjectNotifications,+ subscribeToOrganizationSubscriptionUpdates,+ unsubscribeVisitorActivity,+ unsubscribeEventBatches,+ getProjectAccess,+ getOrganizationAccess,+ getActiveVisitorCount,+ ]) {+ m.mockClear();+ }+});++afterEach(async () => {+ await app.stop(true);+});++interface CloseInfo {+ code: number;+ reason: string;+}++interface WsHarness {+ ws: WebSocket;+ nextMessage(): Promise<string>;+ nextClose(): Promise<CloseInfo>;+}++/**+ * Buffers messages/close events from construction, not from whenever the+ * test happens to `await` for one — the server can send its reject frame+ * and close the socket before the test's next line runs.+ */+function connect(path: string): Promise<WsHarness> {+ return new Promise((resolve, reject) => {+ const ws = new WebSocket(`ws://127.0.0.1:${port}${path}`);+ const messageQueue: string[] = [];+ const pendingMessage: ((value: string) => void)[] = [];+ let closeInfo: CloseInfo | undefined;+ const pendingClose: ((value: CloseInfo) => void)[] = [];++ ws.addEventListener('message', (event) => {+ const data = String(event.data);+ const next = pendingMessage.shift();+ if (next) {+ next(data);+ } else {+ messageQueue.push(data);+ }+ });++ ws.addEventListener('close', (event) => {+ closeInfo = { code: event.code, reason: event.reason };+ for (const next of pendingClose.splice(0)) {+ next(closeInfo);+ }+ });++ ws.addEventListener(+ 'open',+ () => {+ resolve({+ ws,+ nextMessage: () =>+ messageQueue.length > 0+ ? Promise.resolve(messageQueue.shift() as string)+ : new Promise((res) => pendingMessage.push(res)),+ nextClose: () =>+ closeInfo+ ? Promise.resolve(closeInfo)+ : new Promise((res) => pendingClose.push(res)),+ });+ },+ { once: true }+ );+ ws.addEventListener('error', () => reject(new Error('ws error')), {+ once: true,+ });+ });+}++test('wsVisitors: no session required (ADR-011 invariant 10) — upgrades and streams the active count', async () => {+ const { ws, nextMessage } = await connect('/live/visitors/proj_1');+ activeVisitorCount = 5;++ // The subscription is registered async (behind `await subscribeTo...`);+ // give the open handler's microtask a turn before firing the callback.+ while (!visitorActivityCallback) {+ await new Promise((resolve) => setTimeout(resolve, 1));+ }+ visitorActivityCallback();++ await expect(nextMessage()).resolves.toBe('5');+ expect(subscribeToVisitorActivity).toHaveBeenCalledWith(+ 'proj_1',+ expect.any(Function)+ );++ ws.close();+});++test('wsProjectEvents: no session -> "No active session" then close (reject-after-upgrade)', async () => {+ const { nextMessage, nextClose } = await connect('/live/events/proj_1');++ await expect(nextMessage()).resolves.toBe('No active session');+ await nextClose();+ expect(subscribeToProjectEventBatches).not.toHaveBeenCalled();+});++test('wsProjectEvents: session but no project access -> "No access" then close', async () => {+ session = { userId: 'user_1' };+ projectAccess = null;++ const { nextMessage, nextClose } = await connect('/live/events/proj_1');++ await expect(nextMessage()).resolves.toBe('No access');+ await nextClose();+ expect(getProjectAccess).toHaveBeenCalledWith({+ userId: 'user_1',+ projectId: 'proj_1',+ });+ expect(subscribeToProjectEventBatches).not.toHaveBeenCalled();+});++test('wsProjectEvents: authorized caller receives superjson-encoded batch counts', async () => {+ session = { userId: 'user_1' };+ projectAccess = { level: 'read' };++ const { ws, nextMessage } = await connect('/live/events/proj_1');++ while (!eventBatchCallback) {+ await new Promise((resolve) => setTimeout(resolve, 1));+ }+ eventBatchCallback({ count: 9 });++ const raw = await nextMessage();+ expect(getSuperJson<{ count: number }>(raw)).toEqual({ count: 9 });++ ws.close();+});++test('wsProjectEvents: close unsubscribes the redis subscription', async () => {+ session = { userId: 'user_1' };+ projectAccess = { level: 'read' };++ const { ws, nextClose } = await connect('/live/events/proj_1');+ while (!eventBatchCallback) {+ await new Promise((resolve) => setTimeout(resolve, 1));+ }++ ws.close();+ await nextClose();++ // The server's `close(ws)` handler (which unsubscribes) runs on receipt of+ // the client's close frame — causally before the client's own 'close'+ // fires, but not guaranteed synchronous with it; poll briefly rather than+ // assume same-tick ordering across a real socket round-trip.+ for (+ let i = 0;+ i < 50 && unsubscribeEventBatches.mock.calls.length === 0;+ i+++ ) {+ await new Promise((resolve) => setTimeout(resolve, 10));+ }++ expect(unsubscribeEventBatches).toHaveBeenCalledTimes(1);+});++test('wsOrganizationEvents: no session -> "No active session" then close', async () => {+ const { nextMessage, nextClose } = await connect('/live/organization/org_1');++ await expect(nextMessage()).resolves.toBe('No active session');+ await nextClose();+ expect(subscribeToOrganizationSubscriptionUpdates).not.toHaveBeenCalled();+});++test('wsOrganizationEvents: session but no org access -> "No access" then close', async () => {+ session = { userId: 'user_1' };+ organizationAccess = null;++ const { nextMessage, nextClose } = await connect('/live/organization/org_1');++ await expect(nextMessage()).resolves.toBe('No access');+ await nextClose();+ expect(getOrganizationAccess).toHaveBeenCalledWith({+ userId: 'user_1',+ organizationId: 'org_1',+ });+});++test('wsProjectNotifications: no session -> "No active session" then close', async () => {+ const { nextMessage, nextClose } = await connect(+ '/live/notifications/proj_1'+ );++ await expect(nextMessage()).resolves.toBe('No active session');+ await nextClose();+ expect(subscribeToProjectNotifications).not.toHaveBeenCalled();+});diff --git a/packages/core/src/modules/realtime/realtime.routes.ts b/packages/core/src/modules/realtime/realtime.routes.tsnew file mode 100644index 000000000..ab6fff376--- /dev/null+++ b/packages/core/src/modules/realtime/realtime.routes.ts@@ -0,0 +1,195 @@+// The `/live` websocket surface (M6-007), Elysia/Bun-native. Ported FRESH+// from apps/api/src/controllers/live.controller.ts's business logic, NOT+// delegated: V1's Fastify controller uses `@fastify/websocket`'s `WebSocket`+// (the `ws` package, Node EventEmitter semantics), which shares nothing with+// Elysia's `ElysiaWS`/Bun's native `ServerWebSocket` — there is no shim to+// delegate through, and touching the golden-harness-critical V1 ws stack for+// a few lines of framework glue is the risk this port avoids (task notes).+// V1's controller and router are LEFT UNTOUCHED. The shared logic —+// `getActiveVisitorCount`, the four `subscribeToPublishedEvent` calls — moved+// to realtime.service.ts's "/live websocket glue" section; both stacks call+// the exact same Redis subscription underneath.+//+// http/auth.ts's invariant 10 (binding, ADR-011): `/live/visitors/:projectId`+// stays unauthenticated; the other three keep session + access; all four+// keep REJECT-AFTER-UPGRADE — the socket accepts the upgrade, then the open+// handler sends a text frame and closes it, exactly like V1. This is why+// none of these routes requests the `session` macro: that macro would 401+// the HTTP upgrade request itself, which is a different (V1-divergent)+// behaviour.+//+// NAMED GAP, same as every other H module this wave: not yet reachable.+// main.ts does not mount `dashboardRoutes` until a real `AppDeps` exists+// (P3/P4/P8), and `http/session.ts`'s `resolveSession` is still a P6 stub+// that always resolves `null` — so today, the three session-gated routes+// close every connection immediately after upgrade. That is the same gap+// http/auth.test.ts already documents for every other session-macro route.++import { z } from 'zod';+import { defineRoutes } from '../../http/define';+import { setSuperJson } from '../../shared/json';+import {+ getActiveVisitorCount,+ subscribeToOrganizationSubscriptionUpdates,+ subscribeToProjectEventBatches,+ subscribeToProjectNotifications,+ subscribeToVisitorActivity,+} from './realtime.service';++// Dynamic, not a static top-level import: `./src/access` reaches+// `@openpanel/db/src/services/project.service`, which re-exports from+// `@openpanel/core`'s own barrel (`index.ts`) — and this file IS part of that+// barrel's eager chain (`rest.routes.ts` -> `dashboardRoutes`). A static+// import here closes the cycle mid-evaluation (a `getProjectAccess` TDZ+// ReferenceError); every other H module's `src/access.ts` reach is already+// dynamic for the same reason (mcp.routes.ts, assistant.routes.ts).+function loadAccessChecks() {+ return import('./src/access');+}++const NO_ACTIVE_SESSION_MESSAGE = 'No active session';+const NO_ACCESS_MESSAGE = 'No access';++const projectParams = z.object({ projectId: z.string() });+const organizationParams = z.object({ organizationId: z.string() });++interface ClosableSocket {+ send(data: string): unknown;+ close(): unknown;+ raw: object;+}++// Per-connection cleanup, keyed by the underlying native socket: `ws.raw` is+// the same reference for open/message/close on one connection, unlike `ws`+// itself (a fresh `ElysiaWS` wrapper per callback invocation).+const unsubscribeBySocket = new WeakMap<object, () => void>();++function rememberUnsubscribe(ws: ClosableSocket, unsubscribe: () => void) {+ unsubscribeBySocket.set(ws.raw, unsubscribe);+}++function forgetUnsubscribe(ws: ClosableSocket) {+ unsubscribeBySocket.get(ws.raw)?.();+ unsubscribeBySocket.delete(ws.raw);+}++function rejectNoSession(ws: ClosableSocket) {+ ws.send(NO_ACTIVE_SESSION_MESSAGE);+ ws.close();+}++function rejectNoAccess(ws: ClosableSocket) {+ ws.send(NO_ACCESS_MESSAGE);+ ws.close();+}++export const realtimeRoutes = defineRoutes((app) =>+ app+ // V1: wsVisitors. Unauthenticated by intent (ADR-011 invariant 10,+ // docs/ANSWERS.md §3).+ .ws('/live/visitors/:projectId', {+ params: projectParams,+ async open(ws) {+ const { projectId } = ws.data.params;+ rememberUnsubscribe(+ ws,+ await subscribeToVisitorActivity(projectId, () => {+ getActiveVisitorCount(projectId).then(+ (count) => ws.send(String(count)),+ () => ws.send('0')+ );+ })+ );+ },+ close(ws) {+ forgetUnsubscribe(ws);+ },+ })+ // V1: wsProjectEvents.+ .ws('/live/events/:projectId', {+ params: projectParams,+ async open(ws) {+ const { projectId } = ws.data.params;+ const userId = (await ws.data.ctx.session())?.userId;+ if (!userId) {+ rejectNoSession(ws);+ return;+ }++ const { getProjectAccess } = await loadAccessChecks();+ const access = await getProjectAccess({ userId, projectId });+ if (!access) {+ rejectNoAccess(ws);+ return;+ }++ rememberUnsubscribe(+ ws,+ await subscribeToProjectEventBatches(projectId, (event) => {+ ws.send(setSuperJson({ count: event.count }));+ })+ );+ },+ close(ws) {+ forgetUnsubscribe(ws);+ },+ })+ // V1: wsProjectNotifications.+ .ws('/live/notifications/:projectId', {+ params: projectParams,+ async open(ws) {+ const { projectId } = ws.data.params;+ const userId = (await ws.data.ctx.session())?.userId;+ if (!userId) {+ rejectNoSession(ws);+ return;+ }++ const { getProjectAccess } = await loadAccessChecks();+ const access = await getProjectAccess({ userId, projectId });+ if (!access) {+ rejectNoAccess(ws);+ return;+ }++ rememberUnsubscribe(+ ws,+ await subscribeToProjectNotifications(projectId, (notification) => {+ ws.send(setSuperJson(notification));+ })+ );+ },+ close(ws) {+ forgetUnsubscribe(ws);+ },+ })+ // V1: wsOrganizationEvents.+ .ws('/live/organization/:organizationId', {+ params: organizationParams,+ async open(ws) {+ const { organizationId } = ws.data.params;+ const userId = (await ws.data.ctx.session())?.userId;+ if (!userId) {+ rejectNoSession(ws);+ return;+ }++ const { getOrganizationAccess } = await loadAccessChecks();+ const access = await getOrganizationAccess({ userId, organizationId });+ if (!access) {+ rejectNoAccess(ws);+ return;+ }++ rememberUnsubscribe(+ ws,+ await subscribeToOrganizationSubscriptionUpdates((message) => {+ ws.send(setSuperJson(message));+ })+ );+ },+ close(ws) {+ forgetUnsubscribe(ws);+ },+ })+);diff --git a/packages/core/src/modules/realtime/realtime.rpc.test.ts b/packages/core/src/modules/realtime/realtime.rpc.test.tsnew file mode 100644index 000000000..e94b4fbae--- /dev/null+++ b/packages/core/src/modules/realtime/realtime.rpc.test.ts@@ -0,0 +1,77 @@+// Only the "is anyone logged in" boundary is exercised here — no database.+// The access-check + query bodies ride on @openpanel/db (lazy-loaded, see+// realtime.service.ts's header); wiring this router end-to-end against a+// real ClickHouse is P6's (protectedProcedure) job, not this one's — see+// realtime.rpc.ts's header. Same shape as cohort.rpc.test.ts.++import { expect, test } from 'bun:test';+import { stubHttpCtx } from '../../../test/rpc-fixtures';+import { makeTrpcContext } from '../../rpc/base';+import type { CookieOptions } from '../../shared/cookie';+import { realtimeRouter } from './realtime.rpc';++const COOKIE_OPTIONS: CookieOptions = {+ domain: '.openpanel.dev',+ secure: true,+ sameSite: 'lax',+ httpOnly: true,+ path: '/',+};++// EMPTY_SESSION's shape (packages/db/src/services/auth-session.service.ts) —+// `TrpcContext.session` is never literally `null`, only its `userId` is.+const EMPTY_SESSION = { session: null, user: null, userId: null };++async function anonCaller() {+ const { ctx } = stubHttpCtx({}, EMPTY_SESSION);+ const trpcCtx = await makeTrpcContext(ctx, new Headers(), {+ cookieOptions: COOKIE_OPTIONS,+ });+ return realtimeRouter.createCaller(trpcCtx);+}++test('coordinates rejects an unauthenticated caller before querying ClickHouse', async () => {+ const caller = await anonCaller();+ await expect(+ caller.coordinates({ projectId: 'proj_1' })+ ).rejects.toMatchObject({ code: 'UNAUTHORIZED' });+});++test('mapBadgeDetails rejects an unauthenticated caller before querying ClickHouse', async () => {+ const caller = await anonCaller();+ await expect(+ caller.mapBadgeDetails({+ projectId: 'proj_1',+ detailScope: 'country',+ locations: [{ country: 'SE' }],+ })+ ).rejects.toMatchObject({ code: 'UNAUTHORIZED' });+});++test('activeSessions rejects an unauthenticated caller before querying ClickHouse', async () => {+ const caller = await anonCaller();+ await expect(+ caller.activeSessions({ projectId: 'proj_1' })+ ).rejects.toMatchObject({ code: 'UNAUTHORIZED' });+});++test('paths rejects an unauthenticated caller before querying ClickHouse', async () => {+ const caller = await anonCaller();+ await expect(caller.paths({ projectId: 'proj_1' })).rejects.toMatchObject({+ code: 'UNAUTHORIZED',+ });+});++test('referrals rejects an unauthenticated caller before querying ClickHouse', async () => {+ const caller = await anonCaller();+ await expect(caller.referrals({ projectId: 'proj_1' })).rejects.toMatchObject(+ { code: 'UNAUTHORIZED' }+ );+});++test('geo rejects an unauthenticated caller before querying ClickHouse', async () => {+ const caller = await anonCaller();+ await expect(caller.geo({ projectId: 'proj_1' })).rejects.toMatchObject({+ code: 'UNAUTHORIZED',+ });+});diff --git a/packages/core/src/modules/realtime/realtime.rpc.ts b/packages/core/src/modules/realtime/realtime.rpc.tsnew file mode 100644index 000000000..d4bef28bd--- /dev/null+++ b/packages/core/src/modules/realtime/realtime.rpc.ts@@ -0,0 +1,123 @@+// Ported from packages/trpc/src/routers/realtime.ts (M6-007).+//+// V1's `protectedProcedure` — the logger/session-scope/rate-limit middleware+// stack — lands in core with auth (rpc/base.ts: "those need the resolved+// Session shape and the access rules, so they land with auth (P6)"). Until+// then this router does its own minimal "is anyone logged in" + explicit+// `requireProjectAccess({ level: 'read' })` check per procedure, exactly like+// V1's `enforceUserIsAuthed` + `enforceAccess` middleware pair does implicitly+// off the `projectId` input. packages/trpc's realtime router now DELEGATES+// its handler bodies onto `./realtime.service`'s query functions (same as+// notification.ts/reference.ts) while keeping V1's own full+// `protectedProcedure` stack — so the queries have one implementation, called+// through two access-check paths until the ONE shared tRPC instance lands+// with auth (P6).+//+// The per-project access ladder itself IS shared: `./src/access.ts` binds+// core's shared/access.ts ladder to @openpanel/db's real lookups, the same+// way packages/trpc/src/access.ts does for V1.++import { z } from 'zod';+import { createTRPCRouter, procedure } from '../../rpc/base';+import { TRPCAccessError } from '../../rpc/errors';+import {+ getRealtimeActiveSessions,+ getRealtimeCoordinates,+ getRealtimeGeo,+ getRealtimeMapBadgeDetails,+ getRealtimePaths,+ getRealtimeReferrals,+} from './realtime.service';++const MAP_BADGE_LOCATIONS_MIN = 1;+const MAP_BADGE_LOCATIONS_MAX = 200;++const realtimeLocationSchema = z.object({+ country: z.string().optional(),+ city: z.string().optional(),+ lat: z.number().optional(),+ long: z.number().optional(),+});++const realtimeBadgeDetailScopeSchema = z.enum([+ 'country',+ 'city',+ 'coordinate',+ 'merged',+]);++function loadAccessChecks() {+ return import('./src/access');+}++function requireLogin(userId: string | null | undefined): string {+ if (!userId) {+ throw new TRPCAccessError('Not authenticated');+ }+ return userId;+}++async function requireReadAccess(userId: string, projectId: string) {+ const { requireProjectAccess } = await loadAccessChecks();+ await requireProjectAccess({ userId, projectId, level: 'read' });+}++export const realtimeRouter = createTRPCRouter({+ coordinates: procedure+ .input(z.object({ projectId: z.string() }))+ .query(async ({ input, ctx }) => {+ const userId = requireLogin(ctx.session.userId);+ await requireReadAccess(userId, input.projectId);++ return getRealtimeCoordinates(input.projectId);+ }),+ mapBadgeDetails: procedure+ .input(+ z.object({+ detailScope: realtimeBadgeDetailScopeSchema,+ projectId: z.string(),+ locations: z+ .array(realtimeLocationSchema)+ .min(MAP_BADGE_LOCATIONS_MIN)+ .max(MAP_BADGE_LOCATIONS_MAX),+ })+ )+ .query(async ({ input, ctx }) => {+ const userId = requireLogin(ctx.session.userId);+ await requireReadAccess(userId, input.projectId);++ return getRealtimeMapBadgeDetails(input);+ }),+ activeSessions: procedure+ .input(z.object({ projectId: z.string() }))+ .query(async ({ input, ctx }) => {+ const userId = requireLogin(ctx.session.userId);+ await requireReadAccess(userId, input.projectId);++ return getRealtimeActiveSessions(input.projectId);+ }),+ paths: procedure+ .input(z.object({ projectId: z.string() }))+ .query(async ({ input, ctx }) => {+ const userId = requireLogin(ctx.session.userId);+ await requireReadAccess(userId, input.projectId);++ return getRealtimePaths(input.projectId);+ }),+ referrals: procedure+ .input(z.object({ projectId: z.string() }))+ .query(async ({ input, ctx }) => {+ const userId = requireLogin(ctx.session.userId);+ await requireReadAccess(userId, input.projectId);++ return getRealtimeReferrals(input.projectId);+ }),+ geo: procedure+ .input(z.object({ projectId: z.string() }))+ .query(async ({ input, ctx }) => {+ const userId = requireLogin(ctx.session.userId);+ await requireReadAccess(userId, input.projectId);++ return getRealtimeGeo(input.projectId);+ }),+});diff --git a/packages/core/src/modules/realtime/realtime.service.test.ts b/packages/core/src/modules/realtime/realtime.service.test.tsnew file mode 100644index 000000000..85353cbb8--- /dev/null+++ b/packages/core/src/modules/realtime/realtime.service.test.ts@@ -0,0 +1,195 @@+// realtime.service.ts's db/ch/redis access is lazy (`await import(...)`+// inside each function — see the file's header), which is exactly what makes+// `mock.module` work here with no import-time side effects to race: every+// mock below is registered before the subject's first call, not before its+// (side-effect-free) import.+//+// Scope: the "/live websocket glue" (new logic this wave adds) plus one+// representative ClickHouse query (`getRealtimeActiveSessions`) proving the+// lazy-load + filter/limit wiring. The other five queries are a verbatim+// port of packages/trpc/src/routers/realtime.ts's SQL — mechanical, not new+// behaviour — and are exercised end-to-end by realtime.rpc.test.ts's+// unauthenticated-boundary tests plus this repo's local ClickHouse run (see+// the task summary for the executed query + row count).++import { afterAll, beforeAll, beforeEach, expect, mock, test } from 'bun:test';++const activeVisitorCountByProject = new Map<string, number>();+const eventBuffer = {+ getActiveVisitorCount: mock(+ async (projectId: string) => activeVisitorCountByProject.get(projectId) ?? 0+ ),+};+// Spread the real module — `event.service.ts` (reached via+// `getRealtimeActiveSessions`'s `transformEvent` load) imports `botBuffer`+// alongside `eventBuffer` from this same specifier; a partial factory here+// would break that unrelated import, same hazard as the clickhouse/client+// mock below. Snapshotted into a plain object BEFORE mocking: the live+// import binding would reflect the mock too once `mock.module` below swaps+// the specifier, making a same-binding "restore" a no-op.+const actualBuffers = await import('@openpanel/db/src/buffers');+const realBuffers = { ...actualBuffers };+mock.module('@openpanel/db/src/buffers', () => ({+ ...realBuffers,+ eventBuffer,+}));++afterAll(() => {+ mock.module('@openpanel/db/src/buffers', () => realBuffers);+});++const subscribeToPublishedEvent = mock(+ (_channel: string, _type: string, _cb: (event: unknown) => void) => {+ return () => {+ unsubscribeCalls++;+ };+ }+);+let unsubscribeCalls = 0;++// Spread the real module — a partial factory here would be a process-wide+// hazard for every other test file mocking `@openpanel/redis` narrowly (see+// realtime.service.ts's `loadRedis` header for why this file exists at all).+const actualRedis = await import('@openpanel/redis');+const realRedis = { ...actualRedis };+mock.module('@openpanel/redis', () => ({+ ...realRedis,+ subscribeToPublishedEvent,+}));++afterAll(() => {+ mock.module('@openpanel/redis', () => realRedis);+});++const chQuery = mock(async (_query: string) => [] as unknown[]);+const actualClickhouseClient = await import(+ '@openpanel/db/src/clickhouse/client'+);+const realClickhouseClient = { ...actualClickhouseClient };+mock.module('@openpanel/db/src/clickhouse/client', () => ({+ ...realClickhouseClient,+ chQuery,+}));++afterAll(() => {+ mock.module(+ '@openpanel/db/src/clickhouse/client',+ () => realClickhouseClient+ );+});++let subject: typeof import('./realtime.service');++beforeAll(async () => {+ subject = await import('./realtime.service');+});++beforeEach(() => {+ activeVisitorCountByProject.clear();+ subscribeToPublishedEvent.mockClear();+ chQuery.mockClear();+ unsubscribeCalls = 0;+});++test('getActiveVisitorCount reads through the event buffer, keyed by project', async () => {+ activeVisitorCountByProject.set('proj_1', 7);++ await expect(subject.getActiveVisitorCount('proj_1')).resolves.toBe(7);+ expect(eventBuffer.getActiveVisitorCount).toHaveBeenCalledWith('proj_1');+});++test('subscribeToVisitorActivity subscribes on events:batch and filters by projectId', async () => {+ const onActivity = mock(() => undefined);+ const unsubscribe = await subject.subscribeToVisitorActivity(+ 'proj_1',+ onActivity+ );++ expect(subscribeToPublishedEvent).toHaveBeenCalledTimes(1);+ const [channel, type, callback] = subscribeToPublishedEvent.mock.calls[0]!;+ expect(channel).toBe('events');+ expect(type).toBe('batch');++ (callback as (event: unknown) => void)({ projectId: 'proj_other', count: 1 });+ expect(onActivity).not.toHaveBeenCalled();++ (callback as (event: unknown) => void)({ projectId: 'proj_1', count: 1 });+ expect(onActivity).toHaveBeenCalledTimes(1);++ unsubscribe();+ expect(unsubscribeCalls).toBe(1);+});++test('subscribeToProjectEventBatches hands the whole batch through, filtered by projectId', async () => {+ const onBatch = mock((_event: unknown) => undefined);+ await subject.subscribeToProjectEventBatches('proj_1', onBatch);++ const callback = subscribeToPublishedEvent.mock.calls[0]![2] as (+ event: unknown+ ) => void;++ callback({ projectId: 'proj_1', count: 3 });+ expect(onBatch).toHaveBeenCalledWith({ projectId: 'proj_1', count: 3 });+});++test('subscribeToProjectNotifications subscribes on notification:created and filters by projectId', async () => {+ const onNotification = mock((_notification: unknown) => undefined);+ await subject.subscribeToProjectNotifications('proj_1', onNotification);++ const [channel, type, callback] = subscribeToPublishedEvent.mock.calls[0]!;+ expect(channel).toBe('notification');+ expect(type).toBe('created');++ (callback as (event: unknown) => void)({+ projectId: 'proj_other',+ title: 't',+ });+ expect(onNotification).not.toHaveBeenCalled();++ (callback as (event: unknown) => void)({ projectId: 'proj_1', title: 't' });+ expect(onNotification).toHaveBeenCalledTimes(1);+});++test('subscribeToOrganizationSubscriptionUpdates subscribes on organization:subscription_updated, unfiltered', async () => {+ const onUpdate = mock((_message: unknown) => undefined);+ await subject.subscribeToOrganizationSubscriptionUpdates(onUpdate);++ const [channel, type, callback] = subscribeToPublishedEvent.mock.calls[0]!;+ expect(channel).toBe('organization');+ expect(type).toBe('subscription_updated');++ (callback as (event: unknown) => void)({ organizationId: 'org_1' });+ expect(onUpdate).toHaveBeenCalledWith({ organizationId: 'org_1' });+});++test('getRealtimeActiveSessions scopes the query to the project and the 30-minute window', async () => {+ chQuery.mockImplementationOnce(async () => [+ {+ name: 'screen_view',+ session_id: 'sess_1',+ created_at: '2026-09-04 00:00:00',+ path: '/',+ origin: 'https://example.com',+ referrer: '',+ referrer_name: '',+ country: 'SE',+ city: 'Stockholm',+ region: '',+ os: 'macOS',+ os_version: '',+ browser: 'Chrome',+ browser_version: '',+ device: 'desktop',+ },+ ]);++ const result = await subject.getRealtimeActiveSessions('proj_1');++ expect(chQuery).toHaveBeenCalledTimes(1);+ const [query] = chQuery.mock.calls[0]!;+ expect(query).toContain("project_id = 'proj_1'");+ expect(query).toContain('created_at >=');+ expect(query).toContain('LIMIT 50');+ expect(result).toHaveLength(1);+ expect(result[0]?.sessionId).toBe('sess_1');+});diff --git a/packages/core/src/modules/realtime/realtime.service.ts b/packages/core/src/modules/realtime/realtime.service.tsnew file mode 100644index 000000000..c7627325d--- /dev/null+++ b/packages/core/src/modules/realtime/realtime.service.ts@@ -0,0 +1,587 @@+// Two halves ported from different V1 places, both landing here (module map:+// realtime owns "R,H,S"):+//+// 1. The six ClickHouse queries, moved from+// packages/trpc/src/routers/realtime.ts (M6-007). V1's trpc router stays+// the LIVE route (DELEGATE PATTERN, ONE shared tRPC instance) and now+// delegates its handler bodies onto the functions below, exported through+// `@openpanel/core`'s barrel, same as notification.ts/reference.ts.+//+// 2. The `/live` websocket glue, ported FRESH from+// apps/api/src/controllers/live.controller.ts's business logic —+// `getActiveVisitorCount` and the four `subscribeToPublishedEvent` calls,+// filtered by projectId where V1 filters inline in the callback. V1's+// Fastify `@fastify/websocket` controller is LEFT UNTOUCHED: its socket+// type (the `ws` package's `WebSocket`) has nothing in common with+// Elysia/Bun's `ElysiaWS`, so there is no shim to delegate through, and+// touching the golden-harness-critical V1 ws stack for a few lines of+// framework glue is the risk this port avoids (task M6-007 notes).+// `subscribeToPublishedEvent` itself is already framework-agnostic+// (`@openpanel/redis`, plain callback), so both stacks call the exact+// same Redis subscription underneath.+//+// db/ch access is LAZY (`load*` below), not a static top-level import — see+// insight.service.ts's header for the full reasoning (jobs.registry.ts and+// rpc.router.ts pull this module into the eager barrel chain nearly every+// core test file reaches, and constructing @openpanel/db's clients at import+// time would spawn a pino-pretty transport worker thread per test file).+// `clix` (query-builder.ts) has no such side effect and stays a static+// import, same as cohort.service.ts / project.service.ts.+//+// ClickHouse queries here still go through clix/chQuery/sqlstring, not the+// `sql` tag: ADR-013 converts the analytics read path one query per P7 task,+// and this module's queries haven't been converted yet.++import { clix } from '@openpanel/db/src/clickhouse/query-builder';+import type { IClickhouseEvent } from '@openpanel/db/src/services/event.service';+import type { IPublishChannels } from '@openpanel/redis';+import { subMinutes } from 'date-fns';+import sqlstring from 'sqlstring';++const REALTIME_WINDOW_MINUTES = 30;+const ACTIVE_SESSIONS_LIMIT = 50;+const PATHS_LIMIT = 50;+const REFERRALS_LIMIT = 50;+const GEO_LIMIT = 50;+const COORDINATES_QUERY_LIMIT = 5000;+const COORDINATES_CLUSTER_TARGET = 500;+const MAP_BADGE_TOP_LIMIT = 3;+const MAP_BADGE_RECENT_SESSIONS_LIMIT = 8;+const CLUSTER_RADII_DEGREES = [0.5, 1, 3, 10];++function loadChClient() {+ return import('@openpanel/db/src/clickhouse/client');+}++function loadEventService() {+ return import('@openpanel/db/src/services/event.service');+}++function loadProfileService() {+ return import('@openpanel/db/src/services/profile.service');+}++function loadEventBuffer() {+ return import('@openpanel/db/src/buffers').then((m) => m.eventBuffer);+}++function since(): Date {+ return subMinutes(new Date(), REALTIME_WINDOW_MINUTES);+}++export interface RealtimeLocation {+ country?: string;+ city?: string;+ lat?: number;+ long?: number;+}++export type RealtimeBadgeDetailScope =+ | 'country'+ | 'city'+ | 'coordinate'+ | 'merged';++interface CoordinatePoint {+ country: string;+ city: string;+ long: number;+ lat: number;+ count: number;+}++function mergeByRadius(+ points: CoordinatePoint[],+ radius: number+): CoordinatePoint[] {+ // Highest-count points become cluster centers; nearby points get absorbed into them+ const sorted = [...points].sort((a, b) => b.count - a.count);+ const absorbed = new Uint8Array(sorted.length);+ const clusters: CoordinatePoint[] = [];++ for (let i = 0; i < sorted.length; i++) {+ if (absorbed[i]) {+ continue;+ }+ const seed = sorted[i];+ if (!seed) {+ continue;+ }+ const center: CoordinatePoint = { ...seed };+ for (let j = i + 1; j < sorted.length; j++) {+ if (absorbed[j]) {+ continue;+ }+ const other = sorted[j];+ if (!other) {+ continue;+ }+ const dlat = other.lat - center.lat;+ const dlong = other.long - center.long;+ if (Math.sqrt(dlat * dlat + dlong * dlong) <= radius) {+ center.count += other.count;+ absorbed[j] = 1;+ }+ }+ clusters.push(center);+ }++ return clusters;+}++function adaptiveCluster(+ points: CoordinatePoint[],+ target: number+): CoordinatePoint[] {+ if (points.length <= target) {+ return points;+ }++ // Expand merge radius until we hit the target (~55km → ~111km → ~333km → ~1110km)+ for (const radius of CLUSTER_RADII_DEGREES) {+ const clustered = mergeByRadius(points, radius);+ if (clustered.length <= target) {+ return clustered;+ }+ }++ return points.slice(0, target);+}++function buildRealtimeLocationFilter(locations: RealtimeLocation[]): string {+ const tuples = locations+ .filter(+ (+ location+ ): location is RealtimeLocation & { lat: number; long: number } =>+ typeof location.lat === 'number' && typeof location.long === 'number'+ )+ .map(+ (location) =>+ `(${sqlstring.escape(location.country ?? '')}, ${sqlstring.escape(+ location.city ?? ''+ )}, toDecimal64(${location.long.toFixed(4)}, 4), toDecimal64(${location.lat.toFixed(4)}, 4))`+ );++ if (tuples.length === 0) {+ return buildRealtimeCityFilter(locations);+ }++ return `(coalesce(country, ''), coalesce(city, ''), toDecimal64(longitude, 4), toDecimal64(latitude, 4)) IN (${tuples.join(', ')})`;+}++function buildRealtimeCountryFilter(locations: RealtimeLocation[]): string {+ const countries = [+ ...new Set(locations.map((location) => location.country ?? '')),+ ];++ return `coalesce(country, '') IN (${countries+ .map((country) => sqlstring.escape(country))+ .join(', ')})`;+}++function buildRealtimeCityFilter(locations: RealtimeLocation[]): string {+ const tuples = [+ ...new Set(+ locations.map(+ (location) =>+ `(${sqlstring.escape(location.country ?? '')}, ${sqlstring.escape(+ location.city ?? ''+ )})`+ )+ ),+ ];++ if (tuples.length === 0) {+ return buildRealtimeCountryFilter(locations);+ }++ return `(coalesce(country, ''), coalesce(city, '')) IN (${tuples.join(', ')})`;+}++function buildRealtimeBadgeDetailsFilter(input: {+ detailScope: RealtimeBadgeDetailScope;+ locations: RealtimeLocation[];+}): string {+ if (input.detailScope === 'country') {+ return buildRealtimeCountryFilter(input.locations);+ }++ if (input.detailScope === 'city') {+ return buildRealtimeCityFilter(input.locations);+ }++ if (input.detailScope === 'merged') {+ return buildRealtimeCityFilter(input.locations);+ }++ return buildRealtimeLocationFilter(input.locations);+}++export async function getRealtimeCoordinates(projectId: string) {+ const { chQuery, TABLE_NAMES } = await loadChClient();++ const res = await chQuery<CoordinatePoint>(+ `SELECT+ country,+ city,+ longitude as long,+ latitude as lat,+ COUNT(DISTINCT session_id) as count+ FROM ${TABLE_NAMES.events}+ WHERE project_id = ${sqlstring.escape(projectId)}+ AND created_at >= now() - INTERVAL ${REALTIME_WINDOW_MINUTES} MINUTE+ AND longitude IS NOT NULL+ AND latitude IS NOT NULL+ GROUP BY country, city, longitude, latitude+ ORDER BY count DESC+ LIMIT ${COORDINATES_QUERY_LIMIT}`+ );++ return adaptiveCluster(res, COORDINATES_CLUSTER_TARGET);+}++export async function getRealtimeMapBadgeDetails(input: {+ projectId: string;+ detailScope: RealtimeBadgeDetailScope;+ locations: RealtimeLocation[];+}) {+ const {+ ch,+ chQuery,+ TABLE_NAMES,+ formatClickhouseDate,+ convertClickhouseDateToJs,+ } = await loadChClient();+ const { getProfiles } = await loadProfileService();++ const sinceDate = formatClickhouseDate(since());+ const locationFilter = buildRealtimeBadgeDetailsFilter(input);++ const summaryQuery = clix(ch)+ .select<{+ total_sessions: number;+ total_profiles: number;+ }>([+ 'COUNT(DISTINCT session_id) as total_sessions',+ "COUNT(DISTINCT nullIf(profile_id, '')) as total_profiles",+ ])+ .from(TABLE_NAMES.events)+ .where('project_id', '=', input.projectId)+ .where('created_at', '>=', sinceDate)+ .rawWhere(locationFilter);++ const topReferrersQuery = clix(ch)+ .select<{+ referrer_name: string;+ count: number;+ }>(['referrer_name', 'COUNT(DISTINCT session_id) as count'])+ .from(TABLE_NAMES.events)+ .where('project_id', '=', input.projectId)+ .where('created_at', '>=', sinceDate)+ .where('referrer_name', '!=', '')+ .rawWhere(locationFilter)+ .groupBy(['referrer_name'])+ .orderBy('count', 'DESC')+ .limit(MAP_BADGE_TOP_LIMIT);++ const topPathsQuery = clix(ch)+ .select<{+ origin: string;+ path: string;+ count: number;+ }>(['origin', 'path', 'COUNT(DISTINCT session_id) as count'])+ .from(TABLE_NAMES.events)+ .where('project_id', '=', input.projectId)+ .where('created_at', '>=', sinceDate)+ .where('path', '!=', '')+ .rawWhere(locationFilter)+ .groupBy(['origin', 'path'])+ .orderBy('count', 'DESC')+ .limit(MAP_BADGE_TOP_LIMIT);++ const topEventsQuery = clix(ch)+ .select<{+ name: string;+ count: number;+ }>(['name', 'COUNT(DISTINCT session_id) as count'])+ .from(TABLE_NAMES.events)+ .where('project_id', '=', input.projectId)+ .where('created_at', '>=', sinceDate)+ .where('name', 'NOT IN', ['screen_view', 'session_start', 'session_end'])+ .rawWhere(locationFilter)+ .groupBy(['name'])+ .orderBy('count', 'DESC')+ .limit(MAP_BADGE_TOP_LIMIT);++ const [summary, topReferrers, topPaths, topEvents, recentSessions] =+ await Promise.all([+ summaryQuery.execute(),+ topReferrersQuery.execute(),+ topPathsQuery.execute(),+ topEventsQuery.execute(),+ chQuery<{+ profile_id: string;+ session_id: string;+ created_at: string;+ path: string;+ name: string;+ country: string;+ city: string;+ }>(+ `SELECT+ session_id,+ profile_id,+ created_at,+ path,+ name,+ country,+ city+ FROM (+ SELECT+ session_id,+ profile_id,+ created_at,+ path,+ name,+ country,+ city,+ row_number() OVER (+ PARTITION BY session_id ORDER BY created_at DESC+ ) AS rn+ FROM ${TABLE_NAMES.events}+ WHERE project_id = ${sqlstring.escape(input.projectId)}+ AND created_at >= ${sqlstring.escape(sinceDate)}+ AND (${locationFilter})+ ) AS latest_event_per_session+ WHERE rn = 1+ ORDER BY created_at DESC+ LIMIT ${MAP_BADGE_RECENT_SESSIONS_LIMIT}`+ ),+ ]);++ const profiles = await getProfiles(+ recentSessions.map((item) => item.profile_id).filter(Boolean),+ input.projectId+ );+ const profileMap = new Map(profiles.map((profile) => [profile.id, profile]));++ return {+ summary: {+ totalSessions: summary[0]?.total_sessions ?? 0,+ totalProfiles: summary[0]?.total_profiles ?? 0,+ totalLocations: input.locations.length,+ totalCountries: new Set(+ input.locations.map((location) => location.country).filter(Boolean)+ ).size,+ totalCities: new Set(+ input.locations.map((location) => location.city).filter(Boolean)+ ).size,+ },+ topReferrers: topReferrers.map((item) => ({+ referrerName: item.referrer_name,+ count: item.count,+ })),+ topPaths,+ topEvents,+ recentProfiles: recentSessions.map((item) => {+ const profile = profileMap.get(item.profile_id);++ return {+ id: item.profile_id || item.session_id,+ profileId:+ item.profile_id && item.profile_id !== '' ? item.profile_id : null,+ sessionId: item.session_id,+ createdAt: convertClickhouseDateToJs(item.created_at),+ latestPath: item.path,+ latestEvent: item.name,+ city: profile?.properties.city || item.city,+ country: profile?.properties.country || item.country,+ firstName: profile?.firstName ?? '',+ lastName: profile?.lastName ?? '',+ email: profile?.email ?? '',+ avatar: profile?.avatar ?? '',+ };+ }),+ };+}++export async function getRealtimeActiveSessions(projectId: string) {+ const { chQuery, TABLE_NAMES, formatClickhouseDate } = await loadChClient();+ const { transformEvent } = await loadEventService();++ const rows = await chQuery<IClickhouseEvent>(+ `SELECT+ name, session_id, created_at, path, origin, referrer, referrer_name,+ country, city, region, os, os_version, browser, browser_version,+ device+ FROM ${TABLE_NAMES.events}+ WHERE project_id = ${sqlstring.escape(projectId)}+ AND created_at >= '${formatClickhouseDate(since())}'+ ORDER BY created_at DESC+ LIMIT ${ACTIVE_SESSIONS_LIMIT}`+ );+ return rows.map(transformEvent);+}++export async function getRealtimePaths(projectId: string) {+ const { ch, TABLE_NAMES, formatClickhouseDate } = await loadChClient();++ return await clix(ch)+ .select<{+ origin: string;+ path: string;+ count: number;+ avg_duration: number;+ unique_sessions: number;+ }>([+ 'origin',+ 'path',+ 'COUNT(*) as count',+ 'COUNT(DISTINCT session_id) as unique_sessions',+ 'round(avg(duration)/1000, 2) as avg_duration',+ ])+ .from(TABLE_NAMES.events)+ .where('project_id', '=', projectId)+ .where('path', '!=', '')+ .where('created_at', '>=', formatClickhouseDate(since()))+ .groupBy(['path', 'origin'])+ .orderBy('count', 'DESC')+ .limit(PATHS_LIMIT)+ .execute();+}++export async function getRealtimeReferrals(projectId: string) {+ const { ch, TABLE_NAMES, formatClickhouseDate } = await loadChClient();++ return await clix(ch)+ .select<{+ referrer_name: string;+ count: number;+ avg_duration: number;+ unique_sessions: number;+ }>([+ 'referrer_name',+ 'COUNT(*) as count',+ 'COUNT(DISTINCT session_id) as unique_sessions',+ 'round(avg(duration)/1000, 2) as avg_duration',+ ])+ .from(TABLE_NAMES.events)+ .where('project_id', '=', projectId)+ .where('referrer_name', 'IS NOT NULL')+ .where('created_at', '>=', formatClickhouseDate(since()))+ .groupBy(['referrer_name'])+ .orderBy('count', 'DESC')+ .limit(REFERRALS_LIMIT)+ .execute();+}++export async function getRealtimeGeo(projectId: string) {+ const { ch, TABLE_NAMES, formatClickhouseDate } = await loadChClient();++ return await clix(ch)+ .select<{+ country: string;+ city: string;+ count: number;+ avg_duration: number;+ unique_sessions: number;+ }>([+ 'country',+ 'city',+ 'COUNT(*) as count',+ 'COUNT(DISTINCT session_id) as unique_sessions',+ 'round(avg(duration)/1000, 2) as avg_duration',+ ])+ .from(TABLE_NAMES.events)+ .where('project_id', '=', projectId)+ .where('created_at', '>=', formatClickhouseDate(since()))+ .groupBy(['country', 'city'])+ .orderBy('count', 'DESC')+ .limit(GEO_LIMIT)+ .execute();+}++// --- /live websocket glue -------------------------------------------------+//+// Framework-agnostic: resolve to an unsubscribe function each, exactly+// `subscribeToPublishedEvent`'s own shape. realtime.routes.ts (Elysia/Bun)+// awaits these directly; nothing here is HTTP- or ws-library-specific.+//+// `@openpanel/redis` is LAZY here too, same reasoning as `loadChClient` above+// but for a different failure mode: it has no import-time side effect (its+// clients connect lazily on first use — insight.service.ts already imports+// `getRedisCache` from it statically), but several modules' tests replace the+// whole package with `mock.module('@openpanel/redis', () => ({ subset }))`.+// A new static named import here would demand `subscribeToPublishedEvent` on+// every one of those subsets the moment this module joins the eager barrel+// chain (rpc.router.ts), breaking tests this task does not own.+function loadRedis() {+ return import('@openpanel/redis');+}++export async function getActiveVisitorCount(+ projectId: string+): Promise<number> {+ const eventBuffer = await loadEventBuffer();+ return await eventBuffer.getActiveVisitorCount(projectId);+}++/** V1: `wsVisitors` — re-count on every batch touching this project. */+export async function subscribeToVisitorActivity(+ projectId: string,+ onActivity: () => void+): Promise<() => void> {+ const { subscribeToPublishedEvent } = await loadRedis();+ return subscribeToPublishedEvent('events', 'batch', (event) => {+ if (event.projectId === projectId) {+ onActivity();+ }+ });+}++/** V1: `wsProjectEvents` — the batch's own count, not a re-query. */+export async function subscribeToProjectEventBatches(+ projectId: string,+ onBatch: (event: IPublishChannels['events']['batch']) => void+): Promise<() => void> {+ const { subscribeToPublishedEvent } = await loadRedis();+ return subscribeToPublishedEvent('events', 'batch', (event) => {+ if (event.projectId === projectId) {+ onBatch(event);+ }+ });+}++/** V1: `wsProjectNotifications`. */+export async function subscribeToProjectNotifications(+ projectId: string,+ onNotification: (+ notification: IPublishChannels['notification']['created']+ ) => void+): Promise<() => void> {+ const { subscribeToPublishedEvent } = await loadRedis();+ return subscribeToPublishedEvent(+ 'notification',+ 'created',+ (notification) => {+ if (notification.projectId === projectId) {+ onNotification(notification);+ }+ }+ );+}++/** V1: `wsOrganizationEvents` — every subscriber, no per-org filter (V1 has none either). */+export async function subscribeToOrganizationSubscriptionUpdates(+ onUpdate: (+ message: IPublishChannels['organization']['subscription_updated']+ ) => void+): Promise<() => void> {+ const { subscribeToPublishedEvent } = await loadRedis();+ return subscribeToPublishedEvent(+ 'organization',+ 'subscription_updated',+ onUpdate+ );+}diff --git a/packages/core/src/modules/realtime/src/access.ts b/packages/core/src/modules/realtime/src/access.tsnew file mode 100644index 000000000..a72831bb7--- /dev/null+++ b/packages/core/src/modules/realtime/src/access.ts@@ -0,0 +1,33 @@+// Binds core's shared/access.ts ladder to @openpanel/db's real lookups, for+// this module's own router — the same binding packages/trpc/src/access.ts+// does for V1, self-contained here because the general core -> db binding+// itself moves with auth (P6), not this wave. Same shape as+// organization/src/access.ts.+//+// The `/live` ws routes (realtime.routes.ts) want the RAW nullable lookups,+// not the throwing `require*` wrappers: V1's controller (still live,+// untouched) checks truthiness itself and sends a "No access" frame before+// closing the socket, rather than throwing — porting that behaviour means+// re-exporting `getProjectAccess`/`getOrganizationAccess` verbatim.++import {+ canWriteProject,+ getOrganizationAccess,+ getProjectAccess,+} from '@openpanel/db/src/services/access.service';+import { getProjectById } from '@openpanel/db/src/services/project.service';+import { createAccessChecks } from '../../../shared/access';++export {+ getOrganizationAccess,+ getProjectAccess,+} from '@openpanel/db/src/services/access.service';++const checks = createAccessChecks({+ getProjectAccess,+ canWriteProject,+ getOrganizationAccess,+ getProjectById,+});++export const requireProjectAccess = checks.requireProjectAccess;diff --git a/packages/core/src/rest.routes.ts b/packages/core/src/rest.routes.tsindex da490d9ed..a17dbf79a 100644--- a/packages/core/src/rest.routes.ts+++ b/packages/core/src/rest.routes.ts@@ -17,6 +17,7 @@ import { importRoutes } from './modules/import/import.routes';import { integrationRoutes } from './modules/integration/integration.routes';import { mcpRoutes } from './modules/mcp/mcp.routes';import { projectRoutes } from './modules/project/project.routes';+import { realtimeRoutes } from './modules/realtime/realtime.routes';import { subscriptionRoutes } from './modules/subscription/subscription.routes';// ADR-002/ADR-003 pin: @elysiajs/openapi at the 1.4.15 fallback (2.0 is@@ -59,6 +60,8 @@ export const publicApiRoutes = (deps: AppDeps) =>// `corsPaths` allowlist (ADR-002 rule 4), unlike `/gsc`/`/mcp`, and both are// the same shape of unauthenticated third-party-redirected callback as// `/oauth`'s.+// realtime's `/live/*` websockets (M6-007) joined it too — `/live` IS in+// `corsPaths`, same as `/trpc`/`/webhook`/`/oauth`/`/misc`/`/ai`.export const dashboardRoutes = (deps: AppDeps) =>new Elysia({ name: 'core/dashboard-routes' }).use(gscRoutes(deps))@@ -66,7 +69,8 @@ export const dashboardRoutes = (deps: AppDeps) =>.use(mcpRoutes(deps)).use(authRoutes(deps)).use(integrationRoutes(deps))- .use(subscriptionRoutes(deps));+ .use(subscriptionRoutes(deps))+ .use(realtimeRoutes(deps));// healthz/metrics/misc share V1's ops surface (http/context.ts's// UNLOGGED_PATH_PREFIXES) — unauthenticated, uncorsed, unlogged. /metrics anddiff --git a/packages/core/src/rpc.router.ts b/packages/core/src/rpc.router.tsindex 3f4e78b79..5156a1fe0 100644--- a/packages/core/src/rpc.router.ts+++ b/packages/core/src/rpc.router.ts@@ -19,6 +19,7 @@ import { notificationRouter } from './modules/notification/notification.rpc';import { onboardingRouter } from './modules/onboarding/onboarding.rpc';import { organizationRouter } from './modules/organization/organization.rpc';import { projectRouter } from './modules/project/project.rpc';+import { realtimeRouter } from './modules/realtime/realtime.rpc';import { referenceRouter } from './modules/reference/reference.rpc';import { shareRouter } from './modules/share/share.rpc';import { subscriptionRouter } from './modules/subscription/subscription.rpc';@@ -39,6 +40,7 @@ export const appRouter = createTRPCRouter({client: clientRouter,auth: authRouter,onboarding: onboardingRouter,+ realtime: realtimeRouter,reference: referenceRouter,share: shareRouter,email: emailRouter,diff --git a/packages/trpc/src/routers/realtime.ts b/packages/trpc/src/routers/realtime.tsindex 4bc1dd126..bcdc82a7f 100644--- a/packages/trpc/src/routers/realtime.ts+++ b/packages/trpc/src/routers/realtime.ts@@ -1,16 +1,24 @@+// Dissolved into @openpanel/core's realtime module (M6-007): the six+// ClickHouse queries moved to+// packages/core/src/modules/realtime/realtime.service.ts. This router stays+// (DELEGATE PATTERN) — it keeps V1's protectedProcedure stack+// (session/access/logger/rate-limit middleware, which already enforces+// `projectId` read access via `enforceAccess`) and delegates every handler+// body to core's realtime functions, same as notification.ts/reference.ts.+//+// V1's Fastify `/live` websocket controller is untouched (ADR-002/M6-007+// notes: its `ws`-package socket has nothing in common with Elysia/Bun's+// `ElysiaWS`), so this file has no ws surface to delegate — that logic was+// ported fresh into core/realtime.routes.ts instead.+import {- ch,- chQuery,- clix,- convertClickhouseDateToJs,- formatClickhouseDate,- getProfiles,- type IClickhouseEvent,- TABLE_NAMES,- transformEvent,-} from '@openpanel/db';-import { subMinutes } from 'date-fns';-import sqlstring from 'sqlstring';+ getRealtimeActiveSessions,+ getRealtimeCoordinates,+ getRealtimeGeo,+ getRealtimeMapBadgeDetails,+ getRealtimePaths,+ getRealtimeReferrals,+} from '@openpanel/core';import { z } from 'zod';import { createTRPCRouter, protectedProcedure } from '../trpc';@@ -28,172 +36,11 @@ const realtimeBadgeDetailScopeSchema = z.enum(['merged',]);-function buildRealtimeLocationFilter(- locations: z.infer<typeof realtimeLocationSchema>[]-) {- const tuples = locations- .filter(- (- location- ): location is z.infer<typeof realtimeLocationSchema> & {- lat: number;- long: number;- } => typeof location.lat === 'number' && typeof location.long === 'number'- )- .map(- (location) =>- `(${sqlstring.escape(location.country ?? '')}, ${sqlstring.escape(- location.city ?? ''- )}, toDecimal64(${location.long.toFixed(4)}, 4), toDecimal64(${location.lat.toFixed(4)}, 4))`- );-- if (tuples.length === 0) {- return buildRealtimeCityFilter(locations);- }-- return `(coalesce(country, ''), coalesce(city, ''), toDecimal64(longitude, 4), toDecimal64(latitude, 4)) IN (${tuples.join(', ')})`;-}--function buildRealtimeCountryFilter(- locations: z.infer<typeof realtimeLocationSchema>[]-) {- const countries = [- ...new Set(locations.map((location) => location.country ?? '')),- ];-- return `coalesce(country, '') IN (${countries- .map((country) => sqlstring.escape(country))- .join(', ')})`;-}--function buildRealtimeCityFilter(- locations: z.infer<typeof realtimeLocationSchema>[]-) {- const tuples = [- ...new Set(- locations.map(- (location) =>- `(${sqlstring.escape(location.country ?? '')}, ${sqlstring.escape(- location.city ?? ''- )})`- )- ),- ];-- if (tuples.length === 0) {- return buildRealtimeCountryFilter(locations);- }-- return `(coalesce(country, ''), coalesce(city, '')) IN (${tuples.join(', ')})`;-}--function buildRealtimeBadgeDetailsFilter(input: {- detailScope: z.infer<typeof realtimeBadgeDetailScopeSchema>;- locations: z.infer<typeof realtimeLocationSchema>[];-}) {- if (input.detailScope === 'country') {- return buildRealtimeCountryFilter(input.locations);- }-- if (input.detailScope === 'city') {- return buildRealtimeCityFilter(input.locations);- }-- if (input.detailScope === 'merged') {- return buildRealtimeCityFilter(input.locations);- }-- return buildRealtimeLocationFilter(input.locations);-}--interface CoordinatePoint {- country: string;- city: string;- long: number;- lat: number;- count: number;-};--function mergeByRadius(- points: CoordinatePoint[],- radius: number-): CoordinatePoint[] {- // Highest-count points become cluster centers; nearby points get absorbed into them- const sorted = [...points].sort((a, b) => b.count - a.count);- const absorbed = new Uint8Array(sorted.length);- const clusters: CoordinatePoint[] = [];-- for (let i = 0; i < sorted.length; i++) {- if (absorbed[i]) {- continue;- }- const seed = sorted[i];- if (!seed) {- continue;- }- const center: CoordinatePoint = { ...seed };- for (let j = i + 1; j < sorted.length; j++) {- if (absorbed[j]) {- continue;- }- const other = sorted[j];- if (!other) {- continue;- }- const dlat = other.lat - center.lat;- const dlong = other.long - center.long;- if (Math.sqrt(dlat * dlat + dlong * dlong) <= radius) {- center.count += other.count;- absorbed[j] = 1;- }- }- clusters.push(center);- }-- return clusters;-}--function adaptiveCluster(- points: CoordinatePoint[],- target: number-): CoordinatePoint[] {- if (points.length <= target) {- return points;- }-- // Expand merge radius until we hit the target (~55km → ~111km → ~333km → ~1110km)- for (const radius of [0.5, 1, 3, 10]) {- const clustered = mergeByRadius(points, radius);- if (clustered.length <= target) {- return clustered;- }- }-- return points.slice(0, target);-}-export const realtimeRouter = createTRPCRouter({coordinates: protectedProcedure.input(z.object({ projectId: z.string() })).query(async ({ input }) => {- const res = await chQuery<CoordinatePoint>(- `SELECT- country,- city,- longitude as long,- latitude as lat,- COUNT(DISTINCT session_id) as count- FROM ${TABLE_NAMES.events}- WHERE project_id = ${sqlstring.escape(input.projectId)}- AND created_at >= now() - INTERVAL 30 MINUTE- AND longitude IS NOT NULL- AND latitude IS NOT NULL- GROUP BY country, city, longitude, latitude- ORDER BY count DESC- LIMIT 5000`- );-- return adaptiveCluster(res, 500);+ return getRealtimeCoordinates(input.projectId);}),mapBadgeDetails: protectedProcedure.input(@@ -204,271 +51,26 @@ export const realtimeRouter = createTRPCRouter({})).query(async ({ input }) => {- const since = formatClickhouseDate(subMinutes(new Date(), 30));- const locationFilter = buildRealtimeBadgeDetailsFilter(input);-- const summaryQuery = clix(ch)- .select<{- total_sessions: number;- total_profiles: number;- }>([- 'COUNT(DISTINCT session_id) as total_sessions',- "COUNT(DISTINCT nullIf(profile_id, '')) as total_profiles",- ])- .from(TABLE_NAMES.events)- .where('project_id', '=', input.projectId)- .where('created_at', '>=', since)- .rawWhere(locationFilter);-- const topReferrersQuery = clix(ch)- .select<{- referrer_name: string;- count: number;- }>(['referrer_name', 'COUNT(DISTINCT session_id) as count'])- .from(TABLE_NAMES.events)- .where('project_id', '=', input.projectId)- .where('created_at', '>=', since)- .where('referrer_name', '!=', '')- .rawWhere(locationFilter)- .groupBy(['referrer_name'])- .orderBy('count', 'DESC')- .limit(3);-- const topPathsQuery = clix(ch)- .select<{- origin: string;- path: string;- count: number;- }>(['origin', 'path', 'COUNT(DISTINCT session_id) as count'])- .from(TABLE_NAMES.events)- .where('project_id', '=', input.projectId)- .where('created_at', '>=', since)- .where('path', '!=', '')- .rawWhere(locationFilter)- .groupBy(['origin', 'path'])- .orderBy('count', 'DESC')- .limit(3);-- const topEventsQuery = clix(ch)- .select<{- name: string;- count: number;- }>(['name', 'COUNT(DISTINCT session_id) as count'])- .from(TABLE_NAMES.events)- .where('project_id', '=', input.projectId)- .where('created_at', '>=', since)- .where('name', 'NOT IN', [- 'screen_view',- 'session_start',- 'session_end',- ])- .rawWhere(locationFilter)- .groupBy(['name'])- .orderBy('count', 'DESC')- .limit(3);-- const [summary, topReferrers, topPaths, topEvents, recentSessions] =- await Promise.all([- summaryQuery.execute(),- topReferrersQuery.execute(),- topPathsQuery.execute(),- topEventsQuery.execute(),- chQuery<{- profile_id: string;- session_id: string;- created_at: string;- path: string;- name: string;- country: string;- city: string;- }>(- `SELECT- session_id,- profile_id,- created_at,- path,- name,- country,- city- FROM (- SELECT- session_id,- profile_id,- created_at,- path,- name,- country,- city,- row_number() OVER (- PARTITION BY session_id ORDER BY created_at DESC- ) AS rn- FROM ${TABLE_NAMES.events}- WHERE project_id = ${sqlstring.escape(input.projectId)}- AND created_at >= ${sqlstring.escape(since)}- AND (${locationFilter})- ) AS latest_event_per_session- WHERE rn = 1- ORDER BY created_at DESC- LIMIT 8`- ),- ]);-- const profiles = await getProfiles(- recentSessions.map((item) => item.profile_id).filter(Boolean),- input.projectId- );- const profileMap = new Map(- profiles.map((profile) => [profile.id, profile])- );-- return {- summary: {- totalSessions: summary[0]?.total_sessions ?? 0,- totalProfiles: summary[0]?.total_profiles ?? 0,- totalLocations: input.locations.length,- totalCountries: new Set(- input.locations.map((location) => location.country).filter(Boolean)- ).size,- totalCities: new Set(- input.locations.map((location) => location.city).filter(Boolean)- ).size,- },- topReferrers: topReferrers.map((item) => ({- referrerName: item.referrer_name,- count: item.count,- })),- topPaths,- topEvents,- recentProfiles: recentSessions.map((item) => {- const profile = profileMap.get(item.profile_id);-- return {- id: item.profile_id || item.session_id,- profileId:- item.profile_id && item.profile_id !== ''- ? item.profile_id- : null,- sessionId: item.session_id,- createdAt: convertClickhouseDateToJs(item.created_at),- latestPath: item.path,- latestEvent: item.name,- city: profile?.properties.city || item.city,- country: profile?.properties.country || item.country,- firstName: profile?.firstName ?? '',- lastName: profile?.lastName ?? '',- email: profile?.email ?? '',- avatar: profile?.avatar ?? '',- };- }),- };+ return getRealtimeMapBadgeDetails(input);}),activeSessions: protectedProcedure.input(z.object({ projectId: z.string() })).query(async ({ input }) => {- const rows = await chQuery<IClickhouseEvent>(- `SELECT- name, session_id, created_at, path, origin, referrer, referrer_name,- country, city, region, os, os_version, browser, browser_version,- device- FROM ${TABLE_NAMES.events}- WHERE project_id = ${sqlstring.escape(input.projectId)}- AND created_at >= '${formatClickhouseDate(subMinutes(new Date(), 30))}'- ORDER BY created_at DESC- LIMIT 50`- );- return rows.map(transformEvent);+ return getRealtimeActiveSessions(input.projectId);}),paths: protectedProcedure.input(z.object({ projectId: z.string() })).query(async ({ input }) => {- const res = await clix(ch)- .select<{- origin: string;- path: string;- count: number;- avg_duration: number;- unique_sessions: number;- }>([- 'origin',- 'path',- 'COUNT(*) as count',- 'COUNT(DISTINCT session_id) as unique_sessions',- 'round(avg(duration)/1000, 2) as avg_duration',- ])- .from(TABLE_NAMES.events)- .where('project_id', '=', input.projectId)- .where('path', '!=', '')- .where(- 'created_at',- '>=',- formatClickhouseDate(subMinutes(new Date(), 30))- )- .groupBy(['path', 'origin'])- .orderBy('count', 'DESC')- .limit(50)- .execute();-- return res;+ return getRealtimePaths(input.projectId);}),referrals: protectedProcedure.input(z.object({ projectId: z.string() })).query(async ({ input }) => {- const res = await clix(ch)- .select<{- referrer_name: string;- count: number;- avg_duration: number;- unique_sessions: number;- }>([- 'referrer_name',- 'COUNT(*) as count',- 'COUNT(DISTINCT session_id) as unique_sessions',- 'round(avg(duration)/1000, 2) as avg_duration',- ])- .from(TABLE_NAMES.events)- .where('project_id', '=', input.projectId)- .where('referrer_name', 'IS NOT NULL')- .where(- 'created_at',- '>=',- formatClickhouseDate(subMinutes(new Date(), 30))- )- .groupBy(['referrer_name'])- .orderBy('count', 'DESC')- .limit(50)- .execute();-- return res;+ return getRealtimeReferrals(input.projectId);}),geo: protectedProcedure.input(z.object({ projectId: z.string() })).query(async ({ input }) => {- const res = await clix(ch)- .select<{- country: string;- city: string;- count: number;- avg_duration: number;- unique_sessions: number;- }>([- 'country',- 'city',- 'COUNT(*) as count',- 'COUNT(DISTINCT session_id) as unique_sessions',- 'round(avg(duration)/1000, 2) as avg_duration',- ])- .from(TABLE_NAMES.events)- .where('project_id', '=', input.projectId)- .where(- 'created_at',- '>=',- formatClickhouseDate(subMinutes(new Date(), 30))- )- .groupBy(['country', 'city'])- .orderBy('count', 'DESC')- .limit(50)- .execute();-- return res;+ return getRealtimeGeo(input.projectId);}),});