Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

ralph(M3-CLOSE-002): V2 boot entrypoint: apps/api/src/main.ts boots core on Bun as ROLE=api against local services

ralphb677dd6efbe3
diff --git a/apps/api/e2e/boot-proof.sh b/apps/api/e2e/boot-proof.sh
new file mode 100755
index 000000000..1ef2c44eb
--- /dev/null
+++ b/apps/api/e2e/boot-proof.sh
@@ -0,0 +1,145 @@
+#!/usr/bin/env bash
+# M3-CLOSE-002 verification: proves `bun run apps/api/src/main.ts` actually
+# boots, rather than merely typechecking. Three assertions:
+#
+# 1. ROLE=api serves healthz 200 and /metrics 200 on a configurable port.
+# 2. An unknown ROLE fails boot loudly (non-zero exit, named value in the
+# message) — same doctrine as ENABLED_QUEUES.
+# 3. SIGTERM shuts the process down within 5s, exit code 0, no orphan left
+# behind.
+#
+# Run from anywhere: `bash apps/api/e2e/boot-proof.sh`.
+
+set -u
+
+REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)"
+cd "$REPO_ROOT" || exit 1
+
+MAIN_TS="apps/api/src/main.ts"
+SHUTDOWN_TIMEOUT_S=5
+FAILURES=0
+
+pass() { echo "PASS: $1"; }
+fail() {
+ echo "FAIL: $1"
+ FAILURES=$((FAILURES + 1))
+}
+
+# A real free port, not a guessed constant — this box runs other processes.
+find_free_port() {
+ bun -e 'const s = Bun.listen({ port: 0, hostname: "127.0.0.1", socket: { data() {} } }); console.log(s.port); s.stop();'
+}
+
+# --- Part 1: unknown ROLE fails boot loudly ------------------------------
+
+UNKNOWN_LOG="$(mktemp)"
+ROLE=bogus API_PORT=0 bun run "$MAIN_TS" >"$UNKNOWN_LOG" 2>&1
+UNKNOWN_EXIT=$?
+
+if [ "$UNKNOWN_EXIT" -ne 0 ]; then
+ pass "unknown ROLE exits non-zero (got $UNKNOWN_EXIT)"
+else
+ fail "unknown ROLE should exit non-zero, got $UNKNOWN_EXIT"
+fi
+
+if grep -qi 'unknown value' "$UNKNOWN_LOG" && grep -q 'bogus' "$UNKNOWN_LOG"; then
+ pass "unknown ROLE names the offending value in a clear message"
+else
+ fail "unknown ROLE message doesn't name the value — log follows:"
+ cat "$UNKNOWN_LOG"
+fi
+rm -f "$UNKNOWN_LOG"
+
+# --- Part 2: ROLE=api boots and serves healthz + /metrics ----------------
+
+PORT="$(find_free_port)"
+BOOT_LOG="$(mktemp)"
+
+ROLE=api API_PORT="$PORT" bun run "$MAIN_TS" >"$BOOT_LOG" 2>&1 &
+BOOT_PID=$!
+
+READY=0
+for _ in $(seq 1 50); do
+ if curl -s -o /dev/null "http://127.0.0.1:$PORT/healthz/live"; then
+ READY=1
+ break
+ fi
+ # A dead boot process will never become ready — stop waiting for it.
+ if ! kill -0 "$BOOT_PID" 2>/dev/null; then
+ break
+ fi
+ sleep 0.1
+done
+
+if [ "$READY" -ne 1 ]; then
+ fail "server on port $PORT never became ready — log follows:"
+ cat "$BOOT_LOG"
+ kill -9 "$BOOT_PID" 2>/dev/null
+ rm -f "$BOOT_LOG"
+ echo "boot-proof.sh: $FAILURES failure(s)"
+ exit 1
+fi
+
+HEALTHZ_CODE=$(curl -s -o /dev/null -w '%{http_code}' "http://127.0.0.1:$PORT/healthz/live")
+if [ "$HEALTHZ_CODE" = "200" ]; then
+ pass "GET /healthz/live -> 200"
+else
+ fail "GET /healthz/live -> $HEALTHZ_CODE, expected 200"
+fi
+
+METRICS_CODE=$(curl -s -o /dev/null -w '%{http_code}' "http://127.0.0.1:$PORT/metrics")
+if [ "$METRICS_CODE" = "200" ]; then
+ pass "GET /metrics -> 200"
+else
+ fail "GET /metrics -> $METRICS_CODE, expected 200"
+fi
+
+# --- Part 3: SIGTERM shuts down within 5s, exit 0, no orphan -------------
+
+kill -TERM "$BOOT_PID"
+
+WAITED=0
+while kill -0 "$BOOT_PID" 2>/dev/null; do
+ sleep 0.1
+ WAITED=$((WAITED + 1))
+ if [ "$WAITED" -ge $((SHUTDOWN_TIMEOUT_S * 10)) ]; then
+ break
+ fi
+done
+
+if kill -0 "$BOOT_PID" 2>/dev/null; then
+ fail "process still alive ${SHUTDOWN_TIMEOUT_S}s after SIGTERM — killing it"
+ kill -9 "$BOOT_PID" 2>/dev/null
+ wait "$BOOT_PID" 2>/dev/null
+else
+ wait "$BOOT_PID" 2>/dev/null
+ SHUTDOWN_EXIT=$?
+ pass "process exited within ${SHUTDOWN_TIMEOUT_S}s of SIGTERM"
+ if [ "$SHUTDOWN_EXIT" -eq 0 ]; then
+ pass "SIGTERM shutdown exit code 0 (got $SHUTDOWN_EXIT)"
+ else
+ fail "SIGTERM shutdown exit code $SHUTDOWN_EXIT, expected 0"
+ fi
+fi
+
+# The process itself is gone by now; confirm nothing it spawned lingers.
+sleep 0.3
+ORPHANS="$(pgrep -f "$MAIN_TS" || true)"
+if [ -z "$ORPHANS" ]; then
+ pass "no orphan process left behind"
+else
+ fail "orphan process(es) still running: $ORPHANS"
+ # shellcheck disable=SC2086
+ kill -9 $ORPHANS 2>/dev/null
+fi
+
+rm -f "$BOOT_LOG"
+
+echo
+if [ "$FAILURES" -eq 0 ]; then
+ echo "boot-proof.sh: all checks passed"
+ exit 0
+else
+ echo "boot-proof.sh: $FAILURES failure(s)"
+ exit 1
+fi
diff --git a/apps/api/package.json b/apps/api/package.json
index 4422248be..69b6860cd 100644
--- a/apps/api/package.json
+++ b/apps/api/package.json
@@ -31,6 +31,7 @@
"@openpanel/auth": "workspace:^",
"@openpanel/common": "workspace:*",
"@openpanel/constants": "workspace:*",
+ "@openpanel/core": "workspace:*",
"@openpanel/db": "workspace:*",
"@openpanel/geo": "workspace:*",
"@openpanel/integrations": "workspace:^",
diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts
new file mode 100644
index 000000000..f32a453a9
--- /dev/null
+++ b/apps/api/src/main.ts
@@ -0,0 +1,153 @@
+// V2 boot entrypoint (ADR-007 §7 "apps/api — three files"; TARGET_ARCHITECTURE
+// §7 main.ts boot order). Runs on Bun; the V1 Fastify boot at `./index.ts`
+// keeps serving the golden harness untouched until `apps/worker` is deleted
+// at P9.
+//
+// This is the M3 gate boot only: db/ch/redis/clients/buffers are not wired
+// into `AppDeps` yet — their types stay the `unknown` stubs `context.ts`
+// declares until P3/P4/P8 land the real clients — so only the ops surface
+// (healthz + metrics) is mounted here. `dashboardRoutes`/`publicApiRoutes`
+// land with their first module (see `rest.routes.ts`).
+
+process.env.TZ = 'UTC';
+
+import {
+ type AppDeps,
+ opsRoutes,
+ type QueueProducerHandle,
+ queues,
+} from '@openpanel/core';
+import pino from 'pino';
+
+const ROLE_VALUES = ['api', 'worker', 'all'] as const;
+type Role = (typeof ROLE_VALUES)[number];
+
+const DEFAULT_PORT = 3000;
+const SHUTDOWN_FORCE_EXIT_MS = 5000;
+
+const logger = pino({ name: 'api', level: process.env.LOG_LEVEL || 'info' });
+
+/**
+ * Same doctrine as `ENABLED_QUEUES` (apps/worker/src/boot-workers.ts's
+ * `assertKnownQueue`): a stale or mistyped value fails boot loudly, naming
+ * the offending value and the accepted set, instead of being silently
+ * ignored or misinterpreted.
+ */
+function assertKnownRole(value: string): asserts value is Role {
+ if ((ROLE_VALUES as readonly string[]).includes(value)) {
+ return;
+ }
+ logger.fatal(
+ { value, accepted: ROLE_VALUES },
+ `ROLE: unknown value "${value}". Accepted values: ${ROLE_VALUES.join(', ')}.`
+ );
+ process.exit(1);
+}
+
+function resolveRole(): Role {
+ const value = process.env.ROLE?.trim() || 'api';
+ assertKnownRole(value);
+ return value;
+}
+
+/**
+ * `AppDeps.producers` needs a real `QueueProducerHandle`, but core's exports
+ * map (ADR-008) only publishes the type — `createProducers` is internal.
+ * Every registry queue's `jobs` map is still empty (no module has landed
+ * one, see jobs.registry.ts), so there is nothing to enqueue yet; this stub
+ * satisfies the type with no Redis connection. It is replaced by a real
+ * `createProducers` call site inside core once a module needs to enqueue.
+ */
+function stubProducers(): QueueProducerHandle {
+ const emptyQueues = Object.fromEntries(
+ Object.keys(queues).map((name) => [name, {}])
+ ) as QueueProducerHandle['queues'];
+
+ const notWired = (): never => {
+ throw new Error('Job producers are not wired up yet (M3 boot stub)');
+ };
+
+ return {
+ queues: emptyQueues,
+ scope: () => emptyQueues,
+ enqueue: notWired,
+ remove: notWired,
+ bullQueues: [],
+ close: () => Promise.resolve(),
+ };
+}
+
+function buildDeps(): AppDeps {
+ return {
+ // db/ch/redis/clients/buffers are `unknown` stubs in context.ts until
+ // P3/P4/P8 land the real clients — reading one before its type lands is
+ // meant to be a compile error, not a runtime `undefined`.
+ db: undefined,
+ ch: undefined,
+ redis: undefined,
+ clients: undefined,
+ buffers: undefined,
+ producers: stubProducers(),
+ logger,
+ config: { selfHosted: process.env.SELF_HOSTED === 'true' },
+ };
+}
+
+async function main() {
+ const role = resolveRole();
+ const port = Number.parseInt(
+ process.env.API_PORT ?? String(DEFAULT_PORT),
+ 10
+ );
+ const deps = buildDeps();
+
+ const app = opsRoutes(deps);
+
+ if (role !== 'api') {
+ logger.info(
+ { role },
+ 'ROLE=%s: worker/ingest bootstrap (workers, schedulers, Kafka consumer) is not implemented yet — running the HTTP ops surface only',
+ role
+ );
+ }
+
+ app.listen(port, () => {
+ logger.info({ role, port }, 'API listening');
+ });
+
+ let shuttingDown = false;
+ const shutdown = async (signal: string) => {
+ if (shuttingDown) {
+ return;
+ }
+ shuttingDown = true;
+ logger.info({ signal }, 'Starting graceful shutdown');
+
+ const forceExit = setTimeout(() => {
+ logger.error({ signal }, 'Graceful shutdown timed out — forcing exit');
+ process.exit(1);
+ }, SHUTDOWN_FORCE_EXIT_MS);
+ forceExit.unref();
+
+ try {
+ await app.stop();
+ await deps.producers.close();
+ logger.info('Graceful shutdown completed');
+ clearTimeout(forceExit);
+ process.exit(0);
+ } catch (error) {
+ logger.error({ err: error }, 'Error during graceful shutdown');
+ clearTimeout(forceExit);
+ process.exit(1);
+ }
+ };
+
+ process.on('SIGTERM', () => {
+ shutdown('SIGTERM');
+ });
+ process.on('SIGINT', () => {
+ shutdown('SIGINT');
+ });
+}
+
+main();
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 418d50715..4877bc324 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -137,6 +137,9 @@ importers:
'@openpanel/constants':
specifier: workspace:*
version: link:../../packages/constants
+ '@openpanel/core':
+ specifier: workspace:*
+ version: link:../../packages/core
'@openpanel/db':
specifier: workspace:*
version: link:../../packages/db