Skip to content

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

chore(core): trim comments in shared code, http, rpc and tests

Carl-Gerhard Lindesvärd610ed824b2d8
diff --git a/packages/core/scripts/get-bots.ts b/packages/core/scripts/get-bots.ts
index 82bd775dc..ab892f2c5 100644
--- a/packages/core/scripts/get-bots.ts
+++ b/packages/core/scripts/get-bots.ts
@@ -7,25 +7,20 @@ const __dirname = dirname(__filename);
import yaml from 'js-yaml';
-// Regex special characters that indicate we need actual regex
const regexSpecialChars = /[|^$.*+?(){}[\]\\]/;
-// User agents that must NEVER be treated as bots, even though the upstream
-// device-detector list flags them. Its "Generic Bot" pattern lumps bare
-// runtime/client identifiers (e.g. `node`, `Node.js`) into an anchored
-// alternation because browsers never send them — but legitimate server-side
-// traffic does. We only want to flag traffic whose user agent *explicitly*
-// identifies itself as a bot (handled by the separate `bot|crawler|spider...`
-// heuristic), so these plain identifiers are stripped out of the generated
-// patterns here. This runs on every regen, so upstream can never re-introduce
-// the false positives. Values are matched against single alternation branches,
-// so regex metacharacters must be escaped exactly as they appear upstream.
+// User agents that must NEVER be treated as bots even though the upstream
+// device-detector list flags them: its "Generic Bot" pattern lumps bare runtime
+// identifiers (`node`, `Node.js`) into an anchored alternation, but legitimate
+// server-side traffic sends them. Only user agents that explicitly identify as
+// a bot (the separate `bot|crawler|spider...` heuristic) are flagged. Values are
+// matched against single alternation branches, so metacharacters must be
+// escaped exactly as upstream spells them.
export const ALLOWLISTED_BOT_UA_TOKENS = new Set(['node', 'Node\\.js']);
-// Removes allowlisted identifiers from anchored exact-match groups such as
-// `^(?:chrome|node|Node\.js|url)$`, leaving the genuinely suspicious branches
-// intact. If a group ends up empty it is dropped together with a trailing `|`
-// so the surrounding alternation stays valid.
+// Removes allowlisted identifiers from anchored groups such as
+// `^(?:chrome|node|Node\.js|url)$`. An emptied group is dropped with its
+// trailing `|` so the alternation stays valid.
export function stripAllowlistedTokens(regex: string): string {
return regex.replace(
/\^\(\?:([^)]+)\)\$\|?/g,
@@ -92,8 +87,7 @@ async function main() {
}
}
-// Only fetch + regenerate when run directly (e.g. `pnpm gen:bots`), so the
-// transformation helpers can be imported and unit-tested without a network call.
+// Only fetch when run directly, so the helpers can be unit-tested without a network call.
if (process.argv[1] === __filename) {
main();
}
diff --git a/packages/core/scripts/get-datacenter-asns.ts b/packages/core/scripts/get-datacenter-asns.ts
index cf4f19c76..ff0988ed2 100644
--- a/packages/core/scripts/get-datacenter-asns.ts
+++ b/packages/core/scripts/get-datacenter-asns.ts
@@ -5,13 +5,10 @@ import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
-// Upstream list of Autonomous System Numbers that belong to datacenters /
-// hosting providers (AWS, GCP, Azure, OVH, Hetzner, DigitalOcean, …). Traffic
-// originating from these ASNs is almost never a real end user browsing a site;
-// it is scrapers, monitors and automated clients running on rented compute.
-// We resolve an IP's ASN with MaxMind's GeoLite2-ASN db and check membership in
-// this set. The list is regenerated (never hand-edited) so upstream additions
-// flow in on every `pnpm codegen`.
+// Upstream list of ASNs belonging to datacenters / hosting providers. Traffic
+// from them is almost never a real end user, so an IP's ASN (MaxMind GeoLite2-ASN)
+// is checked for membership in this set. The list is regenerated, never
+// hand-edited, so upstream additions flow in on every `pnpm codegen`.
const SOURCE_URL =
'https://raw.githubusercontent.com/X4BNet/lists_vpn/main/input/datacenter/ASN.txt';
@@ -57,8 +54,7 @@ async function main(): Promise<void> {
console.log(`✅ Generated datacenter-asns.ts with ${asns.length} ASNs`);
}
-// Only fetch + regenerate when run directly, so `parseAsnList` can be imported
-// and unit-tested without a network call.
+// Only fetch when run directly, so `parseAsnList` can be unit-tested without a network call.
if (process.argv[1] === __filename) {
main().catch((error) => {
console.error('Error generating datacenter ASN list:', error);
diff --git a/packages/core/scripts/migrate-code.ts b/packages/core/scripts/migrate-code.ts
index 36c224071..e415685c9 100644
--- a/packages/core/scripts/migrate-code.ts
+++ b/packages/core/scripts/migrate-code.ts
@@ -1,10 +1,7 @@
-// Compatibility entrypoint. `code-migrations` moved to @openpanel/db, but the
-// shipped compose files and the Coolify template still run `cd
-// /app/packages/core && bun scripts/migrate-code.ts`. This forwards so a
-// self-hoster pulling the new image keeps migrating.
-//
-// Delete this the moment self-hosting/docker-compose.template.yml,
-// self-hosting/coolify.yml and.github/smoke/docker-compose.yml name
+// Forwards to `@openpanel/db`'s code migrations: the shipped compose files and
+// the Coolify template still run `cd /app/packages/core && bun
+// scripts/migrate-code.ts`. Delete once self-hosting/docker-compose.template.yml,
+// self-hosting/coolify.yml and .github/smoke/docker-compose.yml name
// `packages/db` instead.
import '@openpanel/db/scripts/migrate-code';
diff --git a/packages/core/src/cacheable-per-deps.ts b/packages/core/src/cacheable-per-deps.ts
index 56821f873..668891151 100644
--- a/packages/core/src/cacheable-per-deps.ts
+++ b/packages/core/src/cacheable-per-deps.ts
@@ -1,26 +1,14 @@
-// `cacheable` for a function that needs the caller's `ServiceDeps`.
+// `cacheable` for a function that needs the caller's `ServiceDeps`. Passing
+// `deps` to `cacheable` directly would key on every argument through
+// `stringify`, serializing the whole Prisma client into the Redis key.
//
-// The three cross-module caches on the runtime path (`getEventMetasCached`,
-// `getProfilesCached`, `getProfilePropertyKeysCached`) wrap a function that now
-// reaches Postgres/ClickHouse through `deps`. Passing `deps` to `cacheable`
-// directly is not an option: it keys on EVERY argument through `stringify`,
-// which walks an object's entries recursively — it would serialize the whole
-// Prisma client into the Redis key.
+// `deps` is not cache identity, so the cacheable is built once per `deps` in a
+// WeakMap. The explicit `name` is part of the Redis key (an inline arrow has no
+// `fn.name`).
//
-// `deps` is not cache identity anyway. It is the scope a call runs in (the
-// process's clients plus this request's logger); two calls with the same
-// arguments are the same call whichever scope makes them. So the cacheable is
-// built once per `deps` and remembered in a WeakMap, and the Redis key stays
-// byte-identical to what the module-scope `cacheable(fn, ttl)` this replaces
-// produced — hence the EXPLICIT `name`, which is what `fn.name` used to supply
-// and what an inline arrow would silently drop.
-//
-// Consequence, stated: `createCtx` builds a fresh deps object per request
-// (context.ts's `installLazyServices`), so the L1 LRU inside `cacheable` is per
-// scope rather than per process. The L2 Redis cache — the shared one, the one
-// that actually saves the query — is unchanged, so a repeat call costs one
-// Redis GET where it used to cost none. A cache that must be process-lived
-// takes `cacheablePerDb` below instead.
+// `createCtx` builds a fresh deps per request, so the L1 LRU is per scope, not
+// per process; the shared L2 Redis cache is unaffected. A cache that must be
+// process-lived takes `cacheablePerDb` below.
import { type CacheableOptions, cacheable } from '@openpanel/redis';
import type { ServiceDeps } from './services';
@@ -71,8 +59,7 @@ export function cacheablePerDeps<A extends unknown[], R>(
return run;
}
-/** What a cache keyed on the Postgres client needs from a scope. `AppDeps`,
- * `Ctx` and `ServiceDeps` all satisfy it. */
+/** What a cache keyed on the Postgres client needs from a scope. */
export type DbScope = Pick<ServiceDeps, 'db'>;
export type CacheablePerDb<A extends unknown[], R> = ((
@@ -84,19 +71,13 @@ export type CacheablePerDb<A extends unknown[], R> = ((
};
/**
- * `cacheablePerDeps` for a cache that must be PROCESS-lived, not scope-lived.
- *
- * The three ingest-path caches (`getClientByIdCached`, `getProjectByIdCached`,
- * `getSalts`) used to live inside a factory that was only ever built once.
- * Keying them on the scope like `cacheablePerDeps` does would hand every
- * request a fresh, empty L1 LRU and split `.clear()`
- * across as many instances as there are requests. Keying on `deps.db` — one
- * Postgres client per process — keeps one instance to read and one to
- * invalidate under any scope.
+ * `cacheablePerDeps` for a cache that must be PROCESS-lived. Keying on the scope
+ * would give every request an empty L1 LRU and split `.clear()` across as many
+ * instances. Keying on `deps.db` (one client per process) keeps one instance to
+ * read and invalidate.
*
- * Safe precisely because `fn` can see nothing but `db`: the closure captures
- * the first caller's scope, and `db` is the key, so there is nothing else in
- * it that could differ between sharers.
+ * Safe because `fn` can see nothing but `db`: the closure captures the first
+ * caller's scope, and nothing else in it could differ between sharers.
*/
export function cacheablePerDb<A extends unknown[], R>(
name: string,
diff --git a/packages/core/src/ch-abortable.ts b/packages/core/src/ch-abortable.ts
index 699a8d1d9..0897fd2b9 100644
--- a/packages/core/src/ch-abortable.ts
+++ b/packages/core/src/ch-abortable.ts
@@ -1,13 +1,10 @@
-// A work scope's ClickHouse reads, bound to that scope's AbortSignal, so a read
-// whose answer nobody can receive stops on the server instead of running to
-// completion.
-//
-// Aborting the HTTP call alone does not stop the query: ClickHouse only cancels
-// on client close for a READ-ONLY query with
+// A work scope's ClickHouse reads, bound to that scope's AbortSignal so an
+// abandoned read stops on the server. Aborting the HTTP call alone does not:
+// ClickHouse cancels on client close only for a READ-ONLY query with
// `cancel_http_readonly_queries_on_client_close` set (measured on 26.1).
-// `readonly: 2` still allows per-query settings and temporary tables, which
+// `readonly: 2` still allows per-query settings and the temporary tables
// `GLOBAL IN` needs. Only `query` is bound: writes go through `insert` and
-// `command`, and must never be stopped halfway.
+// `command` and must never be stopped halfway.
import type { ClickHouseSettings } from '@clickhouse/client';
import type { ClickHouseClient } from './context';
diff --git a/packages/core/src/ch-query.ts b/packages/core/src/ch-query.ts
index 293875bc8..8e5098dbb 100644
--- a/packages/core/src/ch-query.ts
+++ b/packages/core/src/ch-query.ts
@@ -1,18 +1,9 @@
-// Core's ClickHouse read path, bound to the scope's client.
+// Core's ClickHouse read path, bound to the scope's client; it logs through
+// `deps.logger` so the `query info` line carries the request's id.
//
-// `chQuery` / `chQueryWithMeta` wrap `deps.ch` — the same round-robin/retry
-// proxy `main.ts` builds and hands to every scope — and log through
-// `deps.logger`, so the `query info` line carries the request's id.
-//
-// `deps.ch.query` IS `withRetry(client => client.query(...))`. The Int-meta
-// coercion below exists because ClickHouse's JSON format returns every
-// Int*/UInt* column as a string, so a caller's `count: number` only holds if
-// it is parsed back out here. The one field that cannot survive the retry
-// proxy is `host`: it does not report which replica served the query.
-// chart/src/run-query.ts makes the same trade.
-//
-// `@openpanel/db/src/clickhouse/sql` is a value import and stays one: it is a
-// compile-time template tag with no client and no request scope.
+// The Int-meta coercion below exists because ClickHouse's JSON format returns
+// every Int*/UInt* column as a string. `host` cannot survive the retry proxy:
+// it does not report which replica served the query.
import type { ClickHouseSettings, ResponseJSON } from '@clickhouse/client';
import {
@@ -21,8 +12,7 @@ import {
} from '@openpanel/db/src/clickhouse/sql';
import type { ServiceDeps } from './services';
-/** All these two need is the scope's client and its logger — narrowed so the
- * buffers, whose `BufferDeps` is not a `ServiceDeps`, can call them too. */
+/** Narrowed so the buffers, whose `BufferDeps` is not a `ServiceDeps`, can call these too. */
export type ChScope = Pick<ServiceDeps, 'ch' | 'logger'>;
/** A raw statement or a SqlFragment carrying its own bound params. */
diff --git a/packages/core/src/clients/create-clients.ts b/packages/core/src/clients/create-clients.ts
index 6dfde7884..a13e883e6 100644
--- a/packages/core/src/clients/create-clients.ts
+++ b/packages/core/src/clients/create-clients.ts
@@ -1,13 +1,8 @@
-// The `clients` handle on `AppDeps`: a NAMING of what already exists under
-// `src/clients/`, not a new abstraction — every member below is the exact
-// function this package already exports, gathered so a service can reach an
-// outbound client through its scoped `Ctx` instead of importing the module
-// directly. Nothing is constructed here — the geo readers open their mmdb
-// lazily and the email / Discord transports read their own credentials — so
-// building it costs one object literal per process.
-//
-// No `slack` or `ai` member here: a client handle cannot reach up into a
-// module, and those transports live in the single module that calls each.
+// The `clients` handle on `AppDeps`: the functions already exported from
+// `src/clients/`, gathered so a service reaches an outbound client through its
+// scoped `Ctx`. Nothing is constructed here (the geo readers open their mmdb
+// lazily). No `slack` or `ai` member: a client handle cannot reach up into a
+// module, and those transports live in the module that calls each.
import { sendEmail } from './email';
import { getAsnInfo, getGeoLocation } from './geo';
diff --git a/packages/core/src/clients/datacenter-asns.test.ts b/packages/core/src/clients/datacenter-asns.test.ts
index 2d00d783d..427918cdd 100644
--- a/packages/core/src/clients/datacenter-asns.test.ts
+++ b/packages/core/src/clients/datacenter-asns.test.ts
@@ -1,12 +1,8 @@
/**
- * Tests for the generated datacenter/hosting ASN list used to flag likely-bot
- * traffic. These exercise the pure list membership (no MaxMind db needed, which
- * is git-ignored and only present after `pnpm codegen`), plus the parser that
- * generates the list. They guard two things:
- * 1. Known hosting providers (AWS, GCP, Azure, OVH, …) stay classified as
- * datacenters, so a regen from upstream can never silently drop them.
- * 2. Residential ISPs (Comcast, AT&T, …) are NOT in the list, so we never
- * mark real end users as bots.
+ * Tests for the generated datacenter/hosting ASN list, exercising list
+ * membership (no MaxMind db needed) and the parser. Known hosting providers must
+ * stay classified as datacenters, and residential ISPs must NOT be in the list,
+ * so real end users are never marked as bots.
*/
import { describe, expect, it } from 'bun:test';
diff --git a/packages/core/src/clients/email.ts b/packages/core/src/clients/email.ts
index dba64c0a3..d95c48722 100644
--- a/packages/core/src/clients/email.ts
+++ b/packages/core/src/clients/email.ts
@@ -1,18 +1,9 @@
-// @openpanel/email stays its own package — the react-email JSX toolchain
-// doesn't belong in core; core wraps it as clients/email.
-//
-// Loaded lazily, deliberately: @openpanel/email depends on @openpanel/db (to
-// check email-unsubscribe rows before sending), and @openpanel/db still
-// depends on @openpanel/core for shared crypto/logging utilities that
-// haven't moved yet. A static top-level import here would make core's own
-// barrel eagerly load @openpanel/db while core is still mid-evaluation — the
-// cycle resolves core's own exports as undefined partway through. Deferring
-// the import to call time sidesteps it: by the time anything actually sends
-// an email, core has finished loading.
+// Loaded lazily: @openpanel/email depends on @openpanel/db, which depends on
+// @openpanel/core, so a static import would make core's barrel load
+// @openpanel/db mid-evaluation and resolve core's own exports as undefined.
//
// No `ProviderError`: `@openpanel/email` swallows every Resend and SMTP failure
-// itself and returns `null`, so nothing reaches this wrapper to classify.
-// Classifying it means changing that package, which is outside this seam.
+// and returns `null`, so nothing reaches this wrapper to classify.
import type { EmailData, EmailTemplate } from '@openpanel/email';
diff --git a/packages/core/src/clients/geo.ts b/packages/core/src/clients/geo.ts
index 383e12dbe..8dd72e3a6 100644
--- a/packages/core/src/clients/geo.ts
+++ b/packages/core/src/clients/geo.ts
@@ -1,9 +1,6 @@
-// The one client with no `ProviderError`: there is no third party on the other
-// end. Both lookups read a bundled MaxMind `.mmdb`, so an IP the database does
-// not carry is a missing thing and comes back as the default value, and a
-// database that will not load fails identically on every retry.
-// `ingest.service.ts` therefore has no failure to classify — it reads a value,
-// never a throw.
+// The one client with no `ProviderError`: both lookups read a bundled MaxMind
+// `.mmdb`, so an IP the database does not carry comes back as the default value
+// and a database that will not load fails identically on every retry.
import { readFile } from 'node:fs/promises';
import path, { dirname } from 'node:path';
@@ -16,16 +13,13 @@ import datacenterAsns from './datacenter-asns';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
-// Resolve a bundled `.mmdb` file, trying the bundled-dist layout first and the
-// local package layout second (mirrors how the file ships via `pnpm codegen`).
-// apps/api's build still bundles every `@openpanel/*` package into one file
-// (tsdown `noExternal`), so `import.meta.url` there resolves to
-// `apps/api/dist/index.js` regardless of this file's nesting under
-// `src/clients/` — three levels up from dist is the repo root.
+// Resolve a bundled `.mmdb` file, bundled-dist layout first, local package
+// second. apps/api bundles every `@openpanel/*` package into one file, so there
+// `import.meta.url` is `apps/api/dist/index.js` and three levels up is the repo root.
async function loadDatabase(filename: string): Promise<ReaderModel | null> {
- // From the api dist bundle
+ // The api dist bundle
const dbPath = path.join(__dirname, `../../../packages/core/${filename}`);
- // From local package (e.g. running core's own tests, unbundled)
+ // The local package (core's own tests, unbundled)
const dbPathLocal = path.join(__dirname, `../../${filename}`);
try {
const dbBuffer = await readFile(dbPath);
@@ -43,7 +37,6 @@ async function loadDatabase(filename: string): Promise<ReaderModel | null> {
}
}
-// Singleton promises - initialized once, awaited on every call
let readerPromise: Promise<ReaderModel | null> | null = null;
let asnReaderPromise: Promise<ReaderModel | null> | null = null;
@@ -109,8 +102,8 @@ export async function getGeoLocation(ip?: string): Promise<GeoLocation> {
cache.set(ip, res);
return res;
} catch {
- // Cache negative lookups too — the reader throws AddressNotFoundError for
- // IPs absent from the db, and re-throwing on every event is wasted work.
+ // Cache negative lookups too: the reader throws AddressNotFoundError for
+ // absent IPs and re-throwing on every event is wasted work.
cache.set(ip, DEFAULT_GEO);
return DEFAULT_GEO;
}
@@ -119,8 +112,7 @@ export async function getGeoLocation(ip?: string): Promise<GeoLocation> {
export interface AsnInfo {
asn: number | undefined;
org: string | undefined;
- // True when the ASN belongs to a datacenter / hosting provider (see
- // `datacenter-asns.ts`). Such traffic is unlikely to be a real end user.
+ // True when the ASN belongs to a datacenter / hosting provider.
isHosting: boolean;
}
@@ -138,8 +130,6 @@ const asnCache = new LRUCache<string, AsnInfo>({
ttlAutopurge: true,
});
-// Resolve the Autonomous System an IP belongs to and whether it is a known
-// datacenter / hosting network. Used to flag (not block) likely-bot traffic.
export async function getAsnInfo(ip?: string): Promise<AsnInfo> {
if (!ip || ignore.includes(ip)) {
return DEFAULT_ASN;
@@ -163,8 +153,8 @@ export async function getAsnInfo(ip?: string): Promise<AsnInfo> {
asnCache.set(ip, res);
return res;
} catch {
- // Cache negative lookups too — the reader throws AddressNotFoundError for
- // IPs absent from the db, and re-throwing on every event is wasted work.
+ // Cache negative lookups too: the reader throws AddressNotFoundError for
+ // absent IPs and re-throwing on every event is wasted work.
asnCache.set(ip, DEFAULT_ASN);
return DEFAULT_ASN;
}
diff --git a/packages/core/src/clients/integrations/discord.ts b/packages/core/src/clients/integrations/discord.ts
index 87fd92d7e..22824a420 100644
--- a/packages/core/src/clients/integrations/discord.ts
+++ b/packages/core/src/clients/integrations/discord.ts
@@ -8,9 +8,7 @@ import {
type WebhookResult,
} from './fetcher';
-// Lives here rather than in integration.constants.ts: a client has no need of
-// another module's vocabulary. It is this transport's own probe wording, and
-// nothing outside this file reads it.
+// This transport's own probe wording, read by nothing outside this file.
const DISCORD_TEST_NOTIFICATION_MESSAGE =
'**🧪 Test [OpenPanel.dev](<https://openpanel.dev/>)**\nIf you can read this, your Discord webhook is functioning correctly!\n';
@@ -22,10 +20,9 @@ export function sendDiscordNotification({
webhookUrl: string;
message: string;
/**
- * Server callers MUST pass `safeWebhookFetcher` from the integration
- * module's `src/safe-fetcher.ts` - the
- * webhook URL is user-supplied and stored, so sending from inside our network
- * with a bare `fetch` makes this an SSRF probe.
+ * Server callers MUST pass `safeWebhookFetcher` from the integration module's
+ * `src/safe-fetcher.ts`: the webhook URL is user-supplied and stored, so a bare
+ * `fetch` from inside our network makes this an SSRF probe.
*/
fetcher?: WebhookFetcher;
}): Promise<WebhookResult> {
diff --git a/packages/core/src/clients/integrations/fetcher.ts b/packages/core/src/clients/integrations/fetcher.ts
index 276543bd1..fac21d49c 100644
--- a/packages/core/src/clients/integrations/fetcher.ts
+++ b/packages/core/src/clients/integrations/fetcher.ts
@@ -1,15 +1,9 @@
/**
- * Webhook delivery is reachable from two very different places:
- *
- * - the dashboard's "send test notification" button, which runs in the
- * browser and is just the user calling their own webhook, and
- * - the worker, which sends from inside our network and therefore must not be
- * usable as an SSRF probe.
- *
- * Injecting the transport keeps this module browser-safe (a plain `fetch`) while
- * letting server callers pass the SSRF-guarded one from the integration
- * module's `src/safe-fetcher.ts`, which
- * pulls in `node:dns`/`undici` and must never reach a client bundle.
+ * Webhook delivery runs both in the browser (the dashboard's "send test
+ * notification" button) and in the worker, which must not be usable as an SSRF
+ * probe. The injected transport keeps this module browser-safe: server callers
+ * pass the SSRF-guarded fetcher, which pulls in `node:dns`/`undici` and must
+ * never reach a client bundle.
*/
import { isRetryableStatus } from '../provider-error';
@@ -30,10 +24,9 @@ export interface WebhookResult {
ok: boolean;
status: number;
/**
- * Classified once here so no caller re-derives it: 429 and 5xx are worth
- * another delivery attempt, every other 4xx is the destination refusing this
- * exact request. A transport failure that produced no response (DNS, connect,
- * TLS, timeout) is retryable — nothing about the request was rejected.
+ * Classified once here: 429 and 5xx are worth another delivery attempt, any
+ * other 4xx is the destination refusing this exact request. A failure with no
+ * response (DNS, connect, TLS, timeout) is retryable.
*/
retryable: boolean;
}
diff --git a/packages/core/src/clients/provider-error.ts b/packages/core/src/clients/provider-error.ts
index 526893960..a16d62b5b 100644
--- a/packages/core/src/clients/provider-error.ts
+++ b/packages/core/src/clients/provider-error.ts
@@ -1,43 +1,32 @@
-// The one failure type every outbound client raises.
-//
-// A client classifies ONCE, at the edge where it still holds the provider's own
-// status code; a handler then reads `retryable` instead of re-deriving it from
-// a message string. The rule the flag encodes: a retryable failure is rethrown
-// so the queue runs the unit of work again, a permanent refusal is logged and
-// swallowed, because a retry cannot change it.
+// A client classifies once, where it still holds the provider's status code. A
+// retryable failure is rethrown so the queue retries; a permanent refusal is
+// logged and swallowed, because a retry cannot change it.
-/** Too Many Requests — the provider is asking for the same call, later. */
+/** Too Many Requests. */
export const RATE_LIMITED_STATUS = 429;
-/** The first status in the "the provider is broken, not the request" range. */
+/** The first status in the "provider is broken, not the request" range. */
const SERVER_ERROR_STATUS_FLOOR = 500;
/**
* 429 and 5xx are worth another attempt; every other 4xx is the provider
- * refusing THIS request (bad credential, unknown bucket, malformed body) and
- * will refuse it identically next time.
+ * refusing THIS request and will refuse it identically next time.
*/
export function isRetryableStatus(status: number): boolean {
return status === RATE_LIMITED_STATUS || status >= SERVER_ERROR_STATUS_FLOOR;
}
export interface ProviderErrorOptions {
- /** Provider status, when the call got far enough to have one. */
status?: number;
/**
- * Overrides the status classification. Only for failures that never reached
- * the provider — DNS, connect, TLS, timeout — where there is no status to
- * read and another attempt genuinely can succeed.
+ * Overrides the status classification, for failures that never reached the
+ * provider (DNS, connect, TLS, timeout) where another attempt can succeed.
*/
retryable?: boolean;
cause?: unknown;
}
-/**
- * A third party refused or failed a call. `provider` names the transport
- * ('slack', 'gcs', 'openai') so a log line identifies the hop without the
- * handler knowing which client it called.
- */
+/** A third party refused or failed a call. `provider` names the transport ('slack', 'gcs', 'openai'). */
export class ProviderError extends Error {
readonly provider: string;
readonly retryable: boolean;
@@ -63,9 +52,9 @@ export function isProviderError(value: unknown): value is ProviderError {
}
/**
- * Every SDK we call reports its HTTP status somewhere different: the AWS SDK
- * under `$metadata.httpStatusCode`, the Google SDK and most fetch wrappers as
- * `code`/`status`/`statusCode`. Read all of them here so no client has to.
+ * Every SDK reports its HTTP status somewhere different: the AWS SDK under
+ * `$metadata.httpStatusCode`, the Google SDK and most fetch wrappers as
+ * `code`/`status`/`statusCode`.
*/
export function providerStatusOf(error: unknown): number | undefined {
if (typeof error !== 'object' || error === null) {
@@ -91,11 +80,7 @@ export function providerStatusOf(error: unknown): number | undefined {
return undefined;
}
-/**
- * Wrap whatever an SDK threw. A `ProviderError` passes through unchanged —
- * it was already classified by the client that raised it, and reclassifying
- * would throw away the one place that had the provider's own answer.
- */
+/** Wrap whatever an SDK threw. A `ProviderError` passes through: it was already classified where the provider's own answer was available. */
export function providerErrorFrom(
provider: string,
error: unknown,
@@ -110,11 +95,7 @@ export function providerErrorFrom(
return new ProviderError(provider, detail, { status, cause: error });
}
-/**
- * Run one outbound call and classify whatever it throws. Every `catch`
- * upstream of it can then read `retryable` instead of inspecting an
- * SDK-specific error shape.
- */
+/** Run one outbound call and classify whatever it throws. */
export async function callProvider<T>(
provider: string,
call: () => Promise<T>
diff --git a/packages/core/src/config.ts b/packages/core/src/config.ts
index b5d15a9a2..7e3431b13 100644
--- a/packages/core/src/config.ts
+++ b/packages/core/src/config.ts
@@ -1,14 +1,6 @@
-// The shape of everything core needs from the environment; only the config
-// loader (`apps/api/src/config/env.ts`) reads `process.env` — it parses,
-// validates and derives, and hands the result down as `AppDeps.config` /
-// `Ctx.config`, so nothing below this file re-derives a value or reaches for
-// `process.env` again.
-//
-// Two conventions hold throughout: - `undefined` means "not set", never
-// "blank". A blank `KEY=` is absent. - a field that only ever had one spelling
-// of a default keeps that default next to the code that documents WHY (e.g. the
-// buffers' batch sizes), so the loader parses and the module decides. Anything
-// DERIVED from more than one variable is resolved here and arrives finished.
+// Only the config loader (`apps/api/src/config/env.ts`) reads `process.env`.
+// `undefined` means "not set", never "blank": a blank `KEY=` is absent. Anything
+// derived from more than one variable is resolved by the loader and arrives finished.
/** Which pino transport ships the logs, and how the service name is built. */
export interface LoggingConfig {
@@ -94,11 +86,9 @@ export const KAFKA_SASL_MECHANISMS = [
export type KafkaSaslMechanism = (typeof KAFKA_SASL_MECHANISMS)[number];
/**
- * TLS/SASL for an external broker. Unauthenticated plaintext when nothing is
- * set. The loader has already checked the combination is coherent (a full
- * credential pair, a known mechanism, TLS options only with TLS); the CA file
- * itself is read where the client is built, so an unreadable path fails there
- * with its own message.
+ * TLS/SASL for an external broker; unauthenticated plaintext when nothing is
+ * set. The CA file is read where the client is built, so an unreadable path
+ * fails there with its own message.
*/
export interface KafkaSecurityConfig {
ssl: {
@@ -189,9 +179,8 @@ export interface SessionConfig {
}
/**
- * Sizing knobs on read and write paths. Every one is a positive integer or
- * `undefined`: a malformed value is not a boot failure, it keeps the default,
- * which is what the modules did when they parsed these themselves.
+ * Sizing knobs on read and write paths. Each is a positive integer or
+ * `undefined`; a malformed value keeps the default instead of failing boot.
*/
export interface QueryConfig {
eventPropertyValueAutocompleteLimit: number | undefined;
diff --git a/packages/core/src/context.test.ts b/packages/core/src/context.test.ts
index e105c5409..cb40b4622 100644
--- a/packages/core/src/context.test.ts
+++ b/packages/core/src/context.test.ts
@@ -8,15 +8,13 @@ import { queues } from './jobs.registry';
import type { Logger } from './logger';
import type { ServiceDeps, Services } from './services';
-// Snapshotted BEFORE `mock.module` below, not after — restoring by re-`import`ing
-// './services' later would resolve the already-mocked registry entry, not the
-// real module (bare `bun test` shares one module registry across every file).
+// Snapshotted BEFORE `mock.module`: re-`import`ing later would resolve the
+// already-mocked registry entry (bare `bun test` shares one module registry).
const realServicesModule = { ...(await import('./services')) };
-// mock.module is not hoisted, so the subject is imported inside beforeAll —
-// see AGENTS.md. Mocking createServices is what makes "not built yet"
-// observable at all — this suite cares about WHEN the factory runs, not what
-// it returns, so the stub container is cast rather than built for real.
+// mock.module is not hoisted, so the subject is imported inside beforeAll.
+// Mocking createServices makes "not built yet" observable: this suite cares
+// about WHEN the factory runs, not what it returns.
const serviceDeps: ServiceDeps[] = [];
const createServices = mock((deps: ServiceDeps): Services => {
serviceDeps.push(deps);
@@ -31,10 +29,9 @@ beforeAll(async () => {
({ createCtx, extendCtx } = await import('./context'));
});
-// Without this, bare `bun test` (one shared module registry, no --isolate)
-// leaks the stub `createServices` — returning `{}` with no `.auth` — into
-// every OTHER file that later imports './context', which is most of the rpc
-// test suite via test/rpc-fixtures.ts's `stubHttpCtx`.
+// Without this, bare `bun test` (one shared module registry) leaks the stub
+// `createServices` (`{}`, no `.auth`) into every other file that imports
+// './context', including most rpc tests via `stubHttpCtx`.
afterAll(() => {
mock.module('./services', () => realServicesModule);
});
diff --git a/packages/core/src/context.ts b/packages/core/src/context.ts
index 8d291e3d3..e7ed9b94b 100644
--- a/packages/core/src/context.ts
+++ b/packages/core/src/context.ts
@@ -1,8 +1,3 @@
-// One boot scope, one work scope, one builder. HTTP routes, tRPC procedures,
-// job handlers and the Kafka consumer all extend the same `Ctx`, so a service
-// written once works under every transport and the requestId minted at the
-// edge reaches the query, the enqueue and the job that enqueue causes.
-
import type { Buffers } from './buffers/create-buffers';
import { bindReadsToSignal } from './ch-abortable';
import type { CoreConfig } from './config';
@@ -12,10 +7,9 @@ import type { SessionValidationResult } from './modules/auth/src/login-session';
import { createServices, type Services } from './services';
import type { CookieJar, CookieOptions } from './shared/cookie';
-// The four boot handles. Each is a TYPE QUERY over the module that
-// constructs the client, so the alias cannot drift from what `main.ts`
-// actually passes; all four are type-only, so core still imports no database
-// at runtime and `bun test` still runs offline.
+// Type queries over the modules that construct the clients, so the aliases
+// cannot drift from what `main.ts` passes. Type-only: core imports no database
+// at runtime and `bun test` runs offline.
export type Db = typeof import('@openpanel/db/src/prisma-client').db;
export type ClickHouseClient =
typeof import('@openpanel/db/src/clickhouse/client').ch;
@@ -24,28 +18,18 @@ export type RedisClient = ReturnType<
>;
export type ServiceClients = import('./clients/create-clients').ServiceClients;
-// The two `@openpanel/db` VALUES core cannot reach through a scope, and the
-// one file allowed to name them: `core-uses-ctx-not-db-internals` exempts
-// this module by path, and it is already where core declares its handles.
-// Both are LAZY, so importing core still constructs no database and
-// `bun test` still runs offline, and neither memoizes its result — the module
-// registry already caches the import, and a second memo is exactly what let
-// the deleted compat seam hand one suite's mocked Prisma client to every
-// later file in the process.
+// `unscopedDb` and the Prisma namespace are lazy so importing core constructs no
+// database. Neither memoizes: the module registry already caches the import, and
+// a second memo once handed one suite's mocked Prisma client to later files.
export type PrismaNamespace =
typeof import('@openpanel/db/src/prisma-client').Prisma;
/**
- * Prisma's JSON sentinels (`DbNull`, `JsonNull`): frozen constants that write
- * an explicit SQL NULL — or a JSON `null` — onto a nullable `Json?` column.
- * They are values on the namespace, not a client, so nothing about them is
- * per-request — but they are still `@openpanel/db` VALUES, so the scope
- * carries them rather than each writer reaching the namespace directly:
- * `main.ts` reads the two off the namespace once and puts them on `AppDeps`;
- * every writer reads `deps.prisma.DbNull`. Two named fields, not the namespace
- * itself — nothing else on it belongs in a request scope, and `Prisma` is a
- * very large type for every consumer's `tsc` to walk.
+ * Prisma's JSON sentinels (`DbNull`, `JsonNull`) that write an explicit SQL NULL
+ * or JSON `null` onto a nullable `Json?` column. The scope carries just these
+ * two instead of the `Prisma` namespace, a very large type for every
+ * consumer's `tsc` to walk.
*/
export interface PrismaSentinels {
DbNull: PrismaNamespace['DbNull'];
@@ -54,34 +38,20 @@ export interface PrismaSentinels {
/**
* The process's Postgres client, for the one path that cannot be handed a
- * scope: `shared/access-lookups.ts`. Its lookups are `cacheable` on their
- * ARGUMENTS, so they cannot take a leading `deps`, and their bare signature is
- * pinned by imports through `packages/db/src/services/access.service.ts` with
- * no app boot at all. It is the same client `main.ts` puts on `AppDeps.db`.
- * Every other caller in core reaches Postgres as `deps.db`.
+ * scope: `shared/access-lookups.ts`, whose lookups are `cacheable` on their
+ * arguments and so cannot take a leading `deps`. Everything else uses `deps.db`.
*/
export function unscopedDb(): Promise<Db> {
return import('@openpanel/db/src/prisma-client').then((m) => m.db);
}
-// Built once by `createBuffers(deps)` in main.ts, never a module singleton.
export type { Buffers } from './buffers/create-buffers';
-// The resolved session. `SessionValidationResult` is Prisma-shaped (Session +
-// User) but the import above is type-only, so nothing of `@openpanel/db` is
-// loaded at runtime — core stays importable with no database, which is what
-// lets `bun test` run offline. It stays defined next to the Prisma-touching
-// session CRUD in `./modules/auth/src/login-session.ts` rather than here, which
-// is the same file that CRUD lazily reaches `@openpanel/db`'s Prisma client
-// from.
export type Session = SessionValidationResult;
-// The parsed environment. `apps/api`'s config/env.ts is the sole reader of
-// process.env and core reads none, so the shape of what core needs is
-// declared in `./config.ts` and arrives here.
export type { CoreConfig } from './config';
-/** Boot scope. Built once in apps/api's main.ts, closed once in shutdown. */
+/** Boot scope. Built once at startup, closed once in shutdown. */
export interface AppDeps {
db: Db;
prisma: PrismaSentinels;
@@ -109,7 +79,7 @@ export interface Ctx {
requestId: string;
}
-/** What HTTP and tRPC add. No req/res in core, from day one. */
+/** What HTTP and tRPC add. */
export interface HttpCtx extends Ctx {
headers: Headers;
ip: string;
@@ -118,9 +88,8 @@ export interface HttpCtx extends Ctx {
session: () => Promise<Session | null>;
setCookie(name: string, value: string, options?: CookieOptions): void;
/**
- * Aborting it stops this request's ClickHouse reads. The request-context
- * derive aborts it when the client disconnects; a transport with a deadline
- * aborts it when the deadline passes. Set only on read (GET/HEAD) requests.
+ * Aborting it stops this request's ClickHouse reads: on client disconnect or,
+ * for a transport with a deadline, when it passes. Set only on GET/HEAD.
*/
cancellation?: AbortController;
}
@@ -138,10 +107,7 @@ export interface ScopeMeta {
signal?: AbortSignal;
}
-/**
- * The single builder. When something new must reach every handler it is added
- * here once and all four transports have it.
- */
+/** The single builder: anything every handler needs is added here once. */
export function createCtx(deps: AppDeps, scope: ScopeMeta): Ctx {
const ctx: Ctx = {
db: deps.db,
@@ -154,7 +120,6 @@ export function createCtx(deps: AppDeps, scope: ScopeMeta): Ctx {
queues: deps.producers.scope({ requestId: scope.requestId }),
config: deps.config,
requestId: scope.requestId,
- // Installed as a getter immediately below.
services: undefined as unknown as Services,
};
@@ -193,8 +158,6 @@ function installLazyServices(ctx: Ctx): void {
});
return built;
},
- // Enumerable so a transport that copies a Ctx keeps the field at all;
- // configurable so one may reinstall it.
enumerable: true,
configurable: true,
});
diff --git a/packages/core/src/http/auth.test.ts b/packages/core/src/http/auth.test.ts
index cc0f59b7a..c70056415 100644
--- a/packages/core/src/http/auth.test.ts
+++ b/packages/core/src/http/auth.test.ts
@@ -7,9 +7,8 @@ import type {
ClientAuthResult,
} from './client-auth';
-// mock.module is not hoisted, so the subject is imported inside beforeAll —
-// see AGENTS.md. Both principals are stubs until P6/P8; mocking them is what
-// lets the macro's two branches be exercised at all.
+// mock.module is not hoisted, so the subject is imported inside beforeAll.
+// Both principals are stubs, which lets the macro's two branches be exercised.
const CLIENT: AuthenticatedClient = {
id: 'client-1',
projectId: 'proj-1',
@@ -103,10 +102,9 @@ test('clientAuth passes the allow list through to the authenticator', async () =
});
});
-// This has TWO 401 bodies and both are a wire contract: the allow-list
-// routers (/export, /insights, /import, /manage) answer with a JSON envelope
-// carrying the validator's own message, and the ingest routers (/track,
-// /event, /profile) answer with that message as plain text.
+// Two 401 bodies, both a wire contract: allow-list routers (/export, /insights,
+// /import, /manage) answer a JSON envelope carrying the validator's message;
+// ingest routers (/track, /event, /profile) answer it as plain text.
test('clientAuth answers 401 with the allow-list body when nothing authenticates', async () => {
result = REFUSAL;
diff --git a/packages/core/src/http/auth.ts b/packages/core/src/http/auth.ts
index 96ae1eba0..78fbc526e 100644
--- a/packages/core/src/http/auth.ts
+++ b/packages/core/src/http/auth.ts
@@ -1,12 +1,7 @@
-// Caller authentication, declared once and requested per route. A macro
-// authenticates the CALLER and stops — a missing authorization check is
-// silent: a broken chart throws, a dropped access check returns 200 with
-// somebody else's data.
-//
-// Elysia's option-bearing macro shape makes `clientAuth: { allow: [...] }`
-// type the resolved client onto the handler, so a route that skips the
-// macro has no `client` binding at all — "did this route authenticate?" is
-// a type question, verified by http/auth.test.ts and `tsc --noEmit`.
+// A macro authenticates the CALLER and stops. A missing authorization check is
+// silent (a dropped access check returns 200 with somebody else's data), so the
+// option-bearing macro types the resolved client onto the handler: a route that
+// skips it has no `client` binding at all.
import { Elysia } from 'elysia';
import type { AppDeps } from '../context';
@@ -15,15 +10,10 @@ import { authenticateClient, type ClientAuthOptions } from './client-auth';
import { requestContext } from './context';
const UNAUTHORIZED = 401;
-/** Allow-list routes answer a 401 with a JSON envelope; ingest routes answer
- * with the refusal message as plain text — both forms are intentional. */
+/** Allow-list routes answer a 401 with a JSON envelope; ingest routes with plain text. */
const UNAUTHORIZED_ERROR = 'Unauthorized';
-/**
- * The named plugin every module reaches through `defineRoutes`. It brings
- * `requestContext(deps)` with it, so `ctx` and the tiers arrive together and a
- * route cannot request a tier without the context that resolves it.
- */
+/** The named plugin every module reaches through `defineRoutes`; it brings `requestContext(deps)` so a route cannot request a tier without its context. */
export function authMacros(deps: AppDeps) {
return new Elysia({ name: 'core/auth-macros' })
.use(requestContext(deps))
diff --git a/packages/core/src/http/bull-board.ts b/packages/core/src/http/bull-board.ts
index 9e24a23c0..a772b2d94 100644
--- a/packages/core/src/http/bull-board.ts
+++ b/packages/core/src/http/bull-board.ts
@@ -1,14 +1,9 @@
-// Bull-board is mounted on the main port, behind the dashboard session
-// guard. This avoids `@bull-board/express` and a second express server —
-// nothing named `@bull-board/fastify` ever existed. `@bull-board/api` +
-// `@bull-board/elysia` are both pinned exact at 9.6.0.
+// Mounted on the main port behind the dashboard session guard. Two things a
+// reader must not mistake for accidents:
//
-// TWO things a reader must not mistake for accidents:
-//
-// 1. **The base path is `/bullboard`, not `/`.** One port serves everything
-// here, so `/` would shadow every other route; the deploy-note is
-// `packages/core/docs/OPS_GRAFANA_MIGRATION.md`. 2. **Pausing `cron` from
-// this UI halts ALL buffer flushing.** Preserved deliberately.
+// 1. The base path is `/bullboard`, not `/`: one port serves everything, so
+// `/` would shadow every other route.
+// 2. Pausing `cron` from this UI halts ALL buffer flushing.
import type { Queue as BullQueue } from 'bullmq';
import { Elysia } from 'elysia';
@@ -22,28 +17,20 @@ const UNAUTHORIZED = 401;
const BULL_BOARD_REALM = 'OpenPanel ops';
/**
- * Mounted only where the role consumes and `DISABLE_BULLBOARD` is unset
- * (main.ts owns both conditions — core reads no environment).
- *
* The guard is `{ as: 'global' }` and re-checks the path itself rather than
* leaning on Elysia's hook scoping: `.use()`-ing a NAMED plugin
* (`@bull-board/elysia`) puts its routes in their own scope, where a `local`
- * hook of the mounting instance would not run at all — and a guard that
- * silently does not run is precisely the failure this must not have. The cost
- * on every other route is one `startsWith`.
+ * hook of the mounting instance would not run at all. The cost on every other
+ * route is one `startsWith`.
*/
export async function bullBoardRoutes(
deps: AppDeps,
queues: BullQueue[]
): Promise<Elysia> {
- // Imported here, not at module scope. `@bull-board/elysia` is CommonJS, so
- // it `require()`s Elysia's CJS build, which `require()`s memoirist — and
- // under Bun 1.4.0 that throws "require() async module ... is unsupported"
- // if it happens while this package's module graph is still evaluating.
- // Deferring it to the one call site that needs it puts the require after
- // evaluation, where it resolves cleanly. Proven by
- // `bun run apps/api/e2e/boot-proof.sh`'s ROLE=worker/all legs, which 401
- // on /bullboard rather than failing to boot.
+ // Imported here, not at module scope: `@bull-board/elysia` is CommonJS and
+ // `require()`s Elysia's CJS build, which under Bun 1.4.0 throws "require()
+ // async module ... is unsupported" while this package's module graph is
+ // still evaluating.
const [{ createBullBoard }, { BullMQAdapter }, { ElysiaAdapter }] =
await Promise.all([
import('@bull-board/api'),
@@ -73,8 +60,7 @@ export async function bullBoardRoutes(
}
// Two gates, both required: a dashboard session proves a human, the
// operator credentials prove an operator. The queue UI can add, retry
- // and clean jobs, so being any signed-up user is not enough
- // (main #511, GHSA-r627-6vrh-65p9).
+ // and clean jobs, so any signed-up user is not enough (GHSA-r627-6vrh-65p9).
if (!(await ctx.session())) {
return status(UNAUTHORIZED);
}
diff --git a/packages/core/src/http/client-auth.ts b/packages/core/src/http/client-auth.ts
index 250882690..83175777f 100644
--- a/packages/core/src/http/client-auth.ts
+++ b/packages/core/src/http/client-auth.ts
@@ -1,28 +1,13 @@
-// Where API/SDK credentials become a client principal.
-//
-// The ingest tier's rules live in `modules/ingest/src/client-auth.ts`; since
-// transport may not deep-import a module, the route that wants the ingest
-// tier hands its own validator down as `clientAuth: { ingest:
-// validateIngestRequest }`.
-//
-// The `allow`-list tier covers export, import and manage clients: identical
-// checks differing only by the accepted `ClientType` set and by the prefix on
-// their error strings, collapsed into `authenticateAllowedClient` below. MCP
-// is NOT here — it authenticates its own `token` form inside
-// `modules/mcp/src/auth.ts`.
-
import type { DbScope } from '../cacheable-per-deps';
import type { HttpCtx } from '../context';
import { verifyClientSecret } from '../shared/client-secret';
import { headerValue, type IngestHeaders } from '../shared/headers';
-/** Refuses a client id that is not a UUID before it ever queries. */
const CLIENT_ID_UUID_REGEX =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
const CLIENT_ID_HEADER = 'openpanel-client-id';
const CLIENT_SECRET_HEADER = 'openpanel-client-secret';
-/** Prisma's `ClientType` enum, by value. */
export type ClientType = 'read' | 'write' | 'root';
export interface AuthenticatedClient {
@@ -33,25 +18,16 @@ export interface AuthenticatedClient {
organizationId: string;
type: ClientType;
/**
- * Whether the supplied client secret VERIFIED against the stored hash.
- * `isBotHook` reads it as "this is a server-side SDK, never a bot", so it
- * follows the verification result, not the presence of a secret string.
+ * Whether the supplied secret VERIFIED against the stored hash. `isBotHook`
+ * reads it as "a server-side SDK, never a bot".
*/
secretVerified: boolean;
}
-/**
- * The surface's name in a refusal message — e.g. `Export: Invalid client
- * secret`. These strings are the 401 BODY on `/export`, `/insights`,
- * `/import` and `/manage`, so they are a wire contract, not decoration.
- */
+/** The surface's name in a refusal message. These strings are the 401 body on `/export`, `/insights`, `/import` and `/manage`: a wire contract. */
export type ClientAuthLabel = 'Export' | 'Import' | 'Manage';
-/**
- * What the ingest tier answers, as transport reads it.
- * `modules/ingest/src/client-auth.ts` owns the rules and returns a wider
- * outcome; only these fields cross the layer boundary.
- */
+/** What the ingest tier answers, as transport reads it; only these fields cross the layer boundary. */
export type IngestTierOutcome =
| {
ok: true;
@@ -65,7 +41,6 @@ export type IngestTierOutcome =
}
| { ok: false; message: string; secretVerified: boolean };
-/** The ingest tier itself, passed in by the route that wants it. */
export type ValidateIngestRequest = (args: {
deps: DbScope;
headers: IngestHeaders;
@@ -78,35 +53,30 @@ export interface ClientAuthOptions {
allow?: ClientType[];
/** Which allow-list surface this route is. */
label?: ClientAuthLabel;
- /** The ingest extension described above, supplied by the ingest module. */
+ /** The ingest tier's validator, supplied by the ingest module. */
ingest?: ValidateIngestRequest;
/** MCP presents `base64(clientId:clientSecret)` instead of the two headers. */
token?: 'basic';
}
/**
- * A refusal is returned, never thrown — same reason
- * `modules/ingest/src/client-auth.ts` gives, and it keeps the choice of 401
- * body shape (plain text on the ingest routes, `{error, message}` JSON on
- * the allow-list ones) a decision of the macro rather than of this function.
+ * A refusal is returned, never thrown, so the route's macro decides the 401
+ * body shape (plain text on ingest routes, `{error, message}` JSON elsewhere).
*/
export type ClientAuthResult =
| { ok: true; client: AuthenticatedClient }
| { ok: false; ingest: boolean; message: string };
-/** What the ingest tier needs beyond the headers: the attribution ip
- * and the body (credential fallback, profile filter, `__revenue` gate). */
+/** What the ingest tier needs beyond the headers. */
export interface ClientAuthRequest {
ip: string;
body: unknown;
}
/**
- * Takes the request's own `Ctx`, not the boot scope. The ingest tier reads only
- * `ctx.db` — `getClientByIdCached`'s L1 is keyed on the Postgres client, so
- * `/track` reaches the one process-lived cache without forcing `ctx.services`.
- * The allow-list tier is not a hot path and goes through `ctx.services.client`
- * like every other handler.
+ * Takes the request's own `Ctx`. The ingest tier reads only `ctx.db`
+ * (`getClientByIdCached`'s L1 is keyed on it), so `/track` never forces
+ * `ctx.services`.
*/
export async function authenticateClient(
ctx: HttpCtx,
@@ -142,27 +112,18 @@ export async function authenticateClient(
};
}
-/** The per-surface "wrong type" message; every other refusal differs only
- * by the label prefix. */
+/** Every refusal other than "wrong type" differs only by the label prefix. */
const FORBIDDEN_TYPE_MESSAGE: Record<ClientAuthLabel, string> = {
Export: 'Export: Client is not allowed to export',
Import: 'Import: Client is not allowed to import',
Manage: 'Manage: Only root clients are allowed to manage resources',
};
-/** A Prisma lookup failure maps onto its own message, unprefixed. */
const MALFORMED_CLIENT_ID_MESSAGE = 'Client ID seems to be malformed';
const PRISMA_KNOWN_REQUEST_ERROR = 'PrismaClientKnownRequestError';
const UNEXPECTED_MESSAGE = 'Unexpected error';
-/**
- * The `allow`-list tier: covers export, import and manage clients, which
- * differ only by the accepted `ClientType` set and by the label their
- * messages carry.
- *
- * `secretVerified` is true on success by construction: this tier verifies the
- * secret, so reaching the return means one was presented and matched.
- */
+/** The `allow`-list tier: export, import and manage clients. */
async function authenticateAllowedClient(
ctx: HttpCtx,
headers: IngestHeaders,
diff --git a/packages/core/src/http/context.test.ts b/packages/core/src/http/context.test.ts
index c94c5f7cd..ffab25a77 100644
--- a/packages/core/src/http/context.test.ts
+++ b/packages/core/src/http/context.test.ts
@@ -12,19 +12,16 @@ import { stubAppDeps } from '../../test/http-fixtures';
import type { HttpCtx } from '../context';
import type { Services } from '../services';
-// Snapshotted BEFORE `mock.module` below, not after — restoring by
-// re-`import`ing later would resolve the already-mocked registry entry, not
-// the real module (bare `bun test` shares one module registry across every
-// file). Without the `afterAll` restore, the stub `createServices` (`{}`,
-// no `.auth`) leaks into every OTHER file that later imports '../context' or
-// './session'.
+// Snapshotted BEFORE `mock.module`: re-`import`ing later would resolve the
+// already-mocked registry entry (bare `bun test` shares one module registry).
+// Without the `afterAll` restore, the stub `createServices` (`{}`, no `.auth`)
+// leaks into every other file that imports '../context' or './session'.
const realServicesModule = { ...(await import('../services')) };
const realSessionModule = { ...(await import('./session')) };
-// mock.module is not hoisted, so the subjects are imported inside beforeAll —
-// see AGENTS.md. Mocking createServices is what makes "not built yet"
-// observable at all — this suite cares about WHEN the factory runs, not what
-// it returns, so the stub container is cast rather than built for real.
+// mock.module is not hoisted, so the subjects are imported inside beforeAll.
+// Mocking createServices makes "not built yet" observable: this suite cares
+// about WHEN the factory runs, not what it returns.
const createServices = mock((): Services => ({}) as Services);
mock.module('../services', () => ({ createServices }));
@@ -51,8 +48,7 @@ beforeEach(() => {
resolveSession.mockClear();
});
-// onAfterResponse runs after `handle` resolves — the response is already on
-// its way out, which is the point of logging there.
+// onAfterResponse runs after `handle` resolves, when the response is already on its way out.
const settled = () => new Promise((resolve) => setTimeout(resolve, 0));
// One request builds exactly one Ctx no matter how many modules each start
@@ -61,9 +57,8 @@ test('derives one ctx per request however many modules use the plugin', async ()
const { deps, scopeCalls, childCalls } = stubAppDeps();
const seen: HttpCtx[] = [];
- // Each observer records the ctx it was handed; the route is registered on
- // the parent AFTER them, because an Elysia hook only applies to routes
- // declared after it.
+ // Each observer records the ctx it was handed; the route is registered AFTER
+ // them because an Elysia hook only applies to routes declared after it.
const observing = () =>
new Elysia()
.use(requestContext(deps))
@@ -264,10 +259,9 @@ describe('requestLogging', () => {
});
});
- // The 2026-09-08 crash class: this hook is global, so it also fires for a
- // request that matched no route — whose `derive` never ran. Reading
- // `ctx.logger` off that missing ctx throws out of a hook nobody awaits, so
- // it lands on the process, not on the request.
+ // This hook is global, so it also fires for a request that matched no route,
+ // whose `derive` never ran. Reading `ctx.logger` off the missing ctx throws
+ // out of a hook nobody awaits, so it lands on the process, not the request.
test('skips a request that matched no route instead of crashing', async () => {
const stub = build();
const crashes: unknown[] = [];
diff --git a/packages/core/src/http/context.ts b/packages/core/src/http/context.ts
index d7404ca4a..9c50687b8 100644
--- a/packages/core/src/http/context.ts
+++ b/packages/core/src/http/context.ts
@@ -1,12 +1,7 @@
-// The per-request plugins: one derive builds `ctx`, one hook logs the request.
-//
-// `requestContext` is a NAMED plugin, and the name is load-bearing. Elysia
-// deduplicates by it, so all 35 modules can start from
-// `.use(requestContext(deps))` and the derive still runs exactly once per
-// request — one `createCtx`, one child logger, one scoped producer set. The
-// corollary is that the first registration wins: every module must be built
-// from the same `AppDeps`, which `defineRoutes` and `rest.routes.ts` enforce
-// by construction.
+// `requestContext` is a NAMED plugin and the name is load-bearing: Elysia
+// deduplicates by it, so every module can start from `.use(requestContext(deps))`
+// and the derive still runs once per request. The first registration wins, so
+// every module must be built from the same `AppDeps`.
import { Elysia } from 'elysia';
import {
@@ -56,9 +51,7 @@ export function requestContext(deps: AppDeps) {
? cancelOnDisconnect(request.signal)
: undefined;
- // `resolveSession` reads `ctx.services.auth`, so the resolver closes
- // over the ctx it is installed on. Safe because it is lazy: nothing
- // calls it during the derive.
+ // The resolver is lazy, so closing over the ctx it is installed on is safe.
const ctx: HttpCtx = extendCtx(
createCtx(deps, { requestId, logger, signal: cancellation?.signal }),
{
@@ -79,17 +72,10 @@ export function requestContext(deps: AppDeps) {
}
export interface RequestLoggingOptions {
- /**
- * Core reads no environment; the parsed client-id list arrives from
- * `apps/api`'s config instead.
- */
verboseClientIds?: string[];
}
-/**
- * One `info` line per request, named `request done` — the `requestId`
- * field rides in from the child logger.
- */
+/** One `info` line per request, named `request done`. */
export function requestLogging(
deps: AppDeps,
options: RequestLoggingOptions = {}
@@ -101,9 +87,8 @@ export function requestLogging(
.onAfterResponse(
{ as: 'global' },
({ ctx, request, path, query, body, timestamp, clientIpHeader }) => {
- // The same shape as `httpMetrics`' guard: this hook is global and also
- // runs for a request that matched no route, whose `derive` never ran.
- // There is no request logger and no arrival timestamp to log with.
+ // This global hook also runs for a request that matched no route, whose
+ // `derive` never ran: no request logger and no arrival timestamp.
if (!ctx) {
return;
}
@@ -149,8 +134,8 @@ export function requestLogging(
);
}
-// Bun aborts `request.signal` when the client goes away — a disconnect, the
-// server's idle timeout, or a closed websocket — but not after a response.
+// Bun aborts `request.signal` when the client goes away (disconnect, idle
+// timeout, closed websocket) but not after a response.
function cancelOnDisconnect(requestSignal: AbortSignal): AbortController {
const cancellation = new AbortController();
requestSignal.addEventListener(
@@ -170,10 +155,8 @@ function wrapCookies(cookie: ElysiaCookies): CookieJar {
};
}
-// `signed` is deliberately not forwarded: Elysia signs by app-level
-// `cookie: { secrets, sign: [...] }` config, not per write, so
-// apps/api/src/main.ts lists the signed names. Everything else maps
-// one-to-one.
+// `signed` is not forwarded: Elysia signs by app-level `cookie: { secrets, sign }`
+// config, so apps/api/src/main.ts lists the signed names.
function writeCookie(
cookie: ElysiaCookies,
name: string,
@@ -191,8 +174,7 @@ function writeCookie(
});
}
-// The dashboard sends the tRPC input as a JSON query param; a batched or
-// malformed one is not worth an error inside a logging hook.
+// A batched or malformed tRPC input is not worth an error inside a logging hook.
function parseTrpcInput(input: string | undefined): unknown {
if (typeof input !== 'string') {
return input;
diff --git a/packages/core/src/http/cors.ts b/packages/core/src/http/cors.ts
index 3be039b0d..3d8d03476 100644
--- a/packages/core/src/http/cors.ts
+++ b/packages/core/src/http/cors.ts
@@ -1,21 +1,12 @@
-// The CORS delegator.
+// `CORS_PRIVATE_PATHS` is the allowlist: a request under one of those prefixes
+// is only allowed from a configured dashboard origin; everything else (`/track`,
+// `/export`, `/insights`, `/import`, `/manage`, `/profile`, `/event`, `/tools`)
+// is open to any origin. `/gsc` and `/mcp` are absent from the list, and so open.
//
-// Two halves, and BOTH are the contract:
-//
-// 1. `CORS_PRIVATE_PATHS` is the allowlist: a request under one of those
-// prefixes is only allowed from a configured dashboard origin; everything
-// else — `/track`, `/export`, `/insights`, `/import`, `/manage`, `/profile`,
-// `/event`, `/tools` — is open to any origin. 2. `/gsc` and `/mcp` are
-// dashboard-scope routes ABSENT from the list, and therefore open.
-//
-// The origins come from `apps/api`'s config, not from an environment read.
-//
-// On an open path that DOES send an `Origin` header, that origin is echoed
-// back with `vary: Origin` and `access-control-allow-credentials: true`,
-// rather than answering `*`. A browser treats an echoed origin plus `Vary`
-// exactly as it treats `*`, so this permits the same set of cross-origin
-// requests. A request with no `Origin` header — every server-side SDK, every
-// golden replay — still gets `*`.
+// On an open path that sends an `Origin`, that origin is echoed with
+// `vary: Origin` and `access-control-allow-credentials: true` instead of `*`;
+// browsers treat the two identically. A request with no `Origin` (every
+// server-side SDK) still gets `*`.
import { cors } from '@elysiajs/cors';
diff --git a/packages/core/src/http/debug.routes.ts b/packages/core/src/http/debug.routes.ts
index b7b601719..1d412ea98 100644
--- a/packages/core/src/http/debug.routes.ts
+++ b/packages/core/src/http/debug.routes.ts
@@ -1,24 +1,16 @@
-// Local-only: `main.ts` mounts this surface only outside production AND only
-// in a consuming role. Those two facts are what keep an unauthenticated "run
-// any cron job now" endpoint off a production box.
+// Local-only: `main.ts` mounts this only outside production AND only in a
+// consuming role, which keeps an unauthenticated "run any cron job now"
+// endpoint off a production box.
//
-// The job list is the `cron` queue's own `jobs`, not a hand-written array of
-// cron type strings — the array could drift from the registry; the registry
-// cannot drift from itself. The queue arrives as an argument (`rest.routes.ts`
-// binds it) because transport may not import a registry.
-//
-// A trigger runs through `runJob` with `{ type }` data — the same entry point
-// the real worker uses — so what this exercises is the production path, not a
-// second dispatcher. `/debug/insights/:projectId?inline=1` summarises with the
-// insight service's own `listAllInsights`, because core reaches Postgres
-// through its services, not through a Prisma client of its own.
+// The job list is the `cron` queue's own `jobs`, so it cannot drift from the
+// registry; the queue arrives as an argument because transport may not import
+// a registry. A trigger runs through `runJob`, the real worker's entry point.
import { z } from 'zod';
import type { AnyJob, QueueDefinition } from '../jobs/define';
import { runJob } from '../jobs/workers';
import { defineRoutes } from './define';
-/** The `cron` queue, as this surface reads it. */
export type CronQueue = QueueDefinition<Record<string, AnyJob>>;
const BAD_REQUEST = 400;
@@ -96,7 +88,6 @@ export const createDebugRoutes = (cronQueue: CronQueue) => {
jobs,
};
},
- // Hidden from the OpenAPI document, like every other ops-surface route.
{ detail: HIDDEN }
)
.all(
@@ -148,9 +139,8 @@ export const createDebugRoutes = (cronQueue: CronQueue) => {
},
{ detail: HIDDEN }
)
- // The insights pipeline for ONE project, bypassing the daily cron's
- // eligibility filter. Default enqueues a real job so it shows up in
- // bull-board; `?inline=1` runs it here and returns a summary.
+ // One project's insights pipeline, bypassing the daily cron's eligibility
+ // filter. Default enqueues a real job; `?inline=1` runs it here.
.get(
'/debug/insights/:projectId',
async ({ params, query, set, ctx }) => {
@@ -200,7 +190,7 @@ export const createDebugRoutes = (cronQueue: CronQueue) => {
},
{ params: projectIdParams, detail: HIDDEN }
)
- // Weekly digest for ONE project, bypassing eligibility.
+ // Weekly digest for one project, bypassing eligibility.
// [email protected] → send only to that address
// (no ?to) → return the assembled payload without sending
// ?force=1 → build even with 0 visitors this week
diff --git a/packages/core/src/http/define.test.ts b/packages/core/src/http/define.test.ts
index f07e0f95a..d60ba3d4d 100644
--- a/packages/core/src/http/define.test.ts
+++ b/packages/core/src/http/define.test.ts
@@ -55,8 +55,8 @@ test('the auth tiers are requestable from a module without extra wiring', async
new Request('http://localhost/manage/projects', { method: 'POST' })
);
- // The P2 authenticator resolves nobody; what is proven here is that the
- // macro ran and typed `client` onto the handler.
+ // The authenticator stub resolves nobody; what is proven is that the macro
+ // ran and typed `client` onto the handler.
expect(response.status).toBe(401);
});
diff --git a/packages/core/src/http/define.ts b/packages/core/src/http/define.ts
index f82b8e874..211033a25 100644
--- a/packages/core/src/http/define.ts
+++ b/packages/core/src/http/define.ts
@@ -1,12 +1,7 @@
// A module's plain-HTTP half: a factory over `AppDeps` returning an Elysia
-// instance. Deps flow top-down as plain arguments, the same way
-// `createXService(deps, services)` does — no decorators at a distance, no
-// options bag.
-//
-// Identity with a name. It fixes the factory signature and guarantees every
-// module starts from the auth plugin, which brings `requestContext(deps)` with
-// it: `ctx` is typed in handlers and `session` / `clientAuth` are requestable
-// without each module re-wiring either.
+// instance. It fixes the factory signature and guarantees every module starts
+// from the auth plugin, which brings `requestContext(deps)` with it, so `ctx` is
+// typed in handlers and `session` / `clientAuth` are requestable.
import type { AppDeps } from '../context';
import { authMacros } from './auth';
diff --git a/packages/core/src/http/errors.ts b/packages/core/src/http/errors.ts
index 7467ccb3c..a8f39870b 100644
--- a/packages/core/src/http/errors.ts
+++ b/packages/core/src/http/errors.ts
@@ -1,13 +1,9 @@
-// The one error handler for the whole app.
-//
// The response body is the `{status, error, message}` shape API consumers
-// already parse, so it is preserved deliberately rather than left to
-// whatever Elysia would produce on its own. Elysia's own `VALIDATION`
-// failures are mapped onto it too, at 400 — a caller sending a bad `/track`
-// body must keep seeing 400, not Elysia's own 422.
+// parse. Elysia's own `VALIDATION` failures map onto it at 400: a bad `/track`
+// body must keep seeing 400, not Elysia's 422.
//
-// There is deliberately NO not-found handler: an unmatched route keeps
-// whatever the framework answers.
+// There is deliberately no not-found handler: an unmatched route keeps the
+// framework's answer.
import { Elysia } from 'elysia';
import type { AppDeps } from '../context';
@@ -21,22 +17,15 @@ const SKIP_LOG_ERROR_CODES = [
'UNAUTHORIZED',
'FORBIDDEN',
'FST_ERR_CTP_INVALID_MEDIA_TYPE',
- // Every request for a route that does not exist logged a warning with a
- // stack trace. A 404 is the caller's business, not an incident.
+ // A 404 is the caller's business, not an incident.
'NOT_FOUND',
];
const VALIDATION_STATUS = 400;
-/** The validation error name callers see is the literal string `'Error'` in
- * the response body — a stable part of the API contract regardless of what
- * actually threw. */
+/** The `error` name in the response body is the literal string `'Error'`: a stable API contract. */
const VALIDATION_ERROR_NAME = 'Error';
-/**
- * Fastify names the request part it validated; Elysia names the same thing in
- * its own vocabulary. The response body carries Fastify's word, because that
- * string is what callers have been parsing.
- */
+/** Elysia's name for the validated request part, mapped to the word the response body has always carried (callers parse it). */
const VALIDATION_SLOT_NAMES: Record<string, string> = {
query: 'querystring',
body: 'body',
@@ -47,7 +36,6 @@ const VALIDATION_SLOT_NAMES: Record<string, string> = {
};
export interface ErrorHandlerOptions {
- /** `NODE_ENV === 'production'` at the call site — core reads no environment. */
production: boolean;
}
@@ -78,8 +66,7 @@ export function errorHandler(deps: AppDeps, options: ErrorHandlerOptions) {
SKIP_LOG_ERROR_CODES.includes(normalized.code);
if (!skipLog) {
- // 4xx are client-side problems (bad payloads, missing fields, etc.) —
- // log as warn so they don't drown out real server errors.
+ // 4xx are client-side problems; warn so they don't drown real errors.
const label =
error instanceof HttpError
? 'internal server error'
@@ -105,9 +92,8 @@ export function errorHandler(deps: AppDeps, options: ErrorHandlerOptions) {
return {
status,
- // HttpError carries an explicit `error` payload (the underlying
- // cause); for everything else we surface the error name so the body is
- // always a stable JSON shape, regardless of what was thrown.
+ // HttpError carries an explicit `error` payload; otherwise surface the
+ // error name so the body is always a stable JSON shape.
error: errorField(error, isValidation, normalized.errorName),
message,
};
@@ -115,16 +101,14 @@ export function errorHandler(deps: AppDeps, options: ErrorHandlerOptions) {
}
/**
- * Produces the `"<slot>/<path> <zod message>"` format that's part of the
- * response body on `/export` and `/insights` — an established part of the API
- * contract. Elysia's own message is a multi-line JSON dump, which is why this
- * reads the structured error fields instead of reformatting it.
+ * Produces the `"<slot>/<path> <zod message>"` format that is part of the
+ * response body on `/export` and `/insights`. Elysia's own message is a
+ * multi-line JSON dump, so this reads the structured error fields instead.
*/
function validationMessage(error: unknown): string {
- // Measured on Elysia 1.4.30 with a zod (Standard Schema) validator: the
- // instance carries `type` (the request part) and `all` (one entry per issue,
- // with a slash-joined `path` string). `message` is the whole report
- // pretty-printed, which is the fallback, not the answer.
+ // With a zod (Standard Schema) validator the instance carries `type` (the
+ // request part) and `all` (one entry per issue, slash-joined `path`).
+ // `message` is the whole pretty-printed report: the fallback.
const detail = error as {
type?: string;
all?: { path?: string; message?: string }[];
diff --git a/packages/core/src/http/hooks.ts b/packages/core/src/http/hooks.ts
index ef1db7a3f..2cca49ba4 100644
--- a/packages/core/src/http/hooks.ts
+++ b/packages/core/src/http/hooks.ts
@@ -1,15 +1,8 @@
-// The root chain, as named Elysia plugins.
-//
-// The order is cors -> requestId -> timestamp -> ip, and it precedes every
-// route-level hook including the rate limiters. `requestContext` composes
-// these three in that order, and `main.ts` mounts `@elysiajs/cors` ahead of
-// it. The cors position is structural rather than conventional — it runs at
-// `onRequest`, a strictly earlier lifecycle phase than `derive`, so it cannot
-// be reordered by accident.
-//
-// The request-logging hook lives with `requestContext` in ./context.ts: it
-// reads the request logger off `ctx` and would otherwise import this file's
-// consumer.
+// The root chain: cors -> requestId -> timestamp -> ip, before every route-level
+// hook including the rate limiters. cors runs at `onRequest`, an earlier phase
+// than `derive`, so its position cannot be reordered by accident. The
+// request-logging hook lives in ./context.ts because it reads the request
+// logger off `ctx`.
import { generateId } from '@openpanel/shared';
import { Elysia } from 'elysia';
@@ -19,9 +12,8 @@ import { getClientIpFromHeaders } from '../shared/get-client-ip';
import { sanitizeRequestId } from '../shared/request-id';
/**
- * First of the three. `requestIdFromCaller` is not decoration: it keeps a
- * caller-supplied id out of per-event log sampling, so the support case that
- * supplied one still resolves.
+ * `requestIdFromCaller` keeps a caller-supplied id out of per-event log
+ * sampling, so the support case that supplied one still resolves.
*/
export function requestIdHook() {
return new Elysia({ name: 'core/http/request-id' }).derive(
@@ -47,10 +39,8 @@ export function timestampHook() {
}
/**
- * Resolves the *attribution* ip, including the empty-string fallback: it
- * prefers client-forwarded headers, which is right for analytics and fatal
- * for a rate-limit bucket. The limiter keys on `openpanel-client-id` and then
- * `getTrustedIpFromHeaders`, and must never read this.
+ * Resolves the *attribution* ip, which prefers client-forwarded headers: right
+ * for analytics, fatal for a rate-limit bucket. Limiters must never read this.
*/
export function clientIpHook(ipHeaders: IpHeaderConfig) {
return new Elysia({ name: 'core/http/client-ip' }).derive(
diff --git a/packages/core/src/http/http.metrics.test.ts b/packages/core/src/http/http.metrics.test.ts
index e56f45a76..303fd9fc1 100644
--- a/packages/core/src/http/http.metrics.test.ts
+++ b/packages/core/src/http/http.metrics.test.ts
@@ -88,9 +88,9 @@ test('an unmatched request produces no series (registeredRoutesOnly)', async ()
expect(await samples(SUMMARY)).not.toContain('status_code="404"');
});
-// The 2026-09-08 crash: a global `onAfterResponse` fires for a request whose
-// `derive` never ran, `performance.now() - undefined` is NaN, prom-client
-// throws on it, and in an async hook that throw exits the process.
+// A global `onAfterResponse` fires for a request whose `derive` never ran;
+// `performance.now() - undefined` is NaN, prom-client throws on it, and in an
+// async hook that exits the process.
test('a duration that is not a finite number >= 0 is dropped, not thrown on', async () => {
const unobservable = [
Number.NaN,
diff --git a/packages/core/src/http/http.metrics.ts b/packages/core/src/http/http.metrics.ts
index 51ae68628..bb371c033 100644
--- a/packages/core/src/http/http.metrics.ts
+++ b/packages/core/src/http/http.metrics.ts
@@ -1,24 +1,7 @@
-// `fastify-metrics`'s two route series, re-created on Elysia so the metric
-// names, help text and labels are reproduced exactly. The plugin itself dies
-// with Fastify, so these are ours now.
-//
-// What "reproduced exactly" pins, from fastify-metrics 12.1.0's own source
-// (dist/fastify-metrics.js:181-210, 258-290):
-//
-// * names `http_request_duration_seconds` (histogram) and
-// `http_request_summary_seconds` (summary) * help "request duration in seconds"
-// / "... summary" * labels `method`, `route`, `status_code`, in that order *
-// unit SECONDS. prom-client's `startTimer` observes seconds; a milliseconds
-// observation on the same series silently multiplies every existing percentile
-// by 1000. * scope HEAD and OPTIONS are excluded (fastify-metrics' default
-// `methodBlacklist`), and only a MATCHED route is observed
-// (`registeredRoutesOnly` defaults true) — so a 404 produces no series, exactly
-// as today.
-//
-// The `route` label VALUE moves, because it is the framework's own route
-// pattern and the framework changed. That is the one thing a dashboard owner
-// has to act on; the old->new mapping is
-// `packages/core/docs/OPS_GRAFANA_MIGRATION.md`.
+// Route duration histogram and summary with names, help text, labels and unit
+// that existing dashboards depend on. The `route` label value is Elysia's route
+// pattern. HEAD and OPTIONS are excluded and only a matched route is observed,
+// so a 404 produces no series.
import { Elysia } from 'elysia';
import client from 'prom-client';
@@ -27,10 +10,9 @@ import { registry } from '../metrics';
const DURATION_HELP = 'request duration in seconds';
const SUMMARY_HELP = 'request duration in seconds summary';
const LABEL_NAMES = ['method', 'route', 'status_code'] as const;
-// fastify-metrics' `methodBlacklist` default (dist/fastify-metrics.js:63-66).
const UNMEASURED_METHODS = new Set(['HEAD', 'OPTIONS']);
-// Elysia's `route` for a request that matched no route. Observing it would
-// create the unbounded-cardinality series `registeredRoutesOnly` avoids.
+// Elysia's `route` for a request that matched no route; observing it would
+// create unbounded label cardinality.
const UNMATCHED_ROUTES = new Set(['', '/*']);
const MS_PER_SECOND = 1000;
// Elysia leaves `set.status` unset on a plain successful return.
@@ -52,16 +34,14 @@ export const httpRequestSummary = new client.Summary({
registers: [registry],
});
-// A bad sample must never take the process down, but it must not vanish
-// either: prom-client's `.observe()` throws on a non-finite value, and in an
-// async hook that throw becomes an unhandled rejection and exits the process.
+// prom-client's `.observe()` throws on a non-finite value, and in an async hook
+// that becomes an unhandled rejection that exits the process; count instead.
export const httpRequestSamplesDropped = new client.Counter({
name: 'http_request_metrics_dropped_total',
help: DROPPED_HELP,
registers: [registry],
});
-/** The one shape prom-client will accept: finite, and not a negative elapsed. */
function isMeasuredDuration(durationMs: unknown): durationMs is number {
return (
typeof durationMs === 'number' &&
@@ -70,17 +50,10 @@ function isMeasuredDuration(durationMs: unknown): durationMs is number {
);
}
-/**
- * Observes a single request. Exported so a test can assert the labels and the
- * unit without standing up a server.
- *
- * Drops, rather than throws on, a sample it cannot observe — see
- * `httpRequestSamplesDropped`.
- */
+/** Observes one request; drops (and counts) a sample it cannot observe. */
export function observeHttpRequest(sample: {
method: string;
- // Elysia types this `string`, but hands the hook `undefined` when the
- // request matched no route.
+ // Elysia types this `string` but passes `undefined` for an unmatched route.
route: string | undefined;
statusCode: number;
durationMs: number;
@@ -108,20 +81,13 @@ export function observeHttpRequest(sample: {
}
/**
- * The one hook. `onAfterResponse` rather than `onAfterHandle` because
- * fastify-metrics observed in `onResponse`: an error mapped to a 4xx/5xx by
- * the error handler never reaches `onAfterHandle`, and dropping those samples
- * would quietly remove every error-status bucket the existing panels group by.
- *
- * The start time rides on a `derive`, not on `store` — `store` is app-level
- * state shared by every in-flight request, so a second concurrent request
- * would overwrite the first one's clock.
+ * `onAfterResponse` rather than `onAfterHandle`: an error mapped to 4xx/5xx by
+ * the error handler never reaches `onAfterHandle`, which would drop every
+ * error-status bucket.
*
- * A `derive` runs per MATCHED route; this hook is global and also runs for a
- * request that matched nothing, where `metricsStartedAt` and `route` are both
- * `undefined`. Such a request has no clock and no route pattern to label, and
- * `registeredRoutesOnly` says not to observe it anyway — so the hook skips,
- * ahead of computing an elapsed against `undefined`.
+ * The start time rides on a `derive`, not `store`, which is shared by all
+ * in-flight requests. A request that matched no route has no `derive`d clock,
+ * so the global hook skips it.
*/
export function httpMetrics() {
return new Elysia({ name: 'core/http/metrics' })
diff --git a/packages/core/src/http/query.ts b/packages/core/src/http/query.ts
index 59cb97a51..60914f034 100644
--- a/packages/core/src/http/query.ts
+++ b/packages/core/src/http/query.ts
@@ -1,15 +1,8 @@
-// The querystring pre-pass: the `parseQueryString` pre-pass as an Elysia
-// lifecycle hook running BEFORE schema validation on `/export` and
-// `/insights`.
-//
-// It exists because ~31 query schemas on those two surfaces are written
-// against already-coerced values — `z.number`, `z.boolean`, `z.array(...)` —
-// while a querystring only ever carries strings. Rewriting those schemas with
-// `z.coerce` instead would change the contract.
-//
-// `transform` is Elysia's pre-validation phase, and the hook MUTATES `query` in
-// place: reassigning the destructured binding would not reach the object the
-// validator then reads.
+// A pre-validation hook that coerces `/export` and `/insights` querystrings: ~31
+// query schemas there expect already-coerced values (`z.number`, `z.boolean`,
+// `z.array`) while a querystring only carries strings, and `z.coerce` would
+// change the contract. It MUTATES `query` in place: reassigning the destructured
+// binding would not reach the object the validator reads.
import { getSafeJson } from '@openpanel/shared';
@@ -45,9 +38,7 @@ export function parseQueryString(
);
}
-/** The `transform` hook itself. Registered LOCAL on the two route surfaces
- * that need it — never globally, or `/track` and `/manage` would start
- * coercing values their handlers read as strings. */
+/** Registered LOCAL on the two surfaces that need it, or `/track` and `/manage` would coerce values their handlers read as strings. */
export function parseQueryStringTransform({
query,
}: {
diff --git a/packages/core/src/http/rate-limit.test.ts b/packages/core/src/http/rate-limit.test.ts
index ce4535097..4640ec716 100644
--- a/packages/core/src/http/rate-limit.test.ts
+++ b/packages/core/src/http/rate-limit.test.ts
@@ -1,6 +1,5 @@
-// The prefix table IS the contract: it has to match what
-// docs/api-reference/rate-limits.mdx publishes, and the paths that page calls
-// unlimited must stay absent from it (ISSUES.md H4).
+// The prefix table IS the contract: it must match the published rate limits,
+// and the paths the docs call unlimited must stay absent from it.
import { describe, expect, test } from 'bun:test';
import { HTTP_RATE_LIMITS, limitFor } from './rate-limit';
diff --git a/packages/core/src/http/rate-limit.ts b/packages/core/src/http/rate-limit.ts
index 781f9f348..00eb41556 100644
--- a/packages/core/src/http/rate-limit.ts
+++ b/packages/core/src/http/rate-limit.ts
@@ -1,6 +1,5 @@
-// The HTTP limiter. Deliberately simpler than the tRPC one in
-// rpc/rate-limit.ts: a fixed window with no escalation, matching what
-// docs/api-reference/rate-limits.mdx publishes (ISSUES.md H4).
+// The HTTP limiter: a fixed window with no escalation, matching the published
+// rate-limit docs.
import { getRedisCache } from '@openpanel/redis';
import { Elysia } from 'elysia';
@@ -13,7 +12,7 @@ const TOO_MANY_REQUESTS = 429;
const KEY_MISSING = -2;
const KEY_WITHOUT_EXPIRY = -1;
-/** Exact response body, matching what api-reference/rate-limits.mdx documents. */
+/** Exact response body the rate-limit docs publish. */
const TOO_MANY_REQUESTS_BODY = {
statusCode: TOO_MANY_REQUESTS,
error: 'Too Many Requests',
@@ -82,12 +81,9 @@ export async function isRateLimited(
}
/**
- * The first matching prefix wins, so order matters only where one prefix
- * contains another — none do today.
- *
- * `/export`, `/insights` and `/manage` are what
- * docs/api-reference/rate-limits.mdx publishes. `/track`, `/profile` and
- * `/import` are absent on purpose: the same page promises they are unlimited.
+ * The first matching prefix wins. `/export`, `/insights` and `/manage` are the
+ * published limits; `/track`, `/profile` and `/import` are absent on purpose:
+ * the docs promise they are unlimited.
*/
export const HTTP_RATE_LIMITS: readonly (HttpRateLimit & {
prefix: string;
@@ -102,11 +98,7 @@ export function limitFor(pathname: string): HttpRateLimit | undefined {
return HTTP_RATE_LIMITS.find((limit) => pathname.startsWith(limit.prefix));
}
-/**
- * Mounted once per route surface rather than per module, so a new `/manage`
- * route cannot quietly arrive without a limit. The prefix table above is
- * that mapping in one place.
- */
+/** Mounted once per route surface so a new `/manage` route cannot arrive without a limit. */
export function httpRateLimit(deps: AppDeps) {
return new Elysia({ name: 'core/http/rate-limit' })
.use(requestContext(deps))
@@ -120,10 +112,8 @@ export function httpRateLimit(deps: AppDeps) {
if (!ctx) {
return;
}
- // No socket address at this layer — `HttpCtx` carries none, and the
- // tRPC context passes `undefined` too (rpc/base.ts). The trusted
- // headers are the fingerprint; without one, callers share the
- // fail-closed `unknown` bucket.
+ // No socket address at this layer; without a trusted header, callers
+ // share the fail-closed `unknown` bucket.
const limited = await isRateLimited(
limit,
request.headers,
diff --git a/packages/core/src/http/session.ts b/packages/core/src/http/session.ts
index 2d6e08d34..fefb869dd 100644
--- a/packages/core/src/http/session.ts
+++ b/packages/core/src/http/session.ts
@@ -1,24 +1,10 @@
-// Where the session cookie becomes a session.
-//
-// `HttpCtx.session` memoizes this call, so a request that asks twice pays once,
-// and the cookie is read through `HttpCtx` rather than through a plugin whose
-// registration order could put it after the guard that needs it.
-//
-// The flow is: decode, `runWithAlsSession`, validate. The `DEMO_USER_ID`
-// branch lives inside `validateSessionToken` itself, so the no-cookie path
-// still goes through it rather than short-circuiting here.
-//
-// Both halves arrive as `ctx.services.auth`, not as a deep import of
-// `modules/auth/src/*`. The derive in `http/context.ts` builds the `Ctx` before
-// it installs this resolver and the resolver is lazy, so the services graph is
-// there by the time a guard asks for a session — a request that never asks
-// (every `/track`) still builds none.
+// `HttpCtx.session` memoizes this call. The flow is decode, `runWithAlsSession`,
+// validate; the `DEMO_USER_ID` branch lives inside `validateSessionToken`, so the
+// no-cookie path still goes through it.
//
// `null` means "nobody is signed in", NOT `EMPTY_SESSION`: the `session` macro,
-// the bull-board guard and the four `/live` handlers all treat the resolved
-// value as truthy-means-authenticated. tRPC is the one caller that wants the
-// empty shape instead, and `makeTrpcContext` maps `null` back to
-// `EMPTY_SESSION` there.
+// the bull-board guard and the `/live` handlers treat the resolved value as
+// truthy-means-authenticated. `makeTrpcContext` maps `null` to `EMPTY_SESSION`.
import type { Ctx, Session } from '../context';
import { runWithAlsSession } from '../shared/als-session';
@@ -37,10 +23,9 @@ export async function resolveSession(
const token = cookies.get(SESSION_COOKIE_NAME);
const auth = ctx.services.auth;
- // No catch: decoding is a hash and cannot fail on any cookie value, so the
- // only thing that throws here is the database. Answering `null` for that
- // would be a 401 and the dashboard would sign every user out during a blip;
- // a 500 makes the client retry instead.
+ // No catch: decoding is a hash and cannot fail, so only the database throws.
+ // Answering `null` would be a 401 and sign every user out during a blip; a
+ // 500 makes the client retry.
const result = await runWithAlsSession(
token ? auth.decodeSessionToken(token) : DEMO_ALS_SESSION_ID,
() => auth.validateSessionToken(token ?? null)
diff --git a/packages/core/src/index.test.ts b/packages/core/src/index.test.ts
index ba44c201d..98e9f6aa4 100644
--- a/packages/core/src/index.test.ts
+++ b/packages/core/src/index.test.ts
@@ -1,10 +1,8 @@
import { expect, test } from 'bun:test';
import * as core from './index';
-// The curated barrel is the package's real public API: what apps/api needs to
-// build AppDeps once and mount the three route surfaces plus the tRPC router.
-// A name missing here is a name apps/api cannot reach — there is no `./*`
-// wildcard to fall back on.
+// The curated barrel is the package's real public API: there is no `./*`
+// wildcard to fall back on, so a name missing here is unreachable from apps/api.
test('the mount surface is curated', () => {
expect(core.appRouter).toBeDefined();
expect(core.publicApiRoutes).toBeTypeOf('function');
@@ -18,9 +16,7 @@ test('the mount surface is curated', () => {
expect(core.queues).toBeDefined();
});
-// ONE tRPC instance: `initTRPC` is called in rpc/base.ts and nowhere else. All
-// 28 routers build on this barrel's builder, router factory and the two
-// injected middleware factories.
+// ONE tRPC instance: `initTRPC` is called in rpc/base.ts and nowhere else.
test('the rpc base is on the barrel, so there is one tRPC instance', () => {
expect(core.procedure).toBeDefined();
expect(core.middleware).toBeTypeOf('function');
@@ -35,9 +31,7 @@ test('a service, a client or a buffer is not on the barrel', () => {
expect(Object.keys(core)).not.toContain('createServices');
});
-// The buffers are boot singletons on AppDeps, so main.ts needs the FACTORY and
-// nothing else. A named instance here would be the module singleton the design
-// refuses.
+// Buffers are boot singletons on AppDeps, so main.ts needs only the FACTORY.
test('buffers reach the barrel as a factory, never as instances', () => {
expect(core.createBuffers).toBeTypeOf('function');
expect(core.registerBufferMetrics).toBeTypeOf('function');
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 26e87ae14..d835412ce 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -1,14 +1,5 @@
-// The curated public surface of @openpanel/core.
-//
-// Never `export *`. What leaves this package is exactly what is named here
-// plus the `*.constants` subpaths in package.json's exports map — see
-// AGENTS.md. Everything below is what `apps/api` needs to build `AppDeps`
-// once and mount the three route surfaces plus the tRPC router over it; a
-// service, a client or a buffer is not reachable from here by design.
+// Never `export *`: what leaves this package is exactly what is named here.
-// packages/db reads ClickHouse row JSON through this; the barrel is how a
-// package outside core reaches it, since the exports map has no ./shared/*
-// entry.
export {
generateId,
generateSecureId,
@@ -46,28 +37,15 @@ export {
safeFetchStream,
verifyPassword,
} from '@openpanel/shared/server';
-// The seven buffers. Only the FACTORY is on the barrel: they are boot
-// singletons on `AppDeps`, built once by `main.ts`, never module singletons.
export type { BufferDeps } from './buffers/base-buffer';
export { registerBufferMetrics } from './buffers/buffer.metrics';
export type { Buffers } from './buffers/create-buffers';
export { createBuffers } from './buffers/create-buffers';
-// Only `createClients` leaves the package; every AI call, the Slack/Discord
-// senders, the geo lookups, the object-store adapters and the integration
-// registry are reached by relative import inside it.
-//
-// `pino-logger` is the concrete implementation of `./logger`'s structural
-// interface; main.ts builds its own named logger from it and mirrors a fatal
-// to the real stderr with the write captured before `interceptProcessOutput`
-// wrapped the stream.
export { createClients } from './clients/create-clients';
export {
isRetryableStatus,
ProviderError,
} from './clients/provider-error';
-// The one config VALUE the loader needs from core: the accepted SASL
-// mechanisms, so `KAFKA_SASL_MECHANISM` is validated against the list the
-// client actually supports rather than a second copy of it.
export { KAFKA_SASL_MECHANISMS, type KafkaSaslMechanism } from './config';
export type {
AppDeps,
@@ -78,18 +56,10 @@ export type {
Session,
} from './context';
export { createCtx, extendCtx } from './context';
-// The role-conditional HTTP surfaces main.ts mounts over the three in
-// rest.routes.ts. `bullBoardRoutes` is async because the adapter reads its own
-// UI assets off disk before it can register.
export { BULL_BOARD_BASE_PATH, bullBoardRoutes } from './http/bull-board';
export { requestContext, requestLogging } from './http/context';
-// The root chain `main.ts` hangs every surface on. Both take their
-// deployment-derived values as arguments.
export { corsDelegator } from './http/cors';
export { errorHandler } from './http/errors';
-// The two runtime seams over the registry. `main.ts` builds producers in every
-// role and workers only where the role consumes; both take the registry as
-// data, so neither opens a connection until it is called.
export type {
AnyJob,
QueueDefinition,
@@ -118,22 +88,12 @@ export {
REQUEST_ID_LENGTH,
REQUEST_ID_LOG_FIELD,
} from './logger';
-// The one registry's own boot-time registrars. `registry` itself is NOT
-// exported: a caller that can reach it can start a second collector graph
-// outside a module.
+// `registry` itself is not exported: a caller that can reach it could start a
+// second collector graph outside a module.
export { registerDefaultMetrics } from './metrics';
-// The chat app, the run context and the filter command take the API's `deps`,
-// so the barrel carries the factory and the types only; `assistant.routes.ts`
-// and `overview.rpc.ts` reach them through `ctx.services.assistant`.
-//
-// `ChatApp` is the one type past `AppRouter` that crosses into apps/start
-// (`src/agents/client.ts`); it stays a TYPE, so no value of this module
-// reaches a browser bundle.
+// `ChatApp` stays a type so no value of the assistant module reaches a browser bundle.
export type { ChatApp } from './modules/assistant/assistant.service';
export { createAssistantService } from './modules/assistant/assistant.service';
-// apps/api's OAuth callbacks call these. `hashPassword` is renamed on the way
-// out: `@openpanel/shared/server` already owns that name for the (unrelated)
-// scrypt hash client secrets use.
export {
Arctic,
cookieOptions,
@@ -148,7 +108,6 @@ export type { AccessLookups } from './modules/auth/src/access';
export { createAccessChecks } from './modules/auth/src/access';
export { validateSessionToken } from './modules/auth/src/login-session';
export { getIsRegistrationAllowed } from './modules/auth/src/registration';
-// The chart engine and the field/filter compilers.
export type {
AggregateChartSqlInput,
ChartSqlInput,
@@ -169,8 +128,6 @@ export { toSeries } from './modules/chart/funnel.service';
export type { IRetentionCohortRow } from './modules/chart/retention.service';
export { processCohortData } from './modules/chart/retention.service';
export { getRawWhereClause } from './modules/chart/sankey.service';
-// The sessions/profiles/events-table filter compiler, distinct from
-// `getEventFiltersWhereClause` above.
export type { FilterTableContext } from './modules/chart/src/table-filter-where';
export { buildFilterWhere } from './modules/chart/src/table-filter-where';
export type { IPublicClient } from './modules/client/client.service';
@@ -184,12 +141,7 @@ export type {
IServiceDashboard,
IServiceDashboards,
} from './modules/dashboard/dashboard.service';
-// R + C only: the router's three bodies are three small `db.emailUnsubscribe`
-// calls, small enough to live inline in `email.rpc.ts` rather than a dedicated
-// `email.service.ts` — see that file's header.
export { emailCategories } from './modules/email/email.constants';
-// Shared by the onboarding module and the organization module's wind-down
-// track.
export type {
SequenceStep,
SequenceSubject,
@@ -209,7 +161,6 @@ export {
export type { IServiceGroup } from './modules/group/group.service';
export { getGscCannibalization } from './modules/gsc/gsc.service';
export { setShuttingDown } from './modules/health/src/shutdown';
-// The ingestion pipeline: the same functions core's own `ingestRoutes` calls.
export type {
BotMatch,
IncomingEventPayload,
@@ -229,8 +180,6 @@ export {
summarizeBotSignals,
validateIngestRequest,
} from './modules/ingest/ingest.service';
-// The Kafka consumer and its per-message handler, which take the kafkajs
-// client, the topic/group names and the retry bounds as arguments.
export type {
DeadLetterMessage,
EventsBatchHandlerDeps,
@@ -241,8 +190,6 @@ export {
startKafkaEventsConsumer,
} from './modules/ingest/src/consumer';
export { createIncomingEventHandler } from './modules/ingest/src/consumer-handler';
-// The readiness probe's two inputs. `markEventsActivity` is the consumer's
-// `onActivity`; `setShuttingDown` is main.ts's signal handler.
export {
enableEventsHeartbeat,
markEventsActivity,
@@ -253,9 +200,6 @@ export type {
} from './modules/ingest/src/incoming-event-handler';
export { incomingEvent } from './modules/ingest/src/incoming-event-handler';
export { ingestConsumerMetrics } from './modules/ingest/src/ingest.metrics';
-// The Kafka transport: producer, consumer factory, admin/lag sampling and every
-// topic/group/retry constant. It constructs no client at import time, so the
-// barrel stays offline-importable.
export type {
Admin,
ConsumerGroupLag,
@@ -273,17 +217,8 @@ export {
sampleConsumerGroupLag,
} from './modules/ingest/src/kafka';
export { explainInsight } from './modules/insight/insight.service';
-// Slack's OAuth token-exchange wire contract — not integration config (stays
-// out of the `*.constants` subpath, see
-// modules/integration/src/slack-contract.ts's header), but apps/api's webhook
-// controller still needs it to validate Slack's `oauth.v2.access` response.
export { zSlackAuthResponse } from './modules/integration/src/slack-contract';
-// Stateless-only, so there is no SessionManager to manage. The barrel carries
-// the factory and the two types; `handleStatelessMcpRequest` needs the API's
-// `deps`, so MCP is reached through `rest.routes.ts`'s `.use(mcpRoutes(deps))`
-// and `ctx.services.mcp`.
export type { McpAuthContext } from './modules/mcp/mcp.service';
-// `GET /misc/og/clear` and `/misc/favicon/clear` are deliberately absent.
export type { INotificationPayload } from './modules/notification/notification.service';
export {
createNotificationService,
@@ -295,11 +230,7 @@ export {
notificationTemplateEvent,
notificationTemplateFunnel,
} from './modules/notification/notification.service';
-// The BullMQ-producer orchestration around a rule match lives in this module's
-// own src/notification-dispatch.ts. Only the one the Kafka message handler is
-// bound to at boot needs to leave the package.
export { checkNotificationRulesForEvent } from './modules/notification/src/notification-dispatch';
-// The onboarding-project mutation and the onboarding email drip.
export { createOnboardingService } from './modules/onboarding/onboarding.service';
export type {
IServiceMember,
@@ -323,8 +254,6 @@ export type {
IServiceProjectWithClients,
} from './modules/project/project.service';
export { createProjectService } from './modules/project/project.service';
-// The realtime ClickHouse queries. The `/live` websocket glue stays internal
-// to realtime.routes.ts.
export type { IServiceReference } from './modules/reference/reference.service';
export { createReferenceService } from './modules/reference/reference.service';
export {
@@ -362,15 +291,10 @@ export {
mergeGlobalFilters,
onlyReportEvents,
} from './modules/report/src/series';
-// `main.ts` calls `createInitialSalts(deps)` directly at boot; `salt.jobs.ts`'s
-// cron handler and everything else reach `rotateSalt`/`getSalts` through
-// `ctx.services.salt`.
export {
createInitialSalts,
createSaltService,
} from './modules/salt/salt.service';
-// The `sessions` queue's own job and the reaper/vacuum cron fragments are
-// registered in jobs.registry.ts, not exported.
export type {
IClickhouseSession,
IServiceSession,
@@ -410,9 +334,6 @@ export {
opsRoutes,
publicApiRoutes,
} from './rest.routes';
-// The RPC base is on the barrel because it is the seam every module's own
-// `<name>.rpc.ts` builds its router on: ONE tRPC instance, mounted by
-// `createTrpcFetchHandler`.
export type {
Meta,
TrpcContext,
@@ -454,6 +375,5 @@ export {
TRUSTED_IP_HEADER_ORDER,
} from './shared/get-client-ip';
export { getReferrerWithQuery, parseReferrer } from './shared/parse-referrer';
-// Below the transports: `rpc/base.ts` needs the empty shape and may not
-// deep-import a module to get it.
+// Shared by `rpc/base.ts`, which may not deep-import a module.
export { EMPTY_SESSION } from './shared/session';
diff --git a/packages/core/src/jobs.registry.test.ts b/packages/core/src/jobs.registry.test.ts
index 1935773f3..c0a4d3bbc 100644
--- a/packages/core/src/jobs.registry.test.ts
+++ b/packages/core/src/jobs.registry.test.ts
@@ -2,8 +2,7 @@ import { expect, test } from 'bun:test';
import { PING_SCHEDULE, schedulersFromRegistry } from './jobs/schedulers';
import { queues } from './jobs.registry';
-// Byte-identity snapshot — see `jobs/schedulers.test.ts` for the matching
-// id-level check.
+// Byte-identity snapshot; `jobs/schedulers.test.ts` has the matching id-level check.
const GOLDEN_SCHEDULER_IDS = [
'cohortRefresh',
'dataHealth',
@@ -27,8 +26,8 @@ const GOLDEN_SCHEDULER_IDS = [
'windDown',
].sort();
-// Retry and retention values kept as-is, defects included — five queues
-// that never retry, four with unbounded failed sets.
+// Retry and retention values pinned as they are: five queues never retry and
+// four have unbounded failed sets.
const PINNED_DEFAULTS = {
sessions: { removeOnComplete: true },
cron: { removeOnComplete: 10 },
@@ -90,9 +89,8 @@ test('every queue has a compat hook — the cutover has no drain step', () => {
}
});
-// The insight module's job — the BullMQ job *name* IS the registry key
-// (defineQueue stamps it), and legacyCompat.insights already discriminates on
-// this exact name (jobs/compat.ts), so this pins the two in agreement.
+// The BullMQ job *name* IS the registry key (defineQueue stamps it) and
+// legacyCompat.insights discriminates on it (jobs/compat.ts); this pins the two.
test('the insights queue carries the insight module job', () => {
expect(Object.keys(queues.insights.jobs)).toEqual(['insightsProject']);
expect(queues.insights.jobs.insightsProject).toMatchObject({
@@ -101,11 +99,9 @@ test('the insights queue carries the insight module job', () => {
});
});
-// The insight module's cron fragment (insight.jobs.ts), spread into the one
-// cron queue. `ping` (misc.jobs.ts) is the only conditional scheduler — it's
-// added by `startSchedulers` only when SELF_HOSTED && production
-// (jobs/schedulers.ts's `PING_SCHEDULE`), but its job HANDLER is always
-// registered here so a scheduled run always has somewhere to land.
+// `ping` (misc.jobs.ts) is the only conditional scheduler: `startSchedulers`
+// adds it only when SELF_HOSTED && production, but its HANDLER is always
+// registered so a scheduled run always has somewhere to land.
test('the cron queue carries the insight module cron fragment', () => {
expect(Object.keys(queues.cron.jobs).sort()).toEqual(
[
@@ -138,9 +134,7 @@ test('the cron queue carries the insight module cron fragment', () => {
}
});
-// The gsc module's own queue job, plus its cron fan-out fragment.
-// legacyCompat.gsc already discriminates on these exact names (jobs/compat.ts),
-// so this pins the two in agreement.
+// legacyCompat.gsc discriminates on these exact names (jobs/compat.ts).
test('the gsc queue carries the gsc module jobs', () => {
expect(Object.keys(queues.gsc.jobs).sort()).toEqual(
['gscProjectBackfill', 'gscProjectSync'].sort()
@@ -159,9 +153,7 @@ test('the cron queue carries the gsc module cron fragment', () => {
});
});
-// The cohort module's own queue job, plus its cron fan-out fragment.
-// legacyCompat.cohortCompute already discriminates on a bare `{cohortId}`
-// (jobs/compat.ts), so this pins the two in agreement.
+// legacyCompat.cohortCompute discriminates on a bare `{cohortId}` (jobs/compat.ts).
test('the cohortCompute queue carries the cohort module job', () => {
expect(Object.keys(queues.cohortCompute.jobs)).toEqual(['cohortCompute']);
expect(queues.cohortCompute.jobs.cohortCompute).toMatchObject({
@@ -177,7 +169,6 @@ test('the cron queue carries the cohort module cron fragment', () => {
});
});
-// The organization module's `delete` cron fragment.
test('the cron queue carries the organization module cron fragment', () => {
expect(queues.cron.jobs.delete).toMatchObject({
queue: 'cron',
@@ -185,7 +176,6 @@ test('the cron queue carries the organization module cron fragment', () => {
});
});
-// The onboarding module's own cron fragment.
test('the cron queue carries the onboarding module cron fragment', () => {
expect(queues.cron.jobs.onboarding).toMatchObject({
queue: 'cron',
@@ -193,9 +183,8 @@ test('the cron queue carries the onboarding module cron fragment', () => {
});
});
-// The session module's own job (legacyCompat.sessions maps the legacy
-// `createSessionEnd` job onto this exact name) and its reaper/vacuum cron
-// fragment — the scheduler ids double as the job names.
+// legacyCompat.sessions maps the legacy `createSessionEnd` job onto this name;
+// the scheduler ids double as the job names.
test('the sessions queue carries the session module job', () => {
expect(Object.keys(queues.sessions.jobs)).toEqual(['session']);
expect(queues.sessions.jobs.session).toMatchObject({
@@ -212,10 +201,8 @@ test('the cron queue carries the session module cron fragment', () => {
}
});
-// The import module's own job. No cron fragment — imports are always
-// user-triggered (import.rpc.ts's create/retry), unlike gsc/cohort/insight.
-// legacyCompat.import already discriminates on this exact name
-// (jobs/compat.ts), so this pins the two in agreement.
+// No cron fragment: imports are always user-triggered. legacyCompat.import
+// discriminates on this name (jobs/compat.ts).
test('the import queue carries the import module job', () => {
expect(Object.keys(queues.import.jobs)).toEqual(['import']);
expect(queues.import.jobs.import).toMatchObject({
@@ -224,10 +211,8 @@ test('the import queue carries the import module job', () => {
});
});
-// The notification module's own job. No cron fragment — notifications are
-// always triggered by a rule match, never scheduled. legacyCompat.notification
-// already discriminates on this exact name (jobs/compat.ts), so this pins the
-// two in agreement.
+// No cron fragment: notifications are triggered by a rule match. legacyCompat.notification
+// discriminates on this name (jobs/compat.ts).
test('the notification queue carries the notification module job', () => {
expect(Object.keys(queues.notification.jobs)).toEqual(['sendNotification']);
expect(queues.notification.jobs.sendNotification).toMatchObject({
@@ -236,11 +221,6 @@ test('the notification queue carries the notification module job', () => {
});
});
-// The join between a cron job and its schedule is enforced by the type
-// system (`defineQueue`'s overload for the `cron` queue requires every job
-// on it to declare `cron`, a schedule or explicit `null`), so this property
-// can no longer drift — it is true by construction, not by a test walking
-// both registries.
test('the cron queue derives the golden 20 scheduler ids', () => {
const derivedIds = [
...schedulersFromRegistry(queues.cron).map((s) => s.id),
diff --git a/packages/core/src/jobs.registry.ts b/packages/core/src/jobs.registry.ts
index d34d7ffb5..70e875d0b 100644
--- a/packages/core/src/jobs.registry.ts
+++ b/packages/core/src/jobs.registry.ts
@@ -1,14 +1,7 @@
-// The seven BullMQ queues, statically composed. Adding a module's jobs is one
-// spread into the queue that owns them; there is no auto-discovery, because
-// static composition is what keeps `QueueProducers` typed.
-//
-// Registry key === Redis name for all seven, `cohortCompute` included: the key
-// is deliberately not renamed, so `COHORTCOMPUTE_CONCURRENCY` keeps working.
+// The seven BullMQ queues, statically composed: static composition is what
+// keeps `QueueProducers` typed. Registry key === Redis name for all seven
+// (`cohortCompute` included), so `COHORTCOMPUTE_CONCURRENCY` keeps working;
// `queueKey` decides what actually reaches Redis.
-//
-// Retry and retention values are preserved as-is, defects included — five
-// queues that never retry, four whose failed sets are unbounded. Changing
-// them is a behaviour change, not a cleanup, and is a separate decision.
import { legacyCompat } from './jobs/compat';
import type { Producers } from './jobs/define';
@@ -65,14 +58,11 @@ const sessions = defineQueue('sessions', {
});
// One queue, one worker at concurrency 1, every scheduled job in the system.
-// Pausing it from bull-board halts all buffer flushing — preserved deliberately
-// — an accepted trade-off.
+// Pausing it from bull-board halts all buffer flushing.
const cron = defineQueue('cron', {
defaults: { removeOnComplete: 10 },
worker: { concurrency: CONCURRENCY.cron },
compat: legacyCompat.cron,
- // Every module's cron fragment spreads in here — there is no separate cron
- // module.
jobs: {
...saltCronJobs,
...eventCronJobs,
@@ -154,15 +144,12 @@ export const queues = {
export type Queues = typeof queues;
// Derived from the `cron` queue's own jobs so a job and its schedule cannot
-// drift apart. It is computed HERE, in the registry, and not in
-// `jobs/schedulers.ts`: that file is transport infrastructure and may not
-// import a registry. `ping` is conditional — see `PING_SCHEDULE` and
-// `startSchedulers`.
+// drift apart. Computed here because `jobs/schedulers.ts` may not import a registry.
export const CRON_SCHEDULES: readonly SchedulerDefinition[] =
schedulersFromRegistry(cron);
/** What `ctx.queues` is: `ctx.queues.import.run.add({ importId })`. */
export type QueueProducers = Producers<Queues>;
-/** What `AppDeps.producers` is — built once at boot, scoped per unit of work. */
+/** What `AppDeps.producers` is: built once at boot, scoped per unit of work. */
export type QueueProducerHandle = ProducerHandle<Queues>;
diff --git a/packages/core/src/logger.ts b/packages/core/src/logger.ts
index 7ef8d169a..2fa54cd0f 100644
--- a/packages/core/src/logger.ts
+++ b/packages/core/src/logger.ts
@@ -1,6 +1,5 @@
-// Structural interface only. pino satisfies this shape once it is instantiated
-// in apps/api — nothing here imports pino, so shared/ and modules/ can depend
-// on the shape of a logger without pulling the implementation into core.
+// Structural interface only: nothing here imports pino, so shared/ and modules/
+// depend on the shape without pulling in the implementation.
export type LogLevel = 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace';
@@ -19,16 +18,12 @@ export interface Logger {
child(bindings: Record<string, unknown>): Logger;
}
-// One identifier, one name, one constant — the field is `requestId` everywhere
-// (JobMeta.requestId, every log line, Ctx). Exported here to kill the
-// four-file literal coupling.
+// The log field is `requestId` everywhere (JobMeta.requestId, every log line, Ctx).
export const REQUEST_ID_LOG_FIELD = 'requestId' as const;
// 126 bits of nanoid. A correlation id, not a secret, and the hot path pays for
-// it 5000x/s — hence `nanoid/non-secure` behind generateId.
+// it 5000x/s, hence `nanoid/non-secure` behind generateId.
export const REQUEST_ID_LENGTH = 21;
-// The wire header stays `request-id` byte-for-byte — it is caller-visible, so
-// changing it would break existing callers, even though the log field it
-// feeds is renamed.
+// The wire header stays `request-id`: it is caller-visible, unlike the log field.
export const REQUEST_ID_HEADER = 'request-id' as const;
diff --git a/packages/core/src/metrics.ts b/packages/core/src/metrics.ts
index ef2aaf636..03c2ef28c 100644
--- a/packages/core/src/metrics.ts
+++ b/packages/core/src/metrics.ts
@@ -1,6 +1,4 @@
-// The one prom-client registry for the whole process. Every collector a core
-// module registers from here on registers on THIS registry, and only this
-// one.
+// The one prom-client registry for the whole process.
import client from 'prom-client';
diff --git a/packages/core/src/pino-logger.ts b/packages/core/src/pino-logger.ts
index 1bb914622..9b0c8d1dd 100644
--- a/packages/core/src/pino-logger.ts
+++ b/packages/core/src/pino-logger.ts
@@ -1,9 +1,3 @@
-// Concrete pino implementation. `../logger.ts` is the structural interface
-// every module and service codes against; this file is what actually
-// instantiates pino, and it is deliberately the only place in core that
-// imports it — apps/api builds its named logger by calling `createLogger`
-// from here rather than owning a copy.
-
import * as HyperDX from '@hyperdx/node-opentelemetry';
import pino, { type Logger as PinoLogger } from 'pino';
import type { CoreConfig } from './config';
@@ -15,9 +9,8 @@ import {
export type ILogger = PinoLogger;
-// Originals captured before interceptProcessOutput wraps the streams. Code
-// that must bypass capture (e.g. crash handlers mirroring fatals to stderr)
-// uses these so the line isn't re-ingested and shipped twice.
+// Captured before interceptProcessOutput wraps the streams, so code that must
+// bypass capture (crash handlers mirroring fatals) is not re-ingested twice.
export const rawStdoutWrite = process.stdout.write.bind(process.stdout);
export const rawStderrWrite = process.stderr.write.bind(process.stderr);
@@ -61,8 +54,7 @@ export function redactSensitive(value: unknown, depth = 0): unknown {
return result;
}
-// Shared by logs and traces so both signals land under the same service
-// name in ClickStack (e.g. new-api-production).
+// Shared by logs and traces so both signals land under one service name.
export function getServiceName(config: CoreConfig, name: string): string {
const { serviceNamePrefix, serviceNameEnvironment } = config.logging;
return [serviceNamePrefix, name, serviceNameEnvironment]
@@ -70,13 +62,10 @@ export function getServiceName(config: CoreConfig, name: string): string {
.join('-');
}
-// pino-pretty's transport runs in a worker thread that pino locates via
-// require.resolve at the CALLING module's location. Under Bun that
-// resolution is broken for a transitive dependency (a caller outside
-// @openpanel/core, e.g. apps/api/src/main.ts's own `createLogger` call)
-// and crashes the process instead of the log line — deterministic on this
-// box, not a flake. Node has no such issue, so this only turns pretty
-// printing off when booted under Bun.
+// pino-pretty's worker-thread transport is located via require.resolve at the
+// CALLING module's location, which is broken under Bun for a transitive
+// dependency (a caller outside @openpanel/core) and crashes the process.
+// Pretty printing is therefore off under Bun.
const isBun = !!process.versions.bun;
export function createLogger({
@@ -132,14 +121,12 @@ let intercepted = false;
* console.*, Node warnings) still reaches the OTLP pipeline. Call it before
* anything else runs in the app entry.
*
- * No feedback loop: pino writes via sonic-boom straight to the file
- * descriptor (and transports write from a worker thread), so pino's own
- * output never passes through these wrappers. A reentrancy guard covers any
- * exotic transport that does.
+ * No feedback loop: pino writes straight to the file descriptor, never through
+ * these wrappers; a reentrancy guard covers any exotic transport that does.
*
- * In otlp mode raw lines are also passed through to the original stream so
- * `docker logs` stays useful. In stdout mode pino's JSON line on stdout IS
- * the container output — teeing would print everything twice.
+ * In otlp mode raw lines are also passed to the original stream so `docker
+ * logs` stays useful. In stdout mode pino's JSON line IS the container output,
+ * so teeing would print everything twice.
*/
export function interceptProcessOutput(
config: CoreConfig,
@@ -148,7 +135,6 @@ export function interceptProcessOutput(
if (intercepted) {
return;
}
- // Keep local dev output untouched.
if (!config.logging.interceptProcessOutput) {
return;
}
diff --git a/packages/core/src/rest.routes.ts b/packages/core/src/rest.routes.ts
index 4b951fdc1..cf00cf5ed 100644
--- a/packages/core/src/rest.routes.ts
+++ b/packages/core/src/rest.routes.ts
@@ -1,8 +1,3 @@
-// The three URL surfaces `app.ts` hangs CORS, OpenAPI and guards on. Each is
-// a factory over `AppDeps`, statically composed from `.use`d modules — no
-// filesystem discovery. Adding a module's HTTP half is one `.use` on the
-// surface it belongs to; most modules touch exactly one.
-
import { openapi } from '@elysiajs/openapi';
import { Elysia } from 'elysia';
import type { AppDeps } from './context';
@@ -29,39 +24,25 @@ import { subscriptionRoutes } from './modules/subscription/subscription.routes';
import { toolsRoutes } from './modules/tools/tools.routes';
// Pinned to the @elysiajs/openapi 1.4.15 fallback; 2.0 is not viable here.
-// `specPath` is set explicitly rather than taking the plugin's `${path}/json`
-// default, because the ops surface's contract is exactly `/openapi.json`.
+// `specPath` is explicit because the ops surface's contract is `/openapi.json`.
const OPENAPI_SPEC_PATH = '/openapi.json';
-// `/metrics` is prometheus text exposition, not an OpenAPI-describable JSON
-// endpoint, so it is excluded from the generated spec.
+// `/metrics` is prometheus text, not an OpenAPI-describable endpoint.
const OPENAPI_EXCLUDED_PATHS = ['/metrics'];
-// How long one collected exposition is served for before it is collected again.
-// M29-001a measured a single `registry.metrics` at 70-80 ms of the api's ONLY
-// JavaScript thread on an idle process against 0.5-0.8 ms for `/healthz`,
-// nearly all of it inside prom-client's heap-space collector, which on Bun is a
-// JSC heap walk whose cost grows with the heap; under write load and a >=1 Hz
-// scrape that was 21.96 % of the thread and every millisecond of it is a
-// millisecond no event can be ingested. 5 s is chosen to sit strictly below the
-// shortest scrape interval a Prometheus is sanely configured with, so a real
-// scraper still collects fresh on every scrape, while a pathologically frequent
-// one pays at most one collection per window.
+// One `registry.metrics()` costs 70-80 ms of the api's only JavaScript thread
+// (prom-client's heap-space collector walks the JSC heap), which at a >=1 Hz
+// scrape starves ingest. 5 s stays below any sane scrape interval, so a real
+// scraper still collects fresh while a pathologically frequent one pays at
+// most one collection per window.
const METRICS_EXPOSITION_TTL_MS = 5000;
-// A factory always takes `deps` even where its body is empty so a module
-// addition never changes the signature. Return types are left inferred, as
-// `defineRoutes`'s `RouteApp` is: `.use`'d plugins widen Elysia's type
-// parameters in a way the bare `Elysia` type cannot express.
-//
-// Client-authed API surface (`/import`, `/manage/*`, `/profile*`, `/export`,
-// `/insights`, `/tools`), not session-authed like dashboardRoutes. `/track` and
-// `/track/device-id` are the hot path, on the ingest `clientAuth` tier, and the
-// one route surface whose hook ORDER is part of the contract.
+// Client-authed API surface, not session-authed like dashboardRoutes. `/track`
+// and `/track/device-id` are the hot path, and the one surface whose hook ORDER
+// is part of the contract.
export const publicApiRoutes = (deps: AppDeps) =>
new Elysia({ name: 'core/public-api-routes' })
- // Mounted on the SURFACE, not per module, so a new /manage or /export
- // route cannot arrive without the limit the docs advertise. The prefix
- // table is in http/rate-limit.ts.
+ // On the surface, not per module, so a new route cannot arrive without
+ // the limit. The prefix table is in http/rate-limit.ts.
.use(httpRateLimit(deps))
.use(ingestRoutes(deps))
.use(importRoutes(deps))
@@ -72,14 +53,11 @@ export const publicApiRoutes = (deps: AppDeps) =>
.use(insightsRoutes(deps))
.use(toolsRoutes(deps));
-// `/gsc` and `/mcp` are dashboard-scope routes absent from the CORS
-// delegator's private-path allowlist (`http/cors.ts`'s `CORS_PRIVATE_PATHS`)
-// and so get `origin: '*'` — a quirk to keep, not fix. `/oauth`, `/webhook`
-// (integration's Slack callback, subscription's Polar callback), `/live` and
-// `/misc` ARE in that allowlist.
+// `/gsc` and `/mcp` are absent from the CORS delegator's private-path allowlist
+// (`CORS_PRIVATE_PATHS`) and so get `origin: '*'`: a quirk to keep, not fix.
export const dashboardRoutes = (deps: AppDeps) =>
new Elysia({ name: 'core/dashboard-routes' })
- // For `/mcp`; every other path on this surface is unmatched by the table.
+ // Only `/mcp` matches the prefix table.
.use(httpRateLimit(deps))
.use(gscRoutes(deps))
.use(assistantRoutes(deps))
@@ -90,15 +68,10 @@ export const dashboardRoutes = (deps: AppDeps) =>
.use(realtimeRoutes(deps))
.use(miscRoutes(deps));
-// The `/metrics` body, collected at most once per METRICS_EXPOSITION_TTL_MS.
-// The endpoint still serves the one core registry's full exposition,
-// including the heap metrics; what changes is how often that exposition is
-// recomputed. Consequence to know: the scrape-time gauges (buffer, queue,
-// session) are as old as the snapshot, i.e. up to the TTL, which is the price
-// of not walking the heap on every request.
+// Scrape-time gauges (buffer, queue, session) are as old as the snapshot, up to
+// the TTL.
let metricsExposition: { body: string; expiresAt: number } | null = null;
-// Concurrent scrapes share one collection instead of queueing N heap walks
-// behind each other on the single thread.
+// Concurrent scrapes share one collection.
let metricsExpositionInFlight: Promise<string> | null = null;
async function collectMetricsExposition(): Promise<string> {
@@ -116,8 +89,7 @@ function readMetricsExposition(): Promise<string> {
return Promise.resolve(cached.body);
}
if (!metricsExpositionInFlight) {
- // A failed collection must not be cached, and must reject exactly as
- // `registry.metrics()` throws, so the route needs no separate error path.
+ // A failed collection is not cached and rejects as `registry.metrics()` does.
metricsExpositionInFlight = collectMetricsExposition().finally(() => {
metricsExpositionInFlight = null;
});
@@ -125,15 +97,9 @@ function readMetricsExposition(): Promise<string> {
return metricsExpositionInFlight;
}
-// `httpMetrics` is on the ops surface because that is where `/metrics` is
-// served and every role mounts it. Its hook is `{ as: 'global' }`, so it
-// covers the dashboard and public-API surfaces too once they mount.
-//
-// healthz/metrics/misc share this ops surface (http/context.ts's
-// UNLOGGED_PATH_PREFIXES) — unauthenticated, uncorsed, unlogged. /metrics and
-// /openapi.json serve the one core registry's prometheus exposition, and the
-// OpenAPI reference built from the same zod schemas the routes validate
-// against.
+// `httpMetrics` sits on the ops surface because every role mounts it; its hook
+// is `{ as: 'global' }`, so it covers the other surfaces too. The ops surface is
+// unauthenticated, uncorsed and unlogged.
export const opsRoutes = (deps: AppDeps) =>
new Elysia({ name: 'core/ops-routes' })
.use(httpMetrics())
@@ -149,8 +115,5 @@ export const opsRoutes = (deps: AppDeps) =>
return await readMetricsExposition();
});
-// The local-only ops surface. It is bound HERE rather than in
-// `http/debug.routes.ts` because that file needs the `cron` queue's job list
-// and transport may not import a registry; a registry binding a transport to a
-// queue is the edge pointing the right way.
+// Bound here, not in `http/debug.routes.ts`: transport may not import a registry.
export const debugRoutes = createDebugRoutes(queues.cron);
diff --git a/packages/core/src/rpc/base.test.ts b/packages/core/src/rpc/base.test.ts
index 067cd8ab5..a547849f2 100644
--- a/packages/core/src/rpc/base.test.ts
+++ b/packages/core/src/rpc/base.test.ts
@@ -13,7 +13,6 @@ import {
} from './base';
import { createTrpcFetchHandler } from './handler';
-// Base cookie options for these tests, with a domain filled in.
const COOKIE_OPTIONS: CookieOptions = {
domain: '.openpanel.dev',
secure: true,
@@ -38,8 +37,7 @@ function build(options: Partial<Parameters<typeof makeTrpcContext>[2]> = {}) {
test('setCookie writes through resHeaders with the documented option precedence', async () => {
const { trpcCtx, resHeaders } = build();
- // Only maxAge and signed are caller-controlled; COOKIE_OPTIONS is spread
- // last, so everything a caller sends for the rest is ignored.
+ // Only maxAge and signed are caller-controlled; the rest is ignored.
(await trpcCtx).setCookie('session', 'the-token', {
maxAge: 600,
domain: 'evil.example',
@@ -116,9 +114,8 @@ test('a signed cookie with no signer throws instead of going out unsigned', asyn
expect(resHeaders.getSetCookie()).toHaveLength(0);
});
-// The context builder resolves the session once, since every procedure reads
-// `ctx.session` as a plain value - and it is what lets `onError` log the
-// session without awaiting.
+// The session is resolved eagerly because every procedure reads `ctx.session`
+// as a plain value and `onError` logs it without awaiting.
test('the session is resolved once, before any procedure runs', async () => {
const stub = stubHttpCtx();
expect(stub.sessionCalls).toBe(0);
@@ -131,10 +128,9 @@ test('the session is resolved once, before any procedure runs', async () => {
expect(ctx.session).toEqual(TEST_SESSION);
});
-// tRPC merges middleware context with `{...ctx, ...next.ctx}` — a spread,
-// which copies own enumerable properties ONLY. A prototype-chained context
-// would lose every inherited field the first time a middleware called
-// `next({ ctx })`, and the next read would be a TypeError inside a mutation.
+// tRPC merges middleware context with a spread, which copies own enumerable
+// properties ONLY: a prototype-chained context would lose every inherited
+// field the first time a middleware called `next({ ctx })`.
test('the HttpCtx is flattened onto own properties, and services stay lazy', async () => {
const { ctx } = stubHttpCtx();
const trpcCtx = await makeTrpcContext(ctx, new Headers(), {
@@ -186,8 +182,6 @@ test('simulateLatency delays the context, and is off by default', async () => {
}
});
-// ------------------------------------------------------- middleware factories
-
function mountWith(
build: (
base: typeof import('./base')
diff --git a/packages/core/src/rpc/base.ts b/packages/core/src/rpc/base.ts
index b33907ee0..41eb95984 100644
--- a/packages/core/src/rpc/base.ts
+++ b/packages/core/src/rpc/base.ts
@@ -1,10 +1,3 @@
-// The tRPC instance, its context, and the middleware factories procedures are
-// built from.
-//
-// The tRPC context IS the Elysia-derived `HttpCtx`: `makeTrpcContext` adds the
-// tRPC-specific bits and overrides exactly one field. There is no `req`/`res`
-// here — a procedure reads `ctx.headers`, `ctx.ip`, `ctx.logger`.
-
import { initTRPC, TRPCError } from '@trpc/server';
import { has } from 'ramda';
import superjson from 'superjson';
@@ -34,15 +27,10 @@ export interface Meta {
* What tRPC procedures see: `HttpCtx` with `session` already resolved, plus
* two RPC-only fields.
*
- * `session` is the one field this OVERRIDES. On an HTTP route it is the lazy,
- * memoized resolver, so a public route pays nothing; on an RPC call it is
- * resolved eagerly, since every procedure reads `ctx.session.userId` directly.
- * Resolving in the context builder is also what lets `onError` log it without
- * awaiting.
- *
- * It is not merely convenience: a middleware that *changed* `session`'s type
- * would make every standalone middleware (`cacheMiddleware`,
- * `rateLimitMiddleware`) unusable after it, because tRPC types `.use()`
+ * `session` is resolved eagerly (on HTTP routes it is a lazy resolver) because
+ * every procedure reads `ctx.session.userId` directly and `onError` logs it
+ * without awaiting. A middleware that changed `session`'s type would make
+ * every standalone middleware unusable after it, since tRPC types `.use()`
* against the context as overwritten so far.
*/
export interface TrpcContext extends Omit<HttpCtx, 'session'> {
@@ -53,16 +41,11 @@ export interface TrpcContext extends Omit<HttpCtx, 'session'> {
* present. It is NOT `ctx.ip`: that is the *attribution* ip, which prefers
* client-forwarded headers and would give every request its own bucket.
*
- * `undefined` where the transport does not expose it. Elysia's
- * `server.requestIP` is not plumbed through `HttpCtx` yet, so the fetch mount
- * leaves it unset and the limiter falls back to its shared `unknown` bucket —
- * fail-closed, which is the documented intent.
+ * `undefined` where the transport does not expose it; the limiter then falls
+ * back to its shared `unknown` bucket (fail-closed).
*/
readonly remoteAddress: string | undefined;
- /**
- * `DEMO_USER_ID` is set. Core reads no environment, so the flag arrives on
- * the context; the demo-mode mutation ban is `enforceAccess`'s to apply.
- */
+ /** `DEMO_USER_ID` is set; `enforceAccess` bans mutations in demo mode. */
readonly demoMode: boolean;
}
@@ -105,23 +88,13 @@ const stopWhenCancelled = t.middleware(async ({ ctx, next }) => {
return result;
});
-/**
- * The bare procedure. It authenticates NOTHING. Use one of the three builders
- * below unless a procedure needs to be built directly on `procedure` itself —
- * the only ones are the share-aware `chartProcedure`/`overviewProcedure`
- * bases, and those are `publicProcedure` plus their own middleware.
- */
/**
* Turns a driver failure caused by the CALLER into the status it deserves.
*
- * A malformed id raised Prisma P2023 before any `findUnique` null check could
- * run, so procedures with a perfectly good not-found guard still answered 500
- * — with the driver's own message, which for ClickHouse echoes the generated
- * SQL. Anything `classifyDriverError` does not recognise is rethrown
- * untouched and stays a 500, because a query bug is not the caller's mistake.
- *
- * This sits on `procedure` itself, which every builder derives from, so it
- * covers every procedure with one `.use()`.
+ * A malformed id raises Prisma P2023 before any `findUnique` null check can
+ * run, and the driver's message (for ClickHouse, the generated SQL) would
+ * otherwise reach the client as a 500. Anything `classifyDriverError` does not
+ * recognise stays a 500, because a query bug is not the caller's mistake.
*/
const mapDriverErrors = t.middleware(async ({ next }) => {
const result = await next();
@@ -138,30 +111,19 @@ const mapDriverErrors = t.middleware(async ({ next }) => {
throw new TRPCError({ code: failure.trpc, message: failure.message });
});
+/** The bare procedure. It authenticates NOTHING; prefer the builders below. */
export const procedure = t.procedure
.use(stopWhenCancelled)
.use(mapDriverErrors);
-// --------------------------------------------------------------------------
-// The procedure stack. It is a middleware stack rather than per-handler code
-// because:
-//
// Authentication runs before input parsing: tRPC runs `.use` middleware ahead
// of the `.input` parser, so an anonymous caller gets UNAUTHORIZED whatever it
-// sends. Doing the same check inside a handler would let the caller learn the
-// input shape first.
-//
-// The check is a property of the builder, not a line a handler might forget
-// to call.
+// sends and learns nothing about the input shape.
//
// `enforceAccess` reads the raw, pre-Zod input and only its top-level
// `projectId` / `organizationId`. A procedure that resolves the project from
// a reportId/dashboardId instead is invisible to it and keeps its own
-// in-handler check — redundant there is harmless, missing is not.
-//
-// The lookups arrive through `ctx.services.auth`; core reaches no database
-// directly.
-// ---------------------------------------------------------------------------
+// in-handler check.
const enforceUserIsAuthed = t.middleware(async ({ ctx, next }) => {
const session = ctx.session;
@@ -170,16 +132,14 @@ const enforceUserIsAuthed = t.middleware(async ({ ctx, next }) => {
}
try {
- // Narrowed, not merely copied: the spread of the checked union member is
- // what gives every handler below a `session.userId` of type `string`.
+ // The spread of the checked union member gives handlers a `session.userId`
+ // of type `string`.
return next({
ctx: {
session: { ...session },
},
});
} catch (error) {
- // Logged via the request-scoped logger, not console (CLAUDE.md bans
- // console in shipped code). The misspelled message is kept as-is.
ctx.logger.error({ err: error }, 'Failes to get user');
throw new TRPCError({
code: 'UNAUTHORIZED',
@@ -188,7 +148,6 @@ const enforceUserIsAuthed = t.middleware(async ({ ctx, next }) => {
}
});
-// Only used on protected routes
const enforceAccess = t.middleware(
async ({ ctx, next, type, meta, getRawInput }) => {
const sessionId = ctx.session?.session?.id ?? null;
@@ -201,10 +160,8 @@ const enforceAccess = t.middleware(
}
if (has('projectId', rawInput)) {
- // Fails closed: any procedure that takes a top-level projectId requires
- // write access to mutate, including ones added later. Procedures that
- // resolve the project from a reportId/dashboardId/etc. are invisible to
- // this check and call requireProjectAccess in the handler instead.
+ // Fails closed: any procedure with a top-level projectId needs write
+ // access to mutate, including ones added later.
const needsWrite = type === 'mutation' && !meta?.readOnlyMutation;
await ctx.services.auth.requireProjectAccess({
@@ -273,9 +230,9 @@ export const protectedProcedure = procedure
.use(enforceAccess)
.use(loggerMiddleware)
.use(sessionScopeMiddleware);
-// Authenticated but WITHOUT the org/project membership check. Use for endpoints
-// that must answer for any logged-in user (e.g. checking your own access to an
-// org you may not belong to) and return null instead of throwing.
+// Authenticated but WITHOUT the org/project membership check, for endpoints
+// that answer any logged-in user (e.g. checking your own access to an org you
+// may not belong to).
export const protectedProcedureWithoutAccess = procedure
.use(enforceUserIsAuthed)
.use(loggerMiddleware)
@@ -287,26 +244,20 @@ const ARTIFICIAL_LATENCY_SPREAD_MS = 500;
const ARTIFICIAL_LATENCY_MAX_MS = 200;
export interface TrpcContextOptions {
- /** Deployment-derived (reads `DASHBOARD_URL`), so it is injected rather than imported. */
cookieOptions: CookieOptions;
- /** `NODE_ENV !== 'production'` at the call site. */
simulateLatency?: boolean;
/**
- * Required only if a procedure asks for `signed: true` (three cookies in the
- * GSC OAuth flow). Absent, `setCookie` throws rather than quietly emitting an
- * unsigned cookie the callback would reject.
+ * Required only if a procedure asks for `signed: true`. Absent, `setCookie`
+ * throws rather than quietly emitting an unsigned cookie.
*/
signCookie?: (value: string) => string;
- /** `DEMO_USER_ID` is set at the call site. Defaults to off. */
demoMode?: boolean;
}
/**
- * Builds the tRPC context from the request-scoped `HttpCtx`.
- *
- * Cookies go out through the fetch adapter's `resHeaders`, not through Elysia:
- * the handler returns a `Response` the framework did not build, so the cookie
- * proxy is not a guaranteed path out.
+ * Builds the tRPC context from the request-scoped `HttpCtx`. Cookies go out
+ * through the fetch adapter's `resHeaders`, not Elysia: the handler returns a
+ * `Response` the framework did not build.
*/
export async function makeTrpcContext(
ctx: HttpCtx,
@@ -330,8 +281,7 @@ export async function makeTrpcContext(
value: string,
cookie: CookieOptions = {}
): void => {
- // Only `maxAge` and `signed` are caller-controlled; everything else
- // comes from COOKIE_OPTIONS, spread last.
+ // Only `maxAge` and `signed` are caller-controlled; the rest is spread last.
const merged: CookieOptions = {
maxAge: cookie.maxAge,
signed: cookie.signed,
@@ -356,25 +306,19 @@ export async function makeTrpcContext(
// FLAT, not prototype-chained onto the HttpCtx. tRPC merges middleware
// context with `{...ctx, ...next.ctx}`, which copies own enumerable
- // properties only — so an inherited `logger`/`db`/`queues` disappears the
- // first time a middleware calls `next({ ctx })`, and the next read of it is
- // a TypeError in the middle of a mutation. Descriptors are COPIED rather
- // than values read, so `services` stays a getter here; tRPC's own spread is
- // what eventually forces it, and only on the RPC path.
+ // properties only, so an inherited `logger`/`db`/`queues` would disappear the
+ // first time a middleware calls `next({ ctx })`. Descriptors are copied
+ // rather than values read, so `services` stays a lazy getter.
const trpcCtx = flattenCtx(ctx) as unknown as TrpcContext;
Object.defineProperties(trpcCtx, {
- // Resolved once here, shadowing HttpCtx's resolver. One HTTP request is
- // one `createContext` call, so a batched request still costs one lookup.
- // `HttpCtx.session()` answers `null` for "nobody is signed in" (see
- // http/session.ts); procedures read `ctx.session.userId` directly, so the
- // empty shape — not `null` — is what a procedure must see.
+ // Resolved once per request, so a batched request costs one lookup.
+ // `HttpCtx.session()` answers `null` for "nobody is signed in", but
+ // procedures read `ctx.session.userId` directly, so they get the empty shape.
session: {
value: (await ctx.session()) ?? EMPTY_SESSION,
enumerable: true,
},
// The fetch adapter is handed a `Request`, which carries no peer address.
- // Elysia's `server.requestIP()` is the source when the dashboard scope
- // mounts; until then the limiter falls back to its shared bucket.
remoteAddress: { value: undefined, enumerable: true },
demoMode: { value: options.demoMode ?? false, enumerable: true },
setCookie: { value: setCookie, enumerable: true },
@@ -423,14 +367,7 @@ const middlewareMarker = 'middlewareMarker' as 'middlewareMarker' & {
__brand: 'middlewareMarker';
};
-/**
- * Query response caching, keyed by procedure path and raw input.
- *
- * A factory over the injected cache rather than a module singleton reaching for
- * `getRedisCache()`: the client is built once in main.ts and handed down, so a
- * test passes a map and a second process does not open a connection it never
- * uses.
- */
+/** Query response caching, keyed by procedure path and raw input. */
export const createCacheMiddleware =
({ cache, serveFromCache }: CacheMiddlewareDeps) =>
(cbOrTtl: number | ((input: any, opts: { path: string }) => number)) =>
@@ -482,14 +419,9 @@ export interface RateLimitOptions {
}
/**
- * The limiter itself, injected. It keys on the trusted IP and talks to Redis;
- * both are boot-scope concerns, and injecting it is what lets a procedure be
- * tested without one.
- *
- * The fingerprint is derived from `headers` and `remoteAddress`, not `ip`: a
- * limiter must never key on `ip`, since it is the attribution address, which
- * prefers client-forwarded headers and would give every request its own
- * bucket.
+ * The injected limiter. The fingerprint is derived from `headers` and
+ * `remoteAddress`, never `ip`: `ip` is the attribution address, which prefers
+ * client-forwarded headers and would give every request its own bucket.
*/
export type EnforceRateLimit = (
args: RateLimitOptions & {
@@ -502,11 +434,7 @@ export type EnforceRateLimit = (
}
) => Promise<void>;
-/**
- * Throttle a procedure by client IP, with an exponentially growing lockout for
- * repeat offenders. See the limiter for the escalation rules and for the log
- * line (`rate limit blocked`) that carries the offending IP.
- */
+/** Throttle a procedure by client IP, with an exponentially growing lockout for repeat offenders. */
export const createRateLimitMiddleware =
(enforceRateLimit: EnforceRateLimit) => (options: RateLimitOptions) =>
t.middleware(async ({ ctx, next, path }) => {
diff --git a/packages/core/src/rpc/deadline.ts b/packages/core/src/rpc/deadline.ts
index b85532362..7533f12d7 100644
--- a/packages/core/src/rpc/deadline.ts
+++ b/packages/core/src/rpc/deadline.ts
@@ -1,10 +1,7 @@
-// How long a tRPC call may run, and what a caller is told when it stops.
-//
// 30 s is the ceiling the dashboard already lived under: Elysia's Bun adapter
-// defaults `idleTimeout` to 30 s, and a non-streamed tRPC response writes no
-// byte before it completes, so nothing that took longer was ever delivered. The
-// deadline keeps that ceiling but turns the silent socket close into an error,
-// and stops the work behind it.
+// defaults `idleTimeout` to 30 s and a non-streamed tRPC response writes no byte
+// before it completes. The deadline keeps the ceiling but turns the silent
+// socket close into an error and stops the work behind it.
import { TRPCError } from '@trpc/server';
diff --git a/packages/core/src/rpc/handler.test.ts b/packages/core/src/rpc/handler.test.ts
index f98528614..0b5354ceb 100644
--- a/packages/core/src/rpc/handler.test.ts
+++ b/packages/core/src/rpc/handler.test.ts
@@ -24,8 +24,6 @@ const COOKIE_OPTIONS: CookieOptions = {
path: '/',
};
-// ---------------------------------------------------------------- onError
-
function report(overrides: Partial<TrpcErrorReport> = {}): TrpcErrorReport {
return {
error: new TRPCError({ code: 'INTERNAL_SERVER_ERROR', message: 'boom' }),
@@ -163,8 +161,6 @@ test('an untrusted forwarded ip is ignored', () => {
expect(payload.ipHeader).toBe('');
});
-// ------------------------------------------------------- the mounted handler
-
const router = createTRPCRouter({
ping: procedure.query(() => ({ pong: true })),
signIn: procedure
@@ -279,8 +275,6 @@ test('a batched request resolves every procedure in the segment', async () => {
]);
});
-// ------------------------------------------------- deadline and disconnect
-
const SHORT_DEADLINE_MS = 20;
const NEVER_FINISHES_MS = 60_000;
diff --git a/packages/core/src/rpc/handler.ts b/packages/core/src/rpc/handler.ts
index 01079bc04..eb51ab22e 100644
--- a/packages/core/src/rpc/handler.ts
+++ b/packages/core/src/rpc/handler.ts
@@ -1,7 +1,3 @@
-// The tRPC mount: the official fetch adapter, one handler, one `onError`.
-// The `onError` fields come from `ctx` and the `Request`, because under a
-// fetch adapter `req` is a `Request` and has neither `socket` nor a logger.
-
import type { AnyRouter, TRPCError } from '@trpc/server';
import { fetchRequestHandler } from '@trpc/server/adapters/fetch';
import type { IpHeaderConfig } from '../config';
@@ -17,8 +13,8 @@ import { armDeadline, RPC_DEADLINE_MS } from './deadline';
/**
* The fetch adapter derives the procedure path with
- * `pathname.slice(endpoint.length)`, and a batched request puts commas in that
- * segment — so the route it mounts on is `.all('/trpc/*')`, not `/trpc/:path`.
+ * `pathname.slice(endpoint.length)` and a batched request puts commas in that
+ * segment, so the route is `.all('/trpc/*')`, not `/trpc/:path`.
*/
export const TRPC_ENDPOINT = '/trpc';
@@ -43,9 +39,8 @@ const SILENCED_UNAUTHORIZED_PATH = 'organization.list';
const DEADLINE_HTTP_STATUS = 504;
/**
- * `bootLogger` is the fallback for when `createContext` itself threw — there is
- * no `ctx` then, and a naive `ctx.logger.error(...)` would turn a
- * context-construction failure into a second throw inside the error handler.
+ * `bootLogger` is the fallback for when `createContext` itself threw: there is
+ * no `ctx` then, and `ctx.logger.error(...)` would throw inside the handler.
*/
export function createTrpcOnError(
bootLogger: Logger,
@@ -59,9 +54,7 @@ export function createTrpcOnError(
return;
}
- // The IP is resolved from trusted headers only (see
- // `getTrustedIpFromHeaders`), so it is the address to hand to
- // Cloudflare when an abuser needs blocking at the edge.
+ // Trusted headers only, so this is the address to block at the edge.
const { ip, header } = getTrustedIpFromHeaders(
ipHeaders,
report.req.headers
@@ -79,8 +72,7 @@ export function createTrpcOnError(
const logger = report.ctx?.logger ?? bootLogger;
- // Being rate limited is the system working, not an error - logging it
- // as one buried the real errors under 15k lines a day.
+ // Being rate limited is the system working, not an error.
if (report.error.code === 'TOO_MANY_REQUESTS') {
logger.warn(payload, 'trpc rate limited');
return;
@@ -98,19 +90,13 @@ export function createTrpcOnError(
export interface TrpcFetchHandlerOptions extends TrpcContextOptions {
router: AnyRouter;
- /** Used only when `createContext` threw. Every other line goes to `ctx.logger`. */
logger: Logger;
- /** `onError` resolves the abuser's IP from trusted headers only. */
ipHeaders: IpHeaderConfig;
endpoint?: string;
- /** How long one call may run before it is stopped. */
deadlineMs?: number;
}
-/**
- * The handler `app.ts` hangs on `.all('/trpc/*')`. It returns a raw
- * `Response`, so `/trpc` sits outside Elysia's response lifecycle.
- */
+/** Returns a raw `Response`, so `/trpc` sits outside Elysia's response lifecycle. */
export function createTrpcFetchHandler(options: TrpcFetchHandlerOptions) {
const {
router,
diff --git a/packages/core/src/rpc/rate-limit.ts b/packages/core/src/rpc/rate-limit.ts
index aa17672ae..c108d4174 100644
--- a/packages/core/src/rpc/rate-limit.ts
+++ b/packages/core/src/rpc/rate-limit.ts
@@ -1,10 +1,3 @@
-// IP rate limiting with an exponentially growing lockout. Implements the seam
-// declared in `rpc/base.ts` (`EnforceRateLimit`, `createRateLimitMiddleware`).
-//
-// The enforcer takes headers, the socket address and a logger rather than a
-// framework request object, which is what lets a procedure be tested without
-// a server.
-
import { getRedisCache, LRUCache } from '@openpanel/redis';
import { TRPCError } from '@trpc/server';
import { getTrustedIpFromHeaders } from '../shared/get-client-ip';
@@ -14,18 +7,13 @@ const SECOND = 1000;
const MINUTE = 60 * SECOND;
const HOUR = 60 * MINUTE;
-/**
- * The block handed out the first time a fingerprint blows through its window.
- * It doubles on every further strike, so a client that keeps knocking walks
- * 5m -> 10m -> 20m -> ... -> BLOCK_MAX_MS.
- */
+/** The first block; it doubles on every further strike, up to BLOCK_MAX_MS. */
const BLOCK_BASE_MS = 5 * MINUTE;
const BLOCK_MAX_MS = 24 * HOUR;
/**
- * Strikes only decay after a full quiet day, and every new strike pushes the
- * expiry out again. Sustained abuse therefore stays at the 24h block: the
- * attacker has to actually stop to climb back down.
+ * Strikes decay only after a full quiet day and every new strike pushes the
+ * expiry out, so sustained abuse stays at the 24h block.
*/
const STRIKE_TTL_MS = 24 * HOUR;
@@ -33,9 +21,9 @@ const STRIKE_TTL_MS = 24 * HOUR;
const MAX_STRIKES = Math.ceil(Math.log2(BLOCK_MAX_MS / BLOCK_BASE_MS)) + 1;
/**
- * A blocked client that keeps hammering earns further strikes, but at most one
- * per cooldown. A human clicking "sign in" three more times in frustration
- * adds one strike; a bot at 5 req/s reaches the 24h cap in under ten minutes.
+ * A blocked client earns further strikes at most once per cooldown: a human
+ * clicking "sign in" in frustration adds one, a bot at 5 req/s reaches the cap
+ * in under ten minutes.
*/
const ESCALATION_COOLDOWN_MS = MINUTE;
@@ -46,20 +34,13 @@ const FALLBACK_CACHE_MAX = 10_000;
const KEY_MISSING = -2;
const KEY_WITHOUT_EXPIRY = -1;
-/**
- * Per-process fallback used only while Redis is unreachable. Without it a
- * Redis blip would leave sign-in completely unthrottled.
- */
+/** Per-process fallback while Redis is unreachable, so sign-in is not left unthrottled. */
const fallbackCounters = new LRUCache<string, number>({
max: FALLBACK_CACHE_MAX,
ttl: 5 * MINUTE,
});
-/**
- * The trusted-header defaults. A limiter must never key on the ATTRIBUTION
- * address: that one prefers client-forwarded headers, so every request would
- * get its own bucket.
- */
+/** The trusted-header defaults: the attribution address is client-forgeable. */
const TRUSTED_ONLY = { attributionOrder: undefined, trustedOrder: undefined };
const keyFor = (kind: string, path: string, fingerprint: string) =>
@@ -88,10 +69,7 @@ function tooManyRequests(blockMs: number): TRPCError {
});
}
-/**
- * Record a strike and (re)arm the block. Returns the new strike count and how
- * long the client is locked out for.
- */
+/** Record a strike and (re)arm the block. */
async function escalate(
strikeKey: string,
blockKey: string,
@@ -120,11 +98,9 @@ async function escalate(
}
/**
- * Blocks are keyed per procedure, so an office NAT that trips the sign-in
- * limit does not lose the rest of the dashboard.
- *
- * Every block is logged as `rate limit blocked` with the resolved IP, so
- * repeat offenders can be pulled out of the logs and blackholed at the edge.
+ * Blocks are keyed per procedure, so an office NAT that trips the sign-in limit
+ * does not lose the rest of the dashboard. Every block is logged with the
+ * resolved IP so repeat offenders can be blackholed at the edge.
*/
export const enforceRateLimit: EnforceRateLimit = async ({
headers,
diff --git a/packages/core/src/services.test.ts b/packages/core/src/services.test.ts
index 161db9a41..e052a3d1c 100644
--- a/packages/core/src/services.test.ts
+++ b/packages/core/src/services.test.ts
@@ -1,8 +1,6 @@
-// The composition root's two runtime invariants. Neither is visible to
-// `tooling/gates/conformance.sh`, which reads signatures only.
-//
-// Deliberately mock-free: this suite exists to run the REAL 36 factories, so a
-// `mock.module` here would test the stub instead of the composition root.
+// The composition root's two runtime invariants, which signatures alone do not
+// show. Deliberately mock-free: it runs the REAL factories, since a
+// `mock.module` would test the stub instead of the composition root.
import { expect, test } from 'bun:test';
import type { Logger } from './logger';
diff --git a/packages/core/src/services.ts b/packages/core/src/services.ts
index 6b8e654e8..d3ce7880a 100644
--- a/packages/core/src/services.ts
+++ b/packages/core/src/services.ts
@@ -36,7 +36,7 @@ import { createShareService } from './modules/share/share.service';
import { createSubscriptionService } from './modules/subscription/subscription.service';
import { createUserService } from './modules/user/user.service';
-/** What every service factory receives — derived from Ctx, so it cannot drift. */
+/** What every service factory receives, derived from Ctx so it cannot drift. */
export type ServiceDeps = Pick<
Ctx,
| 'db'
@@ -50,15 +50,11 @@ export type ServiceDeps = Pick<
| 'config'
>;
-// Two type rules the compiler enforces but cannot explain:
-//
-// 1. `Services` must stay an INTERFACE. A type alias over
-// `ReturnType<typeof createServices>` is circular — resolving it needs
-// every factory's signature and every factory's signature names
-// `Services`. Interface members resolve lazily, which breaks the loop.
-// 2. Every service method needs an explicit return type, or a factory's
-// return type cannot be computed from signatures alone. Omit one and
-// typecheck fails with ts7022/ts7023 naming the method.
+// `Services` must stay an INTERFACE: a type alias over
+// `ReturnType<typeof createServices>` is circular (every factory's signature
+// names `Services`), and interface members resolve lazily. Every service
+// method also needs an explicit return type or typecheck fails with
+// ts7022/ts7023.
export interface Services {
auth: ReturnType<typeof createAuthService>;
insight: ReturnType<typeof createInsightService>;
@@ -75,11 +71,9 @@ export interface Services {
profile: ReturnType<typeof createProfileService>;
group: ReturnType<typeof createGroupService>;
chart: ReturnType<typeof createChartService>;
- // One key per `*.service.ts`: the chart module is four files besides
- // `chart.service.ts`, so each is bound here too. `chart` keeps the composed
- // facade its own callers already use — the factories build stateless closures
- // over `deps`, so binding a sub-module twice binds the same functions, not a
- // second piece of state.
+ // One key per `*.service.ts`. `chart` keeps the composed facade its callers
+ // use; the factories build stateless closures over `deps`, so binding a
+ // sub-module twice binds the same functions, not a second piece of state.
funnel: ReturnType<typeof createFunnelService>;
conversion: ReturnType<typeof createConversionService>;
sankey: ReturnType<typeof createSankeyService>;
@@ -103,13 +97,12 @@ export interface Services {
mcp: ReturnType<typeof createMcpService>;
}
-// Stays a hoisted `function` declaration, not a `const` arrow: a `const`
-// here would put any future ESM cycle through this file in a temporal dead
-// zone that no typecheck reports and that fails at process boot.
+// A hoisted `function` declaration, not a `const` arrow: a `const` would put
+// any future ESM cycle through this file in a temporal dead zone that no
+// typecheck reports and that fails at boot.
export function createServices(deps: ServiceDeps): Services {
// The thunk is captured, not copied, so two services may call each other
- // without a cycle: `container` is assigned before any thunk body can run,
- // because every sibling reach lives inside a method body.
+ // without a cycle: `container` is assigned before any thunk body can run.
const services = (): Services => container;
const container: Services = {
auth: createAuthService(deps, services),
diff --git a/packages/core/src/shared/access-lookups.ts b/packages/core/src/shared/access-lookups.ts
index 8a3a313af..e57fee254 100644
--- a/packages/core/src/shared/access-lookups.ts
+++ b/packages/core/src/shared/access-lookups.ts
@@ -1,34 +1,20 @@
-// The concrete, Prisma-backed access lookups. Deliberately a sibling of
-// modules/auth/src/access.ts rather than living inside it: the ladder must
-// stay importable with no database (see its own header), while this file is
-// the real `@openpanel/db` binding ~28 modules' `src/access.ts` files supply
-// to it.
+// The Prisma-backed access lookups, a sibling of `modules/auth/src/access.ts`
+// so that ladder stays importable with no database. Two lookups are `cacheable`
+// on their ARGUMENTS and so cannot take a `ServiceDeps` parameter; Postgres
+// comes from `context.ts`'s `unscopedDb` (the same client as `ctx.db`).
//
-// Postgres comes from `context.ts`'s `unscopedDb`. Two of the three lookups
-// here are `cacheable`, whose key is derived from the call's ARGUMENTS
-// (packages/redis/cachable.ts), so they cannot take a `ServiceDeps` leading
-// parameter at all; the third (`getClientAccess`) delegates to them and stays
-// symmetric. It is the same client `ctx.db` is, not a second one.
-//
-// `getProjectById` is spelled here rather than imported from
-// `project.service.ts`: `shared/` sits below `modules/` and the ladder reads
-// one field off the row.
+// `getProjectById` is spelled here because `shared/` sits below `modules/`.
import type { AccessLevel } from '@openpanel/db/src/prisma-client';
import { cacheable } from '@openpanel/redis';
-// Lazy: `context.ts` value-imports `services.ts`, so a static import here
-// would drag the whole 36-service graph into the import graph of everything
-// that reaches this file.
+// Lazy: `context.ts` value-imports `services.ts`, and a static import would
+// drag the whole services graph into everything that reaches this file.
function unscopedDb() {
return import('../context').then((m) => m.unscopedDb());
}
-/**
- * The project row the ladder reads (`modules/auth/src/access.ts`'s `AccessLookups`).
- * Same query as `project.service.ts`'s `getProjectById`, without the scope
- * that file's callers have and this one does not.
- */
+/** The project row the access ladder reads. */
export async function getProjectById(
projectId: string
): Promise<{ organizationId: string | null } | null> {
@@ -53,15 +39,13 @@ export function canWriteProject(access: IProjectAccess | null): boolean {
/**
* Resolve a user's access to one project.
*
- * Returns a single shape - `{ level }` or `null` - on purpose. This used to
- * return `true` for members with no explicit ProjectAccess rows and the row
- * itself otherwise, which forced every caller into a `typeof access !==
- * 'boolean'` dance. 26 of 29 mutating procedures skipped the level check
- * entirely as a result (GHSA-f9rx-pxgw-c6rg); with one shape, omitting the
- * check is a type error rather than a silent grant.
+ * Returns a single shape, `{ level }` or `null`, on purpose: returning `true`
+ * for some members forced callers into a `typeof access !== 'boolean'` dance
+ * and 26 of 29 mutating procedures skipped the level check (GHSA-f9rx-pxgw-c6rg).
+ * With one shape, omitting the check is a type error.
*
- * NOTE: the cache key is versioned. Changing the return shape without renaming
- * it would serve old-shape entries for up to 5 minutes across a rolling deploy.
+ * The cache key is versioned: changing the return shape without renaming it
+ * would serve old-shape entries for up to 5 minutes across a rolling deploy.
*/
export const getProjectAccess = cacheable(
'getProjectAccessV2',
diff --git a/packages/core/src/shared/als-session.ts b/packages/core/src/shared/als-session.ts
index 984d8293f..773b9bcd2 100644
--- a/packages/core/src/shared/als-session.ts
+++ b/packages/core/src/shared/als-session.ts
@@ -1,11 +1,8 @@
-// Both transports open the scope and nothing in the session module reads it, so
-// it is request scoping, not session domain logic. Dependency-free —
-// `node:async_hooks` and nothing else — so it sits at the bottom, where a
-// transport may reach it.
-//
-// The ALS scopes a request's dashboard session id so anything downstream —
-// today only the Prisma read-replica consistency extension — can read it
-// without threading a parameter.
+// Request scoping, not session domain logic: both transports open the scope and
+// nothing in the session module reads it. It holds a request's dashboard session
+// id so downstream code (today the Prisma read-replica consistency extension)
+// can read it without threading a parameter. Dependency-free, so a transport
+// may reach it.
import { AsyncLocalStorage } from 'node:async_hooks';
diff --git a/packages/core/src/shared/ch-dates.parity.test.ts b/packages/core/src/shared/ch-dates.parity.test.ts
index 08fa83acb..ed9ed1e07 100644
--- a/packages/core/src/shared/ch-dates.parity.test.ts
+++ b/packages/core/src/shared/ch-dates.parity.test.ts
@@ -1,9 +1,5 @@
-// Guards the second duplication this creates: core owns its own copies of
-// @openpanel/db's ClickHouse date helpers (see ch-dates.ts's header for why),
-// and a divergence would show up as silently wrong date literals in a query
-// rather than as a failing test.
-//
-// This is a test file, which `core-uses-ctx-not-db-internals` exempts.
+// core keeps its own copies of @openpanel/db's ClickHouse date helpers; a
+// divergence would show up as silently wrong date literals in a query.
import { describe, expect, it } from 'bun:test';
import * as dbClient from '@openpanel/db/src/clickhouse/client';
diff --git a/packages/core/src/shared/ch-dates.test.ts b/packages/core/src/shared/ch-dates.test.ts
index 0cabdcc02..ced60726e 100644
--- a/packages/core/src/shared/ch-dates.test.ts
+++ b/packages/core/src/shared/ch-dates.test.ts
@@ -1,6 +1,6 @@
-// The range boundaries the query builders bind. Two shapes arrive: the
-// dashboard's `YYYY-MM-DD HH:mm:ss` (already widened to the day's edges by
-// report/src/chart-dates.ts) and the MCP tools' bare `YYYY-MM-DD`.
+// The range boundaries the query builders bind: the dashboard's
+// `YYYY-MM-DD HH:mm:ss` (already widened to the day's edges) and the MCP tools'
+// bare `YYYY-MM-DD`.
import { describe, expect, test } from 'bun:test';
import { toRangeBoundaryDate, toRangeBoundaryLiteral } from './ch-dates';
diff --git a/packages/core/src/shared/ch-dates.ts b/packages/core/src/shared/ch-dates.ts
index 588bc60dd..4ad77df1d 100644
--- a/packages/core/src/shared/ch-dates.ts
+++ b/packages/core/src/shared/ch-dates.ts
@@ -1,19 +1,10 @@
-// ClickHouse's date literal format, shared across modules.
-//
-// `@openpanel/db/src/clickhouse/client.ts` owns these too, but importing it
-// constructs a real ClickHouse client and a real pino logger at module load and
-// is a value import of `@openpanel/db` from core — see ch-tables.ts's header
-// for the full reasoning. Five modules already carry a byte-identical private
-// copy in their own `src/dates.ts` (chart, event, group, profile, session).
-// `ch-dates.parity.test.ts` asserts this file and @openpanel/db's agree on
-// every input, so the copy cannot drift silently.
+// ClickHouse's date literal format. Duplicated from `@openpanel/db` because
+// importing it constructs a real ClickHouse client at module load;
+// `ch-dates.parity.test.ts` asserts the two agree on every input.
const CLICKHOUSE_DATE_SUFFIX = /(\.\d{3})?Z+$/;
-/**
- * `YYYY-MM-DD HH:mm:ss` in UTC. `skipTime` narrows it to `YYYY-MM-DD`, for
- * the date-only column comparisons the billing counters build.
- */
+/** `YYYY-MM-DD HH:mm:ss` in UTC; `skipTime` narrows it to `YYYY-MM-DD`. */
export function formatClickhouseDate(
date: Date | string,
skipTime = false
@@ -40,15 +31,12 @@ const END_OF_DAY = '23:59:59';
/**
* A range boundary as a ClickHouse `DateTime` literal.
*
- * Two shapes reach the query builders. The dashboard sends
- * `YYYY-MM-DD HH:mm:ss` already widened to the day's edges by
- * `getChartStartEndDate`; the MCP tools send a bare `YYYY-MM-DD`. A bare date
- * names a whole DAY, so an end boundary has to widen to 23:59:59 — left at
- * midnight it drops the last day of every range.
+ * The dashboard sends `YYYY-MM-DD HH:mm:ss` already widened to the day's edges;
+ * the MCP tools send a bare `YYYY-MM-DD`, which names a whole DAY, so an end
+ * boundary must widen to 23:59:59 or the last day of every range is dropped.
*
- * An already-ClickHouse-shaped literal is returned untouched rather than sent
- * through `new Date()`, which reads it in the server's local zone and shifts
- * it by the offset.
+ * An already-ClickHouse-shaped literal is returned untouched: `new Date()`
+ * would read it in the server's local zone and shift it by the offset.
*/
export function toRangeBoundaryLiteral(
value: string,
diff --git a/packages/core/src/shared/ch-fixed-string.ts b/packages/core/src/shared/ch-fixed-string.ts
index b72756e4c..9217794a6 100644
--- a/packages/core/src/shared/ch-fixed-string.ts
+++ b/packages/core/src/shared/ch-fixed-string.ts
@@ -1,7 +1,5 @@
-// ClickHouse `FixedString(N)` pads short values with NUL bytes, so a row with
-// no geo comes back as "\u0000\u0000" rather than an empty string. That text
-// reached /export/events, the dashboard, the MCP tools and the charts
-// (ISSUES.md, API nits).
+// ClickHouse `FixedString(N)` pads short values with NUL bytes, so a row with no
+// geo comes back as "\u0000\u0000" instead of an empty string.
export function stripFixedStringPadding(value: string): string {
// biome-ignore lint/suspicious/noControlCharactersInRegex: the padding IS a control character
diff --git a/packages/core/src/shared/ch-tables.parity.test.ts b/packages/core/src/shared/ch-tables.parity.test.ts
index 419cbf16d..3b0f2a676 100644
--- a/packages/core/src/shared/ch-tables.parity.test.ts
+++ b/packages/core/src/shared/ch-tables.parity.test.ts
@@ -1,11 +1,5 @@
-// Guards the one duplication this creates: core owns its own copy of
-// @openpanel/db's `TABLE_NAMES` (see ch-tables.ts's header for why), and a
-// table added on one side only would otherwise be found by a failing query in
-// production rather than by CI.
-//
-// This is a test file, which `core-uses-ctx-not-db-internals` exempts — the
-// point of the rule is that core's REQUEST path carries `ctx.ch`, and a test
-// has no request.
+// core keeps its own copy of @openpanel/db's `TABLE_NAMES`; this catches a table
+// added on one side only in CI instead of as a failing production query.
import { describe, expect, it } from 'bun:test';
import * as dbClient from '@openpanel/db/src/clickhouse/client';
@@ -16,10 +10,8 @@ describe('ch-tables parity with @openpanel/db', () => {
expect(TABLE_NAMES).toEqual(dbClient.TABLE_NAMES);
});
- // The cluster VERDICT is the config loader's (`config.clickhouseClustered` =
- // CLICKHOUSE_CLUSTER); @openpanel/db still reads it itself. Feeding db's
- // verdict in is what makes this a parity check of the NAME derivation
- // rather than of two env reads.
+ // The cluster verdict is the config loader's; feeding db's verdict in makes
+ // this a parity check of the NAME derivation, not of two env reads.
it('derives the same mutation table name for the same verdict', () => {
const clustered = dbClient.isClickhouseClustered();
for (const name of Object.values(TABLE_NAMES)) {
diff --git a/packages/core/src/shared/ch-tables.ts b/packages/core/src/shared/ch-tables.ts
index e88d31a4f..288bec42a 100644
--- a/packages/core/src/shared/ch-tables.ts
+++ b/packages/core/src/shared/ch-tables.ts
@@ -1,17 +1,8 @@
-// The physical ClickHouse table names core reads and writes, plus the two
-// cluster helpers that derive from them.
+// The ClickHouse table names core reads and writes, plus two cluster helpers.
//
-// These live in `@openpanel/db/src/clickhouse/client.ts` too, and that module
-// is where the migrations (`@openpanel/db`'s `code-migrations/`) still take
-// them from — but importing it constructs a real ClickHouse client and a real
-// pino logger at module load, which is the cost every `load*` lazy loader in
-// this package existed to defer, and it is a value import of `@openpanel/db`
-// from core, which `core-uses-ctx-not-db-internals` now forbids. Core takes the
-// map, not the client: `ch` itself is always `ctx.ch` / `deps.ch`.
-//
-// The duplication is policed, not trusted: `ch-tables.parity.test.ts` asserts
-// this map and @openpanel/db's are identical, so a table added on one side and
-// not the other fails the suite rather than a query.
+// Duplicated from `@openpanel/db/src/clickhouse/client.ts` because importing
+// that constructs a real ClickHouse client and pino logger at module load.
+// `ch-tables.parity.test.ts` asserts the two maps are identical.
import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';
@@ -35,11 +26,10 @@ export const TABLE_NAMES = {
cohort_members: 'cohort_members',
cohort_metadata: 'cohort_metadata',
// Superseded by the two event_*_summary_mv entries below and dropped in
- // migration 24. Kept because migrations 13, 14 and 15 still name them.
+ // migration 24; kept because migrations 13, 14 and 15 still name them.
profile_event_summary_mv: 'profile_event_summary_mv',
- // Same content as the two MVs above, keyed for the cohort criteria that
- // read them (event + window first, profile last) rather than by profile.
- // See migration 20.
+ // Keyed for the cohort criteria that read them (event + window first,
+ // profile last) rather than by profile.
event_profile_summary_mv: 'event_profile_summary_mv',
event_property_profile_summary_mv: 'event_property_profile_summary_mv',
profile_event_property_summary_mv: 'profile_event_property_summary_mv',
@@ -47,13 +37,11 @@ export const TABLE_NAMES = {
/**
* The mutation target as a SQL fragment: `<name>_replicated ON CLUSTER
- * '{cluster}'` when clustered, the plain name otherwise. The verdict is
- * `config.clickhouseClustered`, which is CLICKHOUSE_CLUSTER and nothing else.
+ * '{cluster}'` when clustered, the plain name otherwise.
*
- * Built here rather than fed through `sql.id` because the clustered form is
- * not an identifier: the `ON CLUSTER` clause is literal template text, and
- * `'{cluster}'` is a ClickHouse *macro*, not a `{name:Type}` placeholder — it
- * carries no type suffix, so parameter substitution leaves it alone.
+ * Not fed through `sql.id`: `ON CLUSTER` is literal template text and
+ * `'{cluster}'` is a ClickHouse macro, not a `{name:Type}` placeholder, so
+ * parameter substitution leaves it alone.
*/
export function replicatedTarget(
clustered: boolean,
diff --git a/packages/core/src/shared/client-secret.ts b/packages/core/src/shared/client-secret.ts
index 05211484e..62280d506 100644
--- a/packages/core/src/shared/client-secret.ts
+++ b/packages/core/src/shared/client-secret.ts
@@ -12,10 +12,9 @@ export function hashClientSecret(secret: string): Promise<string> {
}
/**
- * Reads both formats: scrypt, and the argon2 rows the client, project and
- * onboarding services minted while they imported the user-password hasher by
- * mistake. A malformed stored hash is a failed verification, never a 500 on
- * the ingest path.
+ * Reads both formats: scrypt, and the argon2 rows some services minted by
+ * mistake with the user-password hasher. A malformed stored hash is a failed
+ * verification, never a 500 on the ingest path.
*/
export async function verifyClientSecret(
secret: string,
diff --git a/packages/core/src/shared/cookie.ts b/packages/core/src/shared/cookie.ts
index c52dbbd04..59dffab07 100644
--- a/packages/core/src/shared/cookie.ts
+++ b/packages/core/src/shared/cookie.ts
@@ -1,5 +1,4 @@
-// This is the transport-agnostic type HttpCtx.setCookie exposes to every
-// module, so a module depends on this instead of Elysia's cookie type directly.
+// Transport-agnostic, so modules do not depend on Elysia's cookie type.
export interface CookieOptions {
maxAge?: number;
@@ -24,12 +23,9 @@ const SAME_SITE_ATTRIBUTE = {
} as const;
/**
- * Serializes one `Set-Cookie` header value.
- *
- * Attribute order is fixed and deliberate, so a header produced here stays
- * byte-comparable across implementations. `signed` is deliberately not
- * emitted: it is not a cookie attribute, it is an instruction to the
- * caller's signer.
+ * Serializes one `Set-Cookie` header value. Attribute order is fixed so output
+ * stays byte-comparable across implementations. `signed` is not emitted: it is
+ * an instruction to the caller's signer, not a cookie attribute.
*/
export function serializeCookie(
name: string,
@@ -60,13 +56,7 @@ export function serializeCookie(
return header;
}
-/**
- * The read half of a request's cookies, transport-agnostic.
- *
- * `HttpCtx.cookies` is this and not Elysia's cookie record: a module reads a
- * cookie by name and nothing else, so the framework's proxy stays behind
- * `http/context.ts` and a `Ctx` never carries an Elysia type.
- */
+/** The read half of a request's cookies; keeps Elysia's proxy behind `http/context.ts`. */
export interface CookieJar {
get(name: string): string | undefined;
}
diff --git a/packages/core/src/shared/driver-errors.ts b/packages/core/src/shared/driver-errors.ts
index 3b0492acd..c8fc9efcb 100644
--- a/packages/core/src/shared/driver-errors.ts
+++ b/packages/core/src/shared/driver-errors.ts
@@ -1,13 +1,10 @@
-// Postgres and ClickHouse failures that are really BAD INPUT, classified once
-// so every transport answers the same way.
+// Postgres and ClickHouse failures that are really BAD INPUT, classified once so
+// every transport answers the same way instead of a 500 carrying the driver's
+// words (Prisma's invocation text, or ClickHouse's echo of the generated SQL).
//
-// Without this a malformed id reached the caller as a 500 carrying the
-// driver's own words — Prisma's full invocation text, or a ClickHouse message
-// that echoes the generated SQL including its scope clause (ISSUES.md H12).
-//
-// Both drivers label their failures, so nothing here parses a message:
-// Prisma sets `code` to `P####`, and @clickhouse/client sets `code` to the
-// numeric error and `type` to its name.
+// Both drivers label their failures, so nothing here parses a message: Prisma
+// sets `code` to `P####`, and @clickhouse/client sets `code` to the numeric
+// error and `type` to its name.
export interface DriverFailure {
/** tRPC's code; the HTTP status follows from it. */
@@ -22,16 +19,14 @@ const NOT_FOUND = 404;
/** https://www.prisma.io/docs/orm/reference/error-reference */
const PRISMA_FAILURES: Record<string, DriverFailure> = {
- // "Inconsistent column data" — what an `@db.Uuid` column raises for an id
- // that is not a UUID at all. It fires BEFORE any findUnique null check, so
- // procedures with a correct not-found guard still answered 500.
+ // What an `@db.Uuid` column raises for a non-UUID id. It fires BEFORE any
+ // findUnique null check, so a correct not-found guard never gets to run.
P2023: {
trpc: 'BAD_REQUEST',
status: BAD_REQUEST,
message: 'Malformed id',
},
- // "An operation failed because it depends on one or more records that were
- // required but not found" — every `findUniqueOrThrow` miss.
+ // Every `findUniqueOrThrow` miss.
P2025: {
trpc: 'NOT_FOUND',
status: NOT_FOUND,
@@ -40,9 +35,8 @@ const PRISMA_FAILURES: Record<string, DriverFailure> = {
};
/**
- * ClickHouse `type` values that can only come from caller input. Deliberately
- * a short allowlist: anything unlisted stays a 500, because a query bug must
- * not be reported to the caller as their mistake.
+ * ClickHouse `type` values that can only come from caller input. A short
+ * allowlist: a query bug must not be reported as the caller's mistake.
*/
const CLICKHOUSE_BAD_INPUT: Record<string, string> = {
CANNOT_PARSE_UUID: 'Malformed id',
@@ -63,7 +57,7 @@ function readLabels(error: unknown): { code?: string; type?: string } {
};
}
-/** `null` when the failure is not the caller's fault — leave those as 500s. */
+/** `null` when the failure is not the caller's fault; those stay 500s. */
export function classifyDriverError(error: unknown): DriverFailure | null {
const { code, type } = readLabels(error);
diff --git a/packages/core/src/shared/encryption.test.ts b/packages/core/src/shared/encryption.test.ts
index 1426eab8d..80701837b 100644
--- a/packages/core/src/shared/encryption.test.ts
+++ b/packages/core/src/shared/encryption.test.ts
@@ -1,8 +1,5 @@
-// Subject moved to @openpanel/shared; the suite did not follow it. Nothing runs
-// a `test` script in packages/shared yet — the root `test` script names its
-// four workspaces explicitly and hasn't picked up the new one — so moving this
-// file would take it out of every gate. Move it when that line can gain the
-// filter.
+// Tests @openpanel/shared's encryption from here because the root `test` script
+// does not run packages/shared.
import { describe, expect, it } from 'bun:test';
import {
decrypt,
@@ -12,8 +9,7 @@ import {
isEncrypted,
} from '@openpanel/shared/server';
-// Deterministic key for the round-trips — the value the config loader would
-// hand down as `config.encryptionKey`.
+// Deterministic key for the round-trips.
const KEY = 'a'.repeat(64);
describe('encryption (single ENCRYPTION_KEY)', () => {
@@ -50,9 +46,8 @@ describe('encryption (single ENCRYPTION_KEY)', () => {
});
it('decrypt throws a guarded error for a too-short/malformed ciphertext', () => {
- // Shorter than IV_LENGTH + AUTH_TAG_LENGTH: the tag slice comes back
- // empty. Bun's setAuthTag validates the length up front and throws a
- // bare TypeError before this guard existed; the guard normalizes that
+ // Shorter than IV_LENGTH + AUTH_TAG_LENGTH: the tag slice comes back empty.
+ // Bun's setAuthTag throws a bare TypeError on that; the guard normalizes it
// to the same descriptive error on both runtimes.
const tooShort = Buffer.from('short').toString('base64');
expect(() => decrypt(KEY, tooShort)).toThrow(
diff --git a/packages/core/src/shared/errors.ts b/packages/core/src/shared/errors.ts
index f888f4feb..cb5e5c7f2 100644
--- a/packages/core/src/shared/errors.ts
+++ b/packages/core/src/shared/errors.ts
@@ -1,6 +1,5 @@
-// Transport-agnostic: HTTP, jobs and the Kafka consumer all throw and
-// normalize through this, not through an rpc/-specific error type (see
-// rpc/errors.ts for the TRPCError family).
+// Transport-agnostic: HTTP, jobs and the Kafka consumer normalize errors here.
+// The TRPCError family is in rpc/errors.ts.
import { classifyDriverError } from './driver-errors';
@@ -55,8 +54,8 @@ export interface NormalizedError {
export function normalizeError(error: unknown): NormalizedError {
// A driver failure the CALLER caused answers with its own status and a
- // message that is not the driver's — Prisma's invocation text and
- // ClickHouse's scope clause are not the caller's business (ISSUES.md H12).
+ // message that is not the driver's (Prisma's invocation text, ClickHouse's
+ // scope clause).
const driverFailure = classifyDriverError(error);
if (driverFailure) {
return {
diff --git a/packages/core/src/shared/get-client-ip.ts b/packages/core/src/shared/get-client-ip.ts
index 1c8919288..84cc26089 100644
--- a/packages/core/src/shared/get-client-ip.ts
+++ b/packages/core/src/shared/get-client-ip.ts
@@ -1,9 +1,4 @@
-/**
- * Get client IP from headers
- *
- * Both orders are configurable per deployment (IP_HEADER_ORDER,
- * TRUSTED_IP_HEADER_ORDER); the parsed lists arrive as `config.ipHeaders`.
- */
+/** Both header orders are configurable per deployment; the parsed lists arrive as `config.ipHeaders`. */
import type { IpHeaderConfig } from '../config';
// Order matters: client-forwarded headers (set explicitly by SDKs/upstream
diff --git a/packages/core/src/shared/group-by-labels.ts b/packages/core/src/shared/group-by-labels.ts
index 67a79ae14..cc2dc9ad4 100644
--- a/packages/core/src/shared/group-by-labels.ts
+++ b/packages/core/src/shared/group-by-labels.ts
@@ -1,4 +1,3 @@
-// Sole consumer: modules/chart/src/engine/fetch.ts.
export interface ISerieDataItem {
label_0: string | null | undefined;
label_1?: string | null | undefined;
@@ -60,10 +59,9 @@ export function groupByLabels(data: ISerieDataItem[]): GroupedResult[] {
}));
// Every group is padded to the full set of dates so all series share an
- // x-axis. The lookup is a Map rather than a `.find()` per date: that scan
- // was O(groups x dates x points), and a 12-month chart with three
- // breakdowns reaches 4,640 groups over 365 dates. The OUTPUT is unchanged —
- // same dates, same order, same zero-filled points.
+ // x-axis. A Map lookup instead of a `.find()` per date: that scan was
+ // O(groups x dates x points), and a 12-month chart with three breakdowns
+ // reaches 4,640 groups over 365 dates.
const allDates = Array.from(timestamps);
return result
.filter((group) => group.name.length > 0)
diff --git a/packages/core/src/shared/headers.ts b/packages/core/src/shared/headers.ts
index 12ab8a43d..856df4b88 100644
--- a/packages/core/src/shared/headers.ts
+++ b/packages/core/src/shared/headers.ts
@@ -1,13 +1,8 @@
-// A lowercase header record — Fastify's `IncomingHttpHeaders`, or a `Headers`
-// flattened with `Object.fromEntries`. No transport has to build a real
-// `Headers` object from a raw record, which throws on a malformed name where
-// a plain record would not.
-//
-// Both auth macros in `http/` convert Elysia's `Headers` here before anything
-// else runs, and a transport may not deep-import a module's `src/`. The names
-// keep the `Ingest` prefix because the record shape is the ingest wire
-// contract; the three declarations are dependency-free and belong below every
-// layer.
+// A lowercase header record, or a `Headers` flattened with `Object.fromEntries`,
+// so no transport has to build a real `Headers` from a raw record (which throws
+// on a malformed name). A transport may not deep-import a module's `src/`, so
+// both auth macros convert Elysia's `Headers` here. The `Ingest` prefix stays
+// because the record shape is the ingest wire contract.
export type IngestHeaders = Record<string, string | string[] | undefined>;
@@ -19,8 +14,7 @@ export function headerValue(
return Array.isArray(value) ? value[0] : value;
}
-/** `Headers` -> the record shape the ingest path reads. Duplicated values are
- * joined by `Headers` itself, exactly as a Fastify record would hold them. */
+/** `Headers` -> the record shape the ingest path reads; duplicated values are joined by `Headers` itself. */
export function toIngestHeaders(headers: Headers): IngestHeaders {
const record: IngestHeaders = {};
for (const [name, value] of headers) {
diff --git a/packages/core/src/shared/id.test.ts b/packages/core/src/shared/id.test.ts
index a225f82e6..4d02110fc 100644
--- a/packages/core/src/shared/id.test.ts
+++ b/packages/core/src/shared/id.test.ts
@@ -1,8 +1,5 @@
-// Subject moved to @openpanel/shared; the suite did not follow it. Nothing
-// runs a `test` script in packages/shared yet — the root `test` script names
-// its four workspaces explicitly and root package.json was outside that
-// move's scope — so moving this file would take it out of every gate. Move
-// it when that line can gain the filter.
+// Tests @openpanel/shared's id helpers from here because the root `test` script
+// does not run packages/shared.
import { describe, expect, test } from 'bun:test';
import { generateId, shortId } from '@openpanel/shared';
diff --git a/packages/core/src/shared/js-runtime/ast-walker.ts b/packages/core/src/shared/js-runtime/ast-walker.ts
index e4f14dfe3..ce923d6ca 100644
--- a/packages/core/src/shared/js-runtime/ast-walker.ts
+++ b/packages/core/src/shared/js-runtime/ast-walker.ts
@@ -1,6 +1,3 @@
-/**
- * Simple recursive AST walker that doesn't require @babel/traverse
- */
export function walkNode(
node: unknown,
visitor: (
@@ -35,9 +32,6 @@ export function walkNode(
}
}
-/**
- * Track declared variables/parameters to know what identifiers are "local"
- */
export function collectDeclaredIdentifiers(ast: unknown): Set<string> {
const declared = new Set<string>();
@@ -114,9 +108,6 @@ function collectPatternIdentifiers(
}
}
-/**
- * Check if an identifier is used as a property key (not a value reference)
- */
export function isPropertyKey(
node: Record<string, unknown>,
parent?: Record<string, unknown>
diff --git a/packages/core/src/shared/js-runtime/constants.ts b/packages/core/src/shared/js-runtime/constants.ts
index c3e19f862..c7baeffe6 100644
--- a/packages/core/src/shared/js-runtime/constants.ts
+++ b/packages/core/src/shared/js-runtime/constants.ts
@@ -1,6 +1,3 @@
-/**
- * Allowed global identifiers - super restricted allowlist
- */
export const ALLOWED_GLOBALS = new Set([
// Basic values for comparisons
'undefined',
@@ -18,9 +15,6 @@ export const ALLOWED_GLOBALS = new Set([
'JSON',
]);
-/**
- * Allowed methods on built-in objects (static methods)
- */
export const ALLOWED_METHODS: Record<string, Set<string>> = {
// Math methods
Math: new Set(['abs', 'ceil', 'floor', 'round', 'min', 'max', 'random']),
@@ -32,10 +26,6 @@ export const ALLOWED_METHODS: Record<string, Set<string>> = {
Date: new Set(['now']),
};
-/**
- * Allowed instance methods (methods called on values, not on global objects)
- * These are safe methods that can be called on any value
- */
export const ALLOWED_INSTANCE_METHODS = new Set([
// Array instance methods
'map',
diff --git a/packages/core/src/shared/js-runtime/execute.ts b/packages/core/src/shared/js-runtime/execute.ts
index 609ad6b13..4e198b88f 100644
--- a/packages/core/src/shared/js-runtime/execute.ts
+++ b/packages/core/src/shared/js-runtime/execute.ts
@@ -12,32 +12,22 @@ const EXECUTION_TIMEOUT_MS = 250;
/** Cap on the serialized output so a template cannot balloon a webhook body. */
const MAX_OUTPUT_BYTES = 1_000_000;
-/**
- * Executes a JavaScript function template
- * @param code - JavaScript function code (arrow function or function expression)
- * @param payload - Payload object to pass to the function
- * @returns The result of executing the function
- */
export function execute(
code: string,
payload: Record<string, unknown>
): unknown {
- // Templates are checked when they are saved, but the stored string is what
- // ends up being run here. Check it again at run time rather than trusting
- // whatever passed validation at save time.
+ // Re-check at run time: the stored string is what runs, not what passed
+ // validation at save time.
const validation = validate(code);
if (!validation.valid) {
throw new Error(`Invalid JavaScript template: ${validation.error}`);
}
try {
- // The template runs in a fresh V8 context with its own globals, with
- // eval/new Function disabled there. The payload crosses in as JSON and
- // the result crosses out as JSON, so the template never holds a
- // reference to a host-realm object and nothing it returns carries a host
- // prototype or function back into the worker. This is not a security
- // boundary on its own (the validator is), but it means a validator miss
- // lands in an empty realm instead of the worker process.
+ // A fresh V8 context with its own globals and eval/new Function disabled.
+ // Payload and result cross as JSON, so the template never holds a host-realm
+ // reference. Not a security boundary on its own (the validator is), but a
+ // validator miss lands in an empty realm instead of the worker process.
const script = `'use strict'; JSON.stringify((${code})(JSON.parse(payloadJson)));`;
const resultJson: unknown = runInNewContext(
script,
diff --git a/packages/core/src/shared/js-runtime/validate.test.ts b/packages/core/src/shared/js-runtime/validate.test.ts
index d26863b1e..866a4077f 100644
--- a/packages/core/src/shared/js-runtime/validate.test.ts
+++ b/packages/core/src/shared/js-runtime/validate.test.ts
@@ -191,9 +191,9 @@ describe('validate', () => {
});
describe('Reads that reach the Function constructor', () => {
- // Every form here stores or forwards a reference instead of calling it
- // as a member, which the call checks alone never see. See
- // GHSA-mc99-9jf5-22cq / GHSA-fmf9-23m7-xg84.
+ // Every form here stores or forwards a reference instead of calling it as a
+ // member, which the call checks alone never see (GHSA-mc99-9jf5-22cq,
+ // GHSA-fmf9-23m7-xg84).
it('should block reading .constructor into a local', () => {
const result = validate(
'(payload) => { const F = payload.constructor.constructor; return F; }'
diff --git a/packages/core/src/shared/js-runtime/validate.ts b/packages/core/src/shared/js-runtime/validate.ts
index 6727f2bbb..80e416974 100644
--- a/packages/core/src/shared/js-runtime/validate.ts
+++ b/packages/core/src/shared/js-runtime/validate.ts
@@ -11,22 +11,15 @@ import {
} from './constants';
/**
- * The template language is an allowlist, not a denylist.
+ * The template language is an allowlist: every AST node type the walker meets
+ * must be in ALLOWED_NODE_TYPES or the template is refused, so a syntax form
+ * nobody thought about is rejected by default.
*
- * Every AST node type the walker meets must be in ALLOWED_NODE_TYPES or the
- * template is refused, so a syntax form nobody thought about (a tagged
- * template, a sequence expression, a class field, ...) is rejected by
- * default instead of walking past the checks. What is left is deliberately
- * small: build an object from the payload with property access, literals,
- * template strings, ternaries, and the allowlisted built-in methods.
- *
- * There is no way to call a function the template defined itself. Callbacks
- * to .map() and friends are the only place an inline arrow may appear, and
- * only allowlisted methods can invoke them. That removes recursion, IIFEs and
- * every "store a reference now, call it later" escape in one rule.
+ * A function the template defined itself can never be called: inline arrows
+ * appear only as callbacks to allowlisted methods. That removes recursion,
+ * IIFEs and every "store a reference now, call it later" escape.
*/
const ALLOWED_NODE_TYPES = new Set([
- // Structure
'File',
'Program',
'ExpressionStatement',
@@ -38,7 +31,6 @@ const ALLOWED_NODE_TYPES = new Set([
'VariableDeclaration',
'VariableDeclarator',
- // Values
'Identifier',
'NumericLiteral',
'StringLiteral',
@@ -52,31 +44,25 @@ const ALLOWED_NODE_TYPES = new Set([
'ArrayExpression',
'SpreadElement',
- // Access and calls
'MemberExpression',
'OptionalMemberExpression',
'CallExpression',
'OptionalCallExpression',
'NewExpression',
- // Operators
'BinaryExpression',
'LogicalExpression',
'UnaryExpression',
'ConditionalExpression',
'AssignmentExpression',
- // Destructuring in const declarations and callback parameters
'ObjectPattern',
'ArrayPattern',
'RestElement',
'AssignmentPattern',
]);
-/**
- * Friendlier messages for the things people are most likely to try. Anything
- * not listed here or in ALLOWED_NODE_TYPES gets a generic refusal.
- */
+/** Friendlier messages for what people are most likely to try. */
const REJECTION_MESSAGES: Record<string, string> = {
ImportDeclaration: 'import/export statements are not allowed',
ExportNamedDeclaration: 'import/export statements are not allowed',
@@ -122,10 +108,9 @@ const REJECTION_MESSAGES: Record<string, string> = {
};
/**
- * Property names that must never be read or written through. Reading
- * 'constructor' off any value walks up to the Function constructor, and
- * assigning through '__proto__' or 'prototype' reaches objects shared with
- * the rest of the process. A template never needs any of them.
+ * Property names that must never be read or written through: 'constructor'
+ * walks up to the Function constructor, '__proto__' and 'prototype' reach
+ * objects shared with the rest of the process.
*/
const FORBIDDEN_PROPERTIES = new Set([
'__proto__',
@@ -135,7 +120,6 @@ const FORBIDDEN_PROPERTIES = new Set([
'callee',
]);
-/** Globals that may be called directly, as in parseInt(payload.count). */
const ALLOWED_GLOBAL_FUNCTIONS = new Set([
'parseInt',
'parseFloat',
@@ -158,20 +142,15 @@ const ALLOWED_ASSIGNMENT_OPERATORS = new Set([
type Node = Record<string, unknown>;
-/**
- * The static name of a member expression's property, or undefined when the key
- * is only known at run time (obj[someVariable]).
- */
+/** The static name of a member expression's property, or undefined when computed. */
function staticPropertyName(member: Node): string | undefined {
const prop = member.property as Node | undefined;
if (!prop) {
return undefined;
}
if (member.computed) {
- // A literal key can be resolved. Babel has already decoded any \u / \x
- // escapes into StringLiteral.value by this point. A template literal
- // with no substitutions (`__proto__`) is just as static as a string
- // literal and must resolve the same way.
+ // Babel has already decoded \u / \x escapes; a substitution-free template
+ // literal (`__proto__`) is as static as a string and must resolve the same.
if (prop.type === 'StringLiteral') {
return prop.value as string;
}
@@ -191,10 +170,7 @@ function staticPropertyName(member: Node): string | undefined {
return prop.type === 'Identifier' ? (prop.name as string) : undefined;
}
-/**
- * The static key of a property inside an object literal or destructuring
- * pattern, or undefined when it is computed from an expression.
- */
+/** The static key of an object literal or destructuring property, or undefined when computed. */
function staticObjectPropertyKey(prop: Node): string | undefined {
const key = prop.key as Node | undefined;
if (!key) {
@@ -210,9 +186,8 @@ function staticObjectPropertyKey(prop: Node): string | undefined {
}
/**
- * Walk an assignment target back down its member chain and return the first
- * forbidden property name it passes through, if any. payload.__proto__.x is a
- * write to 'x' but goes through '__proto__', so the whole chain matters.
+ * The first forbidden property name an assignment target passes through:
+ * payload.__proto__.x writes 'x' but goes through '__proto__'.
*/
function forbiddenPropertyInChain(target: Node): string | undefined {
let current: Node | undefined = target;
@@ -232,7 +207,6 @@ function forbiddenPropertyInChain(target: Node): string | undefined {
return undefined;
}
-/** The identifier at the root of a member chain: payload in payload.a.b. */
function chainRoot(target: Node): Node | undefined {
let current: Node | undefined = target;
while (
@@ -245,7 +219,6 @@ function chainRoot(target: Node): Node | undefined {
return current;
}
-/** Validate the one statement at the root: a single arrow function. */
function validateRoot(program: Node): string | undefined {
const body = program.body as Node[];
@@ -280,7 +253,6 @@ function validateRoot(program: Node): string | undefined {
return undefined;
}
-/** Check a call's callee names something on the allowlist. */
function validateCall(
callee: Node,
declaredIdentifiers: Set<string>
@@ -289,9 +261,8 @@ function validateCall(
return 'Dynamic import() is not allowed';
}
- // parseInt(x) and friends. A local variable is never callable: the only
- // functions a template can hold are inline arrows, and those are only ever
- // invoked by the allowlisted array methods they are passed to.
+ // A local variable is never callable: the only functions a template can hold
+ // are inline arrows, invoked only by the allowlisted methods they are passed to.
if (callee.type === 'Identifier') {
const name = callee.name as string;
if (declaredIdentifiers.has(name)) {
@@ -310,7 +281,6 @@ function validateCall(
return 'Calling the result of an expression is not allowed. Call a named function or method directly.';
}
- // A computed key (obj[expr]()) cannot be matched against the allowlist.
if (callee.computed) {
return 'Computed property access on a call target is not allowed. Use a literal method name, e.g. value.toUpperCase().';
}
@@ -322,9 +292,8 @@ function validateCall(
}
const methodName = prop.name as string;
- // Static method on an allowed global: Math.round(), JSON.parse(). A local
- // that shadows the global name is an ordinary value and takes the instance
- // branch below.
+ // A local that shadows the global name is an ordinary value and takes the
+ // instance branch below.
if (
obj.type === 'Identifier' &&
ALLOWED_GLOBALS.has(obj.name as string) &&
@@ -337,7 +306,6 @@ function validateCall(
return undefined;
}
- // Instance method on a value: arr.map(), str.toLowerCase(), arr?.map()
if (!ALLOWED_INSTANCE_METHODS.has(methodName)) {
return `Method '.${methodName}()' is not allowed. Only safe methods are permitted.`;
}
@@ -378,8 +346,6 @@ export function validate(code: string): {
const type = node.type as string;
- // Anything outside the allowlist is refused, with a friendlier message
- // where we have one.
if (!ALLOWED_NODE_TYPES.has(type)) {
validationError =
REJECTION_MESSAGES[type] ??
@@ -392,10 +358,9 @@ export function validate(code: string): {
validationError = 'async/await is not allowed';
return;
}
- // Besides the root, an arrow may only be a callback handed straight
- // to a call, e.g. arr.map((x) => ...). One stored in a variable or
- // assigned onto a global is never callable and is only useful for
- // wrapping a built-in in itself.
+ // Besides the root, an arrow may only be a callback handed straight to
+ // a call. One stored in a variable is never callable and is only useful
+ // for wrapping a built-in in itself.
const isDirectCallback =
(parent?.type === 'CallExpression' ||
parent?.type === 'OptionalCallExpression') &&
@@ -435,10 +400,9 @@ export function validate(code: string): {
}
}
- // Every property read is checked, not only the ones that are called or
- // assigned: a read of 'constructor' can be stored and used later. A key
- // that is only known at run time (obj[expr]) could be any of these
- // names, so it is refused too; literal keys and numeric indexes work.
+ // Every read is checked, not only calls and assignments: a read of
+ // 'constructor' can be stored and used later. A run-time key could be
+ // any forbidden name, so it is refused too.
if (type === 'MemberExpression' || type === 'OptionalMemberExpression') {
const name = staticPropertyName(node);
if (name === undefined) {
@@ -452,7 +416,6 @@ export function validate(code: string): {
}
}
- // Object literal keys must be static too; { [expr]: v } is refused.
if (
type === 'ObjectProperty' &&
parent?.type === 'ObjectExpression' &&
@@ -463,7 +426,6 @@ export function validate(code: string): {
return;
}
- // Destructuring is a read too: const { constructor: C } = payload.
if (type === 'ObjectPattern') {
const properties = node.properties as Node[];
for (const prop of properties) {
@@ -515,8 +477,6 @@ export function validate(code: string): {
}
}
- // Plain assignments to locals and to static properties of locals are
- // fine; anything that reaches the prototype chain is not.
if (type === 'AssignmentExpression') {
const operator = node.operator as string;
if (!ALLOWED_ASSIGNMENT_OPERATORS.has(operator)) {
@@ -537,8 +497,7 @@ export function validate(code: string): {
validationError = `Assigning through '${reached}' is not allowed.`;
return;
}
- // Math.round = ..., JSON.parse = ...: writing to a global replaces a
- // built-in for the rest of the run. Only locals may be written.
+ // Writing to a global replaces a built-in for the rest of the run.
const root = chainRoot(target);
if (
root?.type !== 'Identifier' ||
diff --git a/packages/core/src/shared/json.test.ts b/packages/core/src/shared/json.test.ts
index 0176fc847..b7dea1fd8 100644
--- a/packages/core/src/shared/json.test.ts
+++ b/packages/core/src/shared/json.test.ts
@@ -1,7 +1,5 @@
-// Subject moved to @openpanel/shared; the suite did not follow it, since
-// nothing runs a `test` script in packages/shared yet and the root `test`
-// script names its four workspaces explicitly. Move this file once that
-// script can include packages/shared.
+// Tests @openpanel/shared's JSON helpers from here because the root `test` script
+// does not run packages/shared.
import { describe, expect, test } from 'bun:test';
import { getSafeJson, getSuperJson, setSuperJson } from '@openpanel/shared';
diff --git a/packages/core/src/shared/json.ts b/packages/core/src/shared/json.ts
index d9fb38406..662f8f26e 100644
--- a/packages/core/src/shared/json.ts
+++ b/packages/core/src/shared/json.ts
@@ -1,10 +1,5 @@
-// A re-export seam, not an implementation: the JSON helpers live in
-// @openpanel/shared, and every caller inside core imports them from there.
-//
-// This file survives for ONE importer: packages/db/src/clickhouse/client.ts
-// reaches `getSafeJson` by relative path across the package boundary
-// (`../../../core/src/shared/json`), because core depends on @openpanel/db and
-// importing the core barrel there would invert that edge. That import is
-// pointed at the wrong package — the fix is one line in packages/db. Delete
-// this file with it.
+// A re-export seam kept for ONE importer: packages/db/src/clickhouse/client.ts
+// reaches `getSafeJson` by relative path (`../../../core/src/shared/json`)
+// because importing the core barrel there would invert the core -> db edge.
+// That import should point at @openpanel/shared; delete this file with it.
export { getSafeJson, getSuperJson, setSuperJson } from '@openpanel/shared';
diff --git a/packages/core/src/shared/limits.constants.ts b/packages/core/src/shared/limits.constants.ts
index b1f3c33e7..d93c6c812 100644
--- a/packages/core/src/shared/limits.constants.ts
+++ b/packages/core/src/shared/limits.constants.ts
@@ -1,14 +1,7 @@
// Upper bounds for user-supplied strings, shared so modules stop inventing a
-// literal each.
-//
-// Named `*.constants.ts` deliberately: `constants-stay-isomorphic` lets a
-// constants file import zod, another constants file, or nothing, so this is the
-// only shape the rule allows a shared limit to take.
-//
-// These are ceilings, not product rules. A ceiling exists so an input cannot
-// reach work that scales with its length — argon2 in `auth/src/password.ts`,
-// a `Set-Cookie` write, a database column — and is set far above any honest
-// value so it never fires for a real user.
+// literal each. These are ceilings, not product rules: they stop an input
+// reaching work that scales with its length (argon2, a `Set-Cookie` write, a
+// database column) and sit far above any honest value.
/** Argon2 hashes this; 128 is well past any password a person types. */
export const MAX_PASSWORD = 128;
diff --git a/packages/core/src/shared/object.test.ts b/packages/core/src/shared/object.test.ts
index 969d11e6e..2b0a52634 100644
--- a/packages/core/src/shared/object.test.ts
+++ b/packages/core/src/shared/object.test.ts
@@ -1,8 +1,5 @@
-// Subject moved to @openpanel/shared; the suite did not follow it. Nothing runs
-// a `test` script in packages/shared yet — the root `test` script names its
-// four workspaces explicitly, and root package.json was out of scope for that
-// move — so moving this file would take it out of every gate. Move it when
-// that line can gain the filter.
+// Tests @openpanel/shared's object helpers from here because the root `test` script
+// does not run packages/shared.
import { describe, expect, it } from 'bun:test';
import { toDots } from '@openpanel/shared';
diff --git a/packages/core/src/shared/pagination.ts b/packages/core/src/shared/pagination.ts
index fe82ef495..f344485f7 100644
--- a/packages/core/src/shared/pagination.ts
+++ b/packages/core/src/shared/pagination.ts
@@ -1,9 +1,7 @@
-// Two pagination shapes: numeric-page offsets and opaque keyset cursors
-// (generalized to any JSON-serializable cursor).
+// Numeric-page offsets and opaque keyset cursors (any JSON-serializable cursor).
export const DEFAULT_PAGE_SIZE = 50;
-// Page 0 (or no page) is the first page — offset 0.
export function offsetFromPage(
page: number | undefined,
pageSize: number = DEFAULT_PAGE_SIZE
diff --git a/packages/core/src/shared/parser-user-agent.test.ts b/packages/core/src/shared/parser-user-agent.test.ts
index 22b2771fe..2e7c80db3 100644
--- a/packages/core/src/shared/parser-user-agent.test.ts
+++ b/packages/core/src/shared/parser-user-agent.test.ts
@@ -1,7 +1,5 @@
-// Subject moved to @openpanel/shared; the suite did not follow it. Nothing
-// runs a `test` script in packages/shared yet — the root `test` script names
-// its four workspaces explicitly — so moving this file would take it out of
-// every gate. Move it when that line can gain the filter.
+// Tests @openpanel/shared's parser from here because the root `test` script
+// does not run packages/shared.
import { describe, expect, it } from 'bun:test';
import { getDevice, parseUserAgent } from '@openpanel/shared/server';
diff --git a/packages/core/src/shared/request-id.ts b/packages/core/src/shared/request-id.ts
index 33fc06cb8..8eab6f320 100644
--- a/packages/core/src/shared/request-id.ts
+++ b/packages/core/src/shared/request-id.ts
@@ -1,8 +1,7 @@
-// An inbound request-id is honoured but never trusted verbatim — it reaches log
-// storage and a log search. Two transports are handed one from outside the
-// process — the HTTP edge (`http/hooks.ts`) and the Kafka consumer, which reads
-// the id the producer stamped into the envelope — so the rule that decides what
-// is safe to bind to a logger lives here rather than in either.
+// An inbound request-id is honoured but never trusted verbatim: it reaches log
+// storage and log search. Both the HTTP edge and the Kafka consumer receive one
+// from outside the process, so the rule for what is safe to bind to a logger
+// lives here.
import { generateId } from '@openpanel/shared';
import { REQUEST_ID_LENGTH } from '../logger';
diff --git a/packages/core/src/shared/safe-fetch.test.ts b/packages/core/src/shared/safe-fetch.test.ts
index 6276726ff..4fbdc4f96 100644
--- a/packages/core/src/shared/safe-fetch.test.ts
+++ b/packages/core/src/shared/safe-fetch.test.ts
@@ -1,7 +1,5 @@
-// Subject moved to @openpanel/shared; the suite did not follow it. Nothing runs
-// a `test` script in packages/shared yet — the root `test` script names its
-// four workspaces explicitly, so moving this file would take it out of every
-// gate. Move it when that line can gain the filter.
+// Tests @openpanel/shared's safeFetch from here because the root `test` script
+// does not run packages/shared.
import { afterAll, beforeAll, describe, expect, it } from 'bun:test';
import http from 'node:http';
import type { AddressInfo } from 'node:net';
@@ -156,9 +154,8 @@ describe('safeFetchStream', () => {
await new Promise<void>((resolve) => redirectServer.close(() => resolve()));
});
- // The streaming variant is what the importer uses, so it has to hold the
- // same line as safeFetch - a second implementation that forgot one of these
- // is exactly how the importer ended up unguarded in the first place.
+ // The streaming variant must hold the same line as safeFetch; a second
+ // implementation that forgot a check left the importer unguarded once.
it('refuses to fetch a loopback address directly', async () => {
await expect(
safeFetchStream(`http://127.0.0.1:${secretPort}/export.csv`, {
diff --git a/packages/core/src/shared/sanitize-url.ts b/packages/core/src/shared/sanitize-url.ts
index fd78323df..01bcd98e5 100644
--- a/packages/core/src/shared/sanitize-url.ts
+++ b/packages/core/src/shared/sanitize-url.ts
@@ -1,12 +1,9 @@
-// Request URLs are logged as plain strings, so key-based redaction never
-// looks inside them. Some routes take credentials in the query string (the
-// MCP endpoint accepts `?token=`), which would otherwise land verbatim in
-// log lines. The sensitive-key list lives here so the logger's redaction and
-// the URL filter match the same names (main #484).
+// Request URLs are logged as plain strings, so key-based redaction never looks
+// inside them, and some routes take credentials in the query (the MCP endpoint
+// accepts `?token=`). The key list is shared so the logger's redaction and the
+// URL filter match the same names.
-// Substring match (lowercased). Catches camelCase, snake_case, prefixed and
-// suffixed variants in one entry — e.g. 'token' covers accessToken,
-// refresh_token, jwtToken, etc.
+// Lowercased substring match, so 'token' covers accessToken, refresh_token, etc.
export const SENSITIVE_KEY_PATTERNS = [
'password',
'passwd',
@@ -39,9 +36,9 @@ export function isSensitiveKey(key: string): boolean {
}
/**
- * Replaces the values of sensitive query parameters, keeping the path and
- * every other parameter intact. The query is rebuilt from the raw text rather
- * than through URLSearchParams so untouched values keep their encoding.
+ * Replaces the values of sensitive query parameters, keeping everything else.
+ * The query is rebuilt from the raw text, not URLSearchParams, so untouched
+ * values keep their encoding.
*/
export function sanitizeUrlQuery(url: string): string {
const queryIndex = url.indexOf('?');
diff --git a/packages/core/src/shared/session.ts b/packages/core/src/shared/session.ts
index f3d2ea1c1..07793a353 100644
--- a/packages/core/src/shared/session.ts
+++ b/packages/core/src/shared/session.ts
@@ -1,11 +1,6 @@
-// The one "nobody is signed in" session value.
-//
-// It lives below every transport on purpose: `rpc/base.ts` maps
-// `HttpCtx.session`'s `null` onto it at the tRPC boundary, and
-// `modules/auth/src/login-session.ts` returns it from every non-session branch
-// of `validateSessionToken`. Defining it in the module and reaching for it from
-// `rpc/` was the shortest path to working code and an upward import; one
-// constant at the bottom of the stack is the same behaviour with no edge.
+// The one "nobody is signed in" session value, below every transport so
+// `rpc/base.ts` and `modules/auth/src/login-session.ts` can both reach it
+// without an upward import.
import type { Session } from '../context';
diff --git a/packages/core/src/shared/share-access.ts b/packages/core/src/shared/share-access.ts
index 1408bdabc..c7761efc4 100644
--- a/packages/core/src/shared/share-access.ts
+++ b/packages/core/src/shared/share-access.ts
@@ -1,5 +1,3 @@
-// Proof that a viewer entered the password of a password-protected share.
-
import { createHmac, timingSafeEqual } from 'node:crypto';
export type ShareType = 'overview' | 'dashboard' | 'report';
@@ -31,11 +29,10 @@ function requireSecret(secret: string): string {
}
/**
- * An HMAC over the share type, share id and the *current* password hash, so
- * the cookie cannot be forged without the secret, cannot be replayed against
- * another share, and stops working the moment the owner changes or removes
- * the password. Checking only that the cookie existed is what let anyone
- * bypass the password (GHSA-p6c2-mq9r-cx3r).
+ * An HMAC over the share type, share id and the *current* password hash, so the
+ * cookie cannot be forged, replayed against another share, or outlive a
+ * password change. Checking only that the cookie existed let anyone bypass the
+ * password (GHSA-p6c2-mq9r-cx3r).
*/
export function createShareAccessToken(
secret: string,
diff --git a/packages/core/src/shared/slug.test.ts b/packages/core/src/shared/slug.test.ts
index bfab1be54..f994ebbfd 100644
--- a/packages/core/src/shared/slug.test.ts
+++ b/packages/core/src/shared/slug.test.ts
@@ -1,8 +1,5 @@
-// Subject moved to @openpanel/shared; the suite did not follow it. Nothing runs
-// a `test` script in packages/shared yet — the root `test` script names its
-// four workspaces explicitly and hasn't picked up the new one — so moving this
-// file would take it out of every gate. Move it when that line can gain the
-// filter.
+// Tests @openpanel/shared's slug helper from here because the root `test` script
+// does not run packages/shared.
import { describe, expect, it } from 'bun:test';
import { slug } from '@openpanel/shared';
diff --git a/packages/core/src/shared/ssrf.test.ts b/packages/core/src/shared/ssrf.test.ts
index 36d7ef84d..ef6b003e2 100644
--- a/packages/core/src/shared/ssrf.test.ts
+++ b/packages/core/src/shared/ssrf.test.ts
@@ -1,7 +1,5 @@
-// Subject moved to @openpanel/shared; the suite did not follow it. Nothing
-// runs a `test` script in packages/shared yet — the root `test` script names
-// its four workspaces explicitly — so moving this file would take it out of
-// every gate. Move it when that line can gain the filter.
+// Tests @openpanel/shared's SSRF guard from here because the root `test` script
+// does not run packages/shared.
import { describe, expect, it, mock } from 'bun:test';
import {
assertSafeUrl,
@@ -10,8 +8,7 @@ import {
createPinnedLookup,
} from '@openpanel/shared/server';
-// SELF_HOSTED arrives as `config.selfHosted`; the loader is what decides that
-// only `true`/`1` mean self-hosted (`apps/api/src/config/env.test.ts`).
+// SELF_HOSTED arrives as `config.selfHosted`; only `true`/`1` mean self-hosted.
const CLOUD = false;
const SELF_HOSTED = true;
@@ -103,8 +100,8 @@ describe('createPinnedLookup', () => {
describe('createPinnedAgent', () => {
// Under Bun the bare `undici` specifier resolves to a built-in shim whose
- // Agent has no `close()` and ignores `dispatcher`; that broke every
- // safeFetch call (favicons, OG images) and silently dropped the pinning.
+ // Agent has no `close()` and ignores `dispatcher`, which silently dropped the
+ // pinning.
it('returns a real undici Agent, not the runtime shim', () => {
const agent = createPinnedAgent('93.184.216.34');
expect(typeof agent.close).toBe('function');
diff --git a/packages/core/src/shared/try-catch.test.ts b/packages/core/src/shared/try-catch.test.ts
index 39ac8117c..286079f47 100644
--- a/packages/core/src/shared/try-catch.test.ts
+++ b/packages/core/src/shared/try-catch.test.ts
@@ -1,8 +1,5 @@
-// Subject moved to @openpanel/shared; the suite did not follow it. Nothing
-// runs a `test` script in packages/shared yet — the root `test` script names
-// its four workspaces explicitly and root package.json was outside that
-// move's scope — so moving this file would take it out of every gate. Move
-// it when that line can gain the filter.
+// Tests @openpanel/shared's tryCatch from here because the root `test` script
+// does not run packages/shared.
import { describe, expect, test } from 'bun:test';
import { tryCatch } from '@openpanel/shared';
diff --git a/packages/core/src/slug-id.ts b/packages/core/src/slug-id.ts
index 1eb115b99..84bf3d828 100644
--- a/packages/core/src/slug-id.ts
+++ b/packages/core/src/slug-id.ts
@@ -1,12 +1,9 @@
-// Slug-based primary-id generation for project/dashboard/organization rows. A
-// sibling of shared/access-lookups.ts: needs @openpanel/db, so it stays out of
-// shared/id.ts (the database-free id helpers).
-//
-// Postgres comes from the caller's scope (`deps.db`), not a lazy
-// `import('@openpanel/db/...')` — so the requestId minted at the edge reaches
-// the uniqueness probe. `deps` is narrowed to `Pick<ServiceDeps, 'db'>` because
-// mcp's tool handlers have a fixed `@modelcontextprotocol/sdk` signature and
-// only ever hold the db the route closed over.
+// Slug-based primary-id generation for project/dashboard/organization rows.
+// Needs @openpanel/db, so it stays out of shared/id.ts (the database-free id
+// helpers). Postgres comes from the caller's scope (`deps.db`) so the requestId
+// reaches the uniqueness probe; `deps` is narrowed to `Pick<ServiceDeps, 'db'>`
+// because mcp's tool handlers have a fixed `@modelcontextprotocol/sdk` signature
+// and only hold the db the route closed over.
import { slug } from '@openpanel/shared';
import type { ServiceDeps } from './services';
diff --git a/packages/core/test/buffer-fixtures.ts b/packages/core/test/buffer-fixtures.ts
index 2a90c9edb..c29a29cc8 100644
--- a/packages/core/test/buffer-fixtures.ts
+++ b/packages/core/test/buffer-fixtures.ts
@@ -1,5 +1,4 @@
-// Stubs shared by the buffer tests. Not a test file (no `*.test.ts` suffix),
-// so the runner does not pick it up.
+// Stubs shared by the buffer tests.
import type { BufferDeps } from '../src/buffers/base-buffer';
import type { Logger } from '../src/logger';
@@ -17,14 +16,10 @@ const silentLogger: Logger = {
/**
* A buffer's boot scope, silent and never paused. Silent matters: the real
- * `createLogger` spawns a pino transport worker thread per buffer, and these
- * suites build one buffer per test.
+ * `createLogger` spawns a pino transport worker thread per buffer.
*
- * `BufferDeps.ch` is the boot scope's ClickHouse client, so a suite that
- * exercises a flush hands in its own fake here rather than mocking
- * `@openpanel/db`'s module. `stubBufferDeps` hands in a client that throws on
- * first touch — a buffer that reaches ClickHouse without one is a bug this stub
- * should surface, not hide.
+ * `stubBufferDeps` hands in a ClickHouse client that throws on first touch, so
+ * a buffer reaching ClickHouse without a suite's own fake is surfaced.
*/
const throwingClickHouse = new Proxy({} as BufferDeps['ch'], {
get() {
diff --git a/packages/core/test/config-fixture.ts b/packages/core/test/config-fixture.ts
index 06bf99608..30fe1ef54 100644
--- a/packages/core/test/config-fixture.ts
+++ b/packages/core/test/config-fixture.ts
@@ -1,10 +1,7 @@
-// The `CoreConfig` a test hands to a service, a buffer or a route: every
-// variable unset, so each module's own documented default applies. This is not
-// a second config loader — it holds no defaults of its own; `undefined` and
-// the "not set" spelling of every flag is exactly what `apps/api`'s
-// `loadConfig({})` produces for an empty environment.
-//
-// A test that cares about one knob spreads an override over it.
+// The `CoreConfig` a test hands to a service, buffer or route: every variable
+// unset, so each module's own default applies. It holds no defaults of its own;
+// it is what `apps/api`'s `loadConfig({})` produces for an empty environment. A
+// test that cares about one knob spreads an override over it.
import type { CoreConfig } from '../src/config';
diff --git a/packages/core/test/fixture-clock.ts b/packages/core/test/fixture-clock.ts
index 0a62ef0df..1e75259be 100644
--- a/packages/core/test/fixture-clock.ts
+++ b/packages/core/test/fixture-clock.ts
@@ -1,13 +1,10 @@
-// The clock that seeds and queries the shared test/fixtures.ts dataset.
-//
-// The seeder places events at `now - N days - M minutes` and several tests
-// bucket by calendar day, so a `now` within minutes of UTC midnight splits one
-// seeded day across two buckets. Pinning `now` to a fixed time of day keeps
-// every seeded offset inside its own day, whatever time the suite runs.
-//
-// The anchor is a time of day rather than a fixed calendar date because some
-// services under test compare against ClickHouse's own `now()` (the 3-month
-// project card, `inactiveDays`, last-seen buckets), which this cannot fake.
+// The clock that seeds and queries the shared test/fixtures.ts dataset. The
+// seeder places events at `now - N days - M minutes` and tests bucket by
+// calendar day, so a `now` near UTC midnight would split one seeded day across
+// two buckets; pinning the time of day avoids that. The anchor is a time of day,
+// not a date, because some services compare against ClickHouse's own `now()`
+// (the 3-month project card, `inactiveDays`, last-seen buckets), which this
+// cannot fake.
import { setSystemTime } from 'bun:test';
const FIXTURE_ANCHOR_HOUR_UTC = 12;
diff --git a/packages/core/test/http-fixtures.ts b/packages/core/test/http-fixtures.ts
index 67727b86f..a7773ce3f 100644
--- a/packages/core/test/http-fixtures.ts
+++ b/packages/core/test/http-fixtures.ts
@@ -1,5 +1,4 @@
-// Stubs shared by the http tests. Not a test file (no `*.test.ts` suffix), so
-// the runner does not pick it up.
+// Stubs shared by the http tests.
import type { AppDeps, Buffers } from '../src/context';
import { createRecordingProducers } from '../src/jobs/testing';
@@ -10,7 +9,7 @@ import { type CapturedLogger, capturingLogger } from './rpc-fixtures';
export interface AppDepsStub {
deps: AppDeps;
logger: CapturedLogger;
- /** One per `createCtx` — it scopes the producers exactly once. */
+ /** One per `createCtx`. */
scopeCalls: () => number;
childCalls: () => Record<string, unknown>[];
}
diff --git a/packages/core/test/midnight-window.test.ts b/packages/core/test/midnight-window.test.ts
index 7810c471a..d361bf4c4 100644
--- a/packages/core/test/midnight-window.test.ts
+++ b/packages/core/test/midnight-window.test.ts
@@ -1,9 +1,7 @@
-// Proof that the midnight fixture flake is gone: runs the two suites it hit
-// (see test/fixture-clock.ts) in child processes whose wall clock is frozen
-// inside the 00:00-00:25 UTC window where they used to fail.
-//
-// The children share the suites' fixture project ids, so they run one at a
-// time; bun runs test files sequentially, so no sibling file overlaps them.
+// Runs the two suites that used to flake at midnight (see test/fixture-clock.ts)
+// in child processes whose wall clock is frozen inside the 00:00-00:25 UTC
+// window. The children share fixture project ids, so they run one at a time.
+
import { describe, expect, it } from 'bun:test';
import { spawnSync } from 'bun';
import { join } from 'node:path';
@@ -15,17 +13,15 @@ const MIDNIGHT_FLAKE_SUITES = [
'src/modules/chart/chart.service.test.ts',
'src/modules/mcp/src/integration/tools.test.ts',
];
-// A floor, not an exact count: this asserted `54 pass` and went red the moment
-// someone added a test to either child suite, which says nothing about the
-// midnight window. The floor still proves both suites actually ran.
+// A floor, not an exact count, so adding a test to a child suite does not break
+// this; it still proves both suites ran.
const MIDNIGHT_FLAKE_SUITE_MIN_TESTS = 54;
const PASS_COUNT = /(\d+) pass/;
// 00:01 is inside the chart pair's window, 00:10 and 00:19 inside charlie's.
-// Only the TIME of day is the subject here; the date must track the calendar.
+// Only the TIME of day is the subject; the date must track the calendar because
// `inactiveDays` and the last-seen buckets compare against ClickHouse's own
-// `now()`, which `setSystemTime` cannot fake (test/fixture-clock.ts says so),
-// so a hardcoded date drifts further from it every day until the suites fail.
-// Measured on the current fixtures: 26 h of drift still passes, 30 h does not.
+// `now()`, which `setSystemTime` cannot fake. Measured: 26 h of drift still
+// passes, 30 h does not.
const IN_WINDOW_UTC_TIMES = ['00:01', '00:10', '00:19'] as const;
/**
@@ -81,8 +77,7 @@ describe('mcp/chart fixture suites inside the midnight window', () => {
}
});
-// The rot this replaced was a hardcoded date, so the derivation itself is
-// asserted rather than left to the calendar to disprove a year from now.
+// The derivation itself is asserted, so a hardcoded date cannot creep back.
const HOURS_IN_A_DAY = 24;
const MS_PER_HOUR = 3_600_000;
diff --git a/packages/core/test/preload.ts b/packages/core/test/preload.ts
index ccd0adcb5..b0d2d7056 100644
--- a/packages/core/test/preload.ts
+++ b/packages/core/test/preload.ts
@@ -1,16 +1,15 @@
-// Preloaded into every `bun test` process (bunfig.toml `[test] preload`).
+// Preloaded into every `bun test` process (bunfig.toml `[test] preload`). It
+// runs per test PROCESS (bun test has no `globalSetup`), so it must be
+// idempotent and cheap.
//
-// `preload` runs per test PROCESS, not once per run — bun test has no
-// `globalSetup` — so everything here must be idempotent and cheap.
-//
-// The pins below are a safety property, not a convenience: a test must not be
-// able to reach a real database because someone's .env happened to be loaded.
-// Kept in step with test/databases.ts by hand.
+// The pins below are a safety property: a test must not reach a real database
+// because someone's .env happened to be loaded. Kept in step with
+// test/databases.ts by hand.
process.env.DATABASE_URL =
'postgresql://postgres:postgres@localhost:23432/openpanel_test?schema=public';
process.env.CLICKHOUSE_URL = 'http://localhost:23123/openpanel_test';
process.env.REDIS_URL = 'redis://localhost:23379';
process.env.SELF_HOSTED = 'true';
-// Unsubscribe links are HMAC-signed and there is no default secret any more,
-// so a test that exercises one needs a key just like a deployment does.
+// Unsubscribe links are HMAC-signed with no default secret, so a test that
+// exercises one needs a key.
process.env.UNSUBSCRIBE_SECRET ||= 'test-unsubscribe-secret';
diff --git a/packages/core/test/request-id-end-to-end.test.ts b/packages/core/test/request-id-end-to-end.test.ts
index 021c0ed66..25ece8fa8 100644
--- a/packages/core/test/request-id-end-to-end.test.ts
+++ b/packages/core/test/request-id-end-to-end.test.ts
@@ -1,22 +1,8 @@
-// The requestId chain, end to end, on all three paths core actually has. One
-// file, three sections:
-//
-// 1. HTTP: route log -> enqueued envelope meta -> job handler's logger -> the
-// enqueue that job makes. Four hops, one id. 2. CHART: a real
-// `ctx.services.chart` query, observed on the ClickHouse call's own `query
-// info` line — the hop where a module that reached @openpanel/db's client
-// directly would get a connection with no request scope, so the id stops at
-// the service boundary. 3. KAFKA/INGEST: the other edge.
-// `createIncomingEventHandler` is the exact function apps/api's main.ts hands
-// the consumer, and the seam under test — createCtx -> incomingEvent ->
-// ctx.buffers / ctx.db / ctx.services — is the real one. Nothing in this
-// section is mocked.
-//
-// Each half is already covered next to its own code — `createCtx` scoping the
-// producers, `wrap` carrying `meta.requestId`, `runJob` reading it back. What
-// no unit test can show is that they agree, and that agreement is the property
-// core's shape was chosen for: if this goes red the design is wrong, not this
-// file.
+// The requestId chain end to end. Each hop is covered next to its own code;
+// what no unit test can show is that they agree. Four sections: HTTP route ->
+// enqueued envelope -> job logger -> that job's own enqueue; a real chart
+// query's ClickHouse call; the Kafka/ingest handler (nothing mocked); and one
+// request through all six hops.
import { afterAll, beforeAll, beforeEach, expect, mock, test } from 'bun:test';
import { Elysia } from 'elysia';
@@ -51,21 +37,14 @@ interface ProofServices {
ingest: { record(name: string): Promise<string> };
}
-// Snapshotted BEFORE `mock.module` below, not after — restoring by
-// re-`import`ing later would resolve the already-mocked registry entry, not
-// the real module (bare `bun test` shares one module registry across every
-// file, and this specifier and `src/context.test.ts`'s `'./services'`
-// resolve to the same file).
+// Snapshotted BEFORE `mock.module`: re-`import`ing later would resolve the
+// already-mocked registry entry (bare `bun test` shares one module registry).
const realServicesModule = { ...(await import('../src/services')) };
-// `Services` grows with every module that lands, so this proof mocks the whole
-// container with a shape of its own rather than the real one. The mock is
-// still a real service — built from the SCOPED ctx, logging to that request's
-// logger and enqueueing through that request's producers — because a
-// hand-rolled function called from the route would skip exactly the seam under
-// test. It layers `ingest.record` ON TOP of the real container rather than
-// replacing it, since sections 2 and 3 below need `ctx.services.chart` and
-// `ctx.services.session` to stay the real ones.
+// The mock layers `ingest.record` ON TOP of the real container, built from the
+// SCOPED ctx like any service, since a hand-rolled function called from the
+// route would skip the seam under test and later sections need the real
+// `ctx.services.chart` and `ctx.services.session`.
const createServices = mock((deps: ServiceDeps) => ({
...realServicesModule.createServices(deps),
ingest: {
@@ -86,7 +65,7 @@ afterAll(() => {
});
// mock.module applies at call time, not hoisted, so everything that reaches
-// `services` through `context.ts` is imported here rather than at the top.
+// `services` through `context.ts` is imported after it.
let requestLogging: typeof import('../src/http/context').requestLogging;
let defineRoutes: typeof import('../src/http/define').defineRoutes;
let opsRoutes: typeof import('../src/rest.routes').opsRoutes;
@@ -103,17 +82,14 @@ beforeEach(() => {
createServices.mockClear();
});
-// The proof declares its own queue rather than borrowing a registry one.
-// Everything else on the path is the real machinery: real producers, real
-// envelope, real runJob.
+// The proof declares its own queue; the rest of the path is real.
const proofQueue = defineQueue('proof', {
jobs: {
primary: defineJob({
payload: z.object({ name: z.string() }),
handler: async ({ payload, ctx }) => {
ctx.logger.info({ name: payload.name }, 'job handled');
- // Hop 4: a job enqueueing through its own ctx, with no requestId in
- // hand and nothing to pass one to.
+ // Hop 4: a job enqueueing through its own ctx, with no requestId in hand.
await proofProducers(ctx.queues).proof.followUp.add({
of: payload.name,
});
@@ -140,10 +116,8 @@ interface CapturedLine {
payload: Record<string, unknown>;
}
-// pino's child semantics, and they are what makes the assertion direct: a
-// child's bindings ride on every line it writes, so "the same requestId in the
-// route log and in the job's log" is a field lookup rather than an inference
-// about which child was created when.
+// A child's bindings ride on every line it writes, so "the same requestId in
+// the route log and in the job's log" is a field lookup.
function bindingLogger(
lines: CapturedLine[],
bindings: Record<string, unknown> = {}
@@ -187,8 +161,7 @@ function stubDeps() {
return { deps, lines, recorded: producers.recorded };
}
-// The health-mounted app, plus the one route the proof needs: an enqueue has
-// to start somewhere and no module owns a job yet.
+// The health-mounted app plus one route to start an enqueue from.
function buildApp(deps: AppDeps) {
const proofRoutes = defineRoutes((app) =>
app.post('/proof/track', async ({ ctx }) => ({
@@ -204,8 +177,7 @@ function buildApp(deps: AppDeps) {
.use(proofRoutes(deps));
}
-// onAfterResponse runs after `handle` resolves, which is where `request done`
-// is written.
+// onAfterResponse runs after `handle` resolves, where `request done` is written.
const settled = () => new Promise((resolve) => setTimeout(resolve, 0));
/** The envelope BullMQ would hold: `wrap` is what the real producer calls. */
@@ -260,8 +232,7 @@ test('one requestId spans the route log, the enqueue, the job and its follow-up
});
expect(response.status).toBe(200);
- // The mock is the service hop; a silent miss would leave the chain intact
- // and prove nothing.
+ // A silent miss would leave the chain intact and prove nothing.
expect(createServices).toHaveBeenCalledTimes(1);
expect(trail(lines, recorded)).toEqual({
@@ -301,10 +272,6 @@ test('a minted requestId travels the same four hops, and does not leak into the
expect(second.recorded[0]?.meta.requestId).not.toBe(minted as string);
});
-// ===========================================================================
-// Section 2 — the chart query hop.
-// ===========================================================================
-
const CHART_REQUEST_ID = 'm10-003-chart-query';
const CHART_PROJECT_ID = 'requestid-chart-project';
@@ -338,8 +305,7 @@ function chartLogger(
const chartQueries: Array<{ query: string }> = [];
-/** Just enough of the ClickHouse client for `runQuery`: one `query` that
- * answers with an empty JSONEachRow result. */
+/** Just enough of the ClickHouse client for `runQuery`: answers with an empty JSONEachRow result. */
function chartClickHouse(): AppDeps['ch'] {
return {
query: (params: { query: string }) => {
@@ -368,9 +334,8 @@ function chartDeps() {
return { deps, lines };
}
-// `getRetentionSeries` is the narrowest real chart query: one ClickHouse
-// statement, no Postgres and no project-settings lookup, so what the test
-// observes is the transport hop and nothing else.
+// `getRetentionSeries` is one ClickHouse statement with no Postgres lookup, so
+// the test observes only the transport hop.
function buildChartApp(deps: AppDeps) {
const routes = defineRoutes((app) =>
app.post('/proof/chart', async ({ ctx }) => ({
@@ -399,7 +364,7 @@ test("a chart query made through a request-scoped ctx logs the request's own req
expect(response.status).toBe(200);
- // The query really ran through `deps.ch` — a silent miss would leave the
+ // The query really ran through `deps.ch`; a silent miss would make the
// logger assertion below trivially true.
expect(chartQueries).toHaveLength(1);
expect(chartQueries[0]?.query).toContain('FROM events');
@@ -407,7 +372,7 @@ test("a chart query made through a request-scoped ctx logs the request's own req
const bindingOf = (message: string) =>
lines.find((line) => line.message === message)?.bindings.requestId;
- // The ClickHouse call's own log line, and the route's, carry ONE requestId.
+ // The ClickHouse call's log line and the route's carry ONE requestId.
expect(bindingOf('query info')).toBe(CHART_REQUEST_ID);
expect(bindingOf('request done')).toBe(CHART_REQUEST_ID);
});
@@ -433,10 +398,6 @@ test('two concurrent requests do not share a requestId on their ClickHouse calls
expect(queryLineIds.sort()).toEqual(['req-a', 'req-b']);
});
-// ===========================================================================
-// Section 3 — the Kafka/ingest handler hop.
-// ===========================================================================
-
const INGEST_REQUEST_ID = 'adr018-kafka-1';
const INGEST_OTHER_REQUEST_ID = 'adr018-kafka-2';
const INGEST_PROJECT_ID = 'proj_ingest';
@@ -526,8 +487,7 @@ function ingestDeps() {
const eventBuffer = {
add: (event: { id: string }) => eventsBuffered.push(event),
- // The consumer scope reaches the buffer through this view; it must still be
- // the same buffer underneath.
+ // The consumer scope reaches the buffer through this view.
asRedeliverable: () => eventBuffer,
};
@@ -549,9 +509,8 @@ function ingestDeps() {
prisma: {} as AppDeps['prisma'],
db: {
project: {
- // The handler reads the project through `project.service.ts`'s
- // module-scope `getProjectByIdCached`, off the message's own scope,
- // instead of a binding resolved at boot.
+ // The handler reads the project through the module-scope
+ // `getProjectByIdCached` off the message's own scope.
findUnique: () =>
Promise.resolve({ firstEventAt: new Date(), filters: [] }),
updateMany: () => Promise.resolve({ count: 0 }),
@@ -571,8 +530,7 @@ function ingestDeps() {
const ingestBindings: IncomingEventBindings = {
checkNotificationRulesForEvent: () => Promise.resolve(null),
- // Never a duplicate here: this suite is about the requestId, and the marker
- // must not decide anything about the row either way.
+ // Never a duplicate: this suite is about the requestId.
markDuplicateEvent: () => Promise.resolve(false),
};
@@ -662,9 +620,8 @@ test("the envelope's requestId reaches the handler's logger, its buffer write an
]);
});
-// The binding enqueues exactly what `triggerNotification` enqueues, off the
-// deps it was handed, so the envelope must carry the message's own requestId,
-// not a boot-scope one.
+// The binding enqueues what `triggerNotification` enqueues, so the envelope
+// must carry the message's own requestId, not a boot-scope one.
test("a converted read path's own enqueue carries the message's requestId", async () => {
const handleEvent = createIncomingEventHandler(ingestHarness.deps, {
...ingestBindings,
@@ -723,29 +680,6 @@ test('a second message is scoped to its own id, and an envelope without one stil
expect(minted).not.toBe(INGEST_OTHER_REQUEST_ID);
});
-// ===========================================================================
-// Section 4 — one request, one id, all six hops.
-// ===========================================================================
-//
-// One chain end to end: requestId minted at the edge -> ctx -> a service's
-// bound logger -> producers.scope({ requestId }) -> the { payload, meta }
-// envelope -> the job's child logger.
-//
-// Nothing below is a stand-in for a hop. The read path is
-// `ctx.services.chart.getRetentionSeries`, a real service reaching ClickHouse
-// through `deps.ch`; the enqueue is `ctx.services.cohort.enqueueCompute`,
-// writing onto `ctx.queues`; the envelope is what `wrap` produces from what
-// the recording producer captured; and the job is the real `cohortCompute`
-// definition and handler off `jobs.registry.ts`, which reaches ClickHouse
-// again — so the last hop is a read path inside a job, observed on its own
-// `query info` line.
-//
-// Only two things are stubs, and both are the seam under test: the
-// ClickHouse client records what it was asked and the Postgres client answers
-// one row. A loader anywhere on this path, a client that built its own
-// logger, or a handler that reached past `ctx` breaks exactly one assertion
-// below and names itself.
-
const CHAIN_REQUEST_ID = 'adr022-a3-one-request';
const CHAIN_PROJECT_ID = 'chain-project';
const CHAIN_COHORT_ID = 'chain-cohort';
@@ -755,8 +689,8 @@ function chainDeps() {
const queried: string[] = [];
const commanded: string[] = [];
const inserted: string[] = [];
- // The real registry, so the enqueue below goes through the real
- // `cohortCompute` producer and is validated against the real payload schema.
+ // The real registry, so the enqueue goes through the real `cohortCompute`
+ // producer and payload schema.
const producers = createRecordingProducers(queues);
const ch = {
@@ -854,9 +788,8 @@ test('one requestId reaches a converted read path, a real enqueue, the envelope
expect(response.status).toBe(200);
- // Hop 3: a real service's ClickHouse call really ran, and its own log line
- // carries the request's id. A silent miss here would leave every assertion
- // below trivially true.
+ // A real service's ClickHouse call ran and its log line carries the request's
+ // id; a silent miss would make every assertion below trivially true.
expect(queried).toHaveLength(1);
expect(queried[0]).toContain('FROM events');
expect(queryLineIds(lines)).toEqual([CHAIN_REQUEST_ID]);
@@ -871,8 +804,8 @@ test('one requestId reaches a converted read path, a real enqueue, the envelope
expect(enqueued.payload).toEqual({ cohortId: CHAIN_COHORT_ID });
expect(enqueued.meta.requestId).toBe(CHAIN_REQUEST_ID);
- // Hop 6: the REAL job, off the REAL registry definition, reading the REAL
- // envelope — and the converted read path it makes in turn.
+ // Hop 6: the real job off the real registry definition, reading the real
+ // envelope and making its own read.
const queriesBeforeJob = queried.length;
await runJob(
queues.cohortCompute,
@@ -885,21 +818,18 @@ test('one requestId reaches a converted read path, a real enqueue, the envelope
deps
);
- // The handler reached ClickHouse through `ctx.ch`, not a client of its own:
- // one more read, plus the membership DELETE and the metadata write that
- // `updateCohortMembership` makes on the same handle.
+ // The handler reached ClickHouse through `ctx.ch`: one more read, plus the
+ // membership DELETE and the metadata write from `updateCohortMembership`.
expect(queried.length).toBeGreaterThan(queriesBeforeJob);
expect(commanded.join('\n')).toContain('DELETE FROM');
expect(inserted).toContain('cohort_metadata');
- // Every `query info` line in the process — the route's and the job's — is
- // the same request.
+ // Every `query info` line, route's and job's, is the same request.
const allQueryIds = queryLineIds(lines);
expect(allQueryIds.length).toBeGreaterThan(1);
expect(new Set(allQueryIds)).toEqual(new Set([CHAIN_REQUEST_ID]));
- // And the job's child logger carries the job identity alongside it, so a
- // log search on the id shows the request AND what it caused.
+ // The job's child logger carries the job identity alongside it.
const jobLine = lines.find(
(line) => line.message === 'query info' && line.bindings.job !== undefined
);
diff --git a/packages/core/test/rpc-fixtures.ts b/packages/core/test/rpc-fixtures.ts
index 92de56d74..6530813a2 100644
--- a/packages/core/test/rpc-fixtures.ts
+++ b/packages/core/test/rpc-fixtures.ts
@@ -1,5 +1,4 @@
-// Stubs shared by the rpc tests. Not a test file (no `*.test.ts` suffix), so
-// the runner does not pick it up.
+// Stubs shared by the rpc tests.
import {
type AppDeps,
@@ -116,8 +115,8 @@ export function stubHttpCtx(
...rest,
}
);
- // `services` is a getter with no setter on the prototype, so assigning it
- // through extendCtx's Object.assign throws. Shadow it instead.
+ // `services` is a getter with no setter on the prototype, so extendCtx's
+ // Object.assign would throw. Shadow it instead.
if (services) {
Object.defineProperty(ctx, 'services', {
value: services,
@@ -136,13 +135,9 @@ export function stubHttpCtx(
}
/**
- * `services` with the permission ladder already granted.
- *
- * `protectedProcedure` runs `enforceAccess` BEFORE the input parser, so a test
- * that wants to assert on a zod rejection has to get past the ladder first —
- * and the real one reaches Postgres. Everything a procedure does after the
- * parser is out of these tests' scope, so only the two lookups `enforceAccess`
- * makes are stubbed.
+ * `services` with the permission ladder already granted: `protectedProcedure`
+ * runs `enforceAccess` BEFORE the input parser, and the real one reaches
+ * Postgres. Only the two lookups it makes are stubbed.
*/
export function servicesWithProjectAccess(): Services {
return {
diff --git a/packages/core/test/service-deps.ts b/packages/core/test/service-deps.ts
index b698b0787..d21dc6061 100644
--- a/packages/core/test/service-deps.ts
+++ b/packages/core/test/service-deps.ts
@@ -1,16 +1,13 @@
-// A real `ServiceDeps` for integration tests: the same singletons `main.ts`
-// hands to `AppDeps`, pointed at the isolated `openpanel_test` databases by
-// preload.ts. `clients`, `buffers` and `queues` are unused by the read-path
-// services these tests exercise, so they stay unbuilt and a test that reaches
-// one gets a named error rather than silently working against a half-built
-// container.
+// A real `ServiceDeps` for integration tests, pointed at the isolated
+// `openpanel_test` databases by preload.ts. `clients`, `buffers` and `queues`
+// stay unbuilt, so a test that reaches one gets a named error instead of
+// silently working against a half-built container.
import type { Logger } from '../src/logger';
import type { ServiceDeps, Services } from '../src/services';
import { testCoreConfig } from './config-fixture';
-/** Records what the ClickHouse/Postgres call was logged with — the requestId
- * chain's observation point. */
+/** Records what the ClickHouse/Postgres call was logged with: the requestId chain's observation point. */
export function recordingLogger(
bindings: Record<string, unknown> = {},
lines: Array<{ bindings: Record<string, unknown>; message: string }> = []
@@ -40,9 +37,7 @@ function unavailable(name: string): never {
throw new Error(`${name} is not built in this test`);
}
-/** The `services()` thunk every factory takes. No suite here
- * reaches a sibling, so calling it is a named error rather than a silently
- * half-built container; a suite that needs one passes its own thunk. */
+/** The `services()` thunk every factory takes; calling it is a named error unless a suite passes its own. */
export function testServices(): () => Services {
return () => unavailable('services()');
}
diff --git a/packages/core/test/wall-clock-preload.ts b/packages/core/test/wall-clock-preload.ts
index 85f4588b7..0c7165404 100644
--- a/packages/core/test/wall-clock-preload.ts
+++ b/packages/core/test/wall-clock-preload.ts
@@ -1,9 +1,8 @@
-// Preloaded (BUN_OPTIONS=--preload) only by midnight-window.test.ts's child
-// runs: freezes the wall clock at FIXTURE_WALL_CLOCK_ISO before any suite
-// code loads, so the fixtures see the time of day the flake needs.
+// Preloaded (BUN_OPTIONS=--preload) only by midnight-window.test.ts's child runs:
+// freezes the wall clock at FIXTURE_WALL_CLOCK_ISO before any suite code loads.
//
// Core's own preload is imported first because a CLI preload may replace
-// bunfig's, and that one pins every test at the isolated openpanel_test databases.
+// bunfig's, which pins every test at the isolated openpanel_test databases.
import { setSystemTime } from 'bun:test';
import './preload';
import { WALL_CLOCK_PINNED_MARKER } from './wall-clock.constants';