OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
hub fixes
Carl-Gerhard Lindesvärd9724d8358c7e
diff --git a/.env.example b/.env.exampleindex 2646db748..67de7b717 100644--- a/.env.example+++ b/.env.example@@ -1,8 +1,8 @@# STORAGE-REDIS_URL="redis://127.0.0.1:6379"-DATABASE_URL="postgresql://postgres:postgres@localhost:5432/postgres?schema=public"+REDIS_URL="redis://127.0.0.1:23379"+DATABASE_URL="postgresql://postgres:postgres@localhost:23432/postgres?schema=public"DATABASE_URL_DIRECT="$DATABASE_URL"-CLICKHOUSE_URL="http://localhost:8123/openpanel"+CLICKHOUSE_URL="http://localhost:23123/openpanel"# Symmetric key for all at-rest encryption: TOTP secrets, GSC tokens, and# object-store export credentials (S3 secret keys, GCS service-account keys).@@ -54,7 +54,7 @@ API_PORT=3333# and risks reordering after a broker hiccup, so leave it at 1.# KAFKA_PRODUCER_MAX_IN_FLIGHT="1"# Local dev with docker-compose:-# KAFKA_BROKERS="localhost:19092"+# KAFKA_BROKERS="localhost:23092"# EMAIL - set one or both; SMTP takes priority over Resend if SMTP_HOST is set# Option A - Resenddiff --git a/.gitignore b/.gitignoreindex 08fc63dcc..482baa8ac 100644--- a/.gitignore+++ b/.gitignore@@ -188,4 +188,10 @@ dist# Finder (MacOS) folder config.DS_Store-*.tsbuildinfo\ No newline at end of file+*.tsbuildinfo++# hub worktrees and their markers+.worktrees/+.worktree-port+.worktree-db+WORKTREE.mddiff --git a/apps/api/e2e/boot-proof.sh b/apps/api/e2e/boot-proof.shindex bd870d72a..b600debeb 100755--- a/apps/api/e2e/boot-proof.sh+++ b/apps/api/e2e/boot-proof.sh@@ -492,7 +492,7 @@ echoset +aPROOF_NAMESPACE="$PROOF_NAMESPACE" bun -e 'const { Redis } = await import("@openpanel/redis");- const redis = new Redis(process.env.REDIS_URL ?? "redis://127.0.0.1:6379");+ const redis = new Redis(process.env.REDIS_URL ?? "redis://127.0.0.1:23379");const pattern = `bull:*-${process.env.PROOF_NAMESPACE}:*`;let cursor = "0";let removed = 0;diff --git a/apps/api/e2e/legacy-job-proof.ts b/apps/api/e2e/legacy-job-proof.tsindex 63d4adcf8..4fc557cbc 100644--- a/apps/api/e2e/legacy-job-proof.ts+++ b/apps/api/e2e/legacy-job-proof.ts@@ -46,7 +46,7 @@ import { loadConfig } from '../src/config/env';/** Isolates the proof from the shared dev Redis — see the header. */const NAMESPACE = 'm9001proof';-const REDIS_URL = process.env.REDIS_URL || 'redis://127.0.0.1:6379';+const REDIS_URL = process.env.REDIS_URL || 'redis://127.0.0.1:23379';const JOB_WAIT_TIMEOUT_MS = 20_000;const JOB_POLL_INTERVAL_MS = 100;const REAL_HANDLER_QUEUE = 'cron';diff --git a/apps/api/e2e/redis-command-cost.ts b/apps/api/e2e/redis-command-cost.tsindex bf82ec850..b40395555 100644--- a/apps/api/e2e/redis-command-cost.ts+++ b/apps/api/e2e/redis-command-cost.ts@@ -109,7 +109,7 @@ async function time(iterations: number, run: () => Promise<unknown>) {}async function main() {- const url = new URL(process.env.REDIS_URL || 'redis://127.0.0.1:6379');+ const url = new URL(process.env.REDIS_URL || 'redis://127.0.0.1:23379');url.pathname = `/${BENCH_REDIS_DB}`;const redis = new Redis(url.toString());const rows = Array.from({ length: EVENT_BUFFER_BATCH_SIZE }, (_, index) =>diff --git a/apps/start/package.json b/apps/start/package.jsonindex 10f844944..03f31c1b7 100644--- a/apps/start/package.json+++ b/apps/start/package.json@@ -3,7 +3,7 @@"private": true,"type": "module","scripts": {- "dev": "bun run with-env vite dev --port 3000",+ "dev": "bun run with-env vite dev --port ${WEB_PORT:-3000}","preview": "vite preview","deploy": "bun run build && bunx wrangler deploy","cf-typegen": "wrangler types",diff --git a/apps/start/vite.config.ts b/apps/start/vite.config.tsindex 9d99e412b..12855dcd9 100644--- a/apps/start/vite.config.ts+++ b/apps/start/vite.config.ts@@ -27,8 +27,16 @@ if (process.env.NITRO) {plugins.unshift(cloudflare({ viteEnvironment: { name: 'ssr' } }));}+// Behind the hub's Caddy the page is `https://<name>.openpanel.cc`: Vite has to accept that Host,+// and its HMR client has to dial 443 over wss instead of the dev port.+const behindProxy = (process.env.DASHBOARD_URL ?? '').startsWith('https://');+const config = defineConfig({plugins,+ server: {+ allowedHosts: ['.openpanel.cc'],+ ...(behindProxy ? { hmr: { protocol: 'wss', clientPort: 443 } } : {}),+ },ssr: {noExternal: ['react-syntax-highlighter', 'lowlight', 'highlight.js'],},diff --git a/docker-compose.yml b/docker-compose.ymlindex 189574789..0dda0408b 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -7,7 +7,9 @@ services:volumes:- ./docker/data/op-db-data:/var/lib/postgresql/dataports:- - 5432:5432+ # Host ports live in the 23000s so a Postgres, Redis, ClickHouse or Kafka on their+ # default ports can run beside this stack.+ - 127.0.0.1:23432:5432environment:- POSTGRES_USER=postgres- POSTGRES_PASSWORD=postgres@@ -19,7 +21,7 @@ services:- ./docker/data/op-kv-data:/datacommand: ["redis-server", "--maxmemory-policy", "noeviction"]ports:- - 6379:6379+ - 127.0.0.1:23379:6379op-ch:image: clickhouse/clickhouse-server:26.1.3.52@@ -37,9 +39,9 @@ services:soft: 262144hard: 262144ports:- - "8123:8123" # HTTP interface- - "9000:9000" # Native/TCP interface- - "9009:9009" # Inter-server communication+ - "127.0.0.1:23123:8123" # HTTP interface+ - "127.0.0.1:23900:9000" # Native/TCP interface+ - "127.0.0.1:23909:9009" # Inter-server communicationop-rp:image: redpandadata/redpanda:v25.1.4@@ -48,7 +50,7 @@ services:- redpanda- start- --kafka-addr=internal://0.0.0.0:9092,external://0.0.0.0:19092- - --advertise-kafka-addr=internal://op-rp:9092,external://localhost:19092+ - --advertise-kafka-addr=internal://op-rp:9092,external://localhost:23092- --rpc-addr=0.0.0.0:33145- --advertise-rpc-addr=op-rp:33145- --smp=1@@ -59,8 +61,8 @@ services:- ./docker/data/op-rp-data:/var/lib/redpanda/data- ./docker/redpanda/bootstrap.yaml:/etc/redpanda/.bootstrap.yaml:roports:- - "19092:19092" # Kafka API (external)- - "9644:9644" # Admin API+ - "127.0.0.1:23092:19092" # Kafka API (external)+ - "127.0.0.1:23644:9644" # Admin APIop-rp-console:image: redpandadata/console:v3.7.2@@ -72,4 +74,4 @@ services:REDPANDA_ADMINAPI_ENABLED: "true"REDPANDA_ADMINAPI_URLS: http://op-rp:9644ports:- - "8091:8080"+ - "127.0.0.1:23080:8080"diff --git a/hub.config.ts b/hub.config.tsnew file mode 100644index 000000000..70c17639d--- /dev/null+++ b/hub.config.ts@@ -0,0 +1,71 @@+// The one file the hub reads from this repo. Its shape is `hub.config.d.ts` in the hub repo,+// which type-checks this file in its own tests; a field the hub does not know fails there.+export default {+ name: 'openpanel',+ baseBranch: 'rewrite/v2',+ worktreesDir: '.worktrees',+ github: 'Openpanel-dev/openpanel',+ domains: { local: 'local.openpanel.cc', remote: 'openpanel.cc' },+ install: 'bun install && bun run --filter @openpanel/db codegen',++ // port = 21000 + block×100 + offset. Main checkout is block 0.+ processes: {+ // host: label in front of `<name>.<suffix>`; null is the bare `<name>.<suffix>`.+ web: { host: null, offset: 0, cmd: 'bun run --filter start dev', cwd: '.' },+ api: { host: 'api', offset: 1, cmd: 'bun run --filter @openpanel/api dev', cwd: '.' },+ studio: { host: 'studio', offset: 2, cmd: 'bun run --filter @openpanel/db studio', cwd: '.' },+ },++ // Injected as process env. Wins over .env because dotenv-cli runs without -o.+ env: (w) => ({+ API_PORT: w.port('api'),+ API_HOST: '127.0.0.1', // Bun.serve defaults to 0.0.0.0+ WEB_PORT: w.port('web'),+ STUDIO_PORT: w.port('studio'),+ API_URL: w.url('api'),+ API_URL_SSR: `http://127.0.0.1:${w.port('api')}`,+ DASHBOARD_URL: w.url('web'),+ API_CORS_ORIGINS: w.url('web'),+ CUSTOM_COOKIE_DOMAIN: w.hostSuffix, // <name>.openpanel.cc; unset on localhost+ DATABASE_URL: w.db.postgres,+ DATABASE_URL_DIRECT: w.db.postgres,+ CLICKHOUSE_URL: w.db.clickhouse,+ REDIS_URL: w.db.redis,+ QUEUE_NAMESPACE: w.name,+ // One Redpanda; topics and the consumer group are per worktree, or two apis would consume+ // each other's events. Topics auto-create (docker/redpanda/bootstrap.yaml).+ KAFKA_BROKERS: w.db.kafka,+ KAFKA_CLIENT_ID: `api-${w.name}`,+ KAFKA_EVENTS_TOPIC: `events-${w.name}`,+ KAFKA_EVENTS_DLQ_TOPIC: `events-${w.name}-dlq`,+ KAFKA_CONSUMER_GROUP: `api-${w.name}`,+ }),++ // A worktree name is a DNS label; a database name is an identifier, so hyphens become underscores.+ databases: {+ postgres: { shared: 'postgres', isolated: (n) => `openpanel_${n.replace(/-/g, '_')}` },+ clickhouse: { shared: 'openpanel', isolated: (n) => `openpanel_${n.replace(/-/g, '_')}` },+ redis: { index: (block) => block }, // always per worktree+ kafka: { topics: (n) => [`events-${n}`, `events-${n}-dlq`] },+ migrate: 'bun run --filter @openpanel/db migrate:deploy',+ },++ checks: {+ typecheck: 'bun run typecheck',+ lint: 'bun run check',+ test: 'bun run test',+ },++ // The containers belong to the main checkout's compose project, whichever worktree asks.+ data: {+ clickhouse: (w) => `docker compose -f ${w.root}/docker-compose.yml exec op-ch clickhouse-client -d ${w.db.clickhouseName}`,+ redis: (w) => `docker compose -f ${w.root}/docker-compose.yml exec op-kv redis-cli -n ${w.db.redisIndex}`,+ postgres: (w) => `docker compose -f ${w.root}/docker-compose.yml exec op-db psql -U postgres ${w.db.postgresName}`,+ // rpk has no REPL: list this worktree's topics, then leave a shell in the container with rpk on PATH.+ kafka: (w) => `docker compose -f ${w.root}/docker-compose.yml exec op-rp sh -c 'rpk topic list; echo; echo "this worktree: ${w.db.kafkaTopics.join(' ')}"; exec sh'`,+ },++ stack: { up: 'docker compose up -d op-db op-kv op-ch op-rp', cwd: '.' },+ auth: process.platform === 'darwin' ? 'off' : 'password',+ issues: { github: true, userjot: true },+};diff --git a/packages/core/src/buffers/clickhouse-failover.test.ts b/packages/core/src/buffers/clickhouse-failover.test.tsindex 849c4f469..65db77f6e 100644--- a/packages/core/src/buffers/clickhouse-failover.test.ts+++ b/packages/core/src/buffers/clickhouse-failover.test.ts@@ -26,7 +26,7 @@ function loadClickHouse() {*/const CLICKHOUSE_TEST_DATABASE = 'openpanel_test';-const DEFAULT_CLICKHOUSE_BASE_URL = 'http://localhost:8123';+const DEFAULT_CLICKHOUSE_BASE_URL = 'http://localhost:23123';const DEAD_NODE_URL = 'http://127.0.0.1:1';const CLICKHOUSE_TEST_REQUEST_TIMEOUT_MS = 120_000;diff --git a/packages/core/src/modules/overview/src/overview-raw-where.sql.test.ts b/packages/core/src/modules/overview/src/overview-raw-where.sql.test.tsindex 2b00202ab..ffeef8f34 100644--- a/packages/core/src/modules/overview/src/overview-raw-where.sql.test.ts+++ b/packages/core/src/modules/overview/src/overview-raw-where.sql.test.ts@@ -17,7 +17,7 @@* data. WITH FILL TO < FROM is a runtime check, so it's covered by a plain* string assertion instead.*- * Requires a locally reachable CH at http://localhost:8123/openpanel. All+ * Requires a locally reachable CH at http://localhost:23123/openpanel. All* `itCH` tests auto-skip if CH is unreachable.*/diff --git a/packages/core/test/exports-map.test.ts b/packages/core/test/exports-map.test.tsindex bea97a753..95e98a05b 100644--- a/packages/core/test/exports-map.test.ts+++ b/packages/core/test/exports-map.test.ts@@ -14,7 +14,7 @@ test('a non-exported internal path does not resolve', async () => {test('preload pins infrastructure at local addresses', () => {expect(process.env.CLICKHOUSE_URL).toBe(- 'http://localhost:8123/openpanel_test'+ 'http://localhost:23123/openpanel_test');expect(process.env.SELF_HOSTED).toBe('true');});diff --git a/packages/core/test/preload.ts b/packages/core/test/preload.tsindex 19c709739..99190f1f3 100644--- a/packages/core/test/preload.ts+++ b/packages/core/test/preload.ts@@ -10,7 +10,7 @@// loaded. Kept in step with test/databases.ts by hand — core does not import// from the V1 root test directory.process.env.DATABASE_URL =- 'postgresql://postgres:postgres@localhost:5432/openpanel_test?schema=public';-process.env.CLICKHOUSE_URL = 'http://localhost:8123/openpanel_test';-process.env.REDIS_URL = 'redis://localhost:6379';+ 'postgresql://postgres:postgres@localhost:23432/openpanel_test?schema=public';+process.env.CLICKHOUSE_URL = 'http://localhost:23123/openpanel_test';+process.env.REDIS_URL = 'redis://localhost:23379';process.env.SELF_HOSTED = 'true';diff --git a/packages/db/package.json b/packages/db/package.jsonindex 05eba38bf..69661dd43 100644--- a/packages/db/package.json+++ b/packages/db/package.json@@ -6,6 +6,7 @@"scripts": {"codegen": "bun run with-env prisma generate && bun prisma/prisma-json-types.ts","migrate": "bun run with-env prisma migrate dev",+ "studio": "bun run with-env prisma studio --port ${STUDIO_PORT:-5555} --browser none","migrate:deploy:code": "bun run with-env bun ./scripts/migrate-code.ts","migrate:deploy:db": "bun run with-env prisma migrate deploy","migrate:deploy": "bun run migrate:deploy:db && bun run migrate:deploy:code",diff --git a/packages/db/src/clickhouse/migration.ts b/packages/db/src/clickhouse/migration.tsindex 270a1b541..deae71175 100644--- a/packages/db/src/clickhouse/migration.ts+++ b/packages/db/src/clickhouse/migration.ts@@ -34,6 +34,22 @@ const CLUSTER_REPLICA_PATH =const replicated = (tableName: string) => `${tableName}_replicated`;+/**+ * The database the migrations create and query, from `CLICKHOUSE_URL`'s path the same way the+ * client resolves it, so an isolated database (a hub worktree's `openpanel_<name>`) migrates+ * into itself and not into `openpanel`.+ */+export function migrationDatabase(): string {+ const raw = (process.env.CLICKHOUSE_URL ?? '').split(',')[0]?.trim();+ if (!raw) return 'openpanel';+ try {+ const name = new URL(raw).pathname.replace(/^\/+|\/+$/g, '');+ return /^[A-Za-z_][A-Za-z0-9_]*$/.test(name) ? name : 'openpanel';+ } catch {+ return 'openpanel';+ }+}+export const chMigrationClient = createClient({url: process.env.CLICKHOUSE_URL,request_timeout: 3_600_000, // 1 hour in milliseconds@@ -174,7 +190,8 @@ export function dropColumns(export async function getExistingTables() {try {const existingTablesQuery = await chMigrationClient.query({- query: `SELECT name FROM system.tables WHERE database = 'openpanel'`,+ query: `SELECT name FROM system.tables WHERE database = {database:String}`,+ query_params: { database: migrationDatabase() },format: 'JSONEachRow',});return (await existingTablesQuery.json<{ name: string }>())diff --git a/packages/db/src/clickhouse/sql.clickhouse.test.ts b/packages/db/src/clickhouse/sql.clickhouse.test.tsindex 467c06571..2814ab204 100644--- a/packages/db/src/clickhouse/sql.clickhouse.test.ts+++ b/packages/db/src/clickhouse/sql.clickhouse.test.ts@@ -18,7 +18,7 @@ import { sql } from './sql';*/const CLICKHOUSE_TEST_DATABASE = 'openpanel_test';-const DEFAULT_CLICKHOUSE_BASE_URL = 'http://localhost:8123';+const DEFAULT_CLICKHOUSE_BASE_URL = 'http://localhost:23123';/*** Well above the app default (30s): this suite shares one local node withdiff --git a/packages/db/src/clickhouse/sql.round-robin.clickhouse.test.ts b/packages/db/src/clickhouse/sql.round-robin.clickhouse.test.tsindex 34eb3629b..acd5a537f 100644--- a/packages/db/src/clickhouse/sql.round-robin.clickhouse.test.ts+++ b/packages/db/src/clickhouse/sql.round-robin.clickhouse.test.ts@@ -13,7 +13,7 @@ import { sql } from './sql';*/const CLICKHOUSE_TEST_DATABASE = 'openpanel_test';-const DEFAULT_CLICKHOUSE_BASE_URL = 'http://localhost:8123';+const DEFAULT_CLICKHOUSE_BASE_URL = 'http://localhost:23123';/** Port 1 is privileged and unbindable without root, so it is reliably refused. */const DEAD_NODE_URL = 'http://127.0.0.1:1';diff --git a/packages/db/src/code-migrations/3-init-ch.ts b/packages/db/src/code-migrations/3-init-ch.tsindex 2b808f0b8..760886dba 100644--- a/packages/db/src/code-migrations/3-init-ch.ts+++ b/packages/db/src/code-migrations/3-init-ch.ts@@ -5,6 +5,7 @@ import {createTable,dropTable,getExistingTables,+ migrationDatabase,moveDataBetweenTables,renameTable,runClickhouseMigrationCommands,@@ -64,7 +65,7 @@ export async function up(env: CodeMigrationEnv) {}sqls.push(- createDatabase('openpanel', isClustered),+ createDatabase(migrationDatabase(), isClustered),// Create new tables...createTable({name: 'self_hosting',@@ -356,7 +357,7 @@ export async function up(env: CodeMigrationEnv) {existingTables.map((table) =>`docker compose exec -it op-ch clickhouse-client --query "${dropTable(- `openpanel.${table}_tmp`,+ `${migrationDatabase()}.${table}_tmp`,false)}"`)diff --git a/packages/db/src/code-migrations/4-add-sessions.ts b/packages/db/src/code-migrations/4-add-sessions.tsindex f4b106454..9674481d9 100644--- a/packages/db/src/code-migrations/4-add-sessions.ts+++ b/packages/db/src/code-migrations/4-add-sessions.ts@@ -2,6 +2,7 @@ import { formatClickhouseDate, TABLE_NAMES } from '../clickhouse/client';import {chMigrationClient,createTable,+ migrationDatabase,runClickhouseMigrationCommands,} from '../clickhouse/migration';import { type CodeMigrationEnv, getIsCluster, writeSqlDump } from './helpers';@@ -108,10 +109,10 @@ async function createOldSessions() {const endDate = startDate;startDate = new Date(startDate.getTime() + 1000 * 60 * 60 * 24);sqls.push(`- INSERT INTO openpanel.sessions+ INSERT INTO ${migrationDatabase()}.sessionsWITH unique_sessions AS (SELECT session_id, min(created_at) as first_event_at- FROM openpanel.events+ FROM ${migrationDatabase()}.eventsWHEREcreated_at BETWEEN '${formatClickhouseDate(endDate)}' AND '${formatClickhouseDate(startDate)}'AND session_id != ''diff --git a/packages/redis/redis.ts b/packages/redis/redis.tsindex d66ab5f1f..3161134ef 100644--- a/packages/redis/redis.ts+++ b/packages/redis/redis.ts@@ -53,7 +53,7 @@ export const QUEUE_CLIENT_OPTIONS: RedisOptions = {export { Redis };-const REDIS_URL = process.env.REDIS_URL || 'redis://localhost:6379';+const REDIS_URL = process.env.REDIS_URL || 'redis://localhost:23379';export interface ExtendedRedis extends Redis {getJson: <T = any>(key: string) => Promise<T | null>;diff --git a/tooling/gates/p13-images.sh b/tooling/gates/p13-images.shindex 9274af4c5..e121be0b1 100755--- a/tooling/gates/p13-images.sh+++ b/tooling/gates/p13-images.sh@@ -228,7 +228,7 @@ docker run -d --name "$API_CONTAINER" --network host \-e ALLOW_INVITATION=true \-e BATCH_SIZE=5000 \-e BATCH_INTERVAL=10000 \- -e REDIS_URL='redis://localhost:6379' \+ -e REDIS_URL='redis://localhost:23379' \-e CLICKHOUSE_URL='http://localhost:8123/openpanel_test' \-e DATABASE_URL='postgresql://postgres:postgres@localhost:5432/openpanel_test?schema=public' \-e DATABASE_URL_DIRECT='postgresql://postgres:postgres@localhost:5432/openpanel_test?schema=public' \diff --git a/tooling/gates/p13-ssr.sh b/tooling/gates/p13-ssr.shindex b3b2eefbb..5620bacab 100755--- a/tooling/gates/p13-ssr.sh+++ b/tooling/gates/p13-ssr.sh@@ -249,9 +249,9 @@ export_smoke_app_env() {export BATCH_INTERVAL=10000export ALLOW_REGISTRATION=trueexport ALLOW_INVITATION=true- export REDIS_URL=redis://localhost:6379- export CLICKHOUSE_URL=http://localhost:8123/openpanel_test- export DATABASE_URL='postgresql://postgres:postgres@localhost:5432/openpanel_test?schema=public'+ export REDIS_URL=redis://localhost:23379+ export CLICKHOUSE_URL=http://localhost:23123/openpanel_test+ export DATABASE_URL='postgresql://postgres:postgres@localhost:23432/openpanel_test?schema=public'export DATABASE_URL_DIRECT="$DATABASE_URL"export DASHBOARD_URL="http://localhost:$DASHBOARD_PORT"export API_URL="http://localhost:$API_PORT"