Skip to content

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

chore: trim comments in db, seed, redis, shared, payments, email and api

Carl-Gerhard Lindesvärd5638852d24b6
diff --git a/apps/api/src/config/env.test.ts b/apps/api/src/config/env.test.ts
index 1267af05a..fefaa7dc9 100644
--- a/apps/api/src/config/env.test.ts
+++ b/apps/api/src/config/env.test.ts
@@ -127,8 +127,6 @@ describe('the boot flags main.ts branches on', () => {
});
});
-// -- Blank-value parsing the config loader does for itself ------------------
-
describe('blank KEY= is absent, not empty', () => {
it('falls through to the default on every field, not just the preprocessed ones', () => {
const config = loadConfig({ ...base, API_PORT: '', LOG_LEVEL: ' ' });
@@ -337,8 +335,6 @@ describe('derived values, computed once in the transform', () => {
});
it('the dead-letter list cap defaults to 1000 and takes a positive integer', () => {
- // The Kafka DLQ topic above is no longer the dead-letter destination — it
- // is kept only so the seam can be swapped back.
expect(loadConfig(base).INGEST_DEAD_LETTER_MAX_ENTRIES).toBe(1000);
expect(
loadConfig({ ...base, INGEST_DEAD_LETTER_MAX_ENTRIES: '25' })
diff --git a/apps/api/src/config/env.ts b/apps/api/src/config/env.ts
index 4e616ed70..75c265d8b 100644
--- a/apps/api/src/config/env.ts
+++ b/apps/api/src/config/env.ts
@@ -1,22 +1,7 @@
-// The sole `process.env` reader on the boot path: `packages/core` reads none,
-// so every variable it needs is parsed here and travels down as
-// `AppDeps.config` (`CoreConfig`). `packages/db` and `packages/redis` still
-// read their own connection env directly — an accepted pragmatic deviation.
-//
-// Every cross-field invariant runs as a `.superRefine` BEFORE the `.transform`,
-// so a contradiction is named at boot rather than discovered at runtime.
-// `loadConfig(source = process.env)` takes the environment as a parameter so a
-// test can hand in a minimal object.
-//
-// A blank `KEY=` is absent everywhere: `blankToUndefined` runs in front of
-// every field, so `.default` fires on an empty value exactly as it does on an
-// unset one.
-//
-// Invalid config fails boot loudly, with every issue reported at once — never a
-// fail-fast on the first bad var. Two classes, deliberately different:
-// boot-critical values (roles, queues, Kafka wiring) FAIL; tuning knobs
-// (batch sizes, limits, TTLs) fall back to the module's own documented default
-// on a malformed value.
+// The sole `process.env` reader on the boot path; `packages/db` and `packages/redis` read their own
+// connection env. Cross-field invariants run as `.superRefine` before the `.transform` so a
+// contradiction fails at boot. A blank `KEY=` counts as unset. Every issue is reported at once:
+// boot-critical values (roles, queues, Kafka wiring) fail, tuning knobs fall back to the module's default.
import type { CoreConfig, KafkaSaslMechanism } from '@openpanel/core';
import { KAFKA_SASL_MECHANISMS, queues } from '@openpanel/core';
@@ -88,12 +73,7 @@ const DEFAULT_KAFKA_SASL_MECHANISM: KafkaSaslMechanism = 'scram-sha-512';
*/
const DEFAULT_INGEST_DUPLICATE_MARKER_TTL_MS = 120_000;
-/**
- * The Kafka events consumer's token. Renamed from `events_kafka` — there is
- * one events transport now, so there is one token for it. The old spelling
- * gets its own error message below (`RENAMED_QUEUE_TOKENS`) rather than being
- * silently aliased, since a deployment's env is updated at its own pace.
- */
+/** The Kafka events consumer's token. The old `events_kafka` spelling gets its own error (`RENAMED_QUEUE_TOKENS`), not an alias. */
export const KAFKA_QUEUE_TOKEN = 'events';
/** `events` plus the seven registry keys, read from the registry itself so
@@ -138,8 +118,6 @@ function splitTokens(value: string | undefined): string[] {
.filter(Boolean);
}
-// --- field schemas ----------------------------------------------------------
-
const optionalString = z.preprocess(blankToUndefined, z.string().optional());
const stringWithDefault = (fallback: string) =>
@@ -340,7 +318,6 @@ const concurrencyShape = Object.fromEntries(
const rawSchema = z.object({
...concurrencyShape,
- // --- process / boot ---
ROLE: roleSchema,
NODE_ENV: optionalString,
LOG_LEVEL: stringWithDefault(DEFAULT_LOG_LEVEL),
@@ -366,7 +343,6 @@ const rawSchema = z.object({
z.coerce.number().int().positive().default(DEFAULT_SHUTDOWN_FORCE_EXIT_MS)
),
- // --- queues ---
/**
* Redis Cluster hash-tags every queue key (`cron` -> `{cron}`). It decides a
* Redis key name: set it on a deployment whose queues already exist
@@ -386,7 +362,6 @@ const rawSchema = z.object({
ADMIN_USERNAME: optionalString,
ADMIN_PASSWORD: optionalString,
- // --- HTTP surface ---
/**
* The CORS delegator's allowlist: the dashboard's own origin plus any extra
* comma-separated ones. Read once at boot — changing an origin needs a
@@ -405,7 +380,6 @@ const rawSchema = z.object({
/** The client ids whose requests log ip/UA. */
ENABLE_VERBOSE_LOGGING: optionalString,
- // --- logging ---
LOG_SILENT: trueOrOneSchema,
LOG_EXPORTER: z.preprocess(
blankToUndefined,
@@ -414,11 +388,9 @@ const rawSchema = z.object({
LOG_PREFIX: optionalString,
HYPERDX_API_KEY: optionalString,
- // --- storage / crypto ---
CLICKHOUSE_CLUSTER: trueOrOneSchema,
ENCRYPTION_KEY: optionalString,
- // --- auth ---
ALLOW_REGISTRATION: optionalString,
ALLOW_INVITATION: optionalString,
GITHUB_CLIENT_ID: stringWithDefault(''),
@@ -431,7 +403,6 @@ const rawSchema = z.object({
COOKIE_TLDS: tokenList,
CUSTOM_COOKIE_DOMAIN: optionalString,
- // --- outbound providers ---
OPENAI_API_KEY: optionalString,
OPENAI_BASE_URL: optionalString,
OPENAI_PROJECT: optionalString,
@@ -449,7 +420,6 @@ const rawSchema = z.object({
GCS_API_ENDPOINT: optionalString,
DISABLE_PING: definedIsTrueSchema,
- // --- kafka ---
KAFKA_CLIENT_ID: stringWithDefault(DEFAULT_KAFKA_CLIENT_ID),
KAFKA_BROKERS: tokenList,
KAFKA_EVENTS_TOPIC: stringWithDefault(DEFAULT_KAFKA_EVENTS_TOPIC),
@@ -511,17 +481,14 @@ const rawSchema = z.object({
KAFKA_MAX_MESSAGE_BYTES: optionalPositiveInt,
KAFKA_SASL_MECHANISM: kafkaSaslMechanismSchema,
- // --- ingest dead-letter ---
INGEST_DEAD_LETTER_MAX_ENTRIES: positiveIntWithDefault(
DEFAULT_INGEST_DEAD_LETTER_MAX_ENTRIES
),
- // --- ingest duplicate marker ---
INGEST_DUPLICATE_MARKER_TTL_MS: positiveIntWithDefault(
DEFAULT_INGEST_DUPLICATE_MARKER_TTL_MS
),
- // --- buffers ---
BUFFER_ASYNC_INSERTS: definedIsTrueSchema,
BUFFER_CH_INSERT_CONCURRENCY: optionalPositiveInt,
BOT_BUFFER_BATCH_SIZE: optionalPositiveInt,
@@ -543,7 +510,6 @@ const rawSchema = z.object({
SESSION_BUFFER_CHUNK_SIZE: optionalPositiveInt,
SESSION_BUFFER_SQUASH: onUnlessDisabledSchema,
- // --- sessions ---
SESSION_TIMEOUT_MS: optionalPositiveInt,
SESSION_REAPER: onUnlessZeroSchema,
SESSION_REAPER_BATCH_SIZE: optionalPositiveInt,
@@ -560,7 +526,6 @@ const rawSchema = z.object({
),
EXPERIMENTAL_PROFILE_BACKFILL_PROJECTS: tokenList,
- // --- query sizing ---
EVENT_PROPERTY_VALUE_AUTOCOMPLETE_LIMIT: optionalPositiveInt,
COHORT_MATERIALIZE_LIMIT: optionalPositiveInt,
COHORT_QUERY_MEMORY_LIMIT_BYTES: optionalPositiveInt,
@@ -571,21 +536,17 @@ const rawSchema = z.object({
INSIGHTS_RETENTION_DAYS: optionalPositiveInt,
WIND_DOWN_MAX_PER_RUN: optionalPositiveInt,
- // --- object-store export ---
EXPORT_LAG_SECONDS: optionalPositiveInt,
EXPORT_BATCH_SIZE: optionalPositiveInt,
EXPORT_MAX_BATCHES_PER_RUN: optionalPositiveInt,
EXPORT_CONCURRENCY: optionalPositiveInt,
- // --- request IP resolution ---
IP_HEADER_ORDER: optionalTokenList,
TRUSTED_IP_HEADER_ORDER: optionalTokenList,
});
type RawEnv = z.infer<typeof rawSchema>;
-// --- cross-field invariants -------------------------------------------------
-
/** A role that consumes must have something to consume. */
function checkRoleConsumesSomething(raw: RawEnv, ctx: z.RefinementCtx): void {
if (raw.ROLE === 'api' || raw.ENABLED_QUEUES.length > 0) {
@@ -732,8 +693,6 @@ function checkProfileBackfillProjectsHaveAFlag(
});
}
-// --- derivations ------------------------------------------------------------
-
function deriveDashboardUrl(raw: RawEnv): string {
return raw.DASHBOARD_URL ?? '';
}
@@ -958,19 +917,9 @@ export interface Config {
DISABLE_BULLBOARD: boolean;
COOKIE_SECRET: string;
SHUTDOWN_FORCE_EXIT_MS: number;
- /**
- * The dead-letter list's cap. It sits here rather than in `core.kafka`
- * because the destination is no longer Kafka: `apps/api` chooses the
- * dead-letter sink, and `packages/core` only knows the `sendToDeadLetter`
- * seam it is handed.
- */
+ /** Sits here, not in `core.kafka`: `apps/api` picks the dead-letter sink and core only gets the `sendToDeadLetter` seam. */
INGEST_DEAD_LETTER_MAX_ENTRIES: number;
- /**
- * How long the ingest consumer's duplicate marker key lives. Same reason it
- * is not on `core.kafka`: the marker is keyed on the EVENT, not on a Kafka
- * coordinate, and `packages/core` only knows the `markDuplicateEvent` seam
- * it is handed.
- */
+ /** Sits here, not in `core.kafka`: the marker is keyed on the event, not a Kafka coordinate. */
INGEST_DUPLICATE_MARKER_TTL_MS: number;
/** The CORS delegator's origin allowlist, order-sensitive. */
dashboardOrigins: string[];
diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts
index 7e3d91ba7..6a7fab7a6 100644
--- a/apps/api/src/main.ts
+++ b/apps/api/src/main.ts
@@ -1,10 +1,5 @@
-// The boot entrypoint. Runs on Bun; this is the only way the API starts, and
-// `buildHttpApp` below mounts the whole HTTP surface.
-//
-// An unknown ROLE fails boot loudly, naming the value — `config/env.ts`.
-// Inside a consuming role, ENABLED_QUEUES narrows *which* consumers start
-// (cloud runs 4 replicas on `events` and 6 on the rest), and an unknown token
-// there fails boot the same way.
+// The boot entrypoint. ENABLED_QUEUES narrows which consumers start inside a consuming role
+// (cloud runs 4 replicas on `events` and 6 on the rest).
// The only `process.env` touch outside config/env.ts, and a WRITE: it sets the
// process timezone. Every value the app READS comes from `loadConfig` below.
@@ -93,11 +88,6 @@ const HTTP_IDLE_TIMEOUT_MARGIN_SECONDS = 10;
const HTTP_IDLE_TIMEOUT_SECONDS =
RPC_DEADLINE_MS / MS_PER_SECOND + HTTP_IDLE_TIMEOUT_MARGIN_SECONDS;
-/**
- * `config/env.ts` is the sole `process.env` reader on this path; an invalid
- * value fails boot loudly, naming every offending value at once (never just
- * the first), instead of being silently ignored or misinterpreted.
- */
function loadConfigOrExit(): Config {
try {
return loadConfig();
@@ -120,12 +110,7 @@ const roleConsumes = config.ROLE !== 'api';
const roleServesHttp = config.ROLE !== 'worker';
const workersEnabled = roleConsumes && !config.DISABLE_WORKERS;
-/**
- * The connection is `packages/redis`'s dedicated queue client: separate from
- * cache/pub/sub, with `maxRetriesPerRequest: null`, which BullMQ requires. It
- * stays that package's singleton to close; `producers.close` closes the
- * queues over it.
- */
+/** The dedicated queue client of `packages/redis`: BullMQ requires its `maxRetriesPerRequest: null`. `producers.close` closes the queues over it. */
function buildProducerHandle(): QueueProducerHandle {
return createProducers(queues, {
connection: getRedisQueue(),
@@ -147,9 +132,6 @@ function bufferDeps(producers: QueueProducerHandle): BufferDeps {
createLogger: (name) => logger.child({ name }),
isCronPaused: async () => (cron ? await cron.isPaused() : false),
config: config.core,
- // The boot scope's ClickHouse client, so a buffer flush logs under the same
- // client every service reaches as `deps.ch` instead of constructing its
- // own.
ch,
};
}
@@ -166,11 +148,7 @@ function findBullQueue(producers: QueueProducerHandle, name: string) {
function buildDeps(): AppDeps {
const producers = buildProducerHandle();
return {
- // The four boot handles. `packages/db` and `packages/redis` still own
- // their own singletons and read their own env, so these are references
- // to those, not new connections: one Prisma client, one round-robin
- // ClickHouse client and the cache Redis, handed down so a service reaches
- // them through its request-scoped `Ctx` instead of importing them.
+ // References to the `packages/db` and `packages/redis` singletons, not new connections.
db,
// Prisma's two JSON sentinels, so the four modules that write a nullable
// `Json?` column read them off the scope instead of importing the client.
@@ -225,12 +203,7 @@ function warnOnUnhandledSchedulers(schedulerIds: string[]): void {
}
}
-/**
- * The Kafka events consumer. The kafkajs client, the topic, the consumer group,
- * the DLQ producer and the retry bounds all come from core's own
- * `modules/ingest/src/kafka.ts` — still passed in as arguments, so
- * `consumer.ts` spells none of those names itself.
- */
+/** The Kafka events consumer. */
async function startIngestConsumer(
deps: AppDeps
): Promise<KafkaConsumerHandle> {
@@ -259,12 +232,9 @@ async function startIngestConsumer(
ttlMs: config.INGEST_DUPLICATE_MARKER_TTL_MS,
}),
}),
- // A capped Redis list, and the event is DROPPED whether or not the
- // record lands. The Kafka DLQ it replaced (`produceDeadLetterEvent`,
- // still exported from core) produced to a topic nothing creates, and
- // every failure held the offset back — a redelivery loop. The CACHE
- // client, not the queue client: only that one fails fast, and failing
- // fast is the point here.
+ // A capped Redis list, and the event is DROPPED whether or not the record lands: a Kafka DLQ topic nothing creates
+ // held the offset back in a redelivery loop. The CACHE client, not the queue client: only that one fails fast, and
+ // failing fast is the point here.
sendToDeadLetter: createDeadLetterRecorder({
client: deps.redis,
maxEntries: config.INGEST_DEAD_LETTER_MAX_ENTRIES,
@@ -323,12 +293,7 @@ function registerConsumerMetrics(deps: AppDeps): void {
);
}
-/**
- * The three cookies the GSC OAuth flow signs (gsc.rpc.ts's `signed: true`).
- * `signCookie` below produces the same `value.<b64 hmac>` form on the tRPC
- * side, which writes cookies through the fetch adapter's `resHeaders` rather
- * than through Elysia.
- */
+/** The three cookies the GSC OAuth flow signs. `signCookie` produces the same `value.<b64 hmac>` form on the tRPC side. */
const SIGNED_COOKIE_NAMES = [
'gsc_oauth_state',
'gsc_code_verifier',
@@ -418,14 +383,9 @@ async function buildHttpApp(deps: AppDeps) {
}
/**
- * uncaughtException / unhandledRejection: the process state is corrupt, so log
- * and exit fast rather than draining through a poisoned process.
- *
- * Fatals are mirrored to the REAL stderr, bypassing the output interceptor:
- * the OTLP flush window is often lost on the way down, and `docker logs` must
- * always show why we died.
- *
- * Installed in every role, always.
+ * uncaughtException / unhandledRejection: the process state is corrupt, so log and exit fast.
+ * Fatals are mirrored to the REAL stderr, bypassing the output interceptor: the OTLP flush window is often lost
+ * on the way down, and `docker logs` must always show why we died.
*/
function installFatalHandlers(): void {
process.on('uncaughtException', (error) => {
@@ -450,7 +410,6 @@ async function main() {
const role = config.ROLE;
const deps = buildDeps();
- // HTTP and default metrics register everywhere.
registerDefaultMetrics();
if (roleConsumes) {
registerConsumerMetrics(deps);
diff --git a/apps/api/src/shutdown.test.ts b/apps/api/src/shutdown.test.ts
index 8e64d6977..c16bbabc7 100644
--- a/apps/api/src/shutdown.test.ts
+++ b/apps/api/src/shutdown.test.ts
@@ -1,10 +1,4 @@
-/**
- * Regression test: both halves below matter, and the happy path alone would
- * not catch the bug — (a) the event buffer is flushed to Redis BEFORE the
- * Kafka consumer is stopped, and (b) a FAILED flush stops the sequence
- * there: the consumer is never stopped and the process exits non-zero, so
- * Kafka redelivers instead of dropping the events for good.
- */
+/** Both halves matter: the buffer is flushed to Redis BEFORE the consumer stops, and a FAILED flush stops the sequence there (exit non-zero, so Kafka redelivers instead of dropping events). */
import { describe, expect, it, mock } from 'bun:test';
import {
diff --git a/apps/api/src/shutdown.ts b/apps/api/src/shutdown.ts
index 08b039571..5ebbcfed8 100644
--- a/apps/api/src/shutdown.ts
+++ b/apps/api/src/shutdown.ts
@@ -1,25 +1,13 @@
-// The graceful-shutdown sequence, lifted out of `main.ts` so its ORDER is a
-// thing a test can assert rather than a property of how a `Promise.all` was
-// typed.
+// The graceful-shutdown sequence, kept out of `main.ts` so its ORDER can be asserted by a test.
//
-// A SIGTERM restart once permanently lost accepted events (2 of 44,075)
-// while a SIGKILL restart lost none. Graceful shutdown lost them BECAUSE
-// it was graceful: the
-// event buffer's in-process `pendingEvents` array was never flushed to Redis,
-// and the offsets for those events had already been committed, so nothing was
-// redelivered. A crash commits nothing, so Kafka replays the same window.
+// A SIGTERM restart once permanently lost accepted events: the event buffer's in-process `pendingEvents`
+// was never flushed to Redis and the offsets for those events were already committed, so nothing was
+// redelivered. A crash commits nothing, so Kafka replays the window.
//
-// The commit itself is NOT here: kafkajs auto-commits the offsets a batch
-// resolved as soon as `eachBatch` returns, so the events a Kafka batch buffered
-// are made durable inside the batch handler, before it resolves anything
-// (`consumer.ts`'s `flushBufferedEvents`). What is left for this sequence is
-// everything buffered OUTSIDE a Kafka batch — a session-end job's event, an
-// import — which no offset covers and which a `process.exit` would simply drop.
-//
-// Either way it is one rpush of at most `microBatchMaxSize` events —
-// milliseconds, well inside `SHUTDOWN_FORCE_EXIT_MS`. It is NOT a Redis ->
-// ClickHouse drain: the Redis list is durable and the next process, or another
-// replica, drains it.
+// kafkajs commits a batch's offsets as soon as `eachBatch` returns, so events buffered inside a batch are made
+// durable in the batch handler (`flushBufferedEvents`). What is left here is everything buffered OUTSIDE a
+// Kafka batch (a session-end job's event, an import): one rpush of at most `microBatchMaxSize` events,
+// well inside `SHUTDOWN_FORCE_EXIT_MS`. It is not a Redis -> ClickHouse drain; the next process drains the list.
/** Everything succeeded; the offsets are committed and the events are durable. */
export const SHUTDOWN_EXIT_OK = 0;
@@ -70,11 +58,8 @@ export async function runShutdownSequence(
// Only if THIS process consumes cron: waiting on a queue another replica
// owns would stall the whole shutdown budget on someone else's jobs.
await steps.drainCron();
- // After this line nothing new can enter the event buffer: BullMQ has
- // stopped taking jobs and the Kafka consumer has stopped fetching, and
- // both have let their in-flight handlers finish. The two are unrelated
- // teardowns, so they still run concurrently — what changed is that the
- // consumer's DISCONNECT no longer runs here, alongside them.
+ // After this line nothing new can enter the event buffer: BullMQ stopped taking jobs and the Kafka consumer
+ // stopped fetching. The two teardowns are unrelated, so they run concurrently.
await Promise.all([steps.closeWorkers(), steps.stopConsuming()]);
} catch (error) {
logger.error({ err: error }, 'Error during graceful shutdown');
diff --git a/packages/db/scripts/backfill-profile-seen.ts b/packages/db/scripts/backfill-profile-seen.ts
index ed8f427c2..902224b4e 100644
--- a/packages/db/scripts/backfill-profile-seen.ts
+++ b/packages/db/scripts/backfill-profile-seen.ts
@@ -1,28 +1,21 @@
// One-off backfill that reconciles `profiles.created_at` (first seen) and
// `profiles.last_seen_at` (last seen) against actual event activity.
//
-// After migration `16-restructure-profiles.ts` runs, every profile has
-// `last_seen_at = created_at`. From cutover onward the buffer's session-boundary
-// upserts move `last_seen_at` forward — but historically active profiles with no
-// new sessions stay at their migrated value until they're seen again.
+// After migration `16-restructure-profiles.ts` every profile has
+// `last_seen_at = created_at`; historically active profiles with no new
+// sessions keep that value until seen again. Run once per environment to make
+// both columns match the events table.
//
-// Run this once (per environment) when you want post-migration `last_seen_at`
-// (and, defensively, `created_at`) to match what the events table already
-// records.
-//
-// How it works:
-// For each project, INSERT one new row per profile with:
+// For each project, INSERT one new row per profile with:
// created_at = least(existing, min(events.created_at))
// last_seen_at = greatest(existing, max(events.created_at))
// ReplacingMergeTree(last_seen_at) dedups on the next merge, keeping the row
// with the higher `last_seen_at` — i.e. our updated row wins whenever it has
// newer activity, otherwise the existing row wins (greatest = old value).
//
-// Per-project iteration is the trick that avoids needing a temp table:
-// - The events table is sharded/sorted by `project_id` first, so the WHERE
-// clause partition-prunes the events scan to that project.
-// - Memory is bounded by one project's profile count, not the whole table.
-// - Each project is one round-trip, so progress is observable.
+// Per project, so no temp table is needed: events sorts by `project_id`
+// first (the WHERE prunes the scan), memory is bounded by one project's
+// profiles, and progress is observable.
//
// Usage:
// cd packages/db
@@ -147,7 +140,6 @@ async function main() {
`[backfill] ${projectIds.length} project(s) · concurrency=${concurrency}${dryRun ? ' · DRY RUN' : ''}`
);
- // Simple worker-pool: each worker drains a shared cursor.
let cursor = 0;
await Promise.all(
Array.from(
diff --git a/packages/db/scripts/ch-copy-from-remote.ts b/packages/db/scripts/ch-copy-from-remote.ts
index 3b8ad98c2..0c84a952f 100644
--- a/packages/db/scripts/ch-copy-from-remote.ts
+++ b/packages/db/scripts/ch-copy-from-remote.ts
@@ -80,11 +80,10 @@ async function main() {
for (const table of tables) {
console.log(`Processing table: ${table}`);
- // Every remote() argument is a bound param, so the credentials never
- // enter the query text — which is what makes the log line below safe to
- // print. `dbName` and `table` are identifiers: bound as {x:Identifier}
- // inside remote(), validated by sql.id() in the INSERT target, where a
- // param is not accepted.
+ // Every remote() argument is a bound param, so credentials never enter
+ // the query text and the log line below is safe. `dbName` and `table` are
+ // bound as {x:Identifier} inside remote() and validated by sql.id() in
+ // the INSERT target, where a param is not accepted.
const remoteTable = sql`remote(${sql.string(host)}, ${sql.identifier(dbName)}, ${sql.identifier(table)}, ${sql.string(user)}, ${sql.string(password)})`;
const projectFilter =
@@ -98,16 +97,6 @@ async function main() {
sql`INSERT INTO ${sql.id(dbName)}.${sql.id(table)} ${selectQuery}`.toStatement();
console.log(`Executing: ${insertQuery.query}`);
-
- // try {
- // await ch.command({
- // query: insertQuery.query,
- // query_params: insertQuery.query_params,
- // });
- // console.log(`✅ Copied ${table} successfully`);
- // } catch (error) {
- // console.error(`❌ Failed to copy ${table}:`, error);
- // }
}
console.log('\nDone!');
diff --git a/packages/db/scripts/ch-update-sessions-with-revenue.ts b/packages/db/scripts/ch-update-sessions-with-revenue.ts
index 8f3abe048..ad67bb275 100644
--- a/packages/db/scripts/ch-update-sessions-with-revenue.ts
+++ b/packages/db/scripts/ch-update-sessions-with-revenue.ts
@@ -1,9 +1,4 @@
// Local fixture script: give a couple of sessions per hour a random revenue.
-//
-// Took it off `clix` (since deleted) and onto the `sql` tag.
-// Both statements bind every value as a `{pN:Type}` param instead of splicing
-// it into the text, which is also what removes the hand-rolled `'${id}'`
-// quoting the ALTER used to do.
import { ch, chQuery, TABLE_NAMES } from '../src/clickhouse/client';
import { sql } from '../src/clickhouse/sql';
@@ -24,7 +19,7 @@ function getRandomRevenue() {
);
}
-/** `YYYY-MM-DD HH:mm:ss` — the literal form clix escaped a `Date` to. */
+/** `YYYY-MM-DD HH:mm:ss` */
function datetime(date: Date): string {
return date.toISOString().slice(0, 19).replace('T', ' ');
}
@@ -40,7 +35,6 @@ async function main() {
const nextHour = new Date(currentDate.getTime() + MS_PER_HOUR);
console.log(`Processing hour: ${currentDate.toISOString()}`);
- // 1. Pick random sessions for this hour
const sessions = await chQuery<{ id: string }>(sql`
SELECT id
FROM ${sql.id(TABLE_NAMES.sessions)}
@@ -87,7 +81,7 @@ async function main() {
});
console.log('Update command sent.');
- // Wait a bit to not overload mutations if running on a large range
+ // Avoid piling up mutations on a large range.
await new Promise((resolve) =>
setTimeout(resolve, PAUSE_BETWEEN_MUTATIONS_MS)
);
diff --git a/packages/db/scripts/find-duplicate-events.ts b/packages/db/scripts/find-duplicate-events.ts
index 4a6f8c63c..7c24ff1e8 100644
--- a/packages/db/scripts/find-duplicate-events.ts
+++ b/packages/db/scripts/find-duplicate-events.ts
@@ -1,10 +1,8 @@
/**
- * find-duplicate-events.ts
- *
* Reports (and optionally deletes) duplicate rows in the ClickHouse `events`
* table. A "duplicate" is two or more rows that are logically the same event
* but have different `id`s — the signature of the event being processed more
- * than once (see the Kafka consumer offset-handling fix).
+ * than once.
*
* Duplicates are matched by a content hash over the meaningful columns
* (everything that identifies the event, excluding `id`), so genuinely
@@ -34,10 +32,6 @@ import {
TABLE_NAMES,
} from '../src/clickhouse/client';
-// ---------------------------------------------------------------------------
-// Arg parsing
-// ---------------------------------------------------------------------------
-
type Bucket = 'day' | 'hour';
interface Args {
@@ -92,10 +86,6 @@ function parseArgs(): Args {
};
}
-// ---------------------------------------------------------------------------
-// SQL helpers
-// ---------------------------------------------------------------------------
-
// Format a JS Date as a ClickHouse DateTime64(3) literal (UTC).
function chDateTime(date: Date): string {
return date.toISOString().replace('T', ' ').replace('Z', '').slice(0, 23);
@@ -133,10 +123,6 @@ async function query<T>(sql: string): Promise<T[]> {
.then((res) => res.json<T>());
}
-// ---------------------------------------------------------------------------
-// Report
-// ---------------------------------------------------------------------------
-
async function report(args: Args): Promise<void> {
const bucketFn = args.bucket === 'day' ? 'toStartOfDay' : 'toStartOfHour';
const sinceLiteral = chDateTime(args.since);
@@ -236,16 +222,11 @@ async function report(args: Args): Promise<void> {
}
}
-// ---------------------------------------------------------------------------
-// Delete
-// ---------------------------------------------------------------------------
-
function* bucketRanges(
since: Date,
bucket: Bucket
): Generator<{ start: Date; end: Date }> {
const stepMs = bucket === 'day' ? 86_400_000 : 3_600_000;
- // Align the first bucket to the start of the day/hour.
const start = new Date(since);
if (bucket === 'day') {
start.setUTCHours(0, 0, 0, 0);
@@ -309,7 +290,6 @@ async function deleteDuplicates(args: Args): Promise<void> {
`created_at >= '${startLiteral}' AND created_at < '${endLiteral}'` +
`${projectClause(args.project)} AND id IN (${idList})`,
});
- // Avoid piling up mutations.
await new Promise((resolve) => setTimeout(resolve, 200));
}
}
@@ -321,8 +301,6 @@ async function deleteDuplicates(args: Args): Promise<void> {
);
}
-// ---------------------------------------------------------------------------
-
async function main(): Promise<void> {
const args = parseArgs();
await report(args);
diff --git a/packages/db/scripts/migrate-code.ts b/packages/db/scripts/migrate-code.ts
index 0847dda8f..34cbc3b14 100644
--- a/packages/db/scripts/migrate-code.ts
+++ b/packages/db/scripts/migrate-code.ts
@@ -1,11 +1,5 @@
-// The shell for `src/code-migrations`. It reads the environment, the runner
-// does the work — the same split `apps/api/src/main.ts` and `config/env.ts`
-// have, and what keeps every migration file free of `process.env`.
-//
-// `code-migrations` is not a conformance target: it lives in @openpanel/db,
-// runs as a script with direct database access and no services, and copies
-// the vocabulary it needs from core rather than importing it — isolation
-// beats reuse.
+// Reads the environment and hands it to the runner, so no migration file
+// touches `process.env`.
import type { CodeMigrationEnv } from '../src/code-migrations/helpers';
import { runCodeMigrations } from '../src/code-migrations/migrate';
diff --git a/packages/db/src/clickhouse/client.ts b/packages/db/src/clickhouse/client.ts
index 4686527e8..5eb4a8451 100644
--- a/packages/db/src/clickhouse/client.ts
+++ b/packages/db/src/clickhouse/client.ts
@@ -14,12 +14,10 @@ export { createClient } from '@clickhouse/client';
const logger = createLogger({ name: 'clickhouse' });
import type { Logger } from '@clickhouse/client';
-// Reached by relative path, not the `@openpanel/core` barrel: core depends on
-// this package (@openpanel/db), so importing the barrel here would pull core's
-// entire module graph into packages/db for one leaf JSON helper.
+// Relative path, not the `@openpanel/core` barrel: core depends on this
+// package, so the barrel would pull core's module graph in for one helper.
import { getSafeJson } from '../../../core/src/shared/json';
-// All three LogParams types are exported by the client
interface LogParams {
module: string;
message: string;
@@ -68,12 +66,9 @@ export const TABLE_NAMES = {
groups: 'groups',
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.
+ // Dropped in 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 (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',
@@ -116,19 +111,14 @@ function getClickhouseSettings(): ClickHouseSettings {
};
}
-// Request gzip is on by default — pays CPU on the worker to send less data
-// over the wire. For payload-heavy buffers (replay) the gzip step happens on
-// the single Node main thread and can block the event loop, so it's worth
-// being able to flip it off to test. Set CLICKHOUSE_REQUEST_COMPRESSION=false
-// to disable.
+// Gzip runs on the main thread and can block the event loop for payload-heavy
+// buffers (replay), so CLICKHOUSE_REQUEST_COMPRESSION=false turns it off.
const requestCompressionEnabled =
process.env.CLICKHOUSE_REQUEST_COMPRESSION !== 'false' &&
process.env.CLICKHOUSE_REQUEST_COMPRESSION !== '0';
-// Pool size per worker process. With parallel chunk inserts (cap 5 per
-// flush) and a few buffers potentially flushing concurrently across cluster
-// nodes, the previous 30 left headroom but might be tight at peak. Set
-// CLICKHOUSE_MAX_OPEN_CONNECTIONS to override.
+// Pool size per worker process: parallel chunk inserts (cap 5 per flush)
+// from several buffers flushing at once.
const maxOpenConnections = process.env.CLICKHOUSE_MAX_OPEN_CONNECTIONS
? Math.max(
1,
@@ -136,10 +126,8 @@ const maxOpenConnections = process.env.CLICKHOUSE_MAX_OPEN_CONNECTIONS
)
: 50;
-// Per-request timeout, lowered from 300_000 (5 min) — too long for fast
-// failover against a dead node. Stuck inserts should fail and retry on a
-// different node well before 5 min. 30s is enough for any legitimate batch
-// insert in this codebase. Bumpable via env if needed.
+// Short enough that a stuck insert fails over to another node quickly; 30s is
+// enough for any legitimate batch insert.
const requestTimeoutMs = process.env.CLICKHOUSE_REQUEST_TIMEOUT_MS
? Math.max(
1000,
@@ -236,10 +224,8 @@ logger.info(
'ClickHouse clients initialized'
);
-// Backwards-compat export. Some callers (notably gsc.service.ts) use
-// `originalCh` directly to bypass the retry/round-robin layer for one-off
-// DDL or for places where retry semantics aren't wanted. Points at the
-// first node.
+// Bypasses the retry/round-robin layer, for one-off DDL or where retries
+// aren't wanted. Points at the first node.
export const originalCh = clients[0]!;
const cleanQuery = (query?: string) =>
@@ -277,16 +263,13 @@ function urlHostname(url: string | undefined): string | undefined {
}
const INSERT_DEFAULT_SETTINGS: ClickHouseSettings = {
- // Increase insert timeouts and buffer sizes for large batches
max_execution_time: 300,
max_insert_block_size: '500000',
max_http_get_redirects: '0',
- // Ensure JSONEachRow stays efficient
input_format_parallel_parsing: 1,
// Keep long-running inserts/queries from idling out at proxies by sending progress headers
send_progress_in_http_headers: 1,
http_headers_progress_interval_ms: '50000',
- // Ensure server holds the connection until the query is finished
wait_end_of_query: 1,
};
diff --git a/packages/db/src/clickhouse/migration.ts b/packages/db/src/clickhouse/migration.ts
index 0a2a2f01f..3de160acb 100644
--- a/packages/db/src/clickhouse/migration.ts
+++ b/packages/db/src/clickhouse/migration.ts
@@ -64,9 +64,9 @@ export const chMigrationClient = createClient({
},
clickhouse_settings: {
wait_end_of_query: 1,
- // Ask ClickHouse to periodically send query execution progress in HTTP headers, creating some activity in the connection.
+ // Progress headers keep the connection active so long queries are not idled out by proxies.
send_progress_in_http_headers: 1,
- // The interval of sending these progress headers. Here it is less than 60s,
+ // Under 60s, the usual proxy idle timeout.
http_headers_progress_interval_ms: '50000',
},
});
@@ -79,10 +79,7 @@ export function createDatabase(name: string, isClustered: boolean) {
return `CREATE DATABASE IF NOT EXISTS ${name}`;
}
-/**
- * Creates SQL statements for table creation in ClickHouse
- * Handles both clustered and non-clustered scenarios
- */
+/** Creates SQL statements for table creation, clustered or not. */
export function createTable({
name: tableName,
columns,
@@ -106,7 +103,6 @@ export function createTable({
const partitionByClause = partitionBy ? `PARTITION BY ${partitionBy}` : '';
if (!isClustered) {
- // Non-clustered scenario: single table
return [
`CREATE TABLE IF NOT EXISTS ${tableName} (
${columnDefinitions}
@@ -119,7 +115,6 @@ ${settingsClause}`.trim(),
}
return [
- // Local replicated table
`CREATE TABLE IF NOT EXISTS ${replicated(tableName)} ON CLUSTER '{cluster}' (
${columnDefinitions}
)
@@ -127,7 +122,6 @@ ENGINE = Replicated${engine.replace(/^(.+?)\((.+?)?\)/, `$1('${CLUSTER_REPLICA_P
${partitionByClause}
ORDER BY (${orderBy.join(', ')})
${settingsClause}`.trim(),
- // Distributed table
`CREATE TABLE IF NOT EXISTS ${tableName} ON CLUSTER '{cluster}' AS ${replicated(tableName)}
ENGINE = Distributed('{cluster}', currentDatabase(), ${replicated(tableName)}, ${distributionHash})`,
];
@@ -149,9 +143,6 @@ export const modifyTTL = ({
return `ALTER TABLE ${tableName} MODIFY TTL ${ttl}`;
};
-/**
- * Generates ALTER TABLE statements for adding columns
- */
export function addColumns(
tableName: string,
columns: string[],
@@ -169,9 +160,6 @@ export function addColumns(
);
}
-/**
- * Generates ALTER TABLE statements for dropping columns
- */
export function dropColumns(
tableName: string,
columnNames: string[],
@@ -258,10 +246,10 @@ export function moveDataBetweenTables({
return [`INSERT INTO ${to} SELECT ${selectClause} FROM ${from}`];
}
- // Start from today and go back 3 years
+ // Default window: 3 years back from tomorrow, so today is included.
const endDate = batch.endDate || new Date();
if (!batch.endDate) {
- endDate.setDate(endDate.getDate() + 1); // Add 1 day to include today
+ endDate.setDate(endDate.getDate() + 1);
}
const startDate = batch.startDate || new Date();
if (!batch.startDate) {
@@ -271,13 +259,12 @@ export function moveDataBetweenTables({
let currentDate = endDate;
const interval = batch.interval || 'day';
- // Start of the week (Monday) for a given date
const getWeekStart = (date: Date): Date => {
const d = new Date(date);
const day = d.getDay();
- const diff = d.getDate() - day + (day === 0 ? -6 : 1); // Adjust to Monday
+ const diff = d.getDate() - day + (day === 0 ? -6 : 1);
d.setDate(diff);
- d.setHours(0, 0, 0, 0); // Normalize to start of day
+ d.setHours(0, 0, 0, 0);
return d;
};
@@ -310,8 +297,7 @@ export function moveDataBetweenTables({
switch (interval) {
case 'month':
previousDate.setMonth(previousDate.getMonth() - 1);
- // If we've gone below startDate's month, adjust to start of startDate's month
- // This ensures we generate SQL for the month containing startDate
+ // Clamp to the month containing startDate so it is still covered.
if (
previousDate.getFullYear() < startDate.getFullYear() ||
(previousDate.getFullYear() === startDate.getFullYear() &&
@@ -324,7 +310,6 @@ export function moveDataBetweenTables({
break;
case 'week': {
previousDate.setDate(previousDate.getDate() - 7);
- // If we've gone below startDate's week, adjust to start of startDate's week
const startWeekStart = getWeekStart(startDate);
const prevWeekStart = getWeekStart(previousDate);
if (prevWeekStart < startWeekStart) {
@@ -332,17 +317,13 @@ export function moveDataBetweenTables({
}
break;
}
- // day
default:
previousDate.setDate(previousDate.getDate() - 1);
break;
}
- // For monthly/weekly intervals with transform, upperBoundDate should be currentDate
- // because currentDate already represents the start of the period we're processing
- // The WHERE clause uses > previousDate AND <= currentDate to get exactly one period
+ // The WHERE clause uses > previousDate AND <= upperBoundDate to get exactly one period.
let upperBoundDate = currentDate;
- // Don't exceed the endDate
if (upperBoundDate > endDate) {
upperBoundDate = endDate;
}
@@ -353,7 +334,6 @@ export function moveDataBetweenTables({
AND ${batch.column} <= '${batch.transform ? batch.transform(upperBoundDate) : formatClickhouseDate(upperBoundDate, true)}'`;
sqls.push(sql);
- // For monthly/weekly intervals, stop if we've reached the start period
if (interval === 'month') {
const prevYear = previousDate.getFullYear();
const prevMonth = previousDate.getMonth();
@@ -396,7 +376,6 @@ export function createMaterializedView({
const partitionByClause = partitionBy ? `PARTITION BY ${partitionBy}` : '';
- // Transform query to use replicated table names in clustered mode
const transformedQuery = query.replace(/\{(\w+)\}/g, (_, tableName) =>
isClustered ? replicated(tableName) : tableName
);
@@ -414,7 +393,6 @@ AS ${transformedQuery}`.trim(),
}
return [
- // Replicated materialized view
`CREATE MATERIALIZED VIEW IF NOT EXISTS ${replicated(tableName)} ON CLUSTER '{cluster}'
ENGINE = Replicated${engine.replace(/^(.+?)\((.+?)?\)/, `$1('${CLUSTER_REPLICA_PATH.replace('{replicatedVersion}', replicatedVersion)}', '{replica}', $2)`).replace(/, \)$/, ')')}
${partitionByClause}
@@ -422,7 +400,6 @@ ORDER BY (${orderBy.join(', ')})
${settingsClause}
${populate ? 'POPULATE' : ''}
AS ${transformedQuery}`.trim(),
- // Distributed materialized view
`CREATE TABLE IF NOT EXISTS ${tableName} ON CLUSTER '{cluster}' AS ${replicated(tableName)}
ENGINE = Distributed('{cluster}', currentDatabase(), ${replicated(tableName)}, ${distributionHash})`,
];
diff --git a/packages/db/src/clickhouse/round-robin.test.ts b/packages/db/src/clickhouse/round-robin.test.ts
index 396764837..6a7d6f9d2 100644
--- a/packages/db/src/clickhouse/round-robin.test.ts
+++ b/packages/db/src/clickhouse/round-robin.test.ts
@@ -173,7 +173,6 @@ describe('isRetriableConnectionError', () => {
err: unknown;
expected: ErrorClass;
}> = [
- // ── transient: don't sin-bin the node ────────────────────────────
{
label: 'ECONNRESET (stale keep-alive race — the common case)',
err: Object.assign(new Error('read ECONNRESET'), {
@@ -210,7 +209,6 @@ describe('isRetriableConnectionError', () => {
}),
expected: 'transient',
},
- // ── node-down: sin-bin the node ──────────────────────────────────
{
label: 'ECONNREFUSED (node not listening)',
err: Object.assign(new Error('connect ECONNREFUSED 10.1.0.18:8123'), {
@@ -246,7 +244,6 @@ describe('isRetriableConnectionError', () => {
}),
expected: 'node-down',
},
- // ── ch-server: propagate ────────────────────────────────────────
{
label: 'CH server SQL error',
err: new Error('Code: 47, DB::Exception: Unknown identifier'),
@@ -257,7 +254,6 @@ describe('isRetriableConnectionError', () => {
err: new Error('Code: 159, DB::Exception: Timeout exceeded'),
expected: 'ch-server',
},
- // ── ch-server allow-list: overload rejections retry ──────────────
// TOO_MANY_SIMULTANEOUS_QUERIES means the node hit its concurrency
// cap at that instant, not that the query is wrong — another node
// (or a backoff) absorbs it. Transient, so the node is NOT
@@ -291,7 +287,6 @@ describe('isRetriableConnectionError', () => {
),
expected: 'ch-server',
},
- // ── cause-chain preserves classification ─────────────────────────
{
label: 'wrapped error: outer is opaque, cause is ECONNRESET',
err: Object.assign(new Error('Request failed'), {
@@ -335,9 +330,8 @@ describe('isRetriableConnectionError', () => {
},
{
label: 'Error mentioning "connect" in a non-network context',
- // This is the kind of false-positive the old "Connect" substring
- // match was at risk of. Ensure the new matcher doesn't take the
- // bait — there's no system code and no precise transport keyword.
+ // No system code and no precise transport keyword: a bare "connect"
+ // substring must not classify as node-down.
err: new Error('Cannot connect the dots in this query plan'),
},
];
diff --git a/packages/db/src/clickhouse/round-robin.ts b/packages/db/src/clickhouse/round-robin.ts
index bb386d503..15c6bc7c2 100644
--- a/packages/db/src/clickhouse/round-robin.ts
+++ b/packages/db/src/clickhouse/round-robin.ts
@@ -4,11 +4,8 @@ import type { ILogger } from '../logger';
/**
* Round-robin selection across multiple ClickHouse clients with simple
* health tracking and a withRetry wrapper that moves to a different node
- * on connection failures.
- *
- * The Hetzner LB experience taught us that L4 TCP forwarders can add
- * unbounded tail latency. Instead of going through an LB, we now hold a
- * direct connection to each CH node and pick between them ourselves.
+ * on connection failures. Used instead of an L4 load balancer, which can add
+ * unbounded tail latency.
*/
export interface ClientSlot {
@@ -133,7 +130,6 @@ export function classifyError(err: unknown): ErrorClass {
};
const msg = String(e.message ?? '');
- // ── Allow-list: overload rejections retry as transient ────────────────
// Checked before the server-error deny below. `transient` (not
// `node-down`): the node is healthy, just briefly saturated — sin-binning
// it would shrink the pool exactly when capacity is scarcest.
@@ -141,7 +137,6 @@ export function classifyError(err: unknown): ErrorClass {
return 'transient';
}
- // ── Deny: ClickHouse server errors ────────────────────────────────────
if (CH_SERVER_ERROR_PREFIX.test(msg)) {
return 'ch-server';
}
@@ -149,7 +144,6 @@ export function classifyError(err: unknown): ErrorClass {
return 'ch-server';
}
- // ── Explicit error.code wins ──────────────────────────────────────────
if (typeof e.code === 'string') {
if (NODE_DOWN_CODES.has(e.code)) {
return 'node-down';
@@ -159,7 +153,6 @@ export function classifyError(err: unknown): ErrorClass {
}
}
- // ── Message keyword fallback ──────────────────────────────────────────
if (NODE_DOWN_MESSAGE_KEYWORDS.some((k) => msg.includes(k))) {
return 'node-down';
}
@@ -167,7 +160,6 @@ export function classifyError(err: unknown): ErrorClass {
return 'transient';
}
- // ── Bare-code substring fallback ──────────────────────────────────────
if (NODE_DOWN_BARE_CODE_REGEX.test(msg)) {
return 'node-down';
}
@@ -175,7 +167,7 @@ export function classifyError(err: unknown): ErrorClass {
return 'transient';
}
- // ── Wrapped causes (Node 18+ AggregateError, undici wrapping) ─────────
+ // AggregateError / undici wrap the real error in `cause`.
if (e.cause) {
return classifyError(e.cause);
}
diff --git a/packages/db/src/clickhouse/sql.round-robin.clickhouse.test.ts b/packages/db/src/clickhouse/sql.round-robin.clickhouse.test.ts
index 350a9c815..337d0a897 100644
--- a/packages/db/src/clickhouse/sql.round-robin.clickhouse.test.ts
+++ b/packages/db/src/clickhouse/sql.round-robin.clickhouse.test.ts
@@ -112,8 +112,7 @@ describeAgainstClickhouse(
});
it('leaves the plain-string path unchanged', async () => {
- // The 122 existing `chQuery(string)` call sites must be unaffected by the
- // params slot: no params in, no params on the wire.
+ // No params in, no params on the wire.
const rows = await chQuery<{ value: number }>('SELECT 1 AS value');
expect(rows[0]?.value).toBe(1);
});
diff --git a/packages/db/src/clickhouse/sql.test.ts b/packages/db/src/clickhouse/sql.test.ts
index 529e5c928..888dafe82 100644
--- a/packages/db/src/clickhouse/sql.test.ts
+++ b/packages/db/src/clickhouse/sql.test.ts
@@ -175,7 +175,7 @@ describe('local function-scoped builder fallback (R5)', () => {
const PROFILE_COLUMNS = ['first_name', 'country'] as const;
/**
- * The shape R5 sanctions: assembly is imperative and local, but the return
+ * Assembly is imperative and local, but the return
* type is a fragment, so every value still leaves as a bound `{pN:Type}`
* and every identifier still goes through `sql.id`'s whitelist.
*/
diff --git a/packages/db/src/code-migrations/12-add-gsc.ts b/packages/db/src/code-migrations/12-add-gsc.ts
index ebd679840..a78208e63 100644
--- a/packages/db/src/code-migrations/12-add-gsc.ts
+++ b/packages/db/src/code-migrations/12-add-gsc.ts
@@ -32,7 +32,6 @@ export async function up(env: CodeMigrationEnv) {
isClustered,
}),
- // Per-page breakdown
...createTable({
name: 'gsc_pages_daily',
columns: [
@@ -49,7 +48,6 @@ export async function up(env: CodeMigrationEnv) {
isClustered,
}),
- // Per-query breakdown
...createTable({
name: 'gsc_queries_daily',
columns: [
diff --git a/packages/db/src/code-migrations/14-profile-event-property-summary-mv.ts b/packages/db/src/code-migrations/14-profile-event-property-summary-mv.ts
index 7a735bffb..6c4b4438c 100644
--- a/packages/db/src/code-migrations/14-profile-event-property-summary-mv.ts
+++ b/packages/db/src/code-migrations/14-profile-event-property-summary-mv.ts
@@ -10,9 +10,6 @@ import { type CodeMigrationEnv, getIsCluster, writeSqlDump } from './helpers';
// Per-property breakdown of profile events, used when cohort event criteria
// filter on properties.<key> AND as a future fast path for property breakdowns
// in chart queries. populate: false — backfill ad-hoc.
-//
-// NOTE: fork references this MV but never shipped a migration for it; we own
-// the authoritative DDL.
export async function up(env: CodeMigrationEnv) {
const replicatedVersion = '1';
const existingTables = await getExistingTables();
diff --git a/packages/db/src/code-migrations/19-event-property-values-projections.ts b/packages/db/src/code-migrations/19-event-property-values-projections.ts
index b0841ced6..7509c8498 100644
--- a/packages/db/src/code-migrations/19-event-property-values-projections.ts
+++ b/packages/db/src/code-migrations/19-event-property-values-projections.ts
@@ -6,84 +6,53 @@ import {
import { type CodeMigrationEnv, getIsCluster } from './helpers';
/**
- * Aggregating projection for the property-key autocomplete dropdown.
+ * Aggregating projection `epv_keys` for the property-key autocomplete dropdown.
*
- * The key picker reads event_property_values_mv, which is ORDER BY
- * (project_id, name, property_key, property_value). Two shapes exist:
+ * event_property_values_mv is ORDER BY (project_id, name, property_key,
+ * property_value), so listing keys either aggregates a project's whole slice
+ * (no event selected) or still reads every key and value of one event
+ * (event selected; p95 15.9s on a 1.6B-row deployment). A projection on
+ * (project_id, name, property_key) serves both shapes: with an event the
+ * (project_id, name) prefix is seekable, without one the query's GROUP BY is
+ * a subset of the projection's, so the optimizer still substitutes it.
+ * A projection is only substitutable when it contains every column the query
+ * references, so `name` must be part of it.
*
- * no event selected -> WHERE project_id ... GROUP BY property_key
- * event selected -> WHERE project_id AND name ... GROUP BY property_key
- *
- * Neither is cheap on that sort key. The first can seek only to project_id
- * and must then aggregate the project's whole slice (on our deployment,
- * 1.57B rows to return ~6.4K distinct keys). The second prunes to the
- * event's slice, but that slice still holds every key AND every value for
- * the event — measured 120M rows read on average, p95 15.9s.
- *
- * One aggregating projection answers both:
- *
- * epv_keys -> (project_id, name, property_key), max(created_at)
- *
- * With an event selected, (project_id, name) is a seekable prefix, so the
- * read prunes to that event's keys. With no event, the query's GROUP BY is
- * a subset of the projection's, so the optimizer still substitutes it and
- * aggregates over the (tiny) projection instead of the table — verified
- * with EXPLAIN for both shapes. The optimizer rewrites the existing picker
- * queries transparently; no application change.
- *
- * Sizing: the projection is one row per (project, event, key) — 30,212 rows
- * against a 1.637B-row MV on our deployment. Including `name` costs ~3.4x
- * the rows of a (project_id, property_key)-only projection while covering
- * the event-selected shape that one cannot serve at all (a projection is
- * only substitutable when it contains EVERY column the query references,
- * so any filter on `name` disqualifies a projection that lacks it).
- *
- * NOT included: a (project_id, property_key, property_value) projection for
- * the value picker. Its grain is 95.4% of the MV's row count — a near-
- * complete second copy of the table — and it can only serve value lookups
- * with no event selected, since the event-selected shape already gets a
- * full three-column prefix seek on the base table. Measured on our
- * deployment: 2 such queries in 30 days.
+ * A (project_id, property_key, property_value) projection for the value
+ * picker is deliberately absent: its grain is 95% of the MV's row count, and
+ * it would only serve value lookups with no event selected (rare).
*
* Notes:
- * - The projection lives on the MV's STORAGE table — the implicit
- * `.inner_id.<uuid>` table — in every topology. Clustered, neither
- * created name is alterable: `<mv>` is a Distributed table and
- * `<mv>_replicated` is itself a MaterializedView, which rejects
- * MODIFY SETTING / ADD PROJECTION with NOT_IMPLEMENTED.
+ * - The projection lives on the MV's storage table, the implicit
+ * `.inner_id.<uuid>` table, in every topology. Clustered, `<mv>` is a
+ * Distributed table and `<mv>_replicated` is itself a MaterializedView,
+ * which rejects MODIFY SETTING / ADD PROJECTION with NOT_IMPLEMENTED.
* - AggregatingMergeTree refuses ADD PROJECTION while
* deduplicate_merge_projection_mode is 'throw' (the default);
* 'rebuild' keeps projections correct across dedup merges.
- * - The migration ADDs the projection and submits MATERIALIZE PROJECTION
- * for existing parts by default. The mutation is asynchronous (the
- * migration doesn't block on it) and idempotent; queries stay correct
- * over mixed parts while it runs — ClickHouse reads the projection from
- * parts that have it and the base table from those that don't (observed
- * in EXPLAIN as two read nodes). Fresh installs no-op. Progress:
+ * - MATERIALIZE PROJECTION is an asynchronous, idempotent mutation the
+ * migration does not wait for. Queries stay correct over mixed parts while
+ * it runs. Progress (mutations are recorded against `.inner_id.<uuid>`,
+ * not the MV name):
*
* SELECT * FROM system.mutations WHERE command LIKE '%epv_%';
*
- * (mutations are recorded against `.inner_id.<uuid>`, not the MV name)
- *
- * - The mutation rewrites projection data for every part, so deployments
- * with a very large MV that want to control WHEN the backfill runs can
- * apply the setting + ADD PROJECTION + MATERIALIZE PROJECTION statements
- * manually before upgrading (off-peak), against the storage table —
- * the `.inner_id.<uuid>` table, resolvable with
+ * - The mutation rewrites projection data for every part. Deployments with a
+ * very large MV can run the setting + ADD PROJECTION + MATERIALIZE
+ * PROJECTION statements manually off-peak before upgrading, against the
+ * storage table:
*
* SELECT concat('.inner_id.', toString(uuid)) FROM system.tables
* WHERE database = currentDatabase()
* AND name = 'event_property_values_mv_replicated'; -- drop the
* suffix when not clustered
*
- * The migration skips re-materializing only when the projection
- * already exists AND system.mutations records a completed MATERIALIZE —
- * presence alone could be a crashed earlier attempt's ADD, and if
- * mutation state can't be read the migration materializes anyway
- * (idempotent; redundant work beats a silent skip). Note that because
- * ADD uses IF NOT EXISTS, a manual pre-apply must use the definition
- * below verbatim — a same-named projection with a different grain would
- * be kept as-is.
+ * The migration skips re-materializing only when the projection exists AND
+ * system.mutations records a completed MATERIALIZE; presence alone could
+ * be a crashed earlier attempt's ADD. If mutation state can't be read it
+ * materializes anyway (redundant work beats a silent skip). Because ADD
+ * uses IF NOT EXISTS, a manual pre-apply must use the definition below
+ * verbatim; a same-named projection with a different grain is kept as-is.
*/
const MV = TABLE_NAMES.event_property_values_mv;
@@ -95,12 +64,6 @@ const PROJECTIONS = [
},
];
-// The projection lives on the MV's storage table, which is always the
-// implicit `.inner_id.<uuid>` table — never the name we CREATE'd. Clustered,
-// `<mv>_replicated` is itself a MATERIALIZED VIEW (and `<mv>` a Distributed
-// table), so ALTERing either fails with NOT_IMPLEMENTED. Resolve the view's
-// uuid and address its inner table instead.
-//
// `CREATE ... ON CLUSTER` propagates the initiator's uuid, so the inner
// table has the same name on every node and a single ON CLUSTER ALTER
// reaches all of them.
diff --git a/packages/db/src/code-migrations/2-accounts.ts b/packages/db/src/code-migrations/2-accounts.ts
index ac7dc0512..f5ceb8b5e 100644
--- a/packages/db/src/code-migrations/2-accounts.ts
+++ b/packages/db/src/code-migrations/2-accounts.ts
@@ -47,7 +47,6 @@ export async function up() {
}
const dumppath = path.join(__dirname, 'users-dump.csv');
- // check if file exists
if (!(await checkFileExists(dumppath))) {
printBoxMessage('⚠️ Missing Required File ⚠️', [
`File not found: ${dumppath}`,
diff --git a/packages/db/src/code-migrations/21-wind-down-onboarding-pointer.ts b/packages/db/src/code-migrations/21-wind-down-onboarding-pointer.ts
index fb0acec81..eb499a364 100644
--- a/packages/db/src/code-migrations/21-wind-down-onboarding-pointer.ts
+++ b/packages/db/src/code-migrations/21-wind-down-onboarding-pointer.ts
@@ -1,10 +1,8 @@
/**
* Retire the 'onboarding-trial-ended' pointer.
*
- * The onboarding drip used to end with a day-30 'onboarding-trial-ended'
- * email. That moment now belongs to the wind-down sequence (step 0,
- * 'wind-down-expired'), which is anchored on trial expiry rather than signup,
- * so the step was removed from ONBOARDING_EMAILS.
+ * The step was removed from ONBOARDING_EMAILS; the wind-down sequence
+ * ('wind-down-expired') covers that moment, anchored on trial expiry.
*
* Organizations whose `onboarding` column still holds the removed name are
* left pointing at a step that no longer exists. The sequence runner treats an
diff --git a/packages/db/src/code-migrations/3-init-ch.ts b/packages/db/src/code-migrations/3-init-ch.ts
index 760886dba..1480cced3 100644
--- a/packages/db/src/code-migrations/3-init-ch.ts
+++ b/packages/db/src/code-migrations/3-init-ch.ts
@@ -45,7 +45,6 @@ export async function up(env: CodeMigrationEnv) {
const sqls: string[] = [];
- // Move tables to old names if they exists
if (isSelfHostingOld) {
sqls.push(
...existingTables
@@ -66,7 +65,6 @@ export async function up(env: CodeMigrationEnv) {
sqls.push(
createDatabase(migrationDatabase(), isClustered),
- // Create new tables
...createTable({
name: 'self_hosting',
columns: ['`created_at` Date', '`domain` String', '`count` UInt64'],
@@ -189,7 +187,6 @@ export async function up(env: CodeMigrationEnv) {
isClustered,
}),
- // Create materialized views
...createMaterializedView({
name: 'dau_mv',
tableName: 'events',
@@ -268,7 +265,6 @@ export async function up(env: CodeMigrationEnv) {
if (isSelfHostingPostCluster) {
sqls.push(
- // Move data between tables
...(hasSelfHosting
? moveDataBetweenTables({
from: 'self_hosting_replicated_tmp',
diff --git a/packages/db/src/code-migrations/5-add-imports-table.ts b/packages/db/src/code-migrations/5-add-imports-table.ts
index 56e1a98fc..d00c3cbdf 100644
--- a/packages/db/src/code-migrations/5-add-imports-table.ts
+++ b/packages/db/src/code-migrations/5-add-imports-table.ts
@@ -12,7 +12,6 @@ export async function up(env: CodeMigrationEnv) {
...createTable({
name: 'events_imports',
columns: [
- // Same columns as events table
'`id` UUID DEFAULT generateUUIDv4()',
'`name` LowCardinality(String)',
'`sdk_name` LowCardinality(String)',
@@ -43,7 +42,6 @@ export async function up(env: CodeMigrationEnv) {
'`model` LowCardinality(String)',
'`imported_at` Nullable(DateTime) CODEC(Delta(4), LZ4)',
- // Additional metadata columns for import tracking
'`import_id` String CODEC(ZSTD(3))',
"`import_status` LowCardinality(String) DEFAULT 'pending'",
'`imported_at_meta` DateTime DEFAULT now()',
diff --git a/packages/db/src/code-migrations/7-migrate-events-to-series.ts b/packages/db/src/code-migrations/7-migrate-events-to-series.ts
index 447efa5e5..2256e8bef 100644
--- a/packages/db/src/code-migrations/7-migrate-events-to-series.ts
+++ b/packages/db/src/code-migrations/7-migrate-events-to-series.ts
@@ -5,7 +5,6 @@ import { printBoxMessage, shortId } from './helpers';
export async function up() {
printBoxMessage('🔄 Migrating Events to Series Format', []);
- // Get all reports
const reports = await db.report.findMany({
select: {
id: true,
@@ -25,7 +24,6 @@ export async function up() {
>;
const oldFormula = report.formula;
- // Check if any event is missing the 'type' field (old format)
const needsEventMigration =
Array.isArray(events) &&
events.length > 0 &&
@@ -33,7 +31,6 @@ export async function up() {
(event) => !event || typeof event !== 'object' || !('type' in event)
);
- // Check if formula exists and isn't already in the series
const hasFormulaInSeries =
Array.isArray(events) &&
events.some(
@@ -46,13 +43,11 @@ export async function up() {
const needsFormulaMigration = !!oldFormula && !hasFormulaInSeries;
- // Skip if no migration needed
if (!(needsEventMigration || needsFormulaMigration)) {
skippedCount++;
continue;
}
- // Transform events to new format: add type: 'event' to each event
const migratedSeries: IChartEventItem[] = Array.isArray(events)
? events.map((event) => {
if (event && typeof event === 'object' && 'type' in event) {
@@ -66,7 +61,6 @@ export async function up() {
})
: [];
- // Add formula to series if it exists and isn't already there
if (needsFormulaMigration && oldFormula) {
const formulaItem: IChartFormula = {
type: 'formula',
@@ -80,7 +74,6 @@ export async function up() {
console.log(
`Updating report ${report.name} (${report.id}) with ${migratedSeries.length} series`
);
- // Update the report with migrated series
await db.report.update({
where: { id: report.id },
data: {
diff --git a/packages/db/src/code-migrations/8-order-keys.ts b/packages/db/src/code-migrations/8-order-keys.ts
index 72987e4d9..477aec17a 100644
--- a/packages/db/src/code-migrations/8-order-keys.ts
+++ b/packages/db/src/code-migrations/8-order-keys.ts
@@ -52,8 +52,6 @@ export async function up(env: CodeMigrationEnv) {
'INDEX idx_origin origin TYPE bloom_filter(0.05) GRANULARITY 1',
'INDEX idx_path path TYPE bloom_filter(0.01) GRANULARITY 1',
],
- // New ORDER BY: project_id, toDate(created_at), created_at, name
- // Removed profile_id, added created_at for better ordering within same day
orderBy: ['project_id', 'toDate(created_at)', 'created_at', 'name'],
partitionBy: 'toYYYYMM(created_at)',
settings: {
@@ -68,8 +66,6 @@ export async function up(env: CodeMigrationEnv) {
isClustered,
});
- // Step 1: Create temporary tables with new ORDER BY keys
- // Events table with new ORDER BY
sqls.push(...eventTables);
const sessionTables = createTable({
@@ -114,8 +110,6 @@ export async function up(env: CodeMigrationEnv) {
'`sign` Int8',
'`version` UInt64',
],
- // New ORDER BY: project_id, toDate(created_at), created_at, id
- // Removed profile_id, reordered to match query patterns (date first, then id)
orderBy: ['project_id', 'toDate(created_at)', 'created_at'],
partitionBy: 'toYYYYMM(created_at)',
settings: {
@@ -127,7 +121,6 @@ export async function up(env: CodeMigrationEnv) {
isClustered,
});
- // Sessions table with new ORDER BY
sqls.push(...sessionTables);
const firstEventDateResponse = await chMigrationClient.query({
@@ -142,8 +135,7 @@ export async function up(env: CodeMigrationEnv) {
!firstEventDateJson[0]?.created_at.startsWith('1970')
) {
const firstEventDate = new Date(firstEventDateJson[0]?.created_at);
- // Step 2: Copy data from old tables to new tables (partitioned by month for efficiency)
- // Set endDate to first of next month to ensure we capture all data in the current month
+ // First of next month, so the current month is fully captured.
const endDate = new Date();
endDate.setMonth(endDate.getMonth() + 1);
endDate.setDate(1);
@@ -182,7 +174,7 @@ export async function up(env: CodeMigrationEnv) {
const firstSessionDate = new Date(
firstSessionDateJson[0]?.created_at ?? ''
);
- // Set endDate to first of next month to ensure we capture all data in the current month
+ // First of next month, so the current month is fully captured.
const endDate = new Date();
endDate.setMonth(endDate.getMonth() + 1);
endDate.setDate(1);
@@ -254,15 +246,12 @@ export async function up(env: CodeMigrationEnv) {
if (isClustered && sessionTables[1] && eventTables[1]) {
sqls.push(
- // Drop temporary DISTRIBUTED tables (will be recreated)
`DROP TABLE IF EXISTS events_new_20251123 ON CLUSTER '{cluster}'`,
`DROP TABLE IF EXISTS sessions_new_20251123 ON CLUSTER '{cluster}'`,
- // Rename new tables to correct names
`RENAME TABLE events_new_20251123_replicated TO events_replicated ON CLUSTER '{cluster}'`,
`RENAME TABLE sessions_new_20251123_replicated TO sessions_replicated ON CLUSTER '{cluster}'`,
- // Create new distributed tables
- eventTables[1].replaceAll('events_new_20251123', 'events'), // creates a new distributed table
- sessionTables[1].replaceAll('sessions_new_20251123', 'sessions') // creates a new distributed table
+ eventTables[1].replaceAll('events_new_20251123', 'events'),
+ sessionTables[1].replaceAll('sessions_new_20251123', 'sessions')
);
} else {
sqls.push(
diff --git a/packages/db/src/code-migrations/9-migrate-options.ts b/packages/db/src/code-migrations/9-migrate-options.ts
index 67905e5dc..39f27a69e 100644
--- a/packages/db/src/code-migrations/9-migrate-options.ts
+++ b/packages/db/src/code-migrations/9-migrate-options.ts
@@ -5,7 +5,6 @@ import { printBoxMessage } from './helpers';
export async function up() {
printBoxMessage('🔄 Migrating Legacy Fields to Options', []);
- // Get all reports
const reports = await db.report.findMany({
select: {
id: true,
@@ -24,7 +23,6 @@ export async function up() {
for (const report of reports) {
const currentOptions = report.options as IReportOptions | null | undefined;
- // Skip if options already exists and is valid
if (
currentOptions &&
typeof currentOptions === 'object' &&
@@ -36,9 +34,7 @@ export async function up() {
let newOptions: IReportOptions | null = null;
- // Migrate based on chart type
if (report.chartType === 'funnel') {
- // Only create options if we have legacy fields to migrate
if (report.funnelGroup || report.funnelWindow !== null) {
newOptions = {
type: 'funnel',
@@ -47,7 +43,6 @@ export async function up() {
};
}
} else if (report.chartType === 'retention') {
- // Only create options if we have criteria to migrate
if (report.criteria) {
newOptions = {
type: 'retention',
@@ -55,12 +50,10 @@ export async function up() {
};
}
} else if (report.chartType === 'sankey') {
- // Sankey should already have options, but if not, skip
skippedCount++;
continue;
}
- // Only update if we have new options to set
if (newOptions) {
console.log(
`Migrating report ${report.name} (${report.id}) - chartType: ${report.chartType}`
@@ -70,7 +63,6 @@ export async function up() {
where: { id: report.id },
data: {
options: newOptions,
- // Set legacy fields to null after migration
funnelGroup: null,
funnelWindow: null,
criteria: report.chartType === 'retention' ? null : report.criteria,
diff --git a/packages/db/src/code-migrations/constants.ts b/packages/db/src/code-migrations/constants.ts
index 9a4ca2b06..94ed17b43 100644
--- a/packages/db/src/code-migrations/constants.ts
+++ b/packages/db/src/code-migrations/constants.ts
@@ -1,14 +1,8 @@
-// The vocabulary these one-shot migrations need, COPIED from packages/core
-// rather than imported from it. Code-migrations are deliberately isolated
-// from core: a migration reads rows written by a past version of the app, so
-// it must keep describing the shape that existed when it was written — an
-// import of the live `report.constants.ts` would silently redefine what
-// migration 7 and 9 mean the next time someone edits a chart segment.
-//
-// Sources at the time of the move (2026-09-11), for anyone diffing:
-// packages/core/src/modules/report/report.constants.ts (the chart types)
-// packages/core/src/modules/organization/organization.constants.ts
-// (zProjectAccessGrant) These are frozen. Do not re-sync them with core.
+// Copied from packages/core, not imported. A migration reads rows written by
+// a past version of the app, so it must keep describing the shape that
+// existed when it was written: importing the live `report.constants.ts`
+// would silently redefine what migrations 7 and 9 mean. Frozen; do not
+// re-sync with core.
import { z } from 'zod';
diff --git a/packages/db/src/code-migrations/helpers.ts b/packages/db/src/code-migrations/helpers.ts
index 79d1a70aa..4e3108554 100644
--- a/packages/db/src/code-migrations/helpers.ts
+++ b/packages/db/src/code-migrations/helpers.ts
@@ -1,11 +1,9 @@
import fs from 'node:fs';
import { fileURLToPath } from 'node:url';
-// `shortId` is COPIED from @openpanel/shared's id.ts rather than imported, on
-// the same ruling as constants.ts: code-migrations stays isolated, and a
-// one-shot script is not worth a dependency edge. This is nanoid/non-secure's
-// alphabet and algorithm at the length `shortId()` uses, so the ids these
-// migrations write are the same shape the app writes.
+// `shortId` is copied from @openpanel/shared's id.ts to keep code-migrations
+// isolated (see constants.ts). Same nanoid/non-secure alphabet and length, so
+// migration-written ids match the app's.
const SHORT_ID_ALPHABET =
'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict';
const SHORT_ID_ALPHABET_SIZE = 64;
@@ -36,9 +34,7 @@ export function printBoxMessage(title: string, lines: (string | unknown)[]) {
}
/**
- * The environment this script needs, read by its shell
- * (`packages/db/scripts/migrate-code.ts`) rather than here, so no migration
- * file reads `process.env`.
+ * The environment migrations need, read by `packages/db/scripts/migrate-code.ts`.
*/
export interface CodeMigrationEnv {
clickhouseCluster: boolean;
@@ -104,9 +100,8 @@ const STATEMENT_SEPARATOR = '\n\n---\n\n';
* an operator can read what a run will do. The dumps are build artifacts, not
* tracked files.
*
- * Pass `import.meta.url`: it is the one file-location technique that needs
- * neither Bun's ESM `__filename` polyfill nor Node >= 20.11's
- * `import.meta.filename`, both of which this directory used to mix.
+ * Pass `import.meta.url`: it works without Bun's `__filename` polyfill or
+ * Node >= 20.11's `import.meta.filename`.
*/
export function writeSqlDump(migrationUrl: string, sqls: string[]) {
fs.writeFileSync(
diff --git a/packages/db/src/code-migrations/migrate.ts b/packages/db/src/code-migrations/migrate.ts
index 0b6e1c26f..8fc76d0ba 100644
--- a/packages/db/src/code-migrations/migrate.ts
+++ b/packages/db/src/code-migrations/migrate.ts
@@ -12,7 +12,6 @@ import {
redactConnectionUrls,
} from './helpers';
-// The numbered migration files live beside this runner.
const MIGRATIONS_DIR = dirname(fileURLToPath(import.meta.url));
export async function runCodeMigrations(env: CodeMigrationEnv) {
diff --git a/packages/db/src/logger.ts b/packages/db/src/logger.ts
index 1a8f735aa..55c1272e8 100644
--- a/packages/db/src/logger.ts
+++ b/packages/db/src/logger.ts
@@ -1,11 +1,5 @@
-// Self-contained pino instantiation. packages/db is a leaf package and must
-// not reach into @openpanel/core just to build a logger — that direction is
-// backwards, since core itself depends on db.
-//
-// This is the same implementation @openpanel/core's `src/pino-logger.ts`
-// carries, duplicated here deliberately rather than shared: there is no home
-// narrower than "the package itself" that both can reach without
-// reintroducing the db <-> core cycle this file exists to avoid.
+// Duplicates @openpanel/core's `src/pino-logger.ts` on purpose: core depends
+// on db, so db importing it would create a cycle.
import * as HyperDX from '@hyperdx/node-opentelemetry';
import pino, { type Logger as PinoLogger } from 'pino';
@@ -91,9 +85,8 @@ function getServiceName(name: string): string {
.join('-');
}
-// Same Bun/pino-pretty incompatibility as @openpanel/core's
-// `src/pino-logger.ts`'s `isBun` guard — see its comment. Kept in sync by
-// hand, like the rest of this file.
+// Same Bun/pino-pretty incompatibility as the `isBun` guard in
+// @openpanel/core's `src/pino-logger.ts`; keep in sync by hand.
const isBun = !!process.versions.bun;
export function createLogger({ name }: { name: string }): ILogger {
diff --git a/packages/db/src/prisma-client.ts b/packages/db/src/prisma-client.ts
index 67fc94fb2..3d7b624dd 100644
--- a/packages/db/src/prisma-client.ts
+++ b/packages/db/src/prisma-client.ts
@@ -15,11 +15,8 @@ const getPrismaClient = () => {
// emit: 'event' keeps the engine from writing prisma:error lines straight
// to stderr, so they flow through pino to the OTLP pipeline instead.
const client = new PrismaClient({
- // Callsite-free error messages: running from source (not a compiled
- // bundle), Prisma's default error format would splice the file, the line
- // and a source snippet into a message that reaches API clients verbatim
- // (three golden error responses caught exactly that). `minimal` keeps the
- // short `Invalid \`prisma.model.action()\` invocation:` form and keeps our
+ // Prisma's default error format splices file, line and a source snippet
+ // into messages that reach API clients verbatim. `minimal` keeps our
// source layout out of a 500.
errorFormat: 'minimal',
log: [
@@ -100,7 +97,6 @@ const getPrismaClient = () => {
return org.subscriptionEndsAt;
}
- // Hedge against edge cases :D
return new Date(Date.now() + 1000 * 60 * 60 * 24);
},
},
diff --git a/packages/db/src/services/access.service.ts b/packages/db/src/services/access.service.ts
index ddd81daad..449257a49 100644
--- a/packages/db/src/services/access.service.ts
+++ b/packages/db/src/services/access.service.ts
@@ -1,10 +1,4 @@
-// The concrete project/organization/client access lookups live in
-// @openpanel/core now: packages/core/src/shared/access-lookups.ts.
-//
-// Kept here as a deep-path-only re-export (not part of packages/db's index.ts
-// barrel) because this exact path is still imported directly, with no app
-// boot at all. Every real importer in this repo now reaches these functions
-// through `@openpanel/core` directly.
+// Deep-path-only re-export of the lookups in packages/core/src/shared/access-lookups.ts.
export {
canWriteProject,
getClientAccess,
diff --git a/packages/db/src/types.ts b/packages/db/src/types.ts
index 77bbf8828..c52879fd4 100644
--- a/packages/db/src/types.ts
+++ b/packages/db/src/types.ts
@@ -1,7 +1,4 @@
-// `@openpanel/db` takes a type-only `db -> core` dependency edge here,
-// accepted deliberately: `@openpanel/db` already depends on `@openpanel/core`,
-// the edge is `import type` only so it creates no runtime cycle, and it is
-// the same shape as this repo's existing type-only `db -> queue` cycle.
+// Type-only `db -> core` edge: `import type` creates no runtime cycle.
import type {
IClickhouseBotEvent,
IClickhouseEvent,
diff --git a/packages/payments/scripts/create-checkout-link.ts b/packages/payments/scripts/create-checkout-link.ts
index a976d9c62..912937fb2 100644
--- a/packages/payments/scripts/create-checkout-link.ts
+++ b/packages/payments/scripts/create-checkout-link.ts
@@ -4,7 +4,6 @@ import inquirer from 'inquirer';
import inquirerAutocomplete from 'inquirer-autocomplete-prompt';
import { getSuccessUrl } from '..';
-// Register the autocomplete prompt
inquirer.registerPrompt('autocomplete', inquirerAutocomplete);
interface Answers {
@@ -14,7 +13,6 @@ interface Answers {
}
async function promptForInput(polar: Polar) {
- // Get all organizations first
const organizations = await db.organization.findMany({
select: {
id: true,
@@ -22,7 +20,6 @@ async function promptForInput(polar: Polar) {
},
});
- // Fetch all products from Polar
let products: any[] = [];
try {
const productsResponse = await polar.products.list({
@@ -143,7 +140,6 @@ async function main() {
try {
console.log('Creating checkout link...');
- // First, get environment and API key to initialize Polar client
const { isProduction, polarApiKey } = await inquirer.prompt([
{
type: 'list',
diff --git a/packages/payments/scripts/create-products.ts b/packages/payments/scripts/create-products.ts
index 0ce9e1f2d..deea129bb 100644
--- a/packages/payments/scripts/create-products.ts
+++ b/packages/payments/scripts/create-products.ts
@@ -172,7 +172,6 @@ async function main() {
) {
productCreate.prices[0]!.priceAmount = price.price * 100 * 10;
}
- // console.log('CREATE YEARLY', productCreate);
const yearlyProduct = await polar.products.create(productCreate);
console.log('Yearly product created:');
console.log(' - ID:', yearlyProduct.id);
diff --git a/packages/payments/src/polar.ts b/packages/payments/src/polar.ts
index c96114b41..57eb11986 100644
--- a/packages/payments/src/polar.ts
+++ b/packages/payments/src/polar.ts
@@ -56,7 +56,6 @@ export async function createCheckout({
ipAddress: string | undefined;
}) {
return polar.checkouts.create({
- // productPriceId: priceId,
products: [productId],
successUrl: getSuccessUrl(
process.env.DASHBOARD_URL || process.env.NEXT_PUBLIC_DASHBOARD_URL!,
diff --git a/packages/redis/cachable.ts b/packages/redis/cachable.ts
index c446d995e..ac6254ac6 100644
--- a/packages/redis/cachable.ts
+++ b/packages/redis/cachable.ts
@@ -144,7 +144,6 @@ const parseCache = (cached: string) => {
const CACHEABLE_LRU_TTL_MS = 60 * 1000;
const CACHEABLE_LRU_MAX = 1000;
-// Overload 1: cacheable(fn, expireInSec, options?)
export function cacheable<T extends (...args: any) => any>(
fn: T,
expireInSec: number,
@@ -157,7 +156,6 @@ export function cacheable<T extends (...args: any) => any>(
) => (payload: Awaited<ReturnType<T>>) => Promise<'OK'>;
};
-// Overload 2: cacheable(name, fn, expireInSec, options?)
export function cacheable<T extends (...args: any) => any>(
name: string,
fn: T,
@@ -190,13 +188,11 @@ export function cacheable<T extends (...args: any) => any>(
let options: CacheableOptions = {};
if (typeof fnOrName === 'function') {
- // Overload 1: cacheable(fn, expireInSec, options?)
expireInSec = typeof fnOrExpireInSec === 'number' ? fnOrExpireInSec : null;
if (expireInSecOrOptions && typeof expireInSecOrOptions === 'object') {
options = expireInSecOrOptions;
}
} else {
- // Overload 2: cacheable(name, fn, expireInSec, options?)
expireInSec =
typeof expireInSecOrOptions === 'number' ? expireInSecOrOptions : null;
if (maybeOptions) {
diff --git a/packages/redis/dead-letter.test.ts b/packages/redis/dead-letter.test.ts
index 32069f81d..6dbe09617 100644
--- a/packages/redis/dead-letter.test.ts
+++ b/packages/redis/dead-letter.test.ts
@@ -1,15 +1,4 @@
-/**
- * The capped dead-letter list, at the Redis boundary.
- *
- * What the consumer does with a rejection is `packages/core`'s
- * `consumer.test.ts`; what this file pins is the write itself: one MULTI, the
- * record's shape, and the two ways a MULTI can fail without rejecting.
- *
- * No real Redis: an in-memory stand-in with real list semantics. The same
- * assertions were run against a local Redis (`redis://127.0.0.1:6379/15`) on
- * 2026-09-14 before this file was written — LLEN 3 after 7 pushes at N=3,
- * newest first, and a key holding a string rejecting with `WRONGTYPE`.
- */
+/** The capped dead-letter list at the Redis boundary: one MULTI, the record's shape, and the two ways a MULTI can fail without rejecting. Uses an in-memory stand-in with real list semantics. */
import { describe, expect, it } from 'vitest';
import {
diff --git a/packages/redis/dead-letter.ts b/packages/redis/dead-letter.ts
index 6cf95d6e5..02c397a8a 100644
--- a/packages/redis/dead-letter.ts
+++ b/packages/redis/dead-letter.ts
@@ -1,24 +1,15 @@
/**
* The ingest consumer's dead-letter destination: a capped Redis list.
*
- * It replaces `produceDeadLetterEvent`, which produced to a Kafka DLQ topic
- * that was never created — that failure left the offset unresolved, which
- * caused an unbounded handler-error redelivery loop (dozens of laps per
- * message). The Kafka producer is still exported from `@openpanel/core`, and
- * the consumer's `sendToDeadLetter` seam is unchanged, so swapping back is
- * one line in `apps/api`'s wiring.
+ * It exists because a Kafka DLQ topic that was never created left the offset unresolved and caused an unbounded
+ * handler-error redelivery loop.
*
- * THE RECORD IS A DEBUGGING SAMPLE, NOT A RECOVERY MECHANISM. The list keeps
- * the last N and nothing more; the event itself is gone from the pipeline. The
- * volume lives in `kafka_events_dead_lettered_total` /
- * `_dead_letter_failed_total`, because a capped list makes 50,000 drops look
- * exactly like 12.
+ * THE RECORD IS A DEBUGGING SAMPLE, NOT A RECOVERY MECHANISM. The list keeps the last N; the event itself is gone.
+ * The volume lives in `kafka_events_dead_lettered_total` / `_dead_letter_failed_total`, because a capped list makes
+ * 50,000 drops look exactly like 12.
*
- * Why here and not in `packages/core`'s ingest module: the whole of it is
- * Redis mechanics — one MULTI, one LPUSH, one LTRIM — and core's only export
- * door is its barrel. The input type is structural, so `DeadLetterMessage`
- * (kafkajs `Buffer`s and `IHeaders`) satisfies it without this package
- * depending on kafkajs or on core.
+ * The input type is structural, so kafkajs `Buffer`s and `IHeaders` satisfy it without this package depending on
+ * kafkajs or core.
*/
/** The one list. Not configurable: an operator has to be able to find it. */
@@ -29,11 +20,7 @@ interface BinaryLike {
toString(): string;
}
-/**
- * Structurally what `@openpanel/core`'s `DeadLetterMessage` is — the same
- * fields `produceDeadLetterEvent` put in its DLQ headers, so a record carries
- * everything needed to find the message on the source topic.
- */
+/** Structurally `@openpanel/core`'s `DeadLetterMessage`: enough to find the message on the source topic. */
export interface DeadLetterInput {
key: BinaryLike | null;
value: BinaryLike | null;
diff --git a/packages/redis/duplicate-marker.test.ts b/packages/redis/duplicate-marker.test.ts
index f152f7996..d8881a796 100644
--- a/packages/redis/duplicate-marker.test.ts
+++ b/packages/redis/duplicate-marker.test.ts
@@ -1,16 +1,4 @@
-/**
- * The event-keyed duplicate marker, at the Redis boundary.
- *
- * What the ingest handler does with the answer is `packages/core`'s
- * `incoming-event-handler.test.ts`; what this file pins is the command: one
- * `SET key NX PX`, the key shape, and which reply means "seen before".
- *
- * No real Redis here: an in-memory stand-in with real `NX` and expiry
- * semantics. The same four answers were driven through THIS marker against the
- * local Redis (`redis://127.0.0.1:6379/14`) on 2026-09-14 before this file was
- * written, at an 800 ms TTL — first sighting false, `PTTL` 800, second sighting
- * true, a distinct id false, and the same id false again 900 ms later.
- */
+/** The event-keyed duplicate marker at the Redis boundary: one `SET key NX PX`, the key shape, and which reply means "seen before". Uses an in-memory stand-in with real `NX` and expiry semantics. */
import { describe, expect, it } from 'vitest';
import {
diff --git a/packages/redis/duplicate-marker.ts b/packages/redis/duplicate-marker.ts
index 15af3a48a..ae7d73c1a 100644
--- a/packages/redis/duplicate-marker.ts
+++ b/packages/redis/duplicate-marker.ts
@@ -11,20 +11,13 @@
* positive on a suppressing check is silent data loss, so whether the events
* table ever gets real dedupe is a separate decision from this marker.
*
- * ONE round trip, `SET key NX PX`: the set and the "did it already exist"
- * answer are the same command, and there is no clean seam to fold it into —
- * the session buffer's own GET and Lua EVAL live in `packages/core`'s
- * `buffers/`, which this module does not own.
+ * ONE round trip, `SET key NX PX`: the set and the "did it already exist" answer are the same command.
*
* IT MUST BE GIVEN THE CACHE CLIENT. That one fails fast: offline queue off
* once connected, `commandTimeout` 500 ms. `getRedisQueue` keeps
* `maxRetriesPerRequest: null` for BullMQ and would block a handler for tens
* of seconds, risking exactly the kind of consumer eviction — past its Kafka
* session timeout — that produces duplicate rows.
- *
- * Why here and not in `packages/core`'s ingest module: the whole of it is
- * Redis mechanics, and core's only export door is its barrel — the same
- * reason `dead-letter.ts` lives here.
*/
/** Live key prefix. An operator has to be able to find these. */
diff --git a/packages/redis/publisher.test.ts b/packages/redis/publisher.test.ts
index cde682aa7..b3faa83a3 100644
--- a/packages/redis/publisher.test.ts
+++ b/packages/redis/publisher.test.ts
@@ -1,18 +1,4 @@
-/**
- * One subscriber leaving must not silence the others.
- *
- * `subscribeToPublishedEvent` hands every caller the SAME ioredis connection
- * (`getRedisSub`, a process-wide singleton), so the unsubscribe it returns
- * must not take the channel away from the whole process — on the `/live`
- * sockets, closing one used to leave every other open socket receiving
- * nothing for 30s. What is pinned here is the reference count — and, just as
- * important, that the LAST listener leaving still sends a real UNSUBSCRIBE,
- * so the fix cannot degrade into "never unsubscribe".
- *
- * No real Redis: a stand-in for the shared connection that records the wire
- * commands and can push a `message` event, which is the entire surface the
- * publisher uses.
- */
+/** One subscriber leaving must not silence the others: the channel is reference-counted, and the LAST listener leaving still sends a real UNSUBSCRIBE. Uses a stand-in for the shared connection. */
import { setSuperJson } from '@openpanel/shared';
import { beforeEach, describe, expect, it, vi } from 'vitest';
diff --git a/packages/redis/publisher.ts b/packages/redis/publisher.ts
index ed7ec58ea..4c6dbe1e9 100644
--- a/packages/redis/publisher.ts
+++ b/packages/redis/publisher.ts
@@ -57,13 +57,8 @@ type ChannelMessageListener = (message: string) => void;
* process and dispatches by channel name, which also keeps the connection off
* Node's max-listeners warning as sockets accumulate.
*
- * RECONNECT NEEDS NO HANDLING HERE. ioredis re-issues SUBSCRIBE for every
- * channel it believes it holds when the connection comes back
- * (`ioredis/built/redis/event_handler.js:254`, gated on `autoResubscribe`,
- * which defaults to `true` in `redis/RedisOptions.js:45` and is not overridden
- * for this client). Since the wire commands stay one-to-one with the 0 -> 1 and
- * 1 -> 0 edges, ioredis's own set stays exactly the set of channels with a
- * non-zero count.
+ * RECONNECT NEEDS NO HANDLING HERE: ioredis re-issues SUBSCRIBE for every channel it holds (`autoResubscribe`,
+ * default true), and the wire commands stay one-to-one with the 0 -> 1 and 1 -> 0 edges.
*/
const listenersByChannel = new Map<string, Set<ChannelMessageListener>>();
diff --git a/packages/redis/redis.test.ts b/packages/redis/redis.test.ts
index 27c58d36a..5fb5d46f4 100644
--- a/packages/redis/redis.test.ts
+++ b/packages/redis/redis.test.ts
@@ -1,15 +1,4 @@
-/**
- * The CACHE client must reject promptly when Redis is unreachable.
- *
- * Without this, `/track` could block for tens of seconds on a stopped Redis
- * (some requests never answering at all) because the command was queued and
- * waited out ioredis's 20-attempt reconnect cycle. These tests pin the three
- * properties that fixed it, and the one that must NOT change (the queue
- * client).
- *
- * No real Redis: an unreachable port covers "never connected", and a fake
- * RESP server covers "connected, then gone".
- */
+/** The CACHE client must reject promptly when Redis is unreachable, while the queue client keeps BullMQ's retry settings. An unreachable port covers "never connected", a fake RESP server covers "connected, then gone". */
import net from 'node:net';
import { afterEach, describe, expect, it } from 'vitest';
@@ -26,8 +15,6 @@ const PROMPT_WHEN_NEVER_CONNECTED_MS = CACHE_COMMAND_TIMEOUT_MS * 4;
const INSTANT_WHEN_DISCONNECTED_MS = 100;
const READY_TIMEOUT_MS = 5000;
-// ── A fake Redis, just enough of RESP for ioredis to reach `ready` ──────────
-
const INFO_BODY = '# Server\r\nredis_version:7.4.0\r\nloading:0\r\n';
/** Pull every COMPLETE `*N` array of bulk strings out of `buffered`. */
diff --git a/packages/redis/redis.ts b/packages/redis/redis.ts
index e583f0dc2..32da6e99e 100644
--- a/packages/redis/redis.ts
+++ b/packages/redis/redis.ts
@@ -7,18 +7,10 @@ const options: RedisOptions = {
};
/**
- * The cache client's tail bound, for the fault the offline queue cannot see: a
- * server whose socket is UP and which answers nothing (a frozen or partitioned
- * node). Nothing else in the request path sets a deadline there — `/track`
- * never answered inside 30 s in that fault before this.
- *
- * It has to clear the heaviest legitimate command by a wide margin, or a busy
- * event-buffer flush would start failing as if Redis were down, and a failed
- * flush refuses to commit Kafka offsets. 500 ms is roughly 15x the measured
- * p99 of that flush's worst case (`apps/api/e2e/redis-command-cost.ts`), so it
- * will not fire under normal load.
- *
- * Full numbers: `apps/api/e2e/redis-fail-fast.md`.
+ * The cache client's tail bound, for the fault the offline queue cannot see: a server whose socket is UP and which
+ * answers nothing. It has to clear the heaviest legitimate command by a wide margin, or a busy event-buffer flush
+ * would fail as if Redis were down and refuse to commit Kafka offsets. 500 ms is roughly 15x the measured p99 of
+ * that flush's worst case (`apps/api/e2e/redis-command-cost.ts`). Full numbers: `apps/api/e2e/redis-fail-fast.md`.
*/
export const CACHE_COMMAND_TIMEOUT_MS = 500;
@@ -106,28 +98,17 @@ const createRedisClient = (
};
/**
- * The CACHE client fails fast. On ioredis's defaults, a command issued while
- * Redis is down is queued and waits out the reconnect backoff before
- * `MaxRetriesPerRequestError`, which measured as multi-second `/track`
- * blocking on a stopped Redis. Everything on the ingest path already treats
- * these reads as optional — `device-id.ts` catches the session-buffer failure
- * and mints the deterministic session id — so that wait bought nothing but a
- * slower failure.
+ * The CACHE client fails fast: on ioredis's defaults a command issued while Redis is down waits out the reconnect
+ * backoff, which measured as multi-second `/track` blocking. Everything on the ingest path treats these reads as
+ * optional, so that wait bought nothing.
*
- * Two mechanisms, because there are two faults: the offline queue is turned
- * off once connected, so a command issued while the socket is known-down is
- * rejected in microseconds rather than queued; `commandTimeout` bounds the
- * case the offline queue cannot see, where the socket is up and the server
- * answers nothing. `commandTimeout` alone is not enough — ioredis arms the
- * deadline before the writable check, so a queued command still pays it in
- * full. Numbers and the case for 500 ms specifically:
+ * Two mechanisms: the offline queue is turned off once connected (a command on a known-down socket is rejected in
+ * microseconds), and `commandTimeout` bounds the case where the socket is up and the server answers nothing.
+ * `commandTimeout` alone is not enough: ioredis arms the deadline before the writable check. Numbers:
* `apps/api/e2e/redis-fail-fast.md`.
*
- * The offline queue stays on until the client has connected once: ioredis
- * rejects every command issued before the first connect completes when the
- * queue is off, which would make boot order decide whether a command works. A
- * process that has never reached Redis falls back to `commandTimeout`
- * instead; one that has connected fails instantly.
+ * The offline queue stays on until the first connect: with it off, ioredis rejects every command issued before the
+ * first connect completes, so boot order would decide whether a command works.
*/
export function createFailFastCacheClient(
name: string,
diff --git a/packages/seed/src/postgres.ts b/packages/seed/src/postgres.ts
index 8ba464413..a84c1b388 100644
--- a/packages/seed/src/postgres.ts
+++ b/packages/seed/src/postgres.ts
@@ -138,13 +138,9 @@ async function upsertOrganization(
/** Ingest verifies client secrets with scrypt (`verifyPassword`), so that is what the seed stores. */
/**
- * `.seed.json` advertises each project's conversions, and the manifest always
- * did, but nothing ever wrote the rows that make them conversions — so the
- * Conversions tab was empty on every seeded project. `event.service.ts` reads
- * these through `findMany({ where: { conversion: true } })`.
- *
- * Postgres only, and an upsert on the `(name, projectId)` unique, so re-running
- * just the Postgres half is enough; no ClickHouse reseed, no manifest change.
+ * The rows that make each project's advertised events conversions;
+ * `event.service.ts` reads them via `findMany({ where: { conversion: true } })`.
+ * Upserted on the `(name, projectId)` unique.
*/
async function upsertConversions(
projectId: string,
diff --git a/packages/shared/src/date.ts b/packages/shared/src/date.ts
index 699c34192..31ea5d788 100644
--- a/packages/shared/src/date.ts
+++ b/packages/shared/src/date.ts
@@ -1,9 +1,5 @@
// Generic date helpers: pure Date/Luxon math, no ClickHouse or Postgres
// access. This is the one place core re-exports luxon's DateTime from.
-//
-// `getDatesFromRange` and `getChartStartEndDate` are not here: they read
-// report vocabulary (`IChartRange`, `IReportInput`), so they live in
-// `packages/core/src/modules/report/src/chart-dates.ts`.
import { DateTime } from 'luxon';
export { DateTime } from 'luxon';
diff --git a/packages/shared/src/id.ts b/packages/shared/src/id.ts
index 45254e2a1..acf334353 100644
--- a/packages/shared/src/id.ts
+++ b/packages/shared/src/id.ts
@@ -1,5 +1,4 @@
-// apps/start had copied `shortId` into its own utils/math.ts. nanoid/non-secure
-// is deliberate: these are correlation/display ids, not secrets.
+// nanoid/non-secure is deliberate: correlation/display ids, not secrets.
// Regular `nanoid`, not the non-secure variant above: these ids back
// password-reset tokens and invite links, so they must stay cryptographically
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index f10789a00..4d1d1b999 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -1,13 +1,5 @@
-// The isomorphic entrypoint of @openpanel/shared.
-//
-// What may live behind this file: pure functions and types with no workspace
-// import, no db/redis/env/logger/services and no domain vocabulary. Anything
-// that needs one of those stays in the package that owns it.
-//
-// Nothing reachable from here may import a `node:*` builtin or `./server` —
-// this is a browser bundle's entrypoint too, and the leak would be invisible at
-// the call site. The `shared-root-stays-isomorphic` cruiser rule is what
-// enforces it.
+// Nothing reachable from here may import a `node:*` builtin or `./server`: this is a browser bundle's entrypoint too.
+// Enforced by the `shared-root-stays-isomorphic` cruiser rule.
export {
DateTime,
getChartPrevStartEndDate,
diff --git a/packages/shared/src/json.ts b/packages/shared/src/json.ts
index c2d94a5de..83f9e8bfc 100644
--- a/packages/shared/src/json.ts
+++ b/packages/shared/src/json.ts
@@ -1,9 +1,5 @@
-// packages/redis and apps/start each carried a copy, and redis' copy carried
-// the "keep in sync with packages/core" comment that is the whole argument for
-// a package below both. Same semantics: getSafeJson never throws, and
-// getSuperJson only hands off to superjson's parser when the payload looks like
-// superjson's own `{ json, meta }` envelope — a plain JSON payload round-trips
-// through JSON.parse instead.
+// getSafeJson never throws; getSuperJson only uses superjson's parser when the payload looks like its `{ json, meta }`
+// envelope, so a plain JSON payload goes through JSON.parse.
import superjson from 'superjson';
export function getSafeJson<T>(str: string): T | null {
diff --git a/packages/shared/src/math.ts b/packages/shared/src/math.ts
index 371a21ace..5d6cb4804 100644
--- a/packages/shared/src/math.ts
+++ b/packages/shared/src/math.ts
@@ -1,14 +1,4 @@
-// `isFloat` does NOT come along: no importer, anywhere.
-//
-// `getPreviousMetric` left with the report vocabulary it returns — it is
-// `packages/core/src/modules/report/src/previous-metric.ts` now.
-//
-// What was left is generic arithmetic, so it is @openpanel/shared's. apps/start
-// had copied all six of these functions verbatim; that copy is deleted and the
-// dashboard imports them from here.
-//
-// `isNumber` is mathjs's, not `typeof n === 'number'` — it is the filter
-// predicate for every chart aggregate below, so it stays exactly as it was.
+// `isNumber` is mathjs's, not `typeof n === 'number'`: it is the filter predicate for every chart aggregate below.
import { isNumber } from 'mathjs';
export const round = (num: number, decimals = 2) => {
diff --git a/packages/shared/src/object.ts b/packages/shared/src/object.ts
index 7fc5ddade..d89c5f6e3 100644
--- a/packages/shared/src/object.ts
+++ b/packages/shared/src/object.ts
@@ -39,7 +39,6 @@ export function toDots(
}
if (typeof value === 'string' && isMalformedJsonString(value)) {
- // Skip it
return acc;
}
@@ -51,7 +50,6 @@ export function toDots(
...toDots(JSON.parse(value), `${path}${key}.`),
};
} catch {
- // Skip it
return acc;
}
}
@@ -84,7 +82,6 @@ type AnyObject = Record<string, any>;
export function deepMergeObjects<T>(target: AnyObject, source: AnyObject): T {
const merged: AnyObject = {};
- // Include all keys from both objects
const allKeys = new Set([...Object.keys(target), ...Object.keys(source)]);
allKeys.forEach((key) => {
@@ -97,20 +94,16 @@ export function deepMergeObjects<T>(target: AnyObject, source: AnyObject): T {
typeof targetValue === 'string' &&
targetValue !== '')
) {
- // Keep target value if source value is null or undefined
merged[key] = targetValue;
} else if (
sourceValue !== undefined &&
isObject(targetValue) &&
isObject(sourceValue)
) {
- // Recursively merge objects
merged[key] = deepMergeObjects(targetValue, sourceValue);
} else if (sourceValue !== undefined) {
- // Directly assign any non-undefined source values
merged[key] = sourceValue;
} else if (sourceValue === undefined && target[key] !== undefined) {
- // Keep target value if source value is undefined
merged[key] = targetValue;
}
});
@@ -118,7 +111,6 @@ export function deepMergeObjects<T>(target: AnyObject, source: AnyObject): T {
return merged as T;
}
-// Helper function to check if a value is an object (but not null or an array)
function isObject(value: any): boolean {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
diff --git a/packages/shared/src/server/encryption.ts b/packages/shared/src/server/encryption.ts
index 321220053..d2e7670c0 100644
--- a/packages/shared/src/server/encryption.ts
+++ b/packages/shared/src/server/encryption.ts
@@ -32,11 +32,7 @@ function getEncryptionKey(keyHex: EncryptionKey): Buffer {
return Buffer.from(keyHex, 'hex');
}
-// ---------------------------------------------------------------------------
-// Plain encrypt/decrypt — base64(iv + authTag + ciphertext), no prefix.
-// Used for TOTP secrets and GSC tokens. (Kept format-stable so existing
-// ciphertext keeps decrypting; this is the implementation db re-exports.)
-// ---------------------------------------------------------------------------
+// Plain variant: base64(iv + authTag + ciphertext), no prefix, for TOTP secrets and GSC tokens. Format-stable so existing ciphertext keeps decrypting.
export function encrypt(key: EncryptionKey, plaintext: string): string {
const encryptionKey = getEncryptionKey(key);
@@ -74,12 +70,8 @@ export function decrypt(key: EncryptionKey, ciphertext: string): string {
);
}
-// ---------------------------------------------------------------------------
-// Credential variant — enc:base64(iv + ciphertext + authTag). The enc: prefix
-// makes it idempotent (skip already-encrypted values) and lets a plaintext
-// value pass through unchanged, which the integration test-connection flow
-// relies on (it builds adapters from the raw, unsaved config).
-// ---------------------------------------------------------------------------
+// Credential variant: enc:base64(iv + ciphertext + authTag). The prefix makes it idempotent and lets a plaintext value pass
+// through unchanged, which the integration test-connection flow relies on (it builds adapters from the raw, unsaved config).
export function isEncrypted(value: string): boolean {
return value.startsWith(ENCRYPTION_PREFIX);
@@ -92,7 +84,6 @@ export function encryptCredential(
if (!plaintext) {
return plaintext;
}
- // Don't double-encrypt
if (isEncrypted(plaintext)) {
return plaintext;
}
@@ -131,7 +122,6 @@ export function decryptCredential(
const encryptionKey = getEncryptionKey(key);
- // Remove prefix and decode base64
const combined = Buffer.from(
ciphertext.slice(ENCRYPTION_PREFIX.length),
'base64'
@@ -141,7 +131,6 @@ export function decryptCredential(
throw new Error('Invalid encrypted credential: too short');
}
- // Extract components
const iv = combined.subarray(0, IV_LENGTH);
const authTag = combined.subarray(combined.length - AUTH_TAG_LENGTH);
const encryptedData = combined.subarray(
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.ts
index 008ecfc1a..68983cba9 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -1,8 +1,5 @@
// The Node-only entrypoint of @openpanel/shared: `@openpanel/shared/server`.
// Everything behind it may use `node:*`.
-//
-// A web app may not import it — `no-web-to-server` in.dependency-cruiser.cjs
-// forbids apps/start, apps/public and packages/sdks/* from reaching this path.
export {
createHash,
generateSalt,
diff --git a/packages/shared/src/server/parser-user-agent.ts b/packages/shared/src/server/parser-user-agent.ts
index 427ee6a4b..2d08245c1 100644
--- a/packages/shared/src/server/parser-user-agent.ts
+++ b/packages/shared/src/server/parser-user-agent.ts
@@ -12,7 +12,6 @@ const parsedServerUa = {
model: '',
} as const;
-// Pre-compile all regex patterns for better performance
const IPHONE_MODEL_REGEX = /(iPhone|iPad)\s*([0-9,]+)/i;
const IOS_MODEL_REGEX = /(iOS)\s*([0-9.]+)/i;
const IPAD_OS_VERSION_REGEX = /iPadOS\s*([0-9_]+)/i;
@@ -22,7 +21,6 @@ const SINGLE_NAME_VERSION_REGEX = /^[^/]+\/[\d.]+$/;
const APP_MODEL_REGEX = /Model=([^;)]+)/i;
const APP_MANUFACTURER_REGEX = /Manufacturer=([^;)]+)/i;
-// Device detection regexes
const SAMSUNG_MOBILE_REGEX = /SM-[ABDEFGJMNRWZ][0-9]+/i;
const SAMSUNG_TABLET_REGEX = /SM-T[0-9]+/i;
const LG_MOBILE_REGEX = /LG-[A-Z0-9]+/i;
@@ -37,36 +35,24 @@ const MOBILE_KEYWORD_REGEX = /mobile/i;
// Known phone model patterns from top brands (for device type detection)
// These patterns indicate mobile phones, not tablets
const KNOWN_PHONE_PATTERNS = [
- // Xiaomi / Redmi / POCO
/redmi\s*(note|k|[0-9])/i,
/poco\s*[a-z0-9]/i,
/mi\s*([0-9]|note|mix|max)/i,
- // Samsung Galaxy phones (not tablets)
/galaxy\s*(s|a|m|note)[0-9]/i,
/galaxy\s*z\s*(fold|flip)/i, // Foldables
- // Huawei / Honor
/huawei\s*(p|mate|nova|y)[0-9]/i,
/honor\s*[0-9a-z]/i,
- // OPPO
/oppo\s*(a|f|find|reno|k)\s*[a-z0-9]/i,
- // Vivo
/vivo\s*(v|y|x|s|t|iqoo)[0-9]/i,
/iqoo\s*[0-9a-z]/i,
- // OnePlus
/oneplus\s*[0-9]/i,
/one\s*plus\s*[0-9]/i,
- // Google Pixel
/pixel\s*[0-9]/i,
- // Realme
/realme\s*[0-9a-z]/i,
- // Motorola
/moto\s*(g|e|x|z|edge|razr)/i,
/motorola\s*(edge|razr)/i,
- // Nokia
/nokia\s*[0-9]/i,
- // Sony Xperia
/xperia\s*[0-9a-z]/i,
- // Nothing
/nothing\s*phone/i,
];
@@ -104,7 +90,6 @@ const BRAND_PATTERNS: Array<{ pattern: RegExp; brand: string }> = [
{ pattern: /tcl/i, brand: 'TCL' },
];
-// Cache for parsed results - stores up to 1000 unique user agents
const parseCache = new LRUCache<string, UAParser.IResult>({
ttl: 1000 * 60 * 5,
ttlAutopurge: true,
@@ -123,7 +108,6 @@ const isIphone = (ua: string) => {
: null;
};
-// Extract app-style UA info (e.g., "Model=Redmi Note 8 Pro; Manufacturer=Xiaomi")
function extractAppStyleInfo(ua: string): {
model?: string;
manufacturer?: string;
@@ -137,7 +121,6 @@ function extractAppStyleInfo(ua: string): {
};
}
-// Detect brand from UA string or model name
function detectBrand(ua: string, model?: string): string | undefined {
const searchString = `${ua} ${model || ''}`;
for (const { pattern, brand } of BRAND_PATTERNS) {
@@ -148,7 +131,6 @@ function detectBrand(ua: string, model?: string): string | undefined {
return undefined;
}
-// Check if a model name indicates a phone (not tablet)
function isKnownPhoneModel(model?: string): boolean {
if (!model) {
return false;
@@ -323,8 +305,6 @@ function isServer(res: UAParser.IResult) {
}
export function getDevice(ua: string, model?: string) {
- // Check for known phone models first (from top brands)
- // This handles app-style UAs where the model is explicitly stated
if (isKnownPhoneModel(model) || isKnownPhoneModel(ua)) {
return 'mobile';
}
@@ -353,8 +333,6 @@ export function getDevice(ua: string, model?: string) {
return 'mobile';
}
- // Check for tablet patterns
- // Note: We already checked for Samsung mobile/tablet and LG mobile above
const isAndroid = ANDROID_REGEX.test(ua);
const hasMobileKeyword = MOBILE_KEYWORD_REGEX.test(ua);
diff --git a/packages/shared/src/slug.ts b/packages/shared/src/slug.ts
index 63a4aa50b..c443c1544 100644
--- a/packages/shared/src/slug.ts
+++ b/packages/shared/src/slug.ts
@@ -1,5 +1,3 @@
-// apps/start carried a verbatim copy of it, which is deleted. Not to be
-// confused with core's slug-id.ts, which calls this.
import _slugify from 'slugify';
const slugify = (str: string) => {