OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
fix: improve crashes
Carl-Gerhard Lindesvärd9a8a3d62e821
diff --git a/apps/api/Dockerfile b/apps/api/Dockerfileindex b540b3803..6a7b24f24 100644--- a/apps/api/Dockerfile+++ b/apps/api/Dockerfile@@ -117,6 +117,11 @@ RUN pnpm db:codegenWORKDIR /app/apps/api+# Drop a diagnostic report on fatal errors / SIGUSR2 so the next native+# segfault (exit 139) leaves a stack we can read. Override per-environment+# by setting NODE_OPTIONS in the swarm stack file.+ENV NODE_OPTIONS="--report-on-fatalerror --report-on-signal --report-directory=/tmp"+EXPOSE 3000CMD ["node", "dist/index.js"]\ No newline at end of filediff --git a/apps/api/src/controllers/live.controller.ts b/apps/api/src/controllers/live.controller.tsindex d73f267ec..4be0a9a02 100644--- a/apps/api/src/controllers/live.controller.ts+++ b/apps/api/src/controllers/live.controller.ts@@ -6,6 +6,17 @@ import { getProjectAccess } from '@openpanel/trpc';import { getOrganizationAccess } from '@openpanel/trpc/src/access';import type { FastifyRequest } from 'fastify';+// Every ws handler MUST call this before its first await. Without an+// 'error' listener, an ECONNRESET from the client (laptop sleep, network+// flip, LB reset storm) propagates to uncaughtException and kills the+// whole process. The ws library always emits 'close' after 'error', so+// the existing close-based cleanup still runs.+function guardSocket(socket: WebSocket, req: FastifyRequest) {+ socket.on('error', (err) => {+ req.log.warn({ err }, 'ws socket error');+ });+}+export function wsVisitors(socket: WebSocket,req: FastifyRequest<{@@ -14,6 +25,7 @@ export function wsVisitors(};}>) {+ guardSocket(socket, req);const { params } = req;const sendCount = () => {eventBuffer@@ -52,6 +64,7 @@ export async function wsProjectEvents(};}>) {+ guardSocket(socket, req);const { params } = req;const userId = req.session?.userId;@@ -93,6 +106,7 @@ export async function wsProjectNotifications(};}>) {+ guardSocket(socket, req);const { params } = req;const userId = req.session?.userId;@@ -134,6 +148,7 @@ export async function wsOrganizationEvents(};}>) {+ guardSocket(socket, req);const { params } = req;const userId = req.session?.userId;diff --git a/apps/api/src/index.ts b/apps/api/src/index.tsindex d7d289b55..6a3815cbc 100644--- a/apps/api/src/index.ts+++ b/apps/api/src/index.ts@@ -23,13 +23,21 @@ const startServer = async () => {logger.info('Registering graceful shutdown handlers');process.on('SIGTERM', async () => await shutdown(fastify, 'SIGTERM', 0));process.on('SIGINT', async () => await shutdown(fastify, 'SIGINT', 0));- process.on('uncaughtException', async (error) => {- logger.error({ err: error }, 'Uncaught exception');- await shutdown(fastify, 'uncaughtException', 1);++ // After an uncaughtException / unhandledRejection the process state+ // is corrupt — don't try to gracefully drain queues/DBs. Log and+ // exit immediately so Docker can respawn the container. Anything+ // slower than this lets bad requests keep hitting a poisoned process+ // and risks blocking past Docker's stop_grace_period (→ SIGKILL).+ process.on('uncaughtException', (error) => {+ logger.fatal({ err: error }, 'Uncaught exception — exiting');+ // Flush pino, then hard-exit. unref() so the safety net doesn't+ // keep the loop alive on its own.+ setTimeout(() => process.exit(1), 1000).unref();});- process.on('unhandledRejection', async (reason, promise) => {- logger.error({ reason, promise }, 'Unhandled rejection');- await shutdown(fastify, 'unhandledRejection', 1);+ process.on('unhandledRejection', (reason, promise) => {+ logger.fatal({ reason, promise }, 'Unhandled rejection — exiting');+ setTimeout(() => process.exit(1), 1000).unref();});}diff --git a/apps/api/src/utils/graceful-shutdown.ts b/apps/api/src/utils/graceful-shutdown.tsindex d85075915..aac69538a 100644--- a/apps/api/src/utils/graceful-shutdown.ts+++ b/apps/api/src/utils/graceful-shutdown.ts@@ -42,6 +42,20 @@ export async function shutdown(setShuttingDown(true);+ // Hard deadline: if any close() below hangs (Kafka producer stuck,+ // Redis still connecting, BullMQ wait), force-exit before Docker's+ // stop_grace_period elapses. Without this the container can sit in+ // "Stopping" until SIGKILL (exit 137) and look like a real crash.+ const forceExitMs = Number(process.env.SHUTDOWN_FORCE_EXIT_MS || '15000');+ const forceExit = setTimeout(() => {+ logger.error(+ { signal, forceExitMs },+ 'Graceful shutdown timed out — forcing exit',+ );+ process.exit(exitCode);+ }, forceExitMs);+ forceExit.unref();+// Step 1: Wait for load balancer to stop sending traffic (matches preStop sleep)const gracePeriod = Number(process.env.SHUTDOWN_GRACE_PERIOD_MS || '5000');await new Promise((resolve) => setTimeout(resolve, gracePeriod));@@ -122,5 +136,6 @@ export async function shutdown(}logger.info('Graceful shutdown completed');+ clearTimeout(forceExit);process.exit(exitCode);}diff --git a/apps/worker/src/boot-workers.ts b/apps/worker/src/boot-workers.tsindex b90b4f793..5324fce9e 100644--- a/apps/worker/src/boot-workers.ts+++ b/apps/worker/src/boot-workers.ts@@ -335,18 +335,30 @@ export function bootWorkers() {eventName: string,evtOrExitCodeOrError: number | string | Error) {- // Log the actual error details for unhandled rejections/exceptions- if (evtOrExitCodeOrError instanceof Error) {+ logger.info(+ { code: evtOrExitCodeOrError, eventName },+ 'Starting graceful shutdown'+ );++ // Hard deadline: if cron drain or worker.close() hangs, force-exit+ // before Docker's stop_grace_period elapses. Without this the+ // container sits in "Stopping" until SIGKILL (exit 137) and looks+ // like a real crash to the swarm.+ const forceExitMs = Number(+ process.env.SHUTDOWN_FORCE_EXIT_MS || '20000'+ );+ const exitCode = Number.isNaN(+evtOrExitCodeOrError)+ ? 1+ : +evtOrExitCodeOrError;+ const forceExit = setTimeout(() => {logger.error(- { err: evtOrExitCodeOrError, eventName },- 'Unhandled error triggered shutdown'- );- } else {- logger.info(- { code: evtOrExitCodeOrError, eventName },- 'Starting graceful shutdown'+ { eventName, forceExitMs },+ 'Graceful shutdown timed out — forcing exit');- }+ process.exit(exitCode);+ }, forceExitMs);+ forceExit.unref();+try {const time = performance.now();@@ -374,20 +386,30 @@ export function bootWorkers() {'exit handler error');}- const exitCode = Number.isNaN(+evtOrExitCodeOrError)- ? 1- : +evtOrExitCodeOrError;+ clearTimeout(forceExit);process.exit(exitCode);}- ['uncaughtException', 'unhandledRejection', 'SIGTERM', 'SIGINT'].forEach(- (evt) => {- process.on(evt, (code) => {- setShuttingDown(true);- exitHandler(evt, code);- });- }- );+ // SIGTERM / SIGINT: drain in-flight jobs, then exit.+ ['SIGTERM', 'SIGINT'].forEach((evt) => {+ process.on(evt, (code) => {+ setShuttingDown(true);+ exitHandler(evt, code);+ });+ });++ // uncaughtException / unhandledRejection: process state is corrupt.+ // Don't try to drain — log and exit fast so Docker respawns us.+ process.on('uncaughtException', (error) => {+ logger.fatal({ err: error }, 'Uncaught exception — exiting');+ setShuttingDown(true);+ setTimeout(() => process.exit(1), 1000).unref();+ });+ process.on('unhandledRejection', (reason, promise) => {+ logger.fatal({ reason, promise }, 'Unhandled rejection — exiting');+ setShuttingDown(true);+ setTimeout(() => process.exit(1), 1000).unref();+ });return workers;}