OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
feat(api): operator memory diagnostics under /admin/memory
Carl-Gerhard Lindesvärd1d9a9a83bce1
diff --git a/apps/api/src/main.ts b/apps/api/src/main.tsindex f5076326a..1b2b79a66 100644--- a/apps/api/src/main.ts+++ b/apps/api/src/main.ts@@ -35,7 +35,9 @@ import {interceptProcessOutput,type KafkaConsumerHandle,kafkaLogger,+ MEMORY_ROUTES_BASE_PATH,markEventsActivity,+ memoryRoutes,opsRoutes,publicApiRoutes,type QueueDefinition,@@ -380,6 +382,14 @@ async function buildHttpApp(deps: AppDeps) {logger.info('Debug routes enabled at /debug/cron');}+ if (config.core.adminAuth) {+ app.use(memoryRoutes(deps, config.core.adminAuth));+ logger.info(+ { path: MEMORY_ROUTES_BASE_PATH },+ 'Memory diagnostics mounted'+ );+ }+if (roleConsumes && !config.DISABLE_BULLBOARD) {// The board can add, retry and clean jobs, so a dashboard session alone// is not enough to reach it (GHSA-r627-6vrh-65p9): without operatordiff --git a/packages/core/src/http/memory.routes.test.ts b/packages/core/src/http/memory.routes.test.tsnew file mode 100644index 000000000..621a430d0--- /dev/null+++ b/packages/core/src/http/memory.routes.test.ts@@ -0,0 +1,64 @@+import { expect, mock, test } from 'bun:test';+import type { AppDeps } from '../context';+import type {+ GarbageCollectionResult,+ MemorySnapshot,+} from '../shared/memory';+import { memoryRoutes } from './memory.routes';++const ADMIN = { username: 'ops', password: 'secret-pass' };+const BASE = 'http://localhost/admin/memory';++const info = mock((_object: unknown, _message?: string) => undefined);+const deps = { logger: { info } } as unknown as AppDeps;+const app = memoryRoutes(deps, ADMIN);++function basic(username: string, password: string): Record<string, string> {+ return {+ authorization: `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`,+ };+}++const ROUTES = [+ ['GET', BASE],+ ['POST', `${BASE}/gc`],+ ['POST', `${BASE}/gc?all=1`],+ ['GET', `${BASE}/heap-snapshot`],+] as const;++test('every route refuses a missing or wrong password and challenges the browser', async () => {+ for (const [method, url] of ROUTES) {+ for (const headers of [{}, basic('ops', 'wrong')]) {+ const response = await app.handle(new Request(url, { method, headers }));+ expect(response.status).toBe(401);+ expect(response.headers.get('www-authenticate')).toContain('Basic');+ }+ }+});++test('the snapshot reports memory and the requested number of object types', async () => {+ const response = await app.handle(+ new Request(`${BASE}?top=3`, { headers: basic('ops', 'secret-pass') })+ );+ const body = (await response.json()) as MemorySnapshot;++ expect(response.status).toBe(200);+ expect(body.rss).toBeGreaterThan(0);+ expect(body.heapUsed).toBeGreaterThan(0);+ expect(body.topObjectTypes).toHaveLength(3);+});++test('a local gc returns before/after for this process and logs it', async () => {+ const response = await app.handle(+ new Request(`${BASE}/gc`, {+ method: 'POST',+ headers: basic('ops', 'secret-pass'),+ })+ );+ const body = (await response.json()) as GarbageCollectionResult;++ expect(response.status).toBe(200);+ expect(body.before.rss).toBeGreaterThan(0);+ expect(body.freed.heapUsed).toBe(body.before.heapUsed - body.after.heapUsed);+ expect(info).toHaveBeenCalledTimes(1);+});diff --git a/packages/core/src/http/memory.routes.ts b/packages/core/src/http/memory.routes.tsnew file mode 100644index 000000000..d097718cb--- /dev/null+++ b/packages/core/src/http/memory.routes.ts@@ -0,0 +1,97 @@+// Operator memory diagnostics, on every role (workers serve no other HTTP).+// Behind ADMIN_USERNAME / ADMIN_PASSWORD alone, so curl and a scrape-side+// script can reach a worker replica that has no dashboard session to offer.+//+// A request lands on one replica. `POST /admin/memory/gc?all=1` fans out over+// Redis pubsub instead, and each process logs its own result.++import { publishEvent, subscribeToPublishedEvent } from '@openpanel/redis';+import { Elysia } from 'elysia';+import { z } from 'zod';+import type { AppDeps } from '../context';+import type { BasicAuthCredentials } from '../shared/basic-auth';+import { basicAuthChallenge, matchesBasicAuth } from '../shared/basic-auth';+import {+ collectGarbage,+ generateHeapSnapshot,+ readMemorySnapshot,+} from '../shared/memory';++export const MEMORY_ROUTES_BASE_PATH = '/admin/memory';++const UNAUTHORIZED = 401;+const MEMORY_REALM = 'OpenPanel ops';+const HIDDEN = { hide: true } as const;+const MAX_TOP_OBJECT_TYPES = 200;++const snapshotQuery = z.object({+ top: z.coerce.number().int().min(1).max(MAX_TOP_OBJECT_TYPES).optional(),+});+const gcQuery = z.object({ all: z.enum(['1', 'true']).optional() });++export function memoryRoutes(deps: AppDeps, adminAuth: BasicAuthCredentials) {+ const { logger } = deps;+ let stopListening: (() => void) | undefined;++ return new Elysia({+ name: 'core/http/memory',+ prefix: MEMORY_ROUTES_BASE_PATH,+ })+ .onStart(() => {+ stopListening = subscribeToPublishedEvent(+ 'ops',+ 'garbage_collect',+ ({ requestedAt }) => {+ logger.info(+ { requestedAt, ...collectGarbage() },+ 'Garbage collection requested by broadcast'+ );+ }+ );+ })+ .onStop(() => {+ stopListening?.();+ })+ .onBeforeHandle(({ request, set, status }) => {+ if (matchesBasicAuth(request.headers.get('authorization'), adminAuth)) {+ return;+ }+ set.headers = { ...set.headers, ...basicAuthChallenge(MEMORY_REALM) };+ return status(UNAUTHORIZED);+ })+ .get('/', async ({ query }) => await readMemorySnapshot(query.top), {+ query: snapshotQuery,+ detail: HIDDEN,+ })+ .post(+ '/gc',+ async ({ query }) => {+ if (query.all) {+ const receivers = await publishEvent('ops', 'garbage_collect', {+ requestedAt: new Date().toISOString(),+ });+ return {+ broadcast: true,+ receivers,+ message:+ 'Each process logs "Garbage collection requested by broadcast" with its own before/after.',+ };+ }+ const result = collectGarbage();+ logger.info({ ...result }, 'Garbage collection requested over HTTP');+ return result;+ },+ { query: gcQuery, detail: HIDDEN }+ )+ .get(+ '/heap-snapshot',+ ({ set }) => {+ const snapshot = generateHeapSnapshot();+ set.headers['content-type'] = 'application/json';+ set.headers['content-disposition'] =+ `attachment; filename="heap-${Date.now()}.heapsnapshot"`;+ return snapshot;+ },+ { detail: HIDDEN }+ );+}diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 7b7b2bf59..221ecfd27 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -60,6 +60,7 @@ export { BULL_BOARD_BASE_PATH, bullBoardRoutes } from './http/bull-board';export { requestContext, requestLogging } from './http/context';export { corsDelegator } from './http/cors';export { errorHandler } from './http/errors';+export { MEMORY_ROUTES_BASE_PATH, memoryRoutes } from './http/memory.routes';export type {AnyJob,QueueDefinition,diff --git a/packages/core/src/shared/memory.ts b/packages/core/src/shared/memory.tsnew file mode 100644index 000000000..91a15981a--- /dev/null+++ b/packages/core/src/shared/memory.ts@@ -0,0 +1,106 @@+// Operator diagnostics for "is this process leaking?". Bun keeps freed heap+// pages committed and reuses them, so RSS sits at its high-water mark even after+// a full GC: a leak is RSS or heapUsed still climbing past an earlier peak, not+// RSS failing to drop once.++import { hostname } from 'node:os';++const DEFAULT_TOP_OBJECT_TYPES = 25;++// `apps/start`, `@openpanel/email` and `@openpanel/redis` typecheck this source+// without Bun's types, so the runtime is typed here and `bun:jsc` is imported+// by a specifier TypeScript does not resolve.+const BUN_JSC_MODULE = 'bun:jsc';++interface BunJsc {+ heapStats(): {+ objectCount: number;+ objectTypeCounts: Record<string, number>;+ };+}++interface BunRuntime {+ gc(force: boolean): void;+ generateHeapSnapshot(format: 'v8'): string;+}++function bunRuntime(): BunRuntime {+ return (globalThis as unknown as { Bun: BunRuntime }).Bun;+}++export interface MemoryReading {+ rss: number;+ heapUsed: number;+ heapTotal: number;+ external: number;+ arrayBuffers: number;+}++export interface MemorySnapshot extends MemoryReading {+ host: string;+ uptimeSeconds: number;+ objectCount: number;+ topObjectTypes: { type: string; count: number }[];+}++export interface GarbageCollectionResult {+ host: string;+ durationMs: number;+ before: MemoryReading;+ after: MemoryReading;+ freed: MemoryReading;+}++function readMemory(): MemoryReading {+ const { rss, heapUsed, heapTotal, external, arrayBuffers } =+ process.memoryUsage();+ return { rss, heapUsed, heapTotal, external, arrayBuffers };+}++/** Walks the whole JS heap to count objects by type. */+export async function readMemorySnapshot(+ topObjectTypes = DEFAULT_TOP_OBJECT_TYPES+): Promise<MemorySnapshot> {+ const { heapStats } = (await import(BUN_JSC_MODULE)) as BunJsc;+ const stats = heapStats();+ const ranked = Object.entries(stats.objectTypeCounts)+ .map(([type, count]) => ({ type, count }))+ .sort((a, b) => b.count - a.count)+ .slice(0, topObjectTypes);++ return {+ host: hostname(),+ uptimeSeconds: Math.round(process.uptime()),+ ...readMemory(),+ objectCount: stats.objectCount,+ topObjectTypes: ranked,+ };+}++/** A synchronous full collection; blocks the event loop while it runs. */+export function collectGarbage(): GarbageCollectionResult {+ const before = readMemory();+ const startedAt = performance.now();+ bunRuntime().gc(true);+ const durationMs = Math.round(performance.now() - startedAt);+ const after = readMemory();++ return {+ host: hostname(),+ durationMs,+ before,+ after,+ freed: {+ rss: before.rss - after.rss,+ heapUsed: before.heapUsed - after.heapUsed,+ heapTotal: before.heapTotal - after.heapTotal,+ external: before.external - after.external,+ arrayBuffers: before.arrayBuffers - after.arrayBuffers,+ },+ };+}++/** V8 format, which Chrome DevTools' Memory tab loads. Blocks while it runs. */+export function generateHeapSnapshot(): string {+ return bunRuntime().generateHeapSnapshot('v8');+}diff --git a/packages/redis/publisher.ts b/packages/redis/publisher.tsindex 4c6dbe1e9..1ef3fd8d7 100644--- a/packages/redis/publisher.ts+++ b/packages/redis/publisher.ts@@ -14,6 +14,9 @@ export type IPublishChannels = {notification: {created: Prisma.NotificationUncheckedCreateInput;};+ ops: {+ garbage_collect: { requestedAt: string };+ };};export function getSubscribeChannel<Channel extends keyof IPublishChannels>(