OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
ralph(M4-001): config/env.ts: zod-validated sole env reader for the V2 path (main.ts + core); V1 boot byte-untouched
ralphad7bd9df91b9
diff --git a/apps/api/src/config/env.ts b/apps/api/src/config/env.tsnew file mode 100644index 000000000..46c997fe0--- /dev/null+++ b/apps/api/src/config/env.ts@@ -0,0 +1,90 @@+// The sole `process.env` reader on the V2 boot path (main.ts + core wiring),+// per TARGET_ARCHITECTURE §7 "apps/api — three files". `packages/db` and+// `packages/redis` keep reading their own env until they grow factories —+// an accepted pragmatic deviation (ADR-007 §7) — so this catalogue covers+// only what `main.ts` itself reads today: TZ, ROLE, LOG_LEVEL, API_PORT and+// SELF_HOSTED.+//+// Invalid config fails boot loudly, with every issue reported at once —+// never a fail-fast on the first bad var.++import { z } from 'zod';++export const ROLE_VALUES = ['api', 'worker', 'all'] as const;+export type Role = (typeof ROLE_VALUES)[number];++const DEFAULT_API_PORT = 3000;+const DEFAULT_LOG_LEVEL = 'info';+const TRUE_STRING = 'true';++// An unset or blank var should fall through to the default, matching the+// `value?.trim() || fallback` idiom the ported reads used before this file+// existed — `.default()` alone only fires on `undefined`, not `""`.+function blankToUndefined(value: unknown): unknown {+ if (typeof value !== 'string') {+ return value;+ }+ const trimmed = value.trim();+ return trimmed === '' ? undefined : trimmed;+}++/**+ * Same doctrine as `ENABLED_QUEUES` (apps/worker/src/boot-workers.ts's+ * `assertKnownQueue`): a stale or mistyped value fails boot loudly, naming+ * both the offending value and the accepted set.+ */+const roleSchema = z.preprocess(+ blankToUndefined,+ z+ .string()+ .default('api')+ .superRefine((value, ctx) => {+ if (!(ROLE_VALUES as readonly string[]).includes(value)) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: `ROLE: unknown value "${value}". Accepted values: ${ROLE_VALUES.join(', ')}.`,+ });+ }+ })+ // Refine before transform (TARGET_ARCHITECTURE §7): the cast is only+ // ever observed once the refinement above has already accepted the+ // value.+ .transform((value) => value as Role)+);++const envSchema = z.object({+ ROLE: roleSchema,+ LOG_LEVEL: z.preprocess(+ blankToUndefined,+ z.string().default(DEFAULT_LOG_LEVEL)+ ),+ API_PORT: z.coerce.number().int().min(0).default(DEFAULT_API_PORT),+ SELF_HOSTED: z+ .string()+ .optional()+ .default('false')+ .transform((value) => value === TRUE_STRING),+});++export type Config = z.infer<typeof envSchema>;++function formatIssues(issues: z.ZodIssue[]): string {+ return issues+ .map((issue) => ` - ${issue.path.join('.') || '(root)'}: ${issue.message}`)+ .join('\n');+}++/**+ * Validates every V2-path env var in one pass. Throws with every issue+ * listed — never just the first one — so a broken boot names its whole+ * problem in one error.+ */+export function loadConfig(source: NodeJS.ProcessEnv = process.env): Config {+ const result = envSchema.safeParse(source);+ if (!result.success) {+ throw new Error(+ `Invalid environment configuration:\n${formatIssues(result.error.issues)}`+ );+ }+ return result.data;+}diff --git a/apps/api/src/main.ts b/apps/api/src/main.tsindex f32a453a9..42ef23077 100644--- a/apps/api/src/main.ts+++ b/apps/api/src/main.ts@@ -18,37 +18,32 @@ import {queues,} from '@openpanel/core';import pino from 'pino';+import { type Config, loadConfig } from './config/env';-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' });+// Used only to report a config error itself — the real level isn't known+// until `config/env.ts` has validated `LOG_LEVEL`.+const BOOTSTRAP_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.+ * `config/env.ts` is the sole `process.env` reader on this path; an invalid+ * value fails boot loudly, naming every offending value at once (never just+ * the first), instead of being silently ignored or misinterpreted.*/-function assertKnownRole(value: string): asserts value is Role {- if ((ROLE_VALUES as readonly string[]).includes(value)) {- return;+function loadConfigOrExit(): Config {+ try {+ return loadConfig();+ } catch (error) {+ pino({ name: 'api', level: BOOTSTRAP_LOG_LEVEL }).fatal(+ { err: error },+ 'Refusing to start'+ );+ process.exit(1);}- 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;-}+const config = loadConfigOrExit();+const logger = pino({ name: 'api', level: config.LOG_LEVEL });/*** `AppDeps.producers` needs a real `QueueProducerHandle`, but core's exports@@ -89,16 +84,13 @@ function buildDeps(): AppDeps {buffers: undefined,producers: stubProducers(),logger,- config: { selfHosted: process.env.SELF_HOSTED === 'true' },+ config: { selfHosted: config.SELF_HOSTED },};}async function main() {- const role = resolveRole();- const port = Number.parseInt(- process.env.API_PORT ?? String(DEFAULT_PORT),- 10- );+ const role = config.ROLE;+ const port = config.API_PORT;const deps = buildDeps();const app = opsRoutes(deps);