Skip to content

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

ralph(M8-005): code-migrations into core; packages/db reaches its final surface

ralphd4485e78e42b
diff --git a/.gitignore b/.gitignore
index e295b24ff..08fc63dcc 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,6 +1,6 @@
.secrets
packages/db/src/generated/prisma
-packages/db/code-migrations/*.sql
+packages/core/src/code-migrations/*.sql
**/.open-next
# Based on https://raw.githubusercontent.com/github/gitignore/main/Node.gitignore
diff --git a/packages/core/package.json b/packages/core/package.json
index 88934ae44..528b482fd 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -14,7 +14,9 @@
"codegen": "bun scripts/download-geo.ts && bun scripts/get-datacenter-asns.ts",
"gen:asns": "bun scripts/get-datacenter-asns.ts",
"gen:bots": "bun scripts/get-bots.ts && biome format --write ./src/modules/ingest/src/bots/bots.ts",
- "gen:referrers": "bun scripts/get-referrers.ts && biome format --write ./src/shared/referrers/index.ts"
+ "gen:referrers": "bun scripts/get-referrers.ts && biome format --write ./src/shared/referrers/index.ts",
+ "migrate:deploy:code": "pnpm with-env jiti ./src/code-migrations/migrate.ts",
+ "with-env": "dotenv -e ../../.env -c --"
},
"dependencies": {
"@aws-sdk/client-s3": "^3.974.0",
@@ -51,6 +53,7 @@
"fast-deep-equal": "^3.1.3",
"fast-json-stable-hash": "^1.0.3",
"ipaddr.js": "^2.5.0",
+ "jiti": "^2.4.1",
"js-yaml": "^4.1.0",
"kafkajs": "^2.2.4",
"lru-cache": "^11.2.4",
diff --git a/packages/core/src/buffers/lazy-db-buffers.ts b/packages/core/src/buffers/lazy-db-buffers.ts
new file mode 100644
index 000000000..8ea0b3140
--- /dev/null
+++ b/packages/core/src/buffers/lazy-db-buffers.ts
@@ -0,0 +1,12 @@
+// The seven buffer singletons are built once by @openpanel/db's src/buffers
+// (the V1 delegate — see that file's header) and, once V2 owns boot, handed
+// to AppDeps by createBuffers directly. Until then, every core module that
+// needs a buffer ahead of that boot wiring reaches it through THIS one
+// dynamic import() — see session.service.ts's loadProfileService comment:
+// rolldown cannot finalize a dynamic-import cycle when apps/api or
+// apps/worker bundles the workspace and 2+ separate call sites each reopen
+// the same core -> @openpanel/db -> core edge (db/buffers imports
+// `createBuffers` from the core barrel). One edge, one file.
+export function loadDbBuffers() {
+ return import('@openpanel/db/src/buffers');
+}
diff --git a/packages/db/src/exports/batch-creator.ts b/packages/core/src/clients/integrations/export/batch-creator.ts
similarity index 96%
rename from packages/db/src/exports/batch-creator.ts
rename to packages/core/src/clients/integrations/export/batch-creator.ts
index 4bbb32da8..d87f0ffb7 100644
--- a/packages/db/src/exports/batch-creator.ts
+++ b/packages/core/src/clients/integrations/export/batch-creator.ts
@@ -1,8 +1,8 @@
import { Readable } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import { createGzip } from 'node:zlib';
-import { generateSecureId } from '@openpanel/core';
-import { createLogger } from '../logger';
+import { generateSecureId } from '../../../shared/id';
+import { createLogger } from '../../logger';
import type { IExportEvent } from './export-event';
const logger = createLogger({ name: 'batch-creator' });
@@ -121,7 +121,7 @@ function eventTimeRange(events: IExportEvent[]): {
* Create JSONL content from events
*/
function createJsonlContent(events: IExportEvent[]): string {
- return events.map((event) => JSON.stringify(event)).join('\n') + '\n';
+ return `${events.map((event) => JSON.stringify(event)).join('\n')}\n`;
}
/**
diff --git a/packages/db/src/exports/export-event.ts b/packages/core/src/clients/integrations/export/export-event.ts
similarity index 91%
rename from packages/db/src/exports/export-event.ts
rename to packages/core/src/clients/integrations/export/export-event.ts
index 3a440799a..cda15dd24 100644
--- a/packages/db/src/exports/export-event.ts
+++ b/packages/core/src/clients/integrations/export/export-event.ts
@@ -1,5 +1,5 @@
-import { convertClickhouseDateToJs } from '../clickhouse/client';
-import type { IClickhouseEvent } from '../services/event.service';
+import { convertClickhouseDateToJs } from '@openpanel/db/src/clickhouse/client';
+import type { IClickhouseEvent } from '../../../modules/event/event.service';
/**
* Stable, versioned export schema written to the object store (JSONL/Parquet).
@@ -41,7 +41,7 @@ const toIso = (chDate: string): string =>
* Map a ClickHouse event row to the stable export schema.
*/
export function clickhouseEventToExportEvent(
- event: IClickhouseEvent,
+ event: IClickhouseEvent
): IExportEvent {
return {
event_id: event.id,
diff --git a/packages/core/src/clients/integrations/export/index.ts b/packages/core/src/clients/integrations/export/index.ts
new file mode 100644
index 000000000..8959858d7
--- /dev/null
+++ b/packages/core/src/clients/integrations/export/index.ts
@@ -0,0 +1,26 @@
+// Moved from @openpanel/db's src/exports/ (M8-005) — object-store export
+// batch creation, used by the flushExports cron job.
+
+export {
+ createBatch,
+ type ExportFormat,
+ generateBatchPath,
+ getContentType,
+ getFileExtension,
+ type IBatchFile,
+ type IBatchInfo,
+ type IBatchResult,
+} from './batch-creator';
+export {
+ clickhouseEventToExportEvent,
+ EXPORT_SCHEMA_VERSION,
+ type IExportEvent,
+} from './export-event';
+export {
+ createManifest,
+ type IManifest,
+ MANIFEST_CONTENT_TYPE,
+ MANIFEST_FILENAME,
+ parseManifest,
+ serializeManifest,
+} from './manifest';
diff --git a/packages/db/src/exports/manifest.ts b/packages/core/src/clients/integrations/export/manifest.ts
similarity index 98%
rename from packages/db/src/exports/manifest.ts
rename to packages/core/src/clients/integrations/export/manifest.ts
index 529614c5a..69f9734f1 100644
--- a/packages/db/src/exports/manifest.ts
+++ b/packages/core/src/clients/integrations/export/manifest.ts
@@ -27,7 +27,7 @@ const CURRENT_SCHEMA_VERSION = 1;
*/
export function createManifest(
batchInfo: IBatchInfo,
- fileNames: string[],
+ fileNames: string[]
): IManifest {
return {
batch_id: batchInfo.batchId,
diff --git a/packages/core/src/clients/logger.ts b/packages/core/src/clients/logger.ts
index 2c9c8f5c2..aa484d891 100644
--- a/packages/core/src/clients/logger.ts
+++ b/packages/core/src/clients/logger.ts
@@ -97,11 +97,22 @@ export function getServiceName(name: string): string {
.join('-');
}
+// pino-pretty's transport runs in a worker thread that pino locates via
+// require.resolve at the CALLING module's location. Under Bun that
+// resolution is broken for a transitive dependency (a caller outside
+// @openpanel/core, e.g. @openpanel/queue's module-scope `createLogger` call)
+// and crashes the process instead of the log line — deterministic on this
+// box, not a flake. Node has no such issue, so this only turns pretty
+// printing off for the Bun-booted V2 API; every Node-booted process
+// (V1 api/worker) is unaffected.
+const isBun = !!process.versions.bun;
+
export function createLogger({ name }: { name: string }): ILogger {
const service = getServiceName(name);
const useHyperDX = logExporter === 'otlp' && !!process.env.HYPERDX_API_KEY;
- const usePretty = !useHyperDX && process.env.NODE_ENV !== 'production';
+ const usePretty =
+ !(useHyperDX || isBun) && process.env.NODE_ENV !== 'production';
return pino({
name: service,
diff --git a/packages/db/code-migrations/1-settings.ts b/packages/core/src/code-migrations/1-settings.ts
similarity index 100%
rename from packages/db/code-migrations/1-settings.ts
rename to packages/core/src/code-migrations/1-settings.ts
diff --git a/packages/db/code-migrations/10-add-session-replay.ts b/packages/core/src/code-migrations/10-add-session-replay.ts
similarity index 92%
rename from packages/db/code-migrations/10-add-session-replay.ts
rename to packages/core/src/code-migrations/10-add-session-replay.ts
index 964360333..b6c08b329 100644
--- a/packages/db/code-migrations/10-add-session-replay.ts
+++ b/packages/core/src/code-migrations/10-add-session-replay.ts
@@ -1,11 +1,11 @@
import fs from 'node:fs';
import path from 'node:path';
-import { TABLE_NAMES } from '../src/clickhouse/client';
+import { TABLE_NAMES } from '@openpanel/db/src/clickhouse/client';
import {
createTable,
modifyTTL,
runClickhouseMigrationCommands,
-} from '../src/clickhouse/migration';
+} from '@openpanel/db/src/clickhouse/migration';
import { getIsCluster } from './helpers';
export async function up() {
diff --git a/packages/db/code-migrations/11-add-groups.ts b/packages/core/src/code-migrations/11-add-groups.ts
similarity index 93%
rename from packages/db/code-migrations/11-add-groups.ts
rename to packages/core/src/code-migrations/11-add-groups.ts
index e23ae819e..ce0a08509 100644
--- a/packages/db/code-migrations/11-add-groups.ts
+++ b/packages/core/src/code-migrations/11-add-groups.ts
@@ -1,11 +1,11 @@
import fs from 'node:fs';
import path from 'node:path';
-import { TABLE_NAMES } from '../src/clickhouse/client';
+import { TABLE_NAMES } from '@openpanel/db/src/clickhouse/client';
import {
addColumns,
createTable,
runClickhouseMigrationCommands,
-} from '../src/clickhouse/migration';
+} from '@openpanel/db/src/clickhouse/migration';
import { getIsCluster } from './helpers';
export async function up() {
diff --git a/packages/db/code-migrations/12-add-gsc.ts b/packages/core/src/code-migrations/12-add-gsc.ts
similarity index 93%
rename from packages/db/code-migrations/12-add-gsc.ts
rename to packages/core/src/code-migrations/12-add-gsc.ts
index 43d82d9fc..a0267fe8a 100644
--- a/packages/db/code-migrations/12-add-gsc.ts
+++ b/packages/core/src/code-migrations/12-add-gsc.ts
@@ -1,6 +1,9 @@
import fs from 'node:fs';
import path from 'node:path';
-import { createTable, runClickhouseMigrationCommands } from '../src/clickhouse/migration';
+import {
+ createTable,
+ runClickhouseMigrationCommands,
+} from '@openpanel/db/src/clickhouse/migration';
import { getIsCluster } from './helpers';
export async function up() {
@@ -74,9 +77,9 @@ export async function up() {
.trim()
.replace(/;$/, '')
.replace(/\n{2,}/g, '\n')
- .concat(';'),
+ .concat(';')
)
- .join('\n\n---\n\n'),
+ .join('\n\n---\n\n')
);
if (!process.argv.includes('--dry')) {
diff --git a/packages/db/code-migrations/13-cohorts.ts b/packages/core/src/code-migrations/13-cohorts.ts
similarity index 84%
rename from packages/db/code-migrations/13-cohorts.ts
rename to packages/core/src/code-migrations/13-cohorts.ts
index ef3a4c361..fc6df64b4 100644
--- a/packages/db/code-migrations/13-cohorts.ts
+++ b/packages/core/src/code-migrations/13-cohorts.ts
@@ -1,13 +1,13 @@
import fs from 'node:fs';
import path from 'node:path';
-import { TABLE_NAMES } from '../src/clickhouse/client';
+import { TABLE_NAMES } from '@openpanel/db/src/clickhouse/client';
import {
createMaterializedView,
createTable,
dropTable,
getExistingTables,
runClickhouseMigrationCommands,
-} from '../src/clickhouse/migration';
+} from '@openpanel/db/src/clickhouse/migration';
import { getIsCluster } from './helpers';
export async function up() {
@@ -20,8 +20,10 @@ export async function up() {
// 1. cohort_members — which profile_ids belong to which cohorts.
// ReplacingMergeTree(version) = newer compute wins on merge.
if (
- !existingTables.includes(`${TABLE_NAMES.cohort_members}_distributed`) &&
- !existingTables.includes(TABLE_NAMES.cohort_members)
+ !(
+ existingTables.includes(`${TABLE_NAMES.cohort_members}_distributed`) ||
+ existingTables.includes(TABLE_NAMES.cohort_members)
+ )
) {
sqls.push(
...createTable({
@@ -47,14 +49,16 @@ export async function up() {
distributionHash: 'cityHash64(project_id, cohort_id)',
replicatedVersion,
isClustered,
- }),
+ })
);
}
// 2. cohort_metadata — cached member count + sample profiles per cohort.
if (
- !existingTables.includes(`${TABLE_NAMES.cohort_metadata}_distributed`) &&
- !existingTables.includes(TABLE_NAMES.cohort_metadata)
+ !(
+ existingTables.includes(`${TABLE_NAMES.cohort_metadata}_distributed`) ||
+ existingTables.includes(TABLE_NAMES.cohort_metadata)
+ )
) {
sqls.push(
...createTable({
@@ -75,7 +79,7 @@ export async function up() {
distributionHash: 'cityHash64(project_id, cohort_id)',
replicatedVersion,
isClustered,
- }),
+ })
);
}
@@ -83,10 +87,11 @@ export async function up() {
// Used by cohort compute when frequency filters are present.
// populate: false — we have a cluster with lots of events; backfill ad-hoc.
if (
- !existingTables.includes(
- `${TABLE_NAMES.profile_event_summary_mv}_distributed`,
- ) &&
- !existingTables.includes(TABLE_NAMES.profile_event_summary_mv)
+ !(
+ existingTables.includes(
+ `${TABLE_NAMES.profile_event_summary_mv}_distributed`
+ ) || existingTables.includes(TABLE_NAMES.profile_event_summary_mv)
+ )
) {
sqls.push(
...createMaterializedView({
@@ -111,7 +116,7 @@ export async function up() {
replicatedVersion,
isClustered,
populate: false,
- }),
+ })
);
}
@@ -123,9 +128,9 @@ export async function up() {
.trim()
.replace(/;$/, '')
.replace(/\n{2,}/g, '\n')
- .concat(';'),
+ .concat(';')
)
- .join('\n\n---\n\n'),
+ .join('\n\n---\n\n')
);
if (!process.argv.includes('--dry')) {
@@ -137,8 +142,14 @@ export async function down() {
const isClustered = getIsCluster();
const sqls = [
- dropTable(`${TABLE_NAMES.profile_event_summary_mv}_distributed`, isClustered),
- dropTable(`${TABLE_NAMES.profile_event_summary_mv}_replicated`, isClustered),
+ dropTable(
+ `${TABLE_NAMES.profile_event_summary_mv}_distributed`,
+ isClustered
+ ),
+ dropTable(
+ `${TABLE_NAMES.profile_event_summary_mv}_replicated`,
+ isClustered
+ ),
dropTable(TABLE_NAMES.profile_event_summary_mv, isClustered),
dropTable(`${TABLE_NAMES.cohort_metadata}_distributed`, isClustered),
dropTable(`${TABLE_NAMES.cohort_metadata}_replicated`, isClustered),
diff --git a/packages/db/code-migrations/14-profile-event-property-summary-mv.ts b/packages/core/src/code-migrations/14-profile-event-property-summary-mv.ts
similarity index 86%
rename from packages/db/code-migrations/14-profile-event-property-summary-mv.ts
rename to packages/core/src/code-migrations/14-profile-event-property-summary-mv.ts
index 34e0e6a85..564ac4e14 100644
--- a/packages/db/code-migrations/14-profile-event-property-summary-mv.ts
+++ b/packages/core/src/code-migrations/14-profile-event-property-summary-mv.ts
@@ -1,12 +1,12 @@
import fs from 'node:fs';
import path from 'node:path';
-import { TABLE_NAMES } from '../src/clickhouse/client';
+import { TABLE_NAMES } from '@openpanel/db/src/clickhouse/client';
import {
createMaterializedView,
dropTable,
getExistingTables,
runClickhouseMigrationCommands,
-} from '../src/clickhouse/migration';
+} from '@openpanel/db/src/clickhouse/migration';
import { getIsCluster } from './helpers';
// Per-property breakdown of profile events, used when cohort event criteria
@@ -23,10 +23,12 @@ export async function up() {
const sqls: string[] = [];
if (
- !existingTables.includes(
- `${TABLE_NAMES.profile_event_property_summary_mv}_distributed`,
- ) &&
- !existingTables.includes(TABLE_NAMES.profile_event_property_summary_mv)
+ !(
+ existingTables.includes(
+ `${TABLE_NAMES.profile_event_property_summary_mv}_distributed`
+ ) ||
+ existingTables.includes(TABLE_NAMES.profile_event_property_summary_mv)
+ )
) {
sqls.push(
...createMaterializedView({
@@ -61,7 +63,7 @@ export async function up() {
replicatedVersion,
isClustered,
populate: false,
- }),
+ })
);
}
@@ -73,9 +75,9 @@ export async function up() {
.trim()
.replace(/;$/, '')
.replace(/\n{2,}/g, '\n')
- .concat(';'),
+ .concat(';')
)
- .join('\n\n---\n\n'),
+ .join('\n\n---\n\n')
);
if (!process.argv.includes('--dry')) {
@@ -89,11 +91,11 @@ export async function down() {
const sqls = [
dropTable(
`${TABLE_NAMES.profile_event_property_summary_mv}_distributed`,
- isClustered,
+ isClustered
),
dropTable(
`${TABLE_NAMES.profile_event_property_summary_mv}_replicated`,
- isClustered,
+ isClustered
),
dropTable(TABLE_NAMES.profile_event_property_summary_mv, isClustered),
];
diff --git a/packages/db/code-migrations/15-backfill-cohort-mvs.ts b/packages/core/src/code-migrations/15-backfill-cohort-mvs.ts
similarity index 90%
rename from packages/db/code-migrations/15-backfill-cohort-mvs.ts
rename to packages/core/src/code-migrations/15-backfill-cohort-mvs.ts
index c8fe6795c..bc12f2634 100644
--- a/packages/db/code-migrations/15-backfill-cohort-mvs.ts
+++ b/packages/core/src/code-migrations/15-backfill-cohort-mvs.ts
@@ -1,8 +1,8 @@
-import { TABLE_NAMES } from '../src/clickhouse/client';
+import { TABLE_NAMES } from '@openpanel/db/src/clickhouse/client';
import {
chMigrationClient,
runClickhouseMigrationCommands,
-} from '../src/clickhouse/migration';
+} from '@openpanel/db/src/clickhouse/migration';
import { getIsCluster } from './helpers';
/**
@@ -27,7 +27,11 @@ import { getIsCluster } from './helpers';
const DEFAULT_DAYS = 30;
const DEFAULT_BATCH_HOURS = 1;
-type Batch = { startTime: string; endTime: string; sql: string };
+interface Batch {
+ startTime: string;
+ endTime: string;
+ sql: string;
+}
function getArg(name: string): string | undefined {
const prefix = `--${name}=`;
@@ -50,7 +54,7 @@ function generateSummaryBatches(
startDate: Date,
endDate: Date,
batchHours: number,
- targetTable: string,
+ targetTable: string
): Batch[] {
const batches: Batch[] = [];
let cursor = new Date(startDate);
@@ -90,7 +94,7 @@ function generatePropertyBatches(
startDate: Date,
endDate: Date,
batchHours: number,
- targetTable: string,
+ targetTable: string
): Batch[] {
const batches: Batch[] = [];
let cursor = new Date(startDate);
@@ -164,7 +168,7 @@ async function executeBatches(label: string, batches: Batch[]): Promise<void> {
const pct = Math.round((completed / total) * 100);
const lastSec = Math.round((Date.now() - t0) / 1000);
console.log(
- ` [${pct}%] ${completed}/${total} last=${lastSec}s elapsed=${elapsedSec}s (${batch.startTime} → ${batch.endTime})`,
+ ` [${pct}%] ${completed}/${total} last=${lastSec}s elapsed=${elapsedSec}s (${batch.startTime} → ${batch.endTime})`
);
}
}
@@ -177,7 +181,7 @@ export async function up() {
const days = Number.parseInt(getArg('days') ?? String(DEFAULT_DAYS), 10);
const batchHours = Number.parseInt(
getArg('batch-hours') ?? String(DEFAULT_BATCH_HOURS),
- 10,
+ 10
);
const endDate = new Date();
@@ -187,19 +191,23 @@ export async function up() {
const summaryTarget = resolveTargetTable(
TABLE_NAMES.profile_event_summary_mv,
- isClustered,
+ isClustered
);
const propertyTarget = resolveTargetTable(
TABLE_NAMES.profile_event_property_summary_mv,
- isClustered,
+ isClustered
);
console.log('');
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
console.log('📦 Cohort MV backfill');
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
- console.log(` Window: ${formatChDateTime(startDate)} → ${formatChDateTime(endDate)} (${days} days)`);
- console.log(` Batch size: ${batchHours} hour${batchHours === 1 ? '' : 's'}`);
+ console.log(
+ ` Window: ${formatChDateTime(startDate)} → ${formatChDateTime(endDate)} (${days} days)`
+ );
+ console.log(
+ ` Batch size: ${batchHours} hour${batchHours === 1 ? '' : 's'}`
+ );
console.log(` Clustered: ${isClustered}`);
console.log(` Summary MV: ${summaryTarget}`);
console.log(` Property MV: ${propertyTarget}`);
@@ -217,18 +225,20 @@ export async function up() {
startDate,
endDate,
batchHours,
- summaryTarget,
+ summaryTarget
);
const propertyBatches = generatePropertyBatches(
startDate,
endDate,
batchHours,
- propertyTarget,
+ propertyTarget
);
if (isDryRun) {
console.log('');
- console.log(`🔍 DRY RUN — ${summaryBatches.length} summary batches, ${propertyBatches.length} property batches`);
+ console.log(
+ `🔍 DRY RUN — ${summaryBatches.length} summary batches, ${propertyBatches.length} property batches`
+ );
console.log('');
console.log('── Sample batch (profile_event_summary_mv) ──');
console.log(summaryBatches[0]?.sql);
@@ -247,5 +257,7 @@ export async function up() {
export async function down() {
console.log('⚠️ No down migration — backfill writes MV state, not schema.');
- console.log(' If a clean slate is needed, DROP + CREATE the two MVs and re-run.');
+ console.log(
+ ' If a clean slate is needed, DROP + CREATE the two MVs and re-run.'
+ );
}
diff --git a/packages/db/code-migrations/16-restructure-profiles.ts b/packages/core/src/code-migrations/16-restructure-profiles.ts
similarity index 99%
rename from packages/db/code-migrations/16-restructure-profiles.ts
rename to packages/core/src/code-migrations/16-restructure-profiles.ts
index ea489b51b..d3a6244ce 100644
--- a/packages/db/code-migrations/16-restructure-profiles.ts
+++ b/packages/core/src/code-migrations/16-restructure-profiles.ts
@@ -5,7 +5,7 @@ import {
createTable,
renameTable,
runClickhouseMigrationCommands,
-} from '../src/clickhouse/migration';
+} from '@openpanel/db/src/clickhouse/migration';
import { getIsCluster } from './helpers';
// Restructures the `profiles` table so the column names actually mean what
diff --git a/packages/db/code-migrations/17-migrate-deprecated-ranges.ts b/packages/core/src/code-migrations/17-migrate-deprecated-ranges.ts
similarity index 91%
rename from packages/db/code-migrations/17-migrate-deprecated-ranges.ts
rename to packages/core/src/code-migrations/17-migrate-deprecated-ranges.ts
index fd9e8db09..192218b24 100644
--- a/packages/db/code-migrations/17-migrate-deprecated-ranges.ts
+++ b/packages/core/src/code-migrations/17-migrate-deprecated-ranges.ts
@@ -1,4 +1,4 @@
-import { db } from '../index';
+import { db } from '@openpanel/db';
import { printBoxMessage } from './helpers';
export async function up() {
diff --git a/packages/db/code-migrations/18-events-profile-id-index.ts b/packages/core/src/code-migrations/18-events-profile-id-index.ts
similarity index 94%
rename from packages/db/code-migrations/18-events-profile-id-index.ts
rename to packages/core/src/code-migrations/18-events-profile-id-index.ts
index ae311076c..d87bb2395 100644
--- a/packages/db/code-migrations/18-events-profile-id-index.ts
+++ b/packages/core/src/code-migrations/18-events-profile-id-index.ts
@@ -1,7 +1,7 @@
import {
chMigrationClient,
runClickhouseMigrationCommands,
-} from '../src/clickhouse/migration';
+} from '@openpanel/db/src/clickhouse/migration';
import { getIsCluster } from './helpers';
/**
@@ -57,13 +57,13 @@ async function hasIndex(table: string): Promise<boolean> {
});
const [row] = await res.json<{ statement: string }>();
return new RegExp(`INDEX ${INDEX_NAME}([^A-Za-z0-9_]|$)`).test(
- row?.statement ?? '',
+ row?.statement ?? ''
);
}
async function hasCompletedMaterialization(
table: string,
- isClustered: boolean,
+ isClustered: boolean
): Promise<boolean> {
const matchExpr = `match(command, 'MATERIALIZE INDEX ${INDEX_NAME}${NAME_BOUNDARY}') AND is_done = 1`;
try {
@@ -93,8 +93,14 @@ async function hasCompletedMaterialization(
AND ${matchExpr}`,
format: 'JSONEachRow',
});
- const [row] = await res.json<{ total: string | number; done: string | number }>();
- return Number(row?.total ?? 0) > 0 && Number(row?.done ?? 0) >= Number(row?.total ?? 0);
+ const [row] = await res.json<{
+ total: string | number;
+ done: string | number;
+ }>();
+ return (
+ Number(row?.total ?? 0) > 0 &&
+ Number(row?.done ?? 0) >= Number(row?.total ?? 0)
+ );
} catch {
// Can't verify (e.g. no grant on system.mutations / cluster functions) —
// materialize; the mutation is idempotent and redundant work beats a
@@ -120,7 +126,7 @@ export async function up() {
];
if (!backfilled) {
sqls.push(
- `ALTER TABLE ${table}${onCluster} MATERIALIZE INDEX ${INDEX_NAME}`,
+ `ALTER TABLE ${table}${onCluster} MATERIALIZE INDEX ${INDEX_NAME}`
);
}
diff --git a/packages/db/code-migrations/19-event-property-values-projections.ts b/packages/core/src/code-migrations/19-event-property-values-projections.ts
similarity index 95%
rename from packages/db/code-migrations/19-event-property-values-projections.ts
rename to packages/core/src/code-migrations/19-event-property-values-projections.ts
index ee1ed8069..7b2665033 100644
--- a/packages/db/code-migrations/19-event-property-values-projections.ts
+++ b/packages/core/src/code-migrations/19-event-property-values-projections.ts
@@ -1,8 +1,8 @@
-import { TABLE_NAMES } from '../src/clickhouse/client';
+import { TABLE_NAMES } from '@openpanel/db/src/clickhouse/client';
import {
chMigrationClient,
runClickhouseMigrationCommands,
-} from '../src/clickhouse/migration';
+} from '@openpanel/db/src/clickhouse/migration';
import { getIsCluster } from './helpers';
/**
@@ -120,8 +120,7 @@ async function resolveStorageTable(isClustered: boolean): Promise<string> {
// Token-boundary match so a similarly named projection (epv_keys_v2) can
// never satisfy the checks — substring/LIKE matching would.
-const nameBoundary = (name: string) =>
- new RegExp(`${name}([^A-Za-z0-9_]|$)`);
+const nameBoundary = (name: string) => new RegExp(`${name}([^A-Za-z0-9_]|$)`);
async function existingProjections(storage: string): Promise<Set<string>> {
const res = await chMigrationClient.query({
@@ -131,14 +130,14 @@ async function existingProjections(storage: string): Promise<Set<string>> {
const [row] = await res.json<{ statement: string }>();
return new Set(
PROJECTIONS.filter((p) =>
- nameBoundary(`PROJECTION ${p.name}`).test(row?.statement ?? ''),
- ).map((p) => p.name),
+ nameBoundary(`PROJECTION ${p.name}`).test(row?.statement ?? '')
+ ).map((p) => p.name)
);
}
async function materializedProjections(
storage: string,
- isClustered: boolean,
+ isClustered: boolean
): Promise<Set<string>> {
try {
// Clustered: a completed mutation on the connected host doesn't prove
@@ -176,10 +175,10 @@ async function materializedProjections(
PROJECTIONS.filter((p) => {
const matcher = nameBoundary(`MATERIALIZE PROJECTION ${p.name}`);
const hosts = new Set(
- rows.filter((r) => matcher.test(r.command)).map((r) => r.host),
+ rows.filter((r) => matcher.test(r.command)).map((r) => r.host)
);
return hosts.size >= totalHosts;
- }).map((p) => p.name),
+ }).map((p) => p.name)
);
} catch {
// Can't verify (e.g. no grant on system.mutations / cluster functions) —
@@ -205,12 +204,12 @@ export async function up() {
`ALTER TABLE ${tbl}${onCluster} MODIFY SETTING deduplicate_merge_projection_mode = 'rebuild'`,
...PROJECTIONS.map(
(p) =>
- `ALTER TABLE ${tbl}${onCluster} ADD PROJECTION IF NOT EXISTS ${p.name} (${p.def})`,
+ `ALTER TABLE ${tbl}${onCluster} ADD PROJECTION IF NOT EXISTS ${p.name} (${p.def})`
),
...PROJECTIONS.filter(
- (p) => !(existing.has(p.name) && materialized.has(p.name)),
+ (p) => !(existing.has(p.name) && materialized.has(p.name))
).map(
- (p) => `ALTER TABLE ${tbl}${onCluster} MATERIALIZE PROJECTION ${p.name}`,
+ (p) => `ALTER TABLE ${tbl}${onCluster} MATERIALIZE PROJECTION ${p.name}`
),
]);
}
@@ -223,7 +222,8 @@ export async function down() {
await runClickhouseMigrationCommands([
...PROJECTIONS.map(
- (p) => `ALTER TABLE ${tbl}${onCluster} DROP PROJECTION IF EXISTS ${p.name}`,
+ (p) =>
+ `ALTER TABLE ${tbl}${onCluster} DROP PROJECTION IF EXISTS ${p.name}`
),
// Restore the engine default ('throw'). Safe here because this down()
// just dropped the only projections on the table; if you've added your
diff --git a/packages/db/code-migrations/2-accounts.ts b/packages/core/src/code-migrations/2-accounts.ts
similarity index 93%
rename from packages/db/code-migrations/2-accounts.ts
rename to packages/core/src/code-migrations/2-accounts.ts
index c6b39230e..c95b1b261 100644
--- a/packages/db/code-migrations/2-accounts.ts
+++ b/packages/core/src/code-migrations/2-accounts.ts
@@ -1,11 +1,11 @@
import fs from 'node:fs/promises';
-import path from 'node:path';
-import { dirname } from 'node:path';
+import path, { dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
-import { db } from '../index';
+
+import { db } from '@openpanel/db';
import { printBoxMessage } from './helpers';
const simpleCsvParser = (csv: string): Record<string, unknown>[] => {
@@ -17,8 +17,8 @@ const simpleCsvParser = (csv: string): Record<string, unknown>[] => {
acc[headers[index]!] = curr;
return acc;
},
- {} as Record<string, unknown>,
- ),
+ {} as Record<string, unknown>
+ )
);
};
@@ -26,7 +26,7 @@ async function checkFileExists(filePath: string): Promise<boolean> {
try {
await fs.access(filePath);
return true; // File exists
- } catch (error) {
+ } catch (_error) {
return false; // File does not exist
}
}
diff --git a/packages/db/code-migrations/20-cohort-summary-mv-sort-key.ts b/packages/core/src/code-migrations/20-cohort-summary-mv-sort-key.ts
similarity index 86%
rename from packages/db/code-migrations/20-cohort-summary-mv-sort-key.ts
rename to packages/core/src/code-migrations/20-cohort-summary-mv-sort-key.ts
index 786c6ffb4..71e45964e 100644
--- a/packages/db/code-migrations/20-cohort-summary-mv-sort-key.ts
+++ b/packages/core/src/code-migrations/20-cohort-summary-mv-sort-key.ts
@@ -1,11 +1,11 @@
import fs from 'node:fs';
import path from 'node:path';
-import { TABLE_NAMES } from '../src/clickhouse/client';
+import { TABLE_NAMES } from '@openpanel/db/src/clickhouse/client';
import {
createMaterializedView,
getExistingTables,
runClickhouseMigrationCommands,
-} from '../src/clickhouse/migration';
+} from '@openpanel/db/src/clickhouse/migration';
import { getIsCluster } from './helpers';
/**
@@ -48,10 +48,11 @@ export async function up() {
const sqls: string[] = [];
if (
- !existingTables.includes(
- `${TABLE_NAMES.event_profile_summary_mv}_distributed`,
- ) &&
- !existingTables.includes(TABLE_NAMES.event_profile_summary_mv)
+ !(
+ existingTables.includes(
+ `${TABLE_NAMES.event_profile_summary_mv}_distributed`
+ ) || existingTables.includes(TABLE_NAMES.event_profile_summary_mv)
+ )
) {
sqls.push(
...createMaterializedView({
@@ -76,15 +77,17 @@ export async function up() {
replicatedVersion,
isClustered,
populate: false,
- }),
+ })
);
}
if (
- !existingTables.includes(
- `${TABLE_NAMES.event_property_profile_summary_mv}_distributed`,
- ) &&
- !existingTables.includes(TABLE_NAMES.event_property_profile_summary_mv)
+ !(
+ existingTables.includes(
+ `${TABLE_NAMES.event_property_profile_summary_mv}_distributed`
+ ) ||
+ existingTables.includes(TABLE_NAMES.event_property_profile_summary_mv)
+ )
) {
sqls.push(
...createMaterializedView({
@@ -120,15 +123,21 @@ export async function up() {
replicatedVersion,
isClustered,
populate: false,
- }),
+ })
);
}
fs.writeFileSync(
path.join(import.meta.filename.replace('.ts', '.sql')),
sqls
- .map((sql) => sql.trim().replace(/;$/, '').replace(/\n{2,}/g, '\n').concat(';'))
- .join('\n\n---\n\n'),
+ .map((sql) =>
+ sql
+ .trim()
+ .replace(/;$/, '')
+ .replace(/\n{2,}/g, '\n')
+ .concat(';')
+ )
+ .join('\n\n---\n\n')
);
if (process.argv.includes('--dry')) {
diff --git a/packages/db/code-migrations/20-invite-project-access-levels.ts b/packages/core/src/code-migrations/20-invite-project-access-levels.ts
similarity index 96%
rename from packages/db/code-migrations/20-invite-project-access-levels.ts
rename to packages/core/src/code-migrations/20-invite-project-access-levels.ts
index 05af03d6c..38afb3ed9 100644
--- a/packages/db/code-migrations/20-invite-project-access-levels.ts
+++ b/packages/core/src/code-migrations/20-invite-project-access-levels.ts
@@ -1,5 +1,5 @@
+import { db } from '@openpanel/db';
import { zProjectAccessGrant } from '@openpanel/validation';
-import { db } from '../index';
import { getIsDry, printBoxMessage } from './helpers';
/**
@@ -37,13 +37,13 @@ const LEGACY_COLUMN = 'projectAccess_legacy';
// The level accepting one of these invites would have produced anyway.
const IMPLIED_LEVEL = 'write' as const;
-type LegacyInvite = {
+interface LegacyInvite {
id: string;
email: string;
organizationId: string;
legacy: string[] | null;
convertedCount: number;
-};
+}
async function hasLegacyColumn(): Promise<boolean> {
const rows = await db.$queryRaw<{ present: boolean }[]>`
@@ -88,7 +88,7 @@ export async function up() {
select: { id: true, organizationId: true },
});
const organizationByProject = new Map(
- projects.map((project) => [project.id, project.organizationId]),
+ projects.map((project) => [project.id, project.organizationId])
);
const skipped: string[] = [];
@@ -111,11 +111,11 @@ export async function up() {
if (owner === undefined) {
orphans.push(
- `${invite.id} (${invite.email}) -> ${projectId} - project does not exist`,
+ `${invite.id} (${invite.email}) -> ${projectId} - project does not exist`
);
} else if (owner !== invite.organizationId) {
orphans.push(
- `${invite.id} (${invite.email}) -> ${projectId} - belongs to ${owner}, invite is for ${invite.organizationId}`,
+ `${invite.id} (${invite.email}) -> ${projectId} - belongs to ${owner}, invite is for ${invite.organizationId}`
);
}
}
@@ -123,7 +123,7 @@ export async function up() {
// Parse rather than hand-build: if zProjectAccessGrant ever gains a field
// this throws instead of writing a shape the app cannot read.
const grants = projectIds.map((projectId) =>
- zProjectAccessGrant.parse({ projectId, level: IMPLIED_LEVEL }),
+ zProjectAccessGrant.parse({ projectId, level: IMPLIED_LEVEL })
);
converted.push({ id: invite.id, grants });
@@ -164,7 +164,7 @@ export async function up() {
}
await db.$executeRawUnsafe(
- `ALTER TABLE "invites" DROP COLUMN "${LEGACY_COLUMN}"`,
+ `ALTER TABLE "invites" DROP COLUMN "${LEGACY_COLUMN}"`
);
printBoxMessage('✅ Migration Complete', [
diff --git a/packages/db/code-migrations/21-backfill-cohort-summary-mvs.ts b/packages/core/src/code-migrations/21-backfill-cohort-summary-mvs.ts
similarity index 95%
rename from packages/db/code-migrations/21-backfill-cohort-summary-mvs.ts
rename to packages/core/src/code-migrations/21-backfill-cohort-summary-mvs.ts
index 0206fe8c7..2faeaa21c 100644
--- a/packages/db/code-migrations/21-backfill-cohort-summary-mvs.ts
+++ b/packages/core/src/code-migrations/21-backfill-cohort-summary-mvs.ts
@@ -1,8 +1,8 @@
-import { TABLE_NAMES } from '../src/clickhouse/client';
+import { TABLE_NAMES } from '@openpanel/db/src/clickhouse/client';
import {
chMigrationClient,
runClickhouseMigrationCommands,
-} from '../src/clickhouse/migration';
+} from '@openpanel/db/src/clickhouse/migration';
import { getIsCluster } from './helpers';
/**
@@ -53,7 +53,7 @@ import { getIsCluster } from './helpers';
* The same file is the supervised tool. Run it directly to control when
* the work happens, or to redo part of it:
*
- * CLICKHOUSE_URL=... jiti packages/db/code-migrations/21-backfill-cohort-summary-mvs.ts
+ * CLICKHOUSE_URL=... jiti packages/core/src/code-migrations/21-backfill-cohort-summary-mvs.ts
*
* Flags:
* --dry Print the plan and the first batch; run nothing.
@@ -85,7 +85,10 @@ const INSERT_SETTINGS = `SETTINGS
max_insert_threads = 8,
distributed_foreground_insert = 1`;
-type Batch = { label: string; sql: string };
+interface Batch {
+ label: string;
+ sql: string;
+}
function getArg(name: string): string | undefined {
const prefix = `--${name}=`;
@@ -112,7 +115,7 @@ function getPositiveInt(value: string | undefined, fallback: number): number {
function dropPartition(
table: string,
month: number,
- isClustered: boolean,
+ isClustered: boolean
): string {
return isClustered
? `ALTER TABLE ${table}_replicated ON CLUSTER '{cluster}' DROP PARTITION '${month}'`
@@ -176,12 +179,12 @@ function monthBatches(
until: string,
batchDays: number,
target: string,
- select: (start: string, end: string) => string,
+ select: (start: string, end: string) => string
): Batch[] {
const batches: Batch[] = [];
const start = new Date(`${monthStart(month).replace(' ', 'T')}Z`);
const monthEnd = new Date(
- `${monthStart(nextMonth(month)).replace(' ', 'T')}Z`,
+ `${monthStart(nextMonth(month)).replace(' ', 'T')}Z`
);
const untilDate = new Date(`${until.replace(' ', 'T')}Z`);
const end = monthEnd < untilDate ? monthEnd : untilDate;
@@ -210,7 +213,7 @@ function monthBatches(
async function runPool(
batches: Batch[],
parallel: number,
- onDone: (batch: Batch, seconds: number) => void,
+ onDone: (batch: Batch, seconds: number) => void
): Promise<void> {
let next = 0;
await Promise.all(
@@ -223,8 +226,8 @@ async function runPool(
await chMigrationClient.command({ query: batch.sql });
onDone(batch, Math.round((Date.now() - startedAt) / 1000));
}
- },
- ),
+ }
+ )
);
}
@@ -241,7 +244,7 @@ export async function up() {
const batchDays = getPositiveInt(getArg('batch-days'), DEFAULT_BATCH_DAYS);
const parallel = getPositiveInt(getArg('parallel'), DEFAULT_PARALLEL);
const totalEvents = Number(
- (await scalar(`SELECT count() AS c FROM ${TABLE_NAMES.events}`)) ?? 0,
+ (await scalar(`SELECT count() AS c FROM ${TABLE_NAMES.events}`)) ?? 0
);
if (totalEvents === 0) {
console.log('📦 Cohort summary MVs: no events to aggregate, nothing to do');
@@ -261,15 +264,15 @@ export async function up() {
const currentMonth = Number(
await scalar(
- `SELECT toString(toYYYYMM(toDateTime64('${planningUntil}', 3))) AS m`,
- ),
+ `SELECT toString(toYYYYMM(toDateTime64('${planningUntil}', 3))) AS m`
+ )
);
const fromMonth = getPositiveInt(
getArg('from') ??
(await scalar(
- `SELECT toString(toYYYYMM(min(created_at))) AS m FROM ${TABLE_NAMES.events}`,
+ `SELECT toString(toYYYYMM(min(created_at))) AS m FROM ${TABLE_NAMES.events}`
)),
- currentMonth,
+ currentMonth
);
const toMonth = getPositiveInt(getArg('to'), currentMonth);
@@ -319,10 +322,10 @@ export async function up() {
planningUntil,
batchDays,
target.table,
- target.select,
+ target.select
);
console.log(
- `\n-- ${target.label}: ${sample.length} batches for ${months[0]} --`,
+ `\n-- ${target.label}: ${sample.length} batches for ${months[0]} --`
);
console.log(dropPartition(target.table, months[0]!, isClustered));
console.log(sample[0]?.sql);
@@ -349,7 +352,7 @@ export async function up() {
until,
batchDays,
target.table,
- target.select,
+ target.select
);
if (batches.length === 0) {
continue;
@@ -359,7 +362,7 @@ export async function up() {
console.log(` · ${batch.label} (${seconds}s)`);
});
console.log(
- ` ✅ ${month} in ${Math.round((Date.now() - monthStartedAt) / 1000)}s (${batches.length} batches, elapsed=${Math.round((Date.now() - startedAt) / 1000)}s)`,
+ ` ✅ ${month} in ${Math.round((Date.now() - monthStartedAt) / 1000)}s (${batches.length} batches, elapsed=${Math.round((Date.now() - startedAt) / 1000)}s)`
);
}
}
diff --git a/packages/db/code-migrations/21-wind-down-onboarding-pointer.ts b/packages/core/src/code-migrations/21-wind-down-onboarding-pointer.ts
similarity index 92%
rename from packages/db/code-migrations/21-wind-down-onboarding-pointer.ts
rename to packages/core/src/code-migrations/21-wind-down-onboarding-pointer.ts
index c4856f9c2..6e7c5fadb 100644
--- a/packages/db/code-migrations/21-wind-down-onboarding-pointer.ts
+++ b/packages/core/src/code-migrations/21-wind-down-onboarding-pointer.ts
@@ -13,9 +13,9 @@
* emitting a warning for each. Settling them here keeps that path for genuine
* accidents rather than for a rename we already know about.
*
- * pnpm with-env jiti ./code-migrations/21-wind-down-onboarding-pointer.ts --dry
+ * pnpm with-env jiti ./src/code-migrations/21-wind-down-onboarding-pointer.ts --dry
*/
-import { db } from '../src/prisma-client';
+import { db } from '@openpanel/db/src/prisma-client';
import { getIsDry, printBoxMessage } from './helpers';
const RETIRED_POINTER = 'onboarding-trial-ended';
diff --git a/packages/db/code-migrations/22-add-events-inserted-at.ts b/packages/core/src/code-migrations/22-add-events-inserted-at.ts
similarity index 95%
rename from packages/db/code-migrations/22-add-events-inserted-at.ts
rename to packages/core/src/code-migrations/22-add-events-inserted-at.ts
index 8c546e3dd..d46d1ef01 100644
--- a/packages/db/code-migrations/22-add-events-inserted-at.ts
+++ b/packages/core/src/code-migrations/22-add-events-inserted-at.ts
@@ -3,7 +3,7 @@ import path from 'node:path';
import {
addColumns,
runClickhouseMigrationCommands,
-} from '../src/clickhouse/migration';
+} from '@openpanel/db/src/clickhouse/migration';
import { getIsCluster } from './helpers';
export async function up() {
@@ -42,7 +42,7 @@ export async function up() {
...addColumns(
'events',
['`inserted_at` DateTime64(3) DEFAULT created_at AFTER `imported_at`'],
- isClustered,
+ isClustered
),
indexSql,
materializeIndexSql,
@@ -56,9 +56,9 @@ export async function up() {
.trim()
.replace(/;$/, '')
.replace(/\n{2,}/g, '\n')
- .concat(';'),
+ .concat(';')
)
- .join('\n\n---\n\n'),
+ .join('\n\n---\n\n')
);
if (!process.argv.includes('--dry')) {
diff --git a/packages/db/code-migrations/3-init-ch.ts b/packages/core/src/code-migrations/3-init-ch.ts
similarity index 96%
rename from packages/db/code-migrations/3-init-ch.ts
rename to packages/core/src/code-migrations/3-init-ch.ts
index 56fa0f3ea..1a40f4cd1 100644
--- a/packages/db/code-migrations/3-init-ch.ts
+++ b/packages/core/src/code-migrations/3-init-ch.ts
@@ -1,11 +1,11 @@
import fs from 'node:fs';
-import path from 'node:path';
-import { dirname } from 'node:path';
+import path, { dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
-import { formatClickhouseDate } from '../src/clickhouse/client';
+
+import { formatClickhouseDate } from '@openpanel/db/src/clickhouse/client';
import {
createDatabase,
createMaterializedView,
@@ -15,7 +15,7 @@ import {
moveDataBetweenTables,
renameTable,
runClickhouseMigrationCommands,
-} from '../src/clickhouse/migration';
+} from '@openpanel/db/src/clickhouse/migration';
import { getIsCluster, getIsSelfHosting, printBoxMessage } from './helpers';
export async function up() {
@@ -27,7 +27,7 @@ export async function up() {
const hasEventsBots = existingTables.includes('events_bots_distributed');
const hasProfiles = existingTables.includes('profiles_distributed');
const hasProfileAliases = existingTables.includes(
- 'profile_aliases_distributed',
+ 'profile_aliases_distributed'
);
const isSelfHosting = getIsSelfHosting();
@@ -50,8 +50,8 @@ export async function up() {
sqls.push(
...existingTables
.filter((table) => {
- return (
- !table.endsWith('_tmp') && !existingTables.includes(`${table}_tmp`)
+ return !(
+ table.endsWith('_tmp') || existingTables.includes(`${table}_tmp`)
);
})
.flatMap((table) => {
@@ -60,7 +60,7 @@ export async function up() {
to: `${table}_tmp`,
isClustered,
});
- }),
+ })
);
}
@@ -263,7 +263,7 @@ export async function up() {
distributionHash: 'cityHash64(project_id, name)',
replicatedVersion,
isClustered,
- }),
+ })
);
if (isSelfHostingPostCluster) {
@@ -321,7 +321,7 @@ export async function up() {
interval: 'week',
},
})
- : []),
+ : [])
);
}
@@ -336,7 +336,7 @@ export async function up() {
interval: 'week',
},
})
- : []),
+ : [])
);
}
@@ -348,9 +348,9 @@ export async function up() {
.trim()
.replace(/;$/, '')
.replace(/\n{2,}/g, '\n')
- .concat(';'),
+ .concat(';')
)
- .join('\n\n---\n\n'),
+ .join('\n\n---\n\n')
);
printBoxMessage('Will start migration for self-hosting setup.', [
@@ -369,9 +369,9 @@ export async function up() {
(table) =>
`docker compose exec -it op-ch clickhouse-client --query "${dropTable(
`openpanel.${table}_tmp`,
- false,
- )}"`,
- ),
+ false
+ )}"`
+ )
);
}
}
diff --git a/packages/db/code-migrations/4-add-sessions.ts b/packages/core/src/code-migrations/4-add-sessions.ts
similarity index 97%
rename from packages/db/code-migrations/4-add-sessions.ts
rename to packages/core/src/code-migrations/4-add-sessions.ts
index cf1c00bbb..b56eef9d3 100644
--- a/packages/db/code-migrations/4-add-sessions.ts
+++ b/packages/core/src/code-migrations/4-add-sessions.ts
@@ -1,11 +1,14 @@
import fs from 'node:fs';
import path from 'node:path';
-import { TABLE_NAMES, formatClickhouseDate } from '../src/clickhouse/client';
+import {
+ formatClickhouseDate,
+ TABLE_NAMES,
+} from '@openpanel/db/src/clickhouse/client';
import {
chMigrationClient,
createTable,
runClickhouseMigrationCommands,
-} from '../src/clickhouse/migration';
+} from '@openpanel/db/src/clickhouse/migration';
import { getIsCluster } from './helpers';
export async function up() {
@@ -77,9 +80,9 @@ export async function up() {
.trim()
.replace(/;$/, '')
.replace(/\n{2,}/g, '\n')
- .concat(';'),
+ .concat(';')
)
- .join('\n\n---\n\n'),
+ .join('\n\n---\n\n')
);
if (!process.argv.includes('--dry')) {
@@ -104,7 +107,7 @@ async function createOldSessions() {
return null;
}
return new Date(row.created_at);
- } catch (e) {
+ } catch (_e) {
return defaultDate;
}
}
diff --git a/packages/db/code-migrations/5-add-imports-table.ts b/packages/core/src/code-migrations/5-add-imports-table.ts
similarity index 94%
rename from packages/db/code-migrations/5-add-imports-table.ts
rename to packages/core/src/code-migrations/5-add-imports-table.ts
index e9062c74b..0829efba0 100644
--- a/packages/db/code-migrations/5-add-imports-table.ts
+++ b/packages/core/src/code-migrations/5-add-imports-table.ts
@@ -1,11 +1,10 @@
import fs from 'node:fs';
import path from 'node:path';
-import { TABLE_NAMES } from '../src/clickhouse/client';
import {
createTable,
modifyTTL,
runClickhouseMigrationCommands,
-} from '../src/clickhouse/migration';
+} from '@openpanel/db/src/clickhouse/migration';
import { getIsCluster } from './helpers';
export async function up() {
@@ -68,7 +67,7 @@ export async function up() {
tableName: 'events_imports',
isClustered,
ttl: 'imported_at_meta + INTERVAL 7 DAY',
- }),
+ })
);
fs.writeFileSync(
@@ -79,9 +78,9 @@ export async function up() {
.trim()
.replace(/;$/, '')
.replace(/\n{2,}/g, '\n')
- .concat(';'),
+ .concat(';')
)
- .join('\n\n---\n\n'),
+ .join('\n\n---\n\n')
);
if (!process.argv.includes('--dry')) {
diff --git a/packages/db/code-migrations/6-add-revenue-column.ts b/packages/core/src/code-migrations/6-add-revenue-column.ts
similarity index 84%
rename from packages/db/code-migrations/6-add-revenue-column.ts
rename to packages/core/src/code-migrations/6-add-revenue-column.ts
index 715493ea9..647bb766a 100644
--- a/packages/db/code-migrations/6-add-revenue-column.ts
+++ b/packages/core/src/code-migrations/6-add-revenue-column.ts
@@ -3,7 +3,7 @@ import path from 'node:path';
import {
addColumns,
runClickhouseMigrationCommands,
-} from '../src/clickhouse/migration';
+} from '@openpanel/db/src/clickhouse/migration';
import { getIsCluster } from './helpers';
export async function up() {
@@ -13,7 +13,7 @@ export async function up() {
...addColumns(
'events',
['`revenue` UInt64 AFTER `referrer_type`'],
- isClustered,
+ isClustered
),
];
@@ -25,9 +25,9 @@ export async function up() {
.trim()
.replace(/;$/, '')
.replace(/\n{2,}/g, '\n')
- .concat(';'),
+ .concat(';')
)
- .join('\n\n---\n\n'),
+ .join('\n\n---\n\n')
);
if (!process.argv.includes('--dry')) {
diff --git a/packages/db/code-migrations/7-migrate-events-to-series.ts b/packages/core/src/code-migrations/7-migrate-events-to-series.ts
similarity index 93%
rename from packages/db/code-migrations/7-migrate-events-to-series.ts
rename to packages/core/src/code-migrations/7-migrate-events-to-series.ts
index 37ad34ab7..bd23d1af9 100644
--- a/packages/db/code-migrations/7-migrate-events-to-series.ts
+++ b/packages/core/src/code-migrations/7-migrate-events-to-series.ts
@@ -1,10 +1,10 @@
import { shortId } from '@openpanel/common';
+import { db } from '@openpanel/db';
import type {
IChartEvent,
IChartEventItem,
IChartFormula,
} from '@openpanel/validation';
-import { db } from '../index';
import { printBoxMessage } from './helpers';
export async function up() {
@@ -35,7 +35,7 @@ export async function up() {
Array.isArray(events) &&
events.length > 0 &&
events.some(
- (event) => !event || typeof event !== 'object' || !('type' in event),
+ (event) => !event || typeof event !== 'object' || !('type' in event)
);
// Check if formula exists and isn't already in the series
@@ -46,13 +46,13 @@ export async function up() {
item &&
typeof item === 'object' &&
'type' in item &&
- item.type === 'formula',
+ item.type === 'formula'
);
const needsFormulaMigration = !!oldFormula && !hasFormulaInSeries;
// Skip if no migration needed
- if (!needsEventMigration && !needsFormulaMigration) {
+ if (!(needsEventMigration || needsFormulaMigration)) {
skippedCount++;
continue;
}
@@ -83,7 +83,7 @@ export async function up() {
}
console.log(
- `Updating report ${report.name} (${report.id}) with ${migratedSeries.length} series`,
+ `Updating report ${report.name} (${report.id}) with ${migratedSeries.length} series`
);
// Update the report with migrated series
await db.report.update({
diff --git a/packages/db/code-migrations/8-order-keys.ts b/packages/core/src/code-migrations/8-order-keys.ts
similarity index 96%
rename from packages/db/code-migrations/8-order-keys.ts
rename to packages/core/src/code-migrations/8-order-keys.ts
index d36aa2a9b..1638f2046 100644
--- a/packages/db/code-migrations/8-order-keys.ts
+++ b/packages/core/src/code-migrations/8-order-keys.ts
@@ -6,7 +6,7 @@ import {
moveDataBetweenTables,
renameTable,
runClickhouseMigrationCommands,
-} from '../src/clickhouse/migration';
+} from '@openpanel/db/src/clickhouse/migration';
import { getIsCluster } from './helpers';
export async function up() {
@@ -156,7 +156,7 @@ export async function up() {
to: 'events_new_20251123',
batch: {
startDate: firstEventDate,
- endDate: endDate,
+ endDate,
column: 'toDate(created_at)',
interval: 'month',
transform: (date: Date) => {
@@ -165,7 +165,7 @@ export async function up() {
return `${year}-${month}-01`;
},
},
- }),
+ })
);
}
@@ -182,7 +182,7 @@ export async function up() {
!firstSessionDateJson[0]?.created_at.startsWith('1970')
) {
const firstSessionDate = new Date(
- firstSessionDateJson[0]?.created_at ?? '',
+ firstSessionDateJson[0]?.created_at ?? ''
);
// Set endDate to first of next month to ensure we capture all data in the current month
const endDate = new Date();
@@ -234,7 +234,7 @@ export async function up() {
],
batch: {
startDate: firstSessionDate,
- endDate: endDate,
+ endDate,
column: 'toDate(created_at)',
interval: 'month',
transform: (date: Date) => {
@@ -243,15 +243,15 @@ export async function up() {
return `${year}-${month}-01`;
},
},
- }),
+ })
);
}
sqls.push(
- ...renameTable({ from: 'events', to: 'events_20251123', isClustered }),
+ ...renameTable({ from: 'events', to: 'events_20251123', isClustered })
);
sqls.push(
- ...renameTable({ from: 'sessions', to: 'sessions_20251123', isClustered }),
+ ...renameTable({ from: 'sessions', to: 'sessions_20251123', isClustered })
);
if (isClustered && sessionTables[1] && eventTables[1]) {
@@ -264,7 +264,7 @@ export async function up() {
`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
+ sessionTables[1].replaceAll('sessions_new_20251123', 'sessions') // creates a new distributed table
);
} else {
sqls.push(
@@ -272,14 +272,14 @@ export async function up() {
from: 'events_new_20251123',
to: 'events',
isClustered,
- }),
+ })
);
sqls.push(
...renameTable({
from: 'sessions_new_20251123',
to: 'sessions',
isClustered,
- }),
+ })
);
}
@@ -291,9 +291,9 @@ export async function up() {
.trim()
.replace(/;$/, '')
.replace(/\n{2,}/g, '\n')
- .concat(';'),
+ .concat(';')
)
- .join('\n\n---\n\n'),
+ .join('\n\n---\n\n')
);
if (!process.argv.includes('--dry')) {
diff --git a/packages/db/code-migrations/9-migrate-options.ts b/packages/core/src/code-migrations/9-migrate-options.ts
similarity index 97%
rename from packages/db/code-migrations/9-migrate-options.ts
rename to packages/core/src/code-migrations/9-migrate-options.ts
index c39e4b6d3..7c008bfe9 100644
--- a/packages/db/code-migrations/9-migrate-options.ts
+++ b/packages/core/src/code-migrations/9-migrate-options.ts
@@ -1,5 +1,5 @@
+import { db } from '@openpanel/db';
import type { IReportOptions } from '@openpanel/validation';
-import { db } from '../index';
import { printBoxMessage } from './helpers';
export async function up() {
@@ -63,7 +63,7 @@ export async function up() {
// Only update if we have new options to set
if (newOptions) {
console.log(
- `Migrating report ${report.name} (${report.id}) - chartType: ${report.chartType}`,
+ `Migrating report ${report.name} (${report.id}) - chartType: ${report.chartType}`
);
await db.report.update({
diff --git a/packages/db/code-migrations/helpers.ts b/packages/core/src/code-migrations/helpers.ts
similarity index 100%
rename from packages/db/code-migrations/helpers.ts
rename to packages/core/src/code-migrations/helpers.ts
diff --git a/packages/db/code-migrations/migrate.ts b/packages/core/src/code-migrations/migrate.ts
similarity index 85%
rename from packages/db/code-migrations/migrate.ts
rename to packages/core/src/code-migrations/migrate.ts
index 1598f0602..42221c673 100644
--- a/packages/db/code-migrations/migrate.ts
+++ b/packages/core/src/code-migrations/migrate.ts
@@ -1,11 +1,11 @@
import fs from 'node:fs';
-import path from 'node:path';
-import { dirname } from 'node:path';
+import path, { dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
-import { db } from '../index';
+
+import { db } from '@openpanel/db';
import {
getIsCluster,
getIsDry,
@@ -24,12 +24,13 @@ async function migrate() {
.filter((file) => {
const version = file.split('-')[0];
return (
- !Number.isNaN(Number.parseInt(version ?? '')) && file.endsWith('.ts')
+ !Number.isNaN(Number.parseInt(version ?? '', 10)) &&
+ file.endsWith('.ts')
);
})
.sort((a, b) => {
- const aVersion = Number.parseInt(a.split('-')[0]!);
- const bVersion = Number.parseInt(b.split('-')[0]!);
+ const aVersion = Number.parseInt(a.split('-')[0]!, 10);
+ const bVersion = Number.parseInt(b.split('-')[0]!, 10);
return aVersion - bVersion;
});
@@ -38,7 +39,7 @@ async function migrate() {
printBoxMessage('📋 Plan', [
'\t✅ Finished:',
...finishedMigrations.map(
- (migration) => `\t- ${migration.name} (${migration.createdAt})`,
+ (migration) => `\t- ${migration.name} (${migration.createdAt})`
),
'',
'\t🔄 Will run now:',
@@ -46,8 +47,8 @@ async function migrate() {
.filter(
(migration) =>
!finishedMigrations.some(
- (finishedMigration) => finishedMigration.name === migration,
- ),
+ (finishedMigration) => finishedMigration.name === migration
+ )
)
.map((migration) => `\t- ${migration}`),
]);
@@ -63,11 +64,11 @@ async function migrate() {
]);
if (!getIsSelfHosting()) {
- if (!getIsDry()) {
- printBoxMessage('🕒 Migrations starts in 10 seconds', []);
- await new Promise((resolve) => setTimeout(resolve, 10000));
- } else {
+ if (getIsDry()) {
printBoxMessage('🕒 Migrations starts now (dry run)', []);
+ } else {
+ printBoxMessage('🕒 Migrations starts in 10 seconds', []);
+ await new Promise((resolve) => setTimeout(resolve, 10_000));
}
}
@@ -93,7 +94,7 @@ async function runMigration(migrationsDir: string, file: string) {
try {
const migration = await import(path.join(migrationsDir, file));
await migration.up();
- if (!getIsDry() && !getShouldIgnoreRecord()) {
+ if (!(getIsDry() || getShouldIgnoreRecord())) {
await db.codeMigration.upsert({
where: {
name: file,
diff --git a/packages/core/src/context.ts b/packages/core/src/context.ts
index 16824e9a9..4d60d02cd 100644
--- a/packages/core/src/context.ts
+++ b/packages/core/src/context.ts
@@ -4,10 +4,10 @@
// edge reaches the query, the enqueue and the job that enqueue causes
// (ADR-007 decision 18, ADR-018 R1).
-import type { SessionValidationResult } from '@openpanel/db';
import type { Buffers } from './buffers/create-buffers';
import type { QueueProducerHandle, QueueProducers } from './jobs.registry';
import type { Logger } from './logger';
+import type { SessionValidationResult } from './modules/auth/src/login-session';
import type { IncomingEventProducer } from './modules/ingest/src/incoming-event';
import { createServices, type Services } from './services';
import type { CookieJar, CookieOptions } from './shared/cookie';
@@ -26,13 +26,13 @@ export type ServiceClients = unknown;
// module singleton.
export type { Buffers } from './buffers/create-buffers';
-// The resolved session. Type-only, so nothing of `@openpanel/db` is loaded at
-// runtime — core stays importable with no database, which is what lets
-// `bun test` run offline. `SessionValidationResult` is Prisma-shaped
-// (Session + User), so it stays defined next to the Prisma-touching session
-// CRUD in @openpanel/db's auth-session.service.ts rather than here — moving
-// it to core would need a core -> db runtime dependency, and db already
-// depends on core (M4-007).
+// The resolved session. `SessionValidationResult` is Prisma-shaped
+// (Session + User) but the import above is type-only, so nothing of
+// `@openpanel/db` is loaded at runtime — core stays importable with no
+// database, which is what lets `bun test` run offline. It stays defined next
+// to the Prisma-touching session CRUD in `./modules/auth/src/login-session.ts`
+// (M8-005) rather than here, which is the same file that CRUD lazily reaches
+// `@openpanel/db`'s Prisma client from.
export type Session = SessionValidationResult;
/** The env-derived flags core needs. apps/api's config/env.ts is the sole
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 057ab4bdf..76ece8588 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -72,6 +72,25 @@ export {
sendDiscordNotification,
sendTestDiscordNotification,
} from './clients/integrations/discord';
+export {
+ clickhouseEventToExportEvent,
+ createBatch,
+ createManifest,
+ EXPORT_SCHEMA_VERSION,
+ type ExportFormat,
+ generateBatchPath,
+ getContentType,
+ getFileExtension,
+ type IBatchFile,
+ type IBatchInfo,
+ type IBatchResult,
+ type IExportEvent,
+ type IManifest,
+ MANIFEST_CONTENT_TYPE,
+ MANIFEST_FILENAME,
+ parseManifest,
+ serializeManifest,
+} from './clients/integrations/export';
export type {
IObjectStoreAdapter,
IUploadOptions,
@@ -258,6 +277,18 @@ export {
verifyPasswordHash,
verifyTotpCode,
} from './modules/auth/auth.service';
+export { getIsRegistrationAllowed } from './modules/auth/src/registration';
+// Moved from packages/db/src/services/auth-session.service.ts (M8-005) —
+// the Postgres-backed login session CRUD. packages/db keeps a re-export
+// shim (existing `@openpanel/db` importers, apps/api's app.ts).
+export type { SessionValidationResult } from './modules/auth/src/login-session';
+export {
+ createDemoSession,
+ createSession,
+ EMPTY_SESSION,
+ invalidateSession,
+ validateSessionToken,
+} from './modules/auth/src/login-session';
// Dissolved from @openpanel/db's services/chart.service.ts and engine/
// (M7-003) — packages/trpc's chart router, apps/api's export controller,
// V1's funnel/conversion/sankey/retention/overview services and the
@@ -333,6 +364,12 @@ export {
rewriteProfilePropertyRefs,
transformPropertyKey,
} from './modules/chart/chart.service';
+// Moved from packages/db/src/services/filter-where.service.ts (M8-005) — the
+// sessions/profiles/events-table filter compiler, distinct from
+// `getEventFiltersWhereClause` above. packages/db/src/services/
+// filter-where.service.ts stays a re-export shim.
+export type { FilterTableContext } from './modules/chart/src/table-filter-where';
+export { buildFilterWhere } from './modules/chart/src/table-filter-where';
// Dissolved from @openpanel/db's services/conversion.service.ts (M7-004) —
// reached through the chart module's own dispatch and the db shim.
export { getConversion } from './modules/chart/conversion.service';
@@ -1285,6 +1322,13 @@ export type {
ProjectAccessLike,
} from './shared/access';
export { createAccessChecks } from './shared/access';
+export type { IProjectAccess } from './shared/access-lookups';
+export {
+ canWriteProject,
+ getClientAccess,
+ getOrganizationAccess,
+ getProjectAccess,
+} from './shared/access-lookups';
// Dissolved from @openpanel/common/server (M4-003) — a still-live V1 package
// (db, queue, apps/worker) reaches these the same way apps/api and core
// itself do, until its own module lands. mcp reaches it as an internal
@@ -1295,6 +1339,12 @@ export {
hashPassword,
verifyPassword,
} from './shared/crypto';
+export {
+ getChartPrevStartEndDate,
+ getChartStartEndDate,
+ getDatesFromRange,
+ resolveDateRange,
+} from './shared/date';
// Moved from apps/worker/src/jobs/lib/email-sequence.ts (M6-003) — shared by
// the onboarding module and, until it moves too, apps/worker's own
// cron.wind-down.ts, which reaches it through this barrel (same shape as
@@ -1321,6 +1371,7 @@ export {
TRUSTED_IP_HEADER_ORDER,
} from './shared/get-client-ip';
export { generateId, generateSecureId, shortId } from './shared/id';
+export { resolveMaxLookbackDays } from './shared/lookback';
export { getReferrerWithQuery, parseReferrer } from './shared/parse-referrer';
export type {
UserAgentInfo,
@@ -1342,4 +1393,5 @@ export {
safeFetch,
safeFetchStream,
} from './shared/safe-fetch';
+export { getId } from './shared/slug-id';
export { assertSafeUrl, createPinnedLookup } from './shared/ssrf';
diff --git a/packages/core/src/modules/auth/auth.rpc.test.ts b/packages/core/src/modules/auth/auth.rpc.test.ts
index f80ea0780..cb24b8481 100644
--- a/packages/core/src/modules/auth/auth.rpc.test.ts
+++ b/packages/core/src/modules/auth/auth.rpc.test.ts
@@ -18,8 +18,8 @@ const COOKIE_OPTIONS: CookieOptions = {
path: '/',
};
-// EMPTY_SESSION's shape (packages/db/src/services/auth-session.service.ts) —
-// `TrpcContext.session` is never literally `null`, only its `userId` is.
+// EMPTY_SESSION's shape (./src/login-session.ts) — `TrpcContext.session` is
+// never literally `null`, only its `userId` is.
const EMPTY_SESSION = { session: null, user: null, userId: null };
async function anonCaller() {
diff --git a/packages/core/src/modules/auth/auth.service.ts b/packages/core/src/modules/auth/auth.service.ts
index 73b588a46..7564c1671 100644
--- a/packages/core/src/modules/auth/auth.service.ts
+++ b/packages/core/src/modules/auth/auth.service.ts
@@ -1,10 +1,9 @@
-// Moved from @openpanel/auth (M4-007). Only the DB-independent half lives
-// here: token issuance/hashing, argon2 password hashing, TOTP, the OAuth
-// clients and cookie helpers. The Prisma-touching half — creating,
-// validating and invalidating a `sessions` row — stays in @openpanel/db's
-// auth-session.service.ts, because @openpanel/db already depends on
-// @openpanel/core (for exactly this module's token hash) and the reverse
-// edge would be a cycle. That file calls back into `hashSessionToken` below.
+// Moved from @openpanel/auth (M4-007): token issuance/hashing, argon2
+// password hashing, TOTP, the OAuth clients and cookie helpers. The
+// Prisma-touching half — creating, validating and invalidating a `sessions`
+// row — moved here too (M8-005, `./src/login-session.ts`), lazily loading
+// @openpanel/db's Prisma client the same way `loadRegistration` below does,
+// so there is no static core -> db edge.
import { z } from 'zod';
import type { ServiceDeps } from '../../services';
@@ -132,13 +131,12 @@ export function createAuthService(_deps: ServiceDeps): AuthService {
// these same functions).
//
// db/session/registration/share access is LAZY, not a static top-level
-// import — see user.service.ts's header for the full reasoning, and because
-// a static import of @openpanel/db here specifically WOULD be a cycle
-// (this file's own header, above: db already depends on core for
-// `hashSessionToken`). `loadShare` points at `../share/share.service`
-// directly since M6-004 — share.service.ts statically imports this file's
-// own `hashPassword`, so the two are mutually lazy/eager by design, not a
-// live cycle.
+// import — see user.service.ts's header for the full reasoning (constructing
+// @openpanel/db's clients at import time spawns a pino-pretty transport
+// worker thread per `bun test --isolate` file). `loadShare` points at
+// `../share/share.service` directly since M6-004 — share.service.ts
+// statically imports this file's own `hashPassword`, so the two are mutually
+// lazy/eager by design, not a live cycle.
//
// None of these functions take a `TrpcContext`/`Ctx`: they take exactly the
// primitives they touch (`setCookie`, `cookies.get`, `logger`), so this file
@@ -171,7 +169,7 @@ function loadDb() {
}
function loadAuthSession() {
- return import('@openpanel/db/src/services/auth-session.service');
+ return import('./src/login-session');
}
function loadRegistration() {
diff --git a/packages/core/src/modules/auth/src/login-session.ts b/packages/core/src/modules/auth/src/login-session.ts
new file mode 100644
index 000000000..878cceff9
--- /dev/null
+++ b/packages/core/src/modules/auth/src/login-session.ts
@@ -0,0 +1,134 @@
+// Moved from packages/db/src/services/auth-session.service.ts (M8-005).
+// Postgres-backed login sessions (a `sessions` row keyed by the hash of a
+// browser's cookie). Not to be confused with session.service.ts's ClickHouse
+// visitor sessions.
+//
+// Originally split at the Prisma boundary (M4-007) on the belief that a
+// static `@openpanel/db` import here would cycle with db's own (static)
+// `@openpanel/core` imports. `loadDb()` below is the same lazy pattern
+// salt.service.ts and registration.ts already use to reach db's Prisma
+// client with no such cycle — auth.service.ts's own `loadAuthSession()`
+// already reached this file that way, so the move only changes where the
+// file lives, not how its caller loads it.
+//
+// db access is LAZY, not a static top-level import — see salt.service.ts's
+// header for the full reasoning (jobs.registry.ts and services.ts pull this
+// module into the eager barrel chain nearly every core test file reaches,
+// and constructing @openpanel/db's clients at import time would spawn a
+// pino-pretty transport worker thread per test file).
+
+import type { Session, User } from '@openpanel/db/src/prisma-client';
+import { decodeSessionToken, hashSessionToken } from './token';
+
+const SESSION_TTL_MS = 1000 * 60 * 60 * 24 * 30;
+const SESSION_RENEWAL_THRESHOLD_MS = 1000 * 60 * 60 * 24 * 15;
+const DEMO_SESSION_TTL_MS = 1000 * 60 * 60 * 24 * 30 * 365;
+const DEMO_SESSION_ID = '1';
+
+export type SessionValidationResult =
+ | { session: Session; user: User; userId: string }
+ | { session: null; user: null; userId: null };
+
+export const EMPTY_SESSION: SessionValidationResult = {
+ session: null,
+ user: null,
+ userId: null,
+};
+
+function loadDb() {
+ return import('@openpanel/db/src/prisma-client').then((m) => m.db);
+}
+
+export async function createSession(
+ token: string,
+ userId: string
+): Promise<Session> {
+ const db = await loadDb();
+ const session: Session = {
+ id: hashSessionToken(token),
+ userId,
+ expiresAt: new Date(Date.now() + SESSION_TTL_MS),
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ };
+ await db.session.create({
+ data: session,
+ });
+ return session;
+}
+
+export async function createDemoSession(
+ userId: string
+): Promise<SessionValidationResult> {
+ const db = await loadDb();
+ const user = await db.user.findUniqueOrThrow({
+ where: {
+ id: userId,
+ },
+ });
+
+ return {
+ user,
+ userId: user.id,
+ session: {
+ id: DEMO_SESSION_ID,
+ userId: user.id,
+ expiresAt: new Date(Date.now() + DEMO_SESSION_TTL_MS),
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ },
+ };
+}
+
+export async function validateSessionToken(
+ token: string | null | undefined
+): Promise<SessionValidationResult> {
+ if (process.env.DEMO_USER_ID) {
+ return createDemoSession(process.env.DEMO_USER_ID);
+ }
+
+ if (!token) {
+ return EMPTY_SESSION;
+ }
+ const sessionId = decodeSessionToken(token);
+ if (!sessionId) {
+ return EMPTY_SESSION;
+ }
+ const db = await loadDb();
+ const result = await db.session.findUnique({
+ where: {
+ id: sessionId,
+ },
+ include: {
+ user: true,
+ },
+ });
+ if (result === null) {
+ return EMPTY_SESSION;
+ }
+ const { user, ...session } = result;
+ if (Date.now() >= session.expiresAt.getTime()) {
+ await db.session.delete({ where: { id: sessionId } });
+ return EMPTY_SESSION;
+ }
+ if (
+ Date.now() >=
+ session.expiresAt.getTime() - SESSION_RENEWAL_THRESHOLD_MS
+ ) {
+ session.expiresAt = new Date(Date.now() + SESSION_TTL_MS);
+ await db.session.update({
+ where: {
+ id: session.id,
+ },
+ data: {
+ expiresAt: session.expiresAt,
+ },
+ });
+ }
+ return { session, user, userId: user.id };
+}
+
+export async function invalidateSession(sessionId: string): Promise<void> {
+ const db = await loadDb();
+ await db.session.delete({ where: { id: sessionId } });
+}
diff --git a/packages/db/src/services/registration.service.test.ts b/packages/core/src/modules/auth/src/registration.test.ts
similarity index 63%
rename from packages/db/src/services/registration.service.test.ts
rename to packages/core/src/modules/auth/src/registration.test.ts
index 2283ce4d2..e347333b7 100644
--- a/packages/db/src/services/registration.service.test.ts
+++ b/packages/core/src/modules/auth/src/registration.test.ts
@@ -1,21 +1,37 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-const mockUserCount = vi.hoisted(() => vi.fn());
-const mockInviteFindUnique = vi.hoisted(() => vi.fn());
-
-vi.mock('../prisma-client', () => ({
+import {
+ afterEach,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ mock,
+} from 'bun:test';
+
+const mockUserCount = mock(async () => 5);
+const mockInviteFindUnique = mock(
+ async (): Promise<{ id: string } | null> => null
+);
+
+const actualPrismaClient = await import('@openpanel/db/src/prisma-client');
+mock.module('@openpanel/db/src/prisma-client', () => ({
+ ...actualPrismaClient,
db: {
user: { count: mockUserCount },
invite: { findUnique: mockInviteFindUnique },
},
}));
-import { getIsRegistrationAllowed } from './registration.service';
+let getIsRegistrationAllowed: typeof import('./registration').getIsRegistrationAllowed;
+beforeAll(async () => {
+ ({ getIsRegistrationAllowed } = await import('./registration'));
+});
const ORIGINAL_ENV = { ...process.env };
beforeEach(() => {
- vi.clearAllMocks();
+ mockUserCount.mockClear();
+ mockInviteFindUnique.mockClear();
// Not the first user unless a test says otherwise
mockUserCount.mockResolvedValue(5);
mockInviteFindUnique.mockResolvedValue(null);
@@ -30,7 +46,7 @@ describe('getIsRegistrationAllowed', () => {
process.env.ALLOW_REGISTRATION = undefined;
delete process.env.ALLOW_REGISTRATION;
- await expect(getIsRegistrationAllowed()).resolves.toBe(true);
+ expect(await getIsRegistrationAllowed()).toBe(true);
expect(mockUserCount).not.toHaveBeenCalled();
});
@@ -38,13 +54,13 @@ describe('getIsRegistrationAllowed', () => {
process.env.ALLOW_REGISTRATION = 'false';
mockUserCount.mockResolvedValue(0);
- await expect(getIsRegistrationAllowed()).resolves.toBe(true);
+ expect(await getIsRegistrationAllowed()).toBe(true);
});
it('blocks a new user with no invite when registration is disabled', async () => {
process.env.ALLOW_REGISTRATION = 'false';
- await expect(getIsRegistrationAllowed()).resolves.toBe(false);
+ expect(await getIsRegistrationAllowed()).toBe(false);
});
it('allows a new user holding a valid invite when registration is disabled', async () => {
@@ -52,7 +68,7 @@ describe('getIsRegistrationAllowed', () => {
process.env.ALLOW_INVITATION = 'true';
mockInviteFindUnique.mockResolvedValue({ id: 'invite-1' });
- await expect(getIsRegistrationAllowed('invite-1')).resolves.toBe(true);
+ expect(await getIsRegistrationAllowed('invite-1')).toBe(true);
});
it('blocks an unknown invite id', async () => {
@@ -60,7 +76,7 @@ describe('getIsRegistrationAllowed', () => {
process.env.ALLOW_INVITATION = 'true';
mockInviteFindUnique.mockResolvedValue(null);
- await expect(getIsRegistrationAllowed('nope')).resolves.toBe(false);
+ expect(await getIsRegistrationAllowed('nope')).toBe(false);
});
it('blocks a valid invite when invitations are disabled', async () => {
@@ -68,13 +84,13 @@ describe('getIsRegistrationAllowed', () => {
process.env.ALLOW_INVITATION = 'false';
mockInviteFindUnique.mockResolvedValue({ id: 'invite-1' });
- await expect(getIsRegistrationAllowed('invite-1')).resolves.toBe(false);
+ expect(await getIsRegistrationAllowed('invite-1')).toBe(false);
expect(mockInviteFindUnique).not.toHaveBeenCalled();
});
it('allows open self-hosted registration', async () => {
process.env.ALLOW_REGISTRATION = 'true';
- await expect(getIsRegistrationAllowed()).resolves.toBe(true);
+ expect(await getIsRegistrationAllowed()).toBe(true);
});
});
diff --git a/packages/core/src/modules/auth/src/registration.ts b/packages/core/src/modules/auth/src/registration.ts
new file mode 100644
index 000000000..9ac7523c7
--- /dev/null
+++ b/packages/core/src/modules/auth/src/registration.ts
@@ -0,0 +1,49 @@
+// db access is LAZY (`loadDb` below), not a static top-level import — see
+// insight.service.ts's header for the full reasoning (jobs.registry.ts and
+// services.ts pull this module into the eager barrel chain nearly every core
+// test file reaches, and constructing @openpanel/db's clients at import time
+// would spawn a pino-pretty transport worker thread per test file).
+function loadDb() {
+ return import('@openpanel/db/src/prisma-client').then((m) => m.db);
+}
+
+/**
+ * Whether a *new* user may be created right now.
+ *
+ * This must only be consulted at the point where we know the account does not
+ * exist yet. Calling it before an identity is known (e.g. when kicking off an
+ * OAuth redirect) would reject returning users too, since we cannot tell a
+ * sign-in from a sign-up at that stage.
+ */
+export async function getIsRegistrationAllowed(inviteId?: string | null) {
+ // ALLOW_REGISTRATION is always undefined in cloud
+ if (process.env.ALLOW_REGISTRATION === undefined) {
+ return true;
+ }
+
+ const db = await loadDb();
+ // Self-hosting logic
+ // 1. First user is always allowed
+ const count = await db.user.count();
+ if (count === 0) {
+ return true;
+ }
+
+ // 2. If there is an invite, check if it is valid
+ if (inviteId) {
+ if (process.env.ALLOW_INVITATION === 'false') {
+ return false;
+ }
+
+ const invite = await db.invite.findUnique({
+ where: {
+ id: inviteId,
+ },
+ });
+
+ return !!invite;
+ }
+
+ // 3. Otherwise, check if general registration is allowed
+ return process.env.ALLOW_REGISTRATION !== 'false';
+}
diff --git a/packages/db/src/services/retention.service.test.ts b/packages/core/src/modules/chart/retention.service.test.ts
similarity index 88%
rename from packages/db/src/services/retention.service.test.ts
rename to packages/core/src/modules/chart/retention.service.test.ts
index 926967b50..23eec756d 100644
--- a/packages/db/src/services/retention.service.test.ts
+++ b/packages/core/src/modules/chart/retention.service.test.ts
@@ -1,13 +1,12 @@
+import { afterAll, beforeAll, describe, expect, it } from 'bun:test';
import { round } from '@openpanel/common';
-import { afterAll, beforeAll, describe, expect, it } from 'vitest';
-
+import { chQuery, TABLE_NAMES } from '@openpanel/db/src/clickhouse/client';
import {
RETENTION_BLUEPRINT,
RETENTION_FIXTURE,
setupRetentionFixtures,
teardownRetentionFixtures,
-} from '../../../../test/retention-fixtures';
-import { TABLE_NAMES, chQuery } from '../clickhouse/client';
+} from '../../../../../test/retention-fixtures';
import {
getRetentionCohort,
getRetentionSeries,
@@ -18,6 +17,18 @@ import {
const PROJECT_ID = 'test-retention-cohort';
const { day, week } = RETENTION_FIXTURE;
+// bun:test's `toEqual` overloads (unlike vitest's) reject a `readonly` actual
+// against a mutable expected type — the blueprint fixture is `as const`. Pure
+// type-level erasure, no runtime effect.
+type DeepMutable<T> = T extends readonly (infer U)[]
+ ? DeepMutable<U>[]
+ : T extends object
+ ? { -readonly [K in keyof T]: DeepMutable<T[K]> }
+ : T;
+function mutable<T>(value: T): DeepMutable<T> {
+ return value as DeepMutable<T>;
+}
+
// Keep only the per-cohort rows (drop the leading "Weighted Average" row) and
// the fields the blueprint pins down.
function cohortsOnly(rows: IRetentionCohortRow[]) {
@@ -50,7 +61,7 @@ describe('getRetentionCohort', () => {
endDate: day.end,
});
- expect(cohortsOnly(rows)).toEqual(RETENTION_BLUEPRINT.dayOn);
+ expect(cohortsOnly(rows)).toEqual(mutable(RETENTION_BLUEPRINT.dayOn));
});
it('matches the blueprint for day interval, criteria "on_or_after"', async () => {
@@ -64,7 +75,9 @@ describe('getRetentionCohort', () => {
endDate: day.end,
});
- expect(cohortsOnly(rows)).toEqual(RETENTION_BLUEPRINT.dayOnOrAfter);
+ expect(cohortsOnly(rows)).toEqual(
+ mutable(RETENTION_BLUEPRINT.dayOnOrAfter)
+ );
});
it('counts retention across the year boundary (week interval)', async () => {
@@ -81,7 +94,7 @@ describe('getRetentionCohort', () => {
endDate: week.end,
});
- expect(cohortsOnly(rows)).toEqual(RETENTION_BLUEPRINT.weekOn);
+ expect(cohortsOnly(rows)).toEqual(mutable(RETENTION_BLUEPRINT.weekOn));
});
it('prepends a weighted-average row that is 100% retained at interval 0', async () => {
@@ -177,7 +190,7 @@ describe('getRetentionCohort', () => {
filters: [{ name: 'country', operator: 'is', value: ['US'] }],
});
- expect(cohortsOnly(rows)).toEqual(RETENTION_BLUEPRINT.countryUsOn);
+ expect(cohortsOnly(rows)).toEqual(mutable(RETENTION_BLUEPRINT.countryUsOn));
});
it('scopes to a saved cohort via the fast MV path (inCohort)', async () => {
@@ -201,7 +214,7 @@ describe('getRetentionCohort', () => {
],
});
- expect(cohortsOnly(rows)).toEqual(RETENTION_BLUEPRINT.cohortOn);
+ expect(cohortsOnly(rows)).toEqual(mutable(RETENTION_BLUEPRINT.cohortOn));
});
});
@@ -216,7 +229,7 @@ describe('getRetentionSeries', () => {
it('computes week-over-week active-user retention', async () => {
const rows = await getRetentionSeries({ projectId: PROJECT_ID });
- expect(rows).toEqual(RETENTION_BLUEPRINT.weeklySeries);
+ expect(rows).toEqual(mutable(RETENTION_BLUEPRINT.weeklySeries));
});
});
diff --git a/packages/core/src/modules/chart/src/field-resolution.ts b/packages/core/src/modules/chart/src/field-resolution.ts
index d29e48636..63fd1e258 100644
--- a/packages/core/src/modules/chart/src/field-resolution.ts
+++ b/packages/core/src/modules/chart/src/field-resolution.ts
@@ -29,9 +29,9 @@ export const CHART_TABLE = {
} as const;
// Top-level columns on the events table. Derived from the migration in
-// packages/db/code-migrations/3-init-ch.ts (+ revenue added in 6-add-revenue-
-// column.ts). Used to distinguish real columns from property keys and reject
-// unknown identifiers before they reach ClickHouse.
+// code-migrations/3-init-ch.ts (+ revenue added in 6-add-revenue-column.ts).
+// Used to distinguish real columns from property keys and reject unknown
+// identifiers before they reach ClickHouse.
export const EVENT_TOP_LEVEL_COLUMNS = new Set<string>([
'id',
'name',
diff --git a/packages/db/src/services/filter-cast.ts b/packages/core/src/modules/chart/src/filter-cast.ts
similarity index 85%
rename from packages/db/src/services/filter-cast.ts
rename to packages/core/src/modules/chart/src/filter-cast.ts
index 69e4a0e8c..c479670c0 100644
--- a/packages/db/src/services/filter-cast.ts
+++ b/packages/core/src/modules/chart/src/filter-cast.ts
@@ -1,4 +1,7 @@
/** biome-ignore-all lint/style/useDefaultSwitchClause: switch cases are exhaustive by design */
+// Moved from packages/db/src/services/filter-cast.ts (M8-005) — the typed-cast
+// half of `buildFilterWhere` (./table-filter-where.ts), which is the only
+// caller. `./filter-where.ts` (the event-property compiler) imports it too.
import type {
IChartEventFilterOperator,
IChartEventFilterValue,
@@ -42,7 +45,7 @@ export function castSql(expr: string, type?: IChartFilterValueType): string {
* comparison logic so behavior is unchanged.
*/
export function hasTypedCast(
- type?: IChartFilterValueType,
+ type?: IChartFilterValueType
): type is IChartFilterValueType {
return !!type && type !== 'string';
}
@@ -50,16 +53,19 @@ export function hasTypedCast(
// Equality + comparison operators where a declared cast type changes the SQL.
// String-only operators (contains/startsWith/regex/…) and null checks are
// unaffected and keep their existing handling.
-const TYPED_SQL_OPERATOR: Partial<Record<IChartEventFilterOperator, string>> = {
- is: '=',
- isNot: '!=',
- gt: '>',
- gte: '>=',
- lt: '<',
- lte: '<=',
-};
+const TYPED_SQL_OPERATOR: Partial<Record<IChartEventFilterOperator, string>> =
+ {
+ is: '=',
+ isNot: '!=',
+ gt: '>',
+ gte: '>=',
+ lt: '<',
+ lte: '<=',
+ };
-export function isTypedOperator(operator: IChartEventFilterOperator): boolean {
+export function isTypedOperator(
+ operator: IChartEventFilterOperator
+): boolean {
return operator in TYPED_SQL_OPERATOR;
}
@@ -77,7 +83,7 @@ export function buildTypedClause(
leftExpr: string,
operator: IChartEventFilterOperator,
value: IChartEventFilterValue[],
- type: IChartFilterValueType,
+ type: IChartFilterValueType
): string {
const sqlOp = TYPED_SQL_OPERATOR[operator] ?? '=';
const left = castSql(leftExpr, type);
@@ -85,7 +91,7 @@ export function buildTypedClause(
return `(${value
.map((val) => {
const escaped = sqlstring.escape(
- typeof val === 'string' ? val.trim() : val,
+ typeof val === 'string' ? val.trim() : val
);
return `${left} ${sqlOp} ${castSql(escaped, type)}`;
})
diff --git a/packages/core/src/modules/chart/src/filter-where.ts b/packages/core/src/modules/chart/src/filter-where.ts
index 354572919..582afa230 100644
--- a/packages/core/src/modules/chart/src/filter-where.ts
+++ b/packages/core/src/modules/chart/src/filter-where.ts
@@ -7,14 +7,14 @@
// compiled.ts, the one text bridge.
import { stripLeadingAndTrailingSlashes } from '@openpanel/common';
+import type { IChartEventFilter } from '@openpanel/validation';
+import { getCohortIds } from '@openpanel/validation';
+import sqlstring from 'sqlstring';
import {
buildTypedClause,
hasTypedCast,
isTypedOperator,
-} from '@openpanel/db/src/services/filter-cast';
-import type { IChartEventFilter } from '@openpanel/validation';
-import { getCohortIds } from '@openpanel/validation';
-import sqlstring from 'sqlstring';
+} from './filter-cast';
import {
CHART_TABLE,
EVENT_FIELD_ALIASES,
diff --git a/packages/db/src/services/filter-where.test.ts b/packages/core/src/modules/chart/src/table-filter-where.test.ts
similarity index 97%
rename from packages/db/src/services/filter-where.test.ts
rename to packages/core/src/modules/chart/src/table-filter-where.test.ts
index 07427c3ac..82d14cb59 100644
--- a/packages/db/src/services/filter-where.test.ts
+++ b/packages/core/src/modules/chart/src/table-filter-where.test.ts
@@ -9,13 +9,10 @@
* dropped when it does not, which is what the `group.*` and `session.*`
* branches already did.
*/
+import { TABLE_NAMES } from '@openpanel/db/src/clickhouse/client';
import type { IChartEventFilter } from '@openpanel/validation';
-import { describe, expect, it } from 'vitest';
-import { TABLE_NAMES } from '../clickhouse/client';
-import {
- buildFilterWhere,
- type FilterTableContext,
-} from './filter-where.service';
+import { describe, expect, it } from 'bun:test';
+import { buildFilterWhere, type FilterTableContext } from './table-filter-where';
const PROJECT_ID = 'p';
diff --git a/packages/core/src/modules/chart/src/table-filter-where.ts b/packages/core/src/modules/chart/src/table-filter-where.ts
new file mode 100644
index 000000000..96276445a
--- /dev/null
+++ b/packages/core/src/modules/chart/src/table-filter-where.ts
@@ -0,0 +1,399 @@
+/** biome-ignore-all lint/style/useDefaultSwitchClause: switch cases are exhaustive by design */
+// Moved from packages/db/src/services/filter-where.service.ts (M8-005).
+// V1's filter compiler for the sessions/profiles/events tables — distinct
+// from `./filter-where.ts`'s `getEventFiltersWhereClause` (event-property
+// filters). Still sqlstring-escaped text, not the `sql` tag: ADR-013 keeps
+// the two filter compilers as they are ("two behaviours, not two builders")
+// until every caller that splices their output stops using text builders.
+// packages/db/src/services/filter-where.service.ts stays a re-export shim;
+// event/profile/session/cohort services reach this module through the
+// existing lazy `loadFilterCompiler()` dynamic import, now pointed here
+// instead of at packages/db — the dynamic import is what keeps
+// clickhouse/client.ts's module-scope logger construction out of those
+// services' eager import chain.
+
+import {
+ getCohortIds,
+ type IChartEventFilter,
+ type IChartFilterValueType,
+} from '@openpanel/validation';
+import {
+ formatClickhouseDate,
+ TABLE_NAMES,
+} from '@openpanel/db/src/clickhouse/client';
+import sqlstring from 'sqlstring';
+import {
+ buildTypedClause,
+ hasTypedCast,
+ isTypedOperator,
+} from './filter-cast';
+
+export interface FilterTableContext {
+ /** Outer query's primary table. */
+ selfTable: 'sessions' | 'profiles' | 'events';
+ /**
+ * Expression on the outer row that yields the owning profile id. For the
+ * profiles table this is `id`; for events/sessions it's `profile_id`. Used
+ * by cohort + cross-table profile.* filters.
+ */
+ profileIdExpr: string;
+ /**
+ * Expression on the outer row that yields the array of group ids. All three
+ * canonical tables expose a `groups Array(String)` column today.
+ */
+ groupsExpr?: string;
+ /**
+ * Optional date scope passed to subselects that reference the events table
+ * (currently only `session.performed_event`). Without it ClickHouse has to
+ * scan the entire event history for the project.
+ */
+ startDate?: Date;
+ endDate?: Date;
+}
+
+/** Sentinel sessions columns that the UI may filter on directly. */
+const SESSION_NUMERIC_COLUMNS = new Set([
+ 'screen_view_count',
+ 'event_count',
+ 'duration',
+ 'revenue',
+]);
+
+function escape(value: string | number | boolean | null): string {
+ return sqlstring.escape(typeof value === 'string' ? value.trim() : value);
+}
+
+function trimVal(value: string | number | boolean | null): string {
+ return typeof value === 'string' ? value.trim() : String(value);
+}
+
+/**
+ * Build a WHERE-clause fragment for a single non-array column. Mirrors the
+ * operator set used by `getEventFiltersWhereClause` so behaviour stays
+ * consistent across surfaces.
+ */
+function compileScalarClause(
+ column: string,
+ operator: IChartEventFilter['operator'],
+ value: IChartEventFilter['value'],
+ options: { numeric?: boolean; type?: IChartFilterValueType } = {}
+): string | null {
+ if (
+ value.length === 0 &&
+ operator !== 'isNull' &&
+ operator !== 'isNotNull'
+ ) {
+ return null;
+ }
+
+ // Explicit cast type wins over the column-name `numeric` auto-detect. Casts
+ // both the column and each value consistently (see filter-cast.ts).
+ if (hasTypedCast(options.type) && isTypedOperator(operator)) {
+ return buildTypedClause(column, operator, value, options.type!);
+ }
+
+ const numeric = options.numeric === true;
+
+ switch (operator) {
+ case 'is': {
+ if (numeric) {
+ return `(${value
+ .map((v) => `toFloat64(${column}) = toFloat64(${escape(v)})`)
+ .join(' OR ')})`;
+ }
+ if (value.length === 1) {
+ return `${column} = ${escape(value[0]!)}`;
+ }
+ return `${column} IN (${value.map(escape).join(', ')})`;
+ }
+ case 'isNot': {
+ if (numeric) {
+ return `(${value
+ .map((v) => `toFloat64(${column}) != toFloat64(${escape(v)})`)
+ .join(' OR ')})`;
+ }
+ if (value.length === 1) {
+ return `${column} != ${escape(value[0]!)}`;
+ }
+ return `${column} NOT IN (${value.map(escape).join(', ')})`;
+ }
+ case 'contains': {
+ return `(${value
+ .map((v) => `${column} ILIKE ${sqlstring.escape(`%${trimVal(v)}%`)}`)
+ .join(' OR ')})`;
+ }
+ case 'doesNotContain': {
+ return `(${value
+ .map(
+ (v) => `${column} NOT ILIKE ${sqlstring.escape(`%${trimVal(v)}%`)}`
+ )
+ .join(' AND ')})`;
+ }
+ case 'startsWith': {
+ return `(${value
+ .map((v) => `${column} ILIKE ${sqlstring.escape(`${trimVal(v)}%`)}`)
+ .join(' OR ')})`;
+ }
+ case 'endsWith': {
+ return `(${value
+ .map((v) => `${column} ILIKE ${sqlstring.escape(`%${trimVal(v)}`)}`)
+ .join(' OR ')})`;
+ }
+ case 'regex': {
+ return `(${value
+ .map((v) => `match(${column}, ${escape(v)})`)
+ .join(' OR ')})`;
+ }
+ case 'isNull':
+ return `(${column} = '' OR ${column} IS NULL)`;
+ case 'isNotNull':
+ return `(${column} != '' AND ${column} IS NOT NULL)`;
+ case 'gt': {
+ return `(${value
+ .map(
+ (v) =>
+ `${numeric ? `toFloat64(${column})` : column} > ${numeric ? `toFloat64(${escape(v)})` : escape(v)}`
+ )
+ .join(' OR ')})`;
+ }
+ case 'lt': {
+ return `(${value
+ .map(
+ (v) =>
+ `${numeric ? `toFloat64(${column})` : column} < ${numeric ? `toFloat64(${escape(v)})` : escape(v)}`
+ )
+ .join(' OR ')})`;
+ }
+ case 'gte': {
+ return `(${value
+ .map(
+ (v) =>
+ `${numeric ? `toFloat64(${column})` : column} >= ${numeric ? `toFloat64(${escape(v)})` : escape(v)}`
+ )
+ .join(' OR ')})`;
+ }
+ case 'lte': {
+ return `(${value
+ .map(
+ (v) =>
+ `${numeric ? `toFloat64(${column})` : column} <= ${numeric ? `toFloat64(${escape(v)})` : escape(v)}`
+ )
+ .join(' OR ')})`;
+ }
+ }
+
+ return null;
+}
+
+/**
+ * Profiles columns a `profile.<field>` filter may resolve to. Anything else is
+ * not a column name and must not reach the SQL text. Kept in sync with
+ * `getProfilePropertySelect` in chart.service.ts, which lists the same set for
+ * the SELECT side.
+ */
+const PROFILE_COLUMNS = new Set([
+ 'id',
+ 'first_name',
+ 'last_name',
+ 'email',
+ 'avatar',
+ 'created_at',
+ 'last_seen_at',
+]);
+
+/**
+ * Translate `profile.<field>` into the SQL accessor used when querying the
+ * profiles table directly. Bare fields (email, first_name, …) map to columns;
+ * `profile.properties.<key>` maps to the JSON `properties[key]` lookup.
+ * Returns null for a field that is neither, so the caller can drop the filter.
+ */
+function profileColumnSql(name: string): string | null {
+ const withoutPrefix = name.replace(/^profile\./, '');
+ if (withoutPrefix.startsWith('properties.')) {
+ const key = withoutPrefix.replace(/^properties\./, '');
+ return `properties[${sqlstring.escape(key)}]`;
+ }
+ if (PROFILE_COLUMNS.has(withoutPrefix)) {
+ return withoutPrefix;
+ }
+ return null;
+}
+
+/**
+ * Translate `group.<field>` into the SQL accessor used when querying the
+ * groups table directly (no join alias).
+ */
+function groupColumnSql(name: string): string {
+ const withoutPrefix = name.replace(/^group\./, '');
+ if (
+ withoutPrefix === 'name' ||
+ withoutPrefix === 'type' ||
+ withoutPrefix === 'id'
+ ) {
+ return withoutPrefix;
+ }
+ if (withoutPrefix.startsWith('properties.')) {
+ const key = withoutPrefix.replace(/^properties\./, '');
+ return `properties[${sqlstring.escape(key)}]`;
+ }
+ return 'id';
+}
+
+/** Translate `session.<field>` to the underlying sessions column. */
+function sessionColumnSql(name: string): string | null {
+ const withoutPrefix = name.replace(/^session\./, '');
+ if (withoutPrefix === 'is_bounce') return 'is_bounce';
+ if (SESSION_NUMERIC_COLUMNS.has(withoutPrefix)) return withoutPrefix;
+ // performed_event is handled as a subselect, not a column
+ return null;
+}
+
+function buildCohortClause(
+ filter: IChartEventFilter,
+ projectId: string,
+ ctx: FilterTableContext
+): string | null {
+ // `getCohortIds` normalizes the legacy single-value `cohortId` field and
+ // the newer `cohortIds` array into one list. Falls back to extracting the
+ // id from the `cohort:<id>` filter name when neither is set (older URL
+ // formats encoded the id only in the name).
+ let cohortIds = getCohortIds(filter);
+ if (cohortIds.length === 0 && filter.name.startsWith('cohort:')) {
+ cohortIds = [filter.name.slice('cohort:'.length)];
+ }
+ if (cohortIds.length === 0) return null;
+ const negate = filter.operator === 'notInCohort';
+ const op = negate ? 'NOT IN' : 'IN';
+ const escapedIds = cohortIds.map((id) => sqlstring.escape(id)).join(', ');
+ return `${ctx.profileIdExpr} ${op} (SELECT profile_id FROM ${TABLE_NAMES.cohort_members} FINAL WHERE cohort_id IN (${escapedIds}) AND project_id = ${sqlstring.escape(projectId)})`;
+}
+
+function buildGroupClause(
+ filter: IChartEventFilter,
+ projectId: string,
+ ctx: FilterTableContext
+): string | null {
+ if (!ctx.groupsExpr) return null;
+ const column = groupColumnSql(filter.name);
+ const inner = compileScalarClause(column, filter.operator, filter.value, {
+ type: filter.type,
+ });
+ if (!inner) return null;
+ const projectClause = `project_id = ${sqlstring.escape(projectId)}`;
+ return `arrayExists(g -> g IN (SELECT id FROM ${TABLE_NAMES.groups} FINAL WHERE ${projectClause} AND ${inner}), ${ctx.groupsExpr})`;
+}
+
+function buildProfileClause(
+ filter: IChartEventFilter,
+ projectId: string,
+ ctx: FilterTableContext
+): string | null {
+ const column = profileColumnSql(filter.name);
+ if (!column) return null;
+ const numeric = column === 'created_at' || column === 'last_seen_at';
+ const inner = compileScalarClause(column, filter.operator, filter.value, {
+ numeric,
+ type: filter.type,
+ });
+ if (!inner) return null;
+ if (ctx.selfTable === 'profiles') {
+ return inner;
+ }
+ return `${ctx.profileIdExpr} IN (SELECT id FROM ${TABLE_NAMES.profiles} FINAL WHERE project_id = ${sqlstring.escape(projectId)} AND ${inner})`;
+}
+
+function buildSessionClause(
+ filter: IChartEventFilter,
+ projectId: string,
+ ctx: FilterTableContext
+): string | null {
+ if (ctx.selfTable !== 'sessions') return null;
+ const fieldName = filter.name.replace(/^session\./, '');
+
+ if (fieldName === 'performed_event') {
+ if (filter.value.length === 0) return null;
+ const inClause =
+ filter.value.length === 1
+ ? `= ${escape(filter.value[0]!)}`
+ : `IN (${filter.value.map(escape).join(', ')})`;
+ const op = filter.operator === 'isNot' ? 'NOT IN' : 'IN';
+ const dateScope: string[] = [];
+ if (ctx.startDate && ctx.endDate) {
+ dateScope.push(
+ `toDate(created_at) BETWEEN toDate('${formatClickhouseDate(ctx.startDate)}') AND toDate('${formatClickhouseDate(ctx.endDate)}')`
+ );
+ }
+ const scopeSql = dateScope.length ? `AND ${dateScope.join(' AND ')} ` : '';
+ return `id ${op} (SELECT DISTINCT session_id FROM ${TABLE_NAMES.events} WHERE project_id = ${sqlstring.escape(projectId)} ${scopeSql}AND name ${inClause})`;
+ }
+
+ if (fieldName === 'is_bounce') {
+ if (filter.value.length === 0) return null;
+ const wants = filter.value.some((v) =>
+ typeof v === 'boolean' ? v : String(v).toLowerCase() === 'true'
+ );
+ const truthy = filter.operator === 'isNot' ? !wants : wants;
+ return `is_bounce = ${truthy ? 1 : 0}`;
+ }
+
+ const column = sessionColumnSql(filter.name);
+ if (!column) return null;
+ return compileScalarClause(column, filter.operator, filter.value, {
+ numeric: SESSION_NUMERIC_COLUMNS.has(column),
+ type: filter.type,
+ });
+}
+
+/**
+ * Translate `IChartEventFilter[]` into a WHERE-clause record suitable for
+ * merging into `createSqlBuilder().sb.where`. Handles cohort / group / profile
+ * / session prefixes. Event-property (`properties.*`) filters are ignored on
+ * non-events tables — they require a subquery on the events table that is
+ * better expressed as a cohort.
+ */
+export function buildFilterWhere(
+ filters: IChartEventFilter[],
+ projectId: string,
+ ctx: FilterTableContext
+): Record<string, string> {
+ const where: Record<string, string> = {};
+ filters.forEach((filter, index) => {
+ const id = `f${index}`;
+ // Callers concatenate these fragments with AND and no grouping, so each
+ // fragment is parenthesized here to keep a top-level OR inside it from
+ // rebinding the surrounding conditions.
+ const set = (clause: string | null) => {
+ if (clause) where[id] = `(${clause})`;
+ };
+
+ if (filter.operator === 'inCohort' || filter.operator === 'notInCohort') {
+ set(buildCohortClause(filter, projectId, ctx));
+ return;
+ }
+
+ if (filter.name.startsWith('cohort:')) {
+ set(buildCohortClause(filter, projectId, ctx));
+ return;
+ }
+
+ if (filter.name.startsWith('group.')) {
+ set(buildGroupClause(filter, projectId, ctx));
+ return;
+ }
+
+ if (filter.name.startsWith('profile.')) {
+ set(buildProfileClause(filter, projectId, ctx));
+ return;
+ }
+
+ if (filter.name.startsWith('session.')) {
+ set(buildSessionClause(filter, projectId, ctx));
+ return;
+ }
+
+ // properties.* filters only make sense on the events table; ignore on
+ // sessions/profiles queries. Callers that need them should query the
+ // events table directly (e.g. via getEventList) or use a cohort.
+ });
+ return where;
+}
diff --git a/packages/core/src/modules/cohort/cohort.service.ts b/packages/core/src/modules/cohort/cohort.service.ts
index ce89616ae..a7c455a28 100644
--- a/packages/core/src/modules/cohort/cohort.service.ts
+++ b/packages/core/src/modules/cohort/cohort.service.ts
@@ -783,9 +783,7 @@ export async function listCohortMemberProfiles({
filters?: IChartEventFilter[];
}): Promise<{ data: IServiceProfile[]; count: number }> {
const { chQuery } = await loadChClient();
- const { buildFilterWhere } = await import(
- '@openpanel/db/src/services/filter-where.service'
- );
+ const { buildFilterWhere } = await import('../chart/src/table-filter-where');
const { getProfiles, profileSearchSql } = await import(
'@openpanel/db/src/services/profile.service'
);
diff --git a/packages/core/src/modules/event/event.service.ts b/packages/core/src/modules/event/event.service.ts
index 8e5925b38..31d453f7d 100644
--- a/packages/core/src/modules/event/event.service.ts
+++ b/packages/core/src/modules/event/event.service.ts
@@ -27,6 +27,7 @@ import type { EventMeta, Prisma } from '@openpanel/db/src/prisma-client';
import { cacheable } from '@openpanel/redis';
import type { IChartEventFilter } from '@openpanel/validation';
import { clone, mergeDeepRight, uniq } from 'ramda';
+import { loadDbBuffers } from '../../buffers/lazy-db-buffers';
import type { ServiceDeps } from '../../services';
import { getEventFiltersWhereClause } from '../chart/src/filter-where';
import {
@@ -98,10 +99,6 @@ function loadDb() {
return import('@openpanel/db/src/prisma-client').then((m) => m.db);
}
-function loadBuffers() {
- return import('@openpanel/db/src/buffers');
-}
-
// Lazy for the same reason subscription.service.ts's is: core tests that
// partially mock `@openpanel/redis` (no `getCache`) reach this module through
// @openpanel/db's re-export shims and the core barrel.
@@ -110,7 +107,7 @@ function loadCache() {
}
function loadFilterCompiler() {
- return import('@openpanel/db/src/services/filter-where.service');
+ return import('../chart/src/table-filter-where');
}
function loadLookback() {
@@ -545,7 +542,7 @@ export async function createEvent(payload: IServiceCreateEventPayloadWithId) {
groups: payload.groups ?? [],
};
- const { eventBuffer } = await loadBuffers();
+ const { eventBuffer } = await loadDbBuffers();
eventBuffer.add(event);
const promises: Promise<unknown>[] = [];
@@ -826,7 +823,7 @@ export async function createBotEvent({
createdAt,
path,
}: IServiceCreateBotEventPayload) {
- const { botBuffer } = await loadBuffers();
+ const { botBuffer } = await loadDbBuffers();
return botBuffer.add({
id: crypto.randomUUID(),
name,
diff --git a/packages/core/src/modules/event/src/filter-clauses.ts b/packages/core/src/modules/event/src/filter-clauses.ts
index 4a4442c24..9ed664751 100644
--- a/packages/core/src/modules/event/src/filter-clauses.ts
+++ b/packages/core/src/modules/event/src/filter-clauses.ts
@@ -1,6 +1,6 @@
// The ONE place this module splices pre-compiled filter SQL.
//
-// `buildFilterWhere` (packages/db/src/services/filter-where.service.ts) is
+// `buildFilterWhere` (../../chart/src/table-filter-where.ts) is
// V1's filter compiler and still emits sqlstring-escaped SQL text: ADR-013
// leaves the filter compilers as they are ("two behaviours, not two builders")
// until the shared filter compiler converts to fragments. Until then a
diff --git a/packages/core/src/modules/ingest/src/incoming-event-handler.ts b/packages/core/src/modules/ingest/src/incoming-event-handler.ts
index d841c0992..0a1aaeac0 100644
--- a/packages/core/src/modules/ingest/src/incoming-event-handler.ts
+++ b/packages/core/src/modules/ingest/src/incoming-event-handler.ts
@@ -16,6 +16,7 @@
import { getTime, isSameDomain, parsePath } from '@openpanel/common';
import type { IProjectFilters } from '@openpanel/validation';
import { anyPass, isEmpty, isNil, mergeDeepRight, omit, reject } from 'ramda';
+import { loadDbBuffers } from '../../../buffers/lazy-db-buffers';
import type { SessionIngestResult } from '../../../buffers/session-buffer';
import type { Logger } from '../../../logger';
import {
@@ -110,7 +111,7 @@ export async function loadIncomingEventDeps(
overrides: Partial<IncomingEventDeps> = {}
): Promise<IncomingEventDeps> {
const [{ sessionBuffer }, { db }, notifications] = await Promise.all([
- import('@openpanel/db/src/buffers'),
+ loadDbBuffers(),
import('@openpanel/db/src/prisma-client'),
import('@openpanel/db/src/services/notification.service'),
]);
diff --git a/packages/db/src/services/overview-sql.test.ts b/packages/core/src/modules/overview/src/overview-raw-where.sql.test.ts
similarity index 76%
rename from packages/db/src/services/overview-sql.test.ts
rename to packages/core/src/modules/overview/src/overview-raw-where.sql.test.ts
index cbafce004..55fc92492 100644
--- a/packages/db/src/services/overview-sql.test.ts
+++ b/packages/core/src/modules/overview/src/overview-raw-where.sql.test.ts
@@ -1,7 +1,11 @@
/**
- * SQL-syntax tests for the overview query builder. The chart cases moved to
- * packages/core/src/modules/chart/src/chart.sql.test.ts with their subject
- * (M7-003).
+ * SQL-syntax tests for `OverviewService.getRawWhereClause` (the UTM
+ * remapping). Moved from packages/db/src/services/overview-sql.test.ts
+ * (M8-005) alongside its subject, which moved to core in M7-005 — same
+ * pattern as the chart cases moving to chart.sql.test.ts with theirs
+ * (M7-003). `getRawWhereClause` itself is still clix/sqlstring-based
+ * (pre-ADR-013); the rest of OverviewService's queries already run through
+ * overview.sql.ts, covered by overview.sql.test.ts.
*
* Strategy: build the SQL string, then run `EXPLAIN <sql>` against the local
* ClickHouse instance. EXPLAIN parses the query, resolves columns, and builds
@@ -10,16 +14,18 @@
* data. WITH FILL TO < FROM is a runtime check, so it's covered by a plain
* string assertion instead.
*
- * Requires `pnpm dock:up` (or any locally reachable CH at
- * http://localhost:8123/openpanel). All tests auto-skip if CH is unreachable.
+ * Requires a locally reachable CH at http://localhost:8123/openpanel. All
+ * `itCH` tests auto-skip if CH is unreachable.
*/
-import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
-import { ch } from '../clickhouse/client';
-import { OverviewService } from './overview.service';
+
+import { afterAll, beforeAll, describe, expect, it, spyOn } from 'bun:test';
+import { ch } from '@openpanel/db/src/clickhouse/client';
+import { OverviewService } from '../overview.service';
const PROJECT_ID = 'test-sql-validation';
let chReachable = false;
+let logSpy: ReturnType<typeof spyOn>;
async function explain(sql: string): Promise<void> {
// EXPLAIN runs the parser + analyzer and builds the query plan, which
@@ -29,7 +35,7 @@ async function explain(sql: string): Promise<void> {
beforeAll(async () => {
// The chart service is chatty; mute log spam during the test run.
- vi.spyOn(console, 'log').mockImplementation(() => {});
+ logSpy = spyOn(console, 'log').mockImplementation(() => undefined);
try {
await ch.command({ query: 'SELECT 1' });
chReachable = true;
@@ -40,7 +46,7 @@ beforeAll(async () => {
});
afterAll(() => {
- vi.restoreAllMocks();
+ logSpy.mockRestore();
});
const itCH = (name: string, fn: () => Promise<void>) =>
diff --git a/packages/core/src/modules/profile/profile.service.ts b/packages/core/src/modules/profile/profile.service.ts
index 762d432b6..9246bcb5e 100644
--- a/packages/core/src/modules/profile/profile.service.ts
+++ b/packages/core/src/modules/profile/profile.service.ts
@@ -18,6 +18,7 @@ import { strip, toObject } from '@openpanel/common';
import { cacheable } from '@openpanel/redis';
import type { IChartEventFilter } from '@openpanel/validation';
import { assocPath, flatten, map, pathOr, pipe, prop, sort, uniq } from 'ramda';
+import { loadDbBuffers } from '../../buffers/lazy-db-buffers';
import type { ServiceDeps } from '../../services';
import type { IClickhouseEvent } from '../event/event.service';
import type { IClickhouseSession } from '../session/session.service';
@@ -69,11 +70,11 @@ function loadChClient() {
}
function loadProfileBuffer() {
- return import('@openpanel/db/src/buffers').then((m) => m.profileBuffer);
+ return loadDbBuffers().then((m) => m.profileBuffer);
}
function loadFilterCompiler() {
- return import('@openpanel/db/src/services/filter-where.service');
+ return import('../chart/src/table-filter-where');
}
export interface IProfileMetrics {
diff --git a/packages/core/src/modules/profile/src/filter-clauses.ts b/packages/core/src/modules/profile/src/filter-clauses.ts
index 4a4442c24..9ed664751 100644
--- a/packages/core/src/modules/profile/src/filter-clauses.ts
+++ b/packages/core/src/modules/profile/src/filter-clauses.ts
@@ -1,6 +1,6 @@
// The ONE place this module splices pre-compiled filter SQL.
//
-// `buildFilterWhere` (packages/db/src/services/filter-where.service.ts) is
+// `buildFilterWhere` (../../chart/src/table-filter-where.ts) is
// V1's filter compiler and still emits sqlstring-escaped SQL text: ADR-013
// leaves the filter compilers as they are ("two behaviours, not two builders")
// until the shared filter compiler converts to fragments. Until then a
diff --git a/packages/core/src/modules/realtime/realtime.service.ts b/packages/core/src/modules/realtime/realtime.service.ts
index 4dd427f30..a2e50c045 100644
--- a/packages/core/src/modules/realtime/realtime.service.ts
+++ b/packages/core/src/modules/realtime/realtime.service.ts
@@ -33,10 +33,11 @@
// and this module's queries haven't been converted yet.
import { clix } from '@openpanel/db/src/clickhouse/query-builder';
-import type { IClickhouseEvent } from '../event/event.service';
import type { IPublishChannels } from '@openpanel/redis';
import { subMinutes } from 'date-fns';
import sqlstring from 'sqlstring';
+import { loadDbBuffers } from '../../buffers/lazy-db-buffers';
+import type { IClickhouseEvent } from '../event/event.service';
const REALTIME_WINDOW_MINUTES = 30;
const ACTIVE_SESSIONS_LIMIT = 50;
@@ -62,7 +63,7 @@ function loadProfileService() {
}
function loadEventBuffer() {
- return import('@openpanel/db/src/buffers').then((m) => m.eventBuffer);
+ return loadDbBuffers().then((m) => m.eventBuffer);
}
function since(): Date {
diff --git a/packages/core/src/modules/session/session.service.ts b/packages/core/src/modules/session/session.service.ts
index 182ef5a63..336dbe060 100644
--- a/packages/core/src/modules/session/session.service.ts
+++ b/packages/core/src/modules/session/session.service.ts
@@ -54,7 +54,7 @@ function loadProfileService() {
}
function loadFilterCompiler() {
- return import('@openpanel/db/src/services/filter-where.service');
+ return import('../chart/src/table-filter-where');
}
function loadLookback() {
diff --git a/packages/core/src/modules/session/src/filter-clauses.ts b/packages/core/src/modules/session/src/filter-clauses.ts
index 778d80b5c..22b08d5d4 100644
--- a/packages/core/src/modules/session/src/filter-clauses.ts
+++ b/packages/core/src/modules/session/src/filter-clauses.ts
@@ -1,6 +1,6 @@
// The ONE place this module splices pre-compiled filter SQL.
//
-// `buildFilterWhere` (packages/db/src/services/filter-where.service.ts) is
+// `buildFilterWhere` (../../chart/src/table-filter-where.ts) is
// V1's filter compiler and still emits sqlstring-escaped SQL text: ADR-013
// leaves the filter compilers as they are ("two behaviours, not two builders")
// until the shared filter compiler converts to fragments. Until then a
diff --git a/packages/core/src/modules/session/src/runtime.ts b/packages/core/src/modules/session/src/runtime.ts
index 026e3a4f9..b13e6dacb 100644
--- a/packages/core/src/modules/session/src/runtime.ts
+++ b/packages/core/src/modules/session/src/runtime.ts
@@ -5,6 +5,7 @@
// hand in stubs, so no `mock.module` is needed and every assertion is on a
// call the code under test made.
+import { loadDbBuffers } from '../../../buffers/lazy-db-buffers';
import type { IClickhouseSession } from '../session.service';
export interface SessionStore {
@@ -53,7 +54,7 @@ export interface SessionRuntime {
export async function loadSessionRuntime(): Promise<SessionRuntime> {
const [{ getRedisCache }, { sessionBuffer }] = await Promise.all([
import('@openpanel/redis'),
- import('@openpanel/db/src/buffers'),
+ loadDbBuffers(),
]);
return { redis: getRedisCache(), sessions: sessionBuffer };
}
diff --git a/packages/core/src/modules/session/src/session-end.ts b/packages/core/src/modules/session/src/session-end.ts
index 45d1a6f1b..22e45e7eb 100644
--- a/packages/core/src/modules/session/src/session-end.ts
+++ b/packages/core/src/modules/session/src/session-end.ts
@@ -2,6 +2,7 @@
// utils/session-handler.ts (M7-001). The worker's copies are thin delegates
// onto this file until apps/worker dies (P9).
+import { loadDbBuffers } from '../../../buffers/lazy-db-buffers';
import type { EnqueueOptions } from '../../../jobs/define';
import type { Logger } from '../../../logger';
// Static, not lazy like the db imports below: core's event.service touches no
@@ -125,7 +126,7 @@ export async function loadSessionEndDeps(
{ checkNotificationRulesForSessionEnd },
] = await Promise.all([
import('@openpanel/db/src/clickhouse/client'),
- import('@openpanel/db/src/buffers'),
+ loadDbBuffers(),
import('../../notification/notification.service'),
import('@openpanel/db/src/services/notification.service'),
]);
diff --git a/packages/core/src/modules/widget/widget.rpc.ts b/packages/core/src/modules/widget/widget.rpc.ts
index 418f9ffc7..d2a033852 100644
--- a/packages/core/src/modules/widget/widget.rpc.ts
+++ b/packages/core/src/modules/widget/widget.rpc.ts
@@ -21,6 +21,7 @@
import { clix } from '@openpanel/db/src/clickhouse/query-builder';
import ShortUniqueId from 'short-unique-id';
import { z } from 'zod';
+import { loadDbBuffers } from '../../buffers/lazy-db-buffers';
import { createTRPCRouter, procedure } from '../../rpc/base';
import { TRPCAccessError, TRPCNotFoundError } from '../../rpc/errors';
import { getSettingsForProject } from '../organization/organization.service';
@@ -38,7 +39,7 @@ function loadChClient() {
}
function loadEventBuffer() {
- return import('@openpanel/db/src/buffers').then((m) => m.eventBuffer);
+ return loadDbBuffers().then((m) => m.eventBuffer);
}
function loadCache() {
diff --git a/packages/core/src/shared/access-lookups.ts b/packages/core/src/shared/access-lookups.ts
new file mode 100644
index 000000000..76db4f186
--- /dev/null
+++ b/packages/core/src/shared/access-lookups.ts
@@ -0,0 +1,151 @@
+// The concrete, Prisma-backed access lookups (M8-005, moved from
+// packages/db/src/services/access.service.ts). Deliberately a sibling of
+// shared/access.ts rather than living inside it: the ladder in access.ts must
+// stay importable with no database (see its own header), while this file is
+// the real `@openpanel/db` binding ~28 modules' `src/access.ts` files supply
+// to it. Same shape as packages/trpc/src/access.ts's binding.
+//
+// db access is LAZY (`loadDb` below), not a static top-level import — see
+// insight.service.ts's header for the full reasoning (jobs.registry.ts and
+// services.ts pull this module into the eager barrel chain nearly every core
+// test file reaches, and constructing @openpanel/db's clients at import time
+// would spawn a pino-pretty transport worker thread per test file).
+
+import type { AccessLevel } from '@openpanel/db/src/prisma-client';
+import { cacheable } from '@openpanel/redis';
+import { getProjectById } from '../modules/project/project.service';
+
+function loadDb() {
+ return import('@openpanel/db/src/prisma-client').then((m) => m.db);
+}
+
+export interface IProjectAccess {
+ level: AccessLevel;
+}
+
+/** Access levels that may mutate. `admin` is a superset of `write`. */
+const WRITE_LEVELS: ReadonlySet<AccessLevel> = new Set<AccessLevel>([
+ 'write',
+ 'admin',
+]);
+
+export function canWriteProject(access: IProjectAccess | null): boolean {
+ return !!access && WRITE_LEVELS.has(access.level);
+}
+
+/**
+ * Resolve a user's access to one project.
+ *
+ * Returns a single shape - `{ level }` or `null` - on purpose. This used to
+ * return `true` for members with no explicit ProjectAccess rows and the row
+ * itself otherwise, which forced every caller into a `typeof access !==
+ * 'boolean'` dance. 26 of 29 mutating procedures skipped the level check
+ * entirely as a result (GHSA-f9rx-pxgw-c6rg); with one shape, omitting the
+ * check is a type error rather than a silent grant.
+ *
+ * NOTE: the cache key is versioned. Changing the return shape without renaming
+ * it would serve old-shape entries for up to 5 minutes across a rolling deploy.
+ */
+export const getProjectAccess = cacheable(
+ 'getProjectAccessV2',
+ async ({
+ userId,
+ projectId,
+ }: {
+ userId: string;
+ projectId: string;
+ }): Promise<IProjectAccess | null> => {
+ try {
+ // Check if user has access to the project
+ const project = await getProjectById(projectId);
+ if (!project?.organizationId) {
+ return null;
+ }
+
+ const db = await loadDb();
+ const [projectAccess, member] = await Promise.all([
+ db.projectAccess.findMany({
+ where: {
+ userId,
+ organizationId: project.organizationId,
+ },
+ }),
+ db.member.findFirst({
+ where: {
+ organizationId: project.organizationId,
+ userId,
+ },
+ }),
+ ]);
+
+ if (!member) {
+ return null;
+ }
+
+ // No explicit per-project grants means org-wide default access, and the
+ // default is write.
+ if (projectAccess.length === 0) {
+ return { level: 'write' };
+ }
+
+ const row = projectAccess.find((item) => item.projectId === projectId);
+
+ return row ? { level: row.level } : null;
+ } catch (_err) {
+ return null;
+ }
+ },
+ 60 * 5
+);
+
+export const getOrganizationAccess = cacheable(
+ 'getOrganizationAccess',
+ async ({
+ userId,
+ organizationId,
+ }: {
+ userId: string;
+ organizationId: string;
+ }) => {
+ const db = await loadDb();
+ return db.member.findFirst({
+ where: {
+ userId,
+ organizationId,
+ },
+ });
+ },
+ 60 * 5
+);
+
+export async function getClientAccess({
+ userId,
+ clientId,
+}: {
+ userId: string;
+ clientId: string;
+}) {
+ const db = await loadDb();
+ const client = await db.client.findFirst({
+ where: {
+ id: clientId,
+ },
+ });
+
+ if (!client) {
+ return false;
+ }
+
+ if (client.projectId) {
+ return getProjectAccess({ userId, projectId: client.projectId });
+ }
+
+ if (client.organizationId) {
+ return getOrganizationAccess({
+ userId,
+ organizationId: client.organizationId,
+ });
+ }
+
+ return false;
+}
diff --git a/packages/core/src/shared/date.ts b/packages/core/src/shared/date.ts
new file mode 100644
index 000000000..62dddbc7b
--- /dev/null
+++ b/packages/core/src/shared/date.ts
@@ -0,0 +1,297 @@
+// Chart date-range resolution (ADR-007 shared/ layout: "date"). Moved from
+// packages/db/src/services/date.service.ts (M8-005) — pure Date/Luxon math,
+// no ClickHouse or Postgres access.
+import { DateTime } from '@openpanel/common';
+import type { IChartRange, IReportInput } from '@openpanel/validation';
+
+export function resolveDateRange(
+ startDate?: string,
+ endDate?: string
+): { startDate: string; endDate: string } {
+ const end = endDate ?? new Date().toISOString().slice(0, 10);
+ const start =
+ startDate ??
+ new Date(Date.now() - 30 * 86_400_000).toISOString().slice(0, 10);
+ return { startDate: start, endDate: end };
+}
+
+export function getDatesFromRange(range: IChartRange, timezone: string) {
+ if (range === '30min' || range === 'lastHour') {
+ const minutes = range === '30min' ? 30 : 60;
+ const startDate = DateTime.now()
+ .minus({ minute: minutes })
+ .startOf('minute')
+ .setZone(timezone)
+ .toFormat('yyyy-MM-dd HH:mm:ss');
+ const endDate = DateTime.now()
+ .setZone(timezone)
+ .endOf('minute')
+ .toFormat('yyyy-MM-dd HH:mm:ss');
+
+ return {
+ startDate,
+ endDate,
+ };
+ }
+
+ if (range === 'last24h') {
+ const startDate = DateTime.now()
+ .minus({ hour: 24 })
+ .startOf('minute')
+ .setZone(timezone)
+ .toFormat('yyyy-MM-dd HH:mm:ss');
+ const endDate = DateTime.now()
+ .setZone(timezone)
+ .endOf('minute')
+ .toFormat('yyyy-MM-dd HH:mm:ss');
+
+ return {
+ startDate,
+ endDate,
+ };
+ }
+
+ if (range === 'today') {
+ const startDate = DateTime.now()
+ .setZone(timezone)
+ .startOf('day')
+ .toFormat('yyyy-MM-dd HH:mm:ss');
+ const endDate = DateTime.now()
+ .setZone(timezone)
+ .endOf('day')
+ .toFormat('yyyy-MM-dd HH:mm:ss');
+
+ return {
+ startDate,
+ endDate,
+ };
+ }
+
+ if (range === 'yesterday') {
+ const startDate = DateTime.now()
+ .minus({ day: 1 })
+ .setZone(timezone)
+ .startOf('day')
+ .toFormat('yyyy-MM-dd HH:mm:ss');
+ const endDate = DateTime.now()
+ .minus({ day: 1 })
+ .setZone(timezone)
+ .endOf('day')
+ .toFormat('yyyy-MM-dd HH:mm:ss');
+ return {
+ startDate,
+ endDate,
+ };
+ }
+
+ if (range === '7d') {
+ const startDate = DateTime.now()
+ .minus({ day: 7 })
+ .setZone(timezone)
+ .startOf('day')
+ .toFormat('yyyy-MM-dd HH:mm:ss');
+ const endDate = DateTime.now()
+ .setZone(timezone)
+ .endOf('day')
+ .plus({ millisecond: 1 })
+ .toFormat('yyyy-MM-dd HH:mm:ss');
+
+ return {
+ startDate,
+ endDate,
+ };
+ }
+
+ if (range === '3m') {
+ const startDate = DateTime.now()
+ .minus({ month: 3 })
+ .setZone(timezone)
+ .startOf('day')
+ .toFormat('yyyy-MM-dd HH:mm:ss');
+ const endDate = DateTime.now()
+ .setZone(timezone)
+ .endOf('day')
+ .plus({ millisecond: 1 })
+ .toFormat('yyyy-MM-dd HH:mm:ss');
+
+ return {
+ startDate,
+ endDate,
+ };
+ }
+
+ if (range === '6m') {
+ const startDate = DateTime.now()
+ .minus({ month: 6 })
+ .setZone(timezone)
+ .startOf('day')
+ .toFormat('yyyy-MM-dd HH:mm:ss');
+ const endDate = DateTime.now()
+ .setZone(timezone)
+ .endOf('day')
+ .plus({ millisecond: 1 })
+ .toFormat('yyyy-MM-dd HH:mm:ss');
+
+ return {
+ startDate,
+ endDate,
+ };
+ }
+
+ if (range === '12m') {
+ const startDate = DateTime.now()
+ .minus({ month: 12 })
+ .setZone(timezone)
+ .startOf('month')
+ .toFormat('yyyy-MM-dd HH:mm:ss');
+ const endDate = DateTime.now()
+ .setZone(timezone)
+ .endOf('month')
+ .plus({ millisecond: 1 })
+ .toFormat('yyyy-MM-dd HH:mm:ss');
+
+ return {
+ startDate,
+ endDate,
+ };
+ }
+
+ if (range === 'monthToDate') {
+ const startDate = DateTime.now()
+ .setZone(timezone)
+ .startOf('month')
+ .toFormat('yyyy-MM-dd HH:mm:ss');
+ const endDate = DateTime.now()
+ .setZone(timezone)
+ .endOf('day')
+ .plus({ millisecond: 1 })
+ .toFormat('yyyy-MM-dd HH:mm:ss');
+
+ return {
+ startDate,
+ endDate,
+ };
+ }
+
+ if (range === 'lastMonth') {
+ const month = DateTime.now()
+ .minus({ month: 1 })
+ .setZone(timezone)
+ .startOf('month');
+
+ const startDate = month.toFormat('yyyy-MM-dd HH:mm:ss');
+ const endDate = month
+ .endOf('month')
+ .plus({ millisecond: 1 })
+ .toFormat('yyyy-MM-dd HH:mm:ss');
+
+ return {
+ startDate,
+ endDate,
+ };
+ }
+
+ if (range === 'yearToDate') {
+ const startDate = DateTime.now()
+ .setZone(timezone)
+ .startOf('year')
+ .toFormat('yyyy-MM-dd HH:mm:ss');
+ const endDate = DateTime.now()
+ .setZone(timezone)
+ .endOf('day')
+ .plus({ millisecond: 1 })
+ .toFormat('yyyy-MM-dd HH:mm:ss');
+
+ return {
+ startDate,
+ endDate,
+ };
+ }
+
+ if (range === 'lastYear') {
+ const year = DateTime.now().minus({ year: 1 }).setZone(timezone);
+ const startDate = year.startOf('year').toFormat('yyyy-MM-dd HH:mm:ss');
+ const endDate = year.endOf('year').toFormat('yyyy-MM-dd HH:mm:ss');
+
+ return {
+ startDate,
+ endDate,
+ };
+ }
+
+ // range === '30d'
+ const startDate = DateTime.now()
+ .minus({ day: 30 })
+ .setZone(timezone)
+ .startOf('day')
+ .toFormat('yyyy-MM-dd HH:mm:ss');
+ const endDate = DateTime.now()
+ .setZone(timezone)
+ .endOf('day')
+ .plus({ millisecond: 1 })
+ .toFormat('yyyy-MM-dd HH:mm:ss');
+
+ return {
+ startDate,
+ endDate,
+ };
+}
+
+const DATE_ONLY_REGEX = /^\d{4}-\d{2}-\d{2}$/;
+
+function normalizeBoundary(value: string, boundary: 'start' | 'end'): string {
+ if (DATE_ONLY_REGEX.test(value)) {
+ return boundary === 'start' ? `${value} 00:00:00` : `${value} 23:59:59`;
+ }
+ return value;
+}
+
+export function getChartStartEndDate(
+ {
+ startDate,
+ endDate,
+ range,
+ }: Pick<IReportInput, 'endDate' | 'startDate' | 'range'>,
+ timezone: string
+) {
+ const normalizedStart = startDate
+ ? normalizeBoundary(startDate, 'start')
+ : startDate;
+ const normalizedEnd = endDate ? normalizeBoundary(endDate, 'end') : endDate;
+
+ if (normalizedStart && normalizedEnd) {
+ return { startDate: normalizedStart, endDate: normalizedEnd };
+ }
+
+ const ranges = getDatesFromRange(range, timezone);
+ if (!normalizedStart && normalizedEnd) {
+ return { startDate: ranges.startDate, endDate: normalizedEnd };
+ }
+
+ return ranges;
+}
+
+export function getChartPrevStartEndDate({
+ startDate,
+ endDate,
+}: {
+ startDate: string;
+ endDate: string;
+}) {
+ let diff = DateTime.fromFormat(endDate, 'yyyy-MM-dd HH:mm:ss').diff(
+ DateTime.fromFormat(startDate, 'yyyy-MM-dd HH:mm:ss')
+ );
+
+ if ((diff.milliseconds / 1000) % 2 !== 0) {
+ diff = diff.plus({ millisecond: 1 });
+ }
+
+ return {
+ startDate: DateTime.fromFormat(startDate, 'yyyy-MM-dd HH:mm:ss')
+ .minus({ millisecond: diff.milliseconds })
+ .toFormat('yyyy-MM-dd HH:mm:ss'),
+ endDate: DateTime.fromFormat(endDate, 'yyyy-MM-dd HH:mm:ss')
+ .minus({ millisecond: diff.milliseconds })
+ .toFormat('yyyy-MM-dd HH:mm:ss'),
+ };
+}
diff --git a/packages/core/src/shared/lookback.test.ts b/packages/core/src/shared/lookback.test.ts
new file mode 100644
index 000000000..942755743
--- /dev/null
+++ b/packages/core/src/shared/lookback.test.ts
@@ -0,0 +1,70 @@
+import { afterEach, describe, expect, it } from 'bun:test';
+import { resolveMaxLookbackDays } from './lookback';
+
+function withEnv(name: string, value: string | undefined, fn: () => void) {
+ const previous = process.env[name];
+ if (value === undefined) {
+ delete process.env[name];
+ } else {
+ process.env[name] = value;
+ }
+ try {
+ fn();
+ } finally {
+ if (previous === undefined) {
+ delete process.env[name];
+ } else {
+ process.env[name] = previous;
+ }
+ }
+}
+
+describe('resolveMaxLookbackDays', () => {
+ afterEach(() => {
+ delete process.env.EVENT_LIST_MAX_LOOKBACK_DAYS;
+ delete process.env.SESSION_LIST_MAX_LOOKBACK_DAYS;
+ });
+
+ it('returns the caller default when unset', () => {
+ withEnv('EVENT_LIST_MAX_LOOKBACK_DAYS', '', () => {
+ expect(
+ resolveMaxLookbackDays('EVENT_LIST_MAX_LOOKBACK_DAYS', 365 * 5)
+ ).toBe(365 * 5);
+ expect(
+ resolveMaxLookbackDays('SESSION_LIST_MAX_LOOKBACK_DAYS', 365)
+ ).toBe(365);
+ });
+ });
+
+ it('replaces the ceiling when set to a positive integer', () => {
+ withEnv('EVENT_LIST_MAX_LOOKBACK_DAYS', '7', () => {
+ expect(
+ resolveMaxLookbackDays('EVENT_LIST_MAX_LOOKBACK_DAYS', 365 * 5)
+ ).toBe(7);
+ });
+ // Raising past the default is allowed too — it's a ceiling, not a min.
+ withEnv('SESSION_LIST_MAX_LOOKBACK_DAYS', '3650', () => {
+ expect(
+ resolveMaxLookbackDays('SESSION_LIST_MAX_LOOKBACK_DAYS', 365)
+ ).toBe(3650);
+ });
+ });
+
+ it('reads each list its own variable — no cross-talk', () => {
+ withEnv('EVENT_LIST_MAX_LOOKBACK_DAYS', '7', () => {
+ expect(
+ resolveMaxLookbackDays('SESSION_LIST_MAX_LOOKBACK_DAYS', 365)
+ ).toBe(365);
+ });
+ });
+
+ it('falls back to the default for malformed values', () => {
+ for (const bad of ['0', '-1', '7.5', '7days', 'junk']) {
+ withEnv('EVENT_LIST_MAX_LOOKBACK_DAYS', bad, () => {
+ expect(
+ resolveMaxLookbackDays('EVENT_LIST_MAX_LOOKBACK_DAYS', 365)
+ ).toBe(365);
+ });
+ }
+ });
+});
diff --git a/packages/core/src/shared/lookback.ts b/packages/core/src/shared/lookback.ts
new file mode 100644
index 000000000..bb16da2c3
--- /dev/null
+++ b/packages/core/src/shared/lookback.ts
@@ -0,0 +1,30 @@
+/**
+ * Ceiling (in days) for the empty-result lookback expansion on the event and
+ * session lists.
+ *
+ * When a cursor window matches nothing, those lists double the window and
+ * retry until the ceiling is reached. The doubling geometry keeps the total
+ * cost at roughly 2x the final window, so the ceiling is what actually
+ * bounds the worst case: with a filter no index can prune (e.g. a
+ * properties value) that matches nothing at all, every step is a full scan
+ * of its window, and a multi-year ceiling turns one page view into minutes
+ * of scanning.
+ *
+ * Each list has its own variable (EVENT_LIST_MAX_LOOKBACK_DAYS,
+ * SESSION_LIST_MAX_LOOKBACK_DAYS) because their built-in ceilings differ —
+ * the surfaces have different cost profiles and a shared knob would couple
+ * them. Values are human-sized day counts (1 / 7 / 365 / ...); unset or
+ * invalid (non-integer, zero, negative) keeps the caller's default, so
+ * behavior is unchanged unless a variable is set.
+ */
+export function resolveMaxLookbackDays(
+ envName: string,
+ defaultDays: number
+): number {
+ const raw = process.env[envName];
+ if (!(raw && /^\d+$/.test(raw))) {
+ return defaultDays;
+ }
+ const parsed = Number(raw);
+ return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : defaultDays;
+}
diff --git a/packages/core/src/shared/slug-id.ts b/packages/core/src/shared/slug-id.ts
new file mode 100644
index 000000000..bdf3a48a1
--- /dev/null
+++ b/packages/core/src/shared/slug-id.ts
@@ -0,0 +1,52 @@
+// Slug-based primary-id generation for project/dashboard/organization rows.
+// Moved from packages/db/src/services/id.service.ts (M8-005) — a sibling of
+// shared/access-lookups.ts: needs @openpanel/db, so it stays out of
+// shared/id.ts (the database-free id helpers).
+//
+// db access is LAZY (`loadDb` below), not a static top-level import — see
+// insight.service.ts's header for the full reasoning (jobs.registry.ts and
+// services.ts pull this module into the eager barrel chain nearly every core
+// test file reaches, and constructing @openpanel/db's clients at import time
+// would spawn a pino-pretty transport worker thread per test file).
+
+import { slug } from '@openpanel/common';
+
+function loadDb() {
+ return import('@openpanel/db/src/prisma-client').then((m) => m.db);
+}
+
+export async function getId(
+ tableName: 'project' | 'dashboard' | 'organization',
+ name: string
+): Promise<string> {
+ const newId = slug(name);
+ const db = await loadDb();
+ if (!db[tableName]) {
+ throw new Error('Table does not exists');
+ }
+
+ if (!('findUnique' in db[tableName])) {
+ throw new Error('findUnique does not exists');
+ }
+
+ // @ts-expect-error
+ const existingProject = await db[tableName].findUnique({
+ where: {
+ id: newId,
+ },
+ });
+
+ function random(str: string) {
+ const numbers = Math.floor(1000 + Math.random() * 9000);
+ if (str.match(/-\d{4}$/g)) {
+ return str.replace(/-\d{4}$/g, `-${numbers}`);
+ }
+ return `${str}-${numbers}`;
+ }
+
+ if (existingProject) {
+ return getId(tableName, random(name));
+ }
+
+ return newId;
+}
diff --git a/packages/db/index.ts b/packages/db/index.ts
index b7b9471d5..452d6a408 100644
--- a/packages/db/index.ts
+++ b/packages/db/index.ts
@@ -3,7 +3,6 @@ export * from './src/clickhouse/client';
export * from './src/clickhouse/query-builder';
export * from './src/encryption';
export * from './src/engine';
-export * from './src/engine';
export * from './src/exports';
export * from './src/gsc';
export * from './src/prisma-client';
diff --git a/packages/db/package.json b/packages/db/package.json
index 63bf51640..ddbe52d66 100644
--- a/packages/db/package.json
+++ b/packages/db/package.json
@@ -6,7 +6,7 @@
"scripts": {
"codegen": "pnpm with-env prisma generate && jiti prisma/prisma-json-types.ts",
"migrate": "pnpm with-env prisma migrate dev",
- "migrate:deploy:code": "pnpm with-env jiti ./code-migrations/migrate.ts",
+ "migrate:deploy:code": "pnpm --filter @openpanel/core run migrate:deploy:code",
"migrate:deploy:db": "pnpm with-env prisma migrate deploy",
"migrate:deploy": "pnpm migrate:deploy:db && pnpm migrate:deploy:code",
"duplicate-events": "pnpm with-env jiti ./scripts/find-duplicate-events.ts",
diff --git a/packages/db/src/clickhouse/migration.ts b/packages/db/src/clickhouse/migration.ts
index 2b2241d4f..2f1f7a395 100644
--- a/packages/db/src/clickhouse/migration.ts
+++ b/packages/db/src/clickhouse/migration.ts
@@ -1,6 +1,6 @@
import crypto from 'node:crypto';
-import { createClient } from './client';
-import { formatClickhouseDate } from './client';
+import type { EventEmitter } from 'node:events';
+import { createClient, formatClickhouseDate } from './client';
interface CreateTableOptions {
name: string;
@@ -36,7 +36,7 @@ const replicated = (tableName: string) => `${tableName}_replicated`;
export const chMigrationClient = createClient({
url: process.env.CLICKHOUSE_URL,
- request_timeout: 3600000, // 1 hour in milliseconds
+ request_timeout: 3_600_000, // 1 hour in milliseconds
keep_alive: {
enabled: true,
},
@@ -137,7 +137,7 @@ export const modifyTTL = ({
export function addColumns(
tableName: string,
columns: string[],
- isClustered: boolean,
+ isClustered: boolean
): string[] {
if (isClustered) {
return columns.flatMap((col) => [
@@ -147,7 +147,7 @@ export function addColumns(
}
return columns.map(
- (col) => `ALTER TABLE ${tableName} ADD COLUMN IF NOT EXISTS ${col}`,
+ (col) => `ALTER TABLE ${tableName} ADD COLUMN IF NOT EXISTS ${col}`
);
}
@@ -157,7 +157,7 @@ export function addColumns(
export function dropColumns(
tableName: string,
columnNames: string[],
- isClustered: boolean,
+ isClustered: boolean
): string[] {
if (isClustered) {
return columnNames.flatMap((colName) => [
@@ -167,7 +167,7 @@ export function dropColumns(
}
return columnNames.map(
- (colName) => `ALTER TABLE ${tableName} DROP COLUMN IF EXISTS ${colName}`,
+ (colName) => `ALTER TABLE ${tableName} DROP COLUMN IF EXISTS ${colName}`
);
}
@@ -266,7 +266,7 @@ export function moveDataBetweenTables({
const shouldContinue = (
current: Date,
start: Date,
- intervalType: string,
+ intervalType: string
): boolean => {
if (intervalType === 'month') {
// For months, compare by year and month
@@ -383,7 +383,7 @@ export function createMaterializedView({
// Transform query to use replicated table names in clustered mode
const transformedQuery = query.replace(/\{(\w+)\}/g, (_, tableName) =>
- isClustered ? replicated(tableName) : tableName,
+ isClustered ? replicated(tableName) : tableName
);
if (!isClustered) {
@@ -423,7 +423,7 @@ export async function runClickhouseMigrationCommands(sqls: string[]) {
const handleTermination = async (signal: string) => {
console.warn(
- `Received ${signal}. Cleaning up active queries before exit...`,
+ `Received ${signal}. Cleaning up active queries before exit...`
);
if (abort) {
@@ -464,7 +464,9 @@ export async function runClickhouseMigrationCommands(sqls: string[]) {
let checking = false; // Add flag to prevent multiple concurrent checks
async function check() {
- if (checking) return; // Skip if already checking
+ if (checking) {
+ return; // Skip if already checking
+ }
checking = true;
try {
@@ -501,7 +503,7 @@ export async function runClickhouseMigrationCommands(sqls: string[]) {
const { elapsed, read_rows, written_rows, memory_usage } =
res[0] as any;
console.log(
- `Progress: ${elapsed.toFixed(2)}s | Memory: ${formatMemory(memory_usage)} | Read: ${formatNumber(read_rows)} rows | Written: ${formatNumber(written_rows)} rows`,
+ `Progress: ${elapsed.toFixed(2)}s | Memory: ${formatMemory(memory_usage)} | Read: ${formatNumber(read_rows)} rows | Written: ${formatNumber(written_rows)} rows`
);
}
} finally {
@@ -545,8 +547,14 @@ export async function runClickhouseMigrationCommands(sqls: string[]) {
throw e;
} finally {
- // Clean up event listeners
- process.off('SIGTERM', handleSigterm);
- process.off('SIGINT', handleSigint);
+ // Clean up event listeners. Cast needed under core's bun-types-only
+ // `types` array (M8-005 first pulled this file into that compilation via
+ // code-migrations/): bun-types 1.4.0's `Process.off` override only
+ // declares its own "memoryPressure" overload, so the plain
+ // @types/node Signals overload TS picks under packages/db's own tsconfig
+ // isn't visible there.
+ const emitter = process as unknown as EventEmitter;
+ emitter.off('SIGTERM', handleSigterm);
+ emitter.off('SIGINT', handleSigint);
}
}
diff --git a/packages/db/src/exports/index.ts b/packages/db/src/exports/index.ts
index 0aed4a1a7..5bd8c2f92 100644
--- a/packages/db/src/exports/index.ts
+++ b/packages/db/src/exports/index.ts
@@ -1,25 +1,23 @@
+// Object-store export batch creation lives in @openpanel/core now (M8-005):
+// packages/core/src/clients/integrations/export/. Re-exported here for the
+// existing `@openpanel/db` importer (apps/worker's flush-exports cron job) —
+// same shape as event.service.ts since M7-002.
export {
+ clickhouseEventToExportEvent,
createBatch,
+ createManifest,
+ EXPORT_SCHEMA_VERSION,
+ type ExportFormat,
generateBatchPath,
- getFileExtension,
getContentType,
- type ExportFormat,
- type IBatchInfo,
+ getFileExtension,
type IBatchFile,
+ type IBatchInfo,
type IBatchResult,
-} from './batch-creator';
-
-export {
- createManifest,
- serializeManifest,
- parseManifest,
- MANIFEST_FILENAME,
- MANIFEST_CONTENT_TYPE,
- type IManifest,
-} from './manifest';
-
-export {
- clickhouseEventToExportEvent,
- EXPORT_SCHEMA_VERSION,
type IExportEvent,
-} from './export-event';
+ type IManifest,
+ MANIFEST_CONTENT_TYPE,
+ MANIFEST_FILENAME,
+ parseManifest,
+ serializeManifest,
+} from '@openpanel/core';
diff --git a/packages/db/src/logger.ts b/packages/db/src/logger.ts
index b91fda0eb..786d1d33a 100644
--- a/packages/db/src/logger.ts
+++ b/packages/db/src/logger.ts
@@ -91,11 +91,17 @@ function getServiceName(name: string): string {
.join('-');
}
+// Same Bun/pino-pretty incompatibility as @openpanel/core/clients/logger.ts's
+// `isBun` guard — see its comment. Kept in sync by hand, like the rest of
+// this file.
+const isBun = !!process.versions.bun;
+
export function createLogger({ name }: { name: string }): ILogger {
const service = getServiceName(name);
const useHyperDX = logExporter === 'otlp' && !!process.env.HYPERDX_API_KEY;
- const usePretty = !useHyperDX && process.env.NODE_ENV !== 'production';
+ const usePretty =
+ !(useHyperDX || isBun) && process.env.NODE_ENV !== 'production';
return pino({
name: service,
diff --git a/packages/db/src/services/access.service.ts b/packages/db/src/services/access.service.ts
index 4404a0fcc..38c81ea05 100644
--- a/packages/db/src/services/access.service.ts
+++ b/packages/db/src/services/access.service.ts
@@ -1,130 +1,13 @@
-import type { AccessLevel } from '../generated/prisma/client';
-import { cacheable } from '@openpanel/redis';
-import { db } from '../prisma-client';
-import { getProjectById } from './project.service';
-
-export type IProjectAccess = { level: AccessLevel };
-
-/** Access levels that may mutate. `admin` is a superset of `write`. */
-const WRITE_LEVELS: ReadonlySet<AccessLevel> = new Set<AccessLevel>([
- 'write',
- 'admin',
-]);
-
-export function canWriteProject(access: IProjectAccess | null): boolean {
- return !!access && WRITE_LEVELS.has(access.level);
-}
-
-/**
- * Resolve a user's access to one project.
- *
- * Returns a single shape - `{ level }` or `null` - on purpose. This used to
- * return `true` for members with no explicit ProjectAccess rows and the row
- * itself otherwise, which forced every caller into a `typeof access !==
- * 'boolean'` dance. 26 of 29 mutating procedures skipped the level check
- * entirely as a result (GHSA-f9rx-pxgw-c6rg); with one shape, omitting the
- * check is a type error rather than a silent grant.
- *
- * NOTE: the cache key is versioned. Changing the return shape without renaming
- * it would serve old-shape entries for up to 5 minutes across a rolling deploy.
- */
-export const getProjectAccess = cacheable(
- 'getProjectAccessV2',
- async ({
- userId,
- projectId,
- }: {
- userId: string;
- projectId: string;
- }): Promise<IProjectAccess | null> => {
- try {
- // Check if user has access to the project
- const project = await getProjectById(projectId);
- if (!project?.organizationId) {
- return null;
- }
-
- const [projectAccess, member] = await Promise.all([
- db.projectAccess.findMany({
- where: {
- userId,
- organizationId: project.organizationId,
- },
- }),
- db.member.findFirst({
- where: {
- organizationId: project.organizationId,
- userId,
- },
- }),
- ]);
-
- if (!member) {
- return null;
- }
-
- // No explicit per-project grants means org-wide default access, and the
- // default is write.
- if (projectAccess.length === 0) {
- return { level: 'write' };
- }
-
- const row = projectAccess.find((item) => item.projectId === projectId);
-
- return row ? { level: row.level } : null;
- } catch (err) {
- return null;
- }
- },
- 60 * 5
-);
-
-export const getOrganizationAccess = cacheable(
- 'getOrganizationAccess',
- async ({
- userId,
- organizationId,
- }: {
- userId: string;
- organizationId: string;
- }) => {
- return db.member.findFirst({
- where: {
- userId,
- organizationId,
- },
- });
- },
- 60 * 5
-);
-
-export async function getClientAccess({
- userId,
- clientId,
-}: {
- userId: string;
- clientId: string;
-}) {
- const client = await db.client.findFirst({
- where: {
- id: clientId,
- },
- });
-
- if (!client) {
- return false;
- }
-
- if (client.projectId) {
- return getProjectAccess({ userId, projectId: client.projectId });
- }
-
- if (client.organizationId) {
- return getOrganizationAccess({
- userId,
- organizationId: client.organizationId,
- });
- }
-
- return false;
-}
+// The concrete project/organization/client access lookups live in
+// @openpanel/core now (M8-005): packages/core/src/shared/access-lookups.ts.
+// Re-exported here for existing `@openpanel/db` importers (packages/trpc's
+// access.ts, apps/api's app.ts + live.controller.ts, and the ~28 core
+// modules' own `src/access.ts` files that deep-import this exact specifier)
+// — same shape as event.service.ts since M7-002.
+export {
+ canWriteProject,
+ getClientAccess,
+ getOrganizationAccess,
+ getProjectAccess,
+ type IProjectAccess,
+} from '@openpanel/core';
diff --git a/packages/db/src/services/auth-session.service.ts b/packages/db/src/services/auth-session.service.ts
index 6727bf3e4..39755a18f 100644
--- a/packages/db/src/services/auth-session.service.ts
+++ b/packages/db/src/services/auth-session.service.ts
@@ -1,118 +1,12 @@
-// Postgres-backed login sessions (a `sessions` row keyed by the hash of a
-// browser's cookie). Not to be confused with session.service.ts's ClickHouse
-// visitor sessions.
-//
-// Moved from @openpanel/auth (M4-007), split at the Prisma boundary: token
-// issuance/hashing lives in @openpanel/core's auth module (no db needed), and
-// this half — the part that actually touches `sessions`/`users` — stays here,
-// because @openpanel/core cannot depend on @openpanel/db (db already depends
-// on core) without a cycle.
-
-import { decodeSessionToken, hashSessionToken } from '@openpanel/core';
-import type { Session, User } from '../prisma-client';
-import { db } from '../prisma-client';
-
-const SESSION_TTL_MS = 1000 * 60 * 60 * 24 * 30;
-const SESSION_RENEWAL_THRESHOLD_MS = 1000 * 60 * 60 * 24 * 15;
-const DEMO_SESSION_TTL_MS = 1000 * 60 * 60 * 24 * 30 * 365;
-const DEMO_SESSION_ID = '1';
-
-export type SessionValidationResult =
- | { session: Session; user: User; userId: string }
- | { session: null; user: null; userId: null };
-
-export const EMPTY_SESSION: SessionValidationResult = {
- session: null,
- user: null,
- userId: null,
-};
-
-export async function createSession(
- token: string,
- userId: string
-): Promise<Session> {
- const session: Session = {
- id: hashSessionToken(token),
- userId,
- expiresAt: new Date(Date.now() + SESSION_TTL_MS),
- createdAt: new Date(),
- updatedAt: new Date(),
- };
- await db.session.create({
- data: session,
- });
- return session;
-}
-
-export async function createDemoSession(
- userId: string
-): Promise<SessionValidationResult> {
- const user = await db.user.findUniqueOrThrow({
- where: {
- id: userId,
- },
- });
-
- return {
- user,
- userId: user.id,
- session: {
- id: DEMO_SESSION_ID,
- userId: user.id,
- expiresAt: new Date(Date.now() + DEMO_SESSION_TTL_MS),
- createdAt: new Date(),
- updatedAt: new Date(),
- },
- };
-}
-
-export async function validateSessionToken(
- token: string | null | undefined
-): Promise<SessionValidationResult> {
- if (process.env.DEMO_USER_ID) {
- return createDemoSession(process.env.DEMO_USER_ID);
- }
-
- if (!token) {
- return EMPTY_SESSION;
- }
- const sessionId = decodeSessionToken(token);
- if (!sessionId) {
- return EMPTY_SESSION;
- }
- const result = await db.session.findUnique({
- where: {
- id: sessionId,
- },
- include: {
- user: true,
- },
- });
- if (result === null) {
- return EMPTY_SESSION;
- }
- const { user, ...session } = result;
- if (Date.now() >= session.expiresAt.getTime()) {
- await db.session.delete({ where: { id: sessionId } });
- return EMPTY_SESSION;
- }
- if (
- Date.now() >=
- session.expiresAt.getTime() - SESSION_RENEWAL_THRESHOLD_MS
- ) {
- session.expiresAt = new Date(Date.now() + SESSION_TTL_MS);
- await db.session.update({
- where: {
- id: session.id,
- },
- data: {
- expiresAt: session.expiresAt,
- },
- });
- }
- return { session, user, userId: user.id };
-}
-
-export async function invalidateSession(sessionId: string): Promise<void> {
- await db.session.delete({ where: { id: sessionId } });
-}
+// The Postgres-backed login session CRUD lives in @openpanel/core now
+// (M8-005): packages/core/src/modules/auth/src/login-session.ts. Re-exported
+// here for existing `@openpanel/db` importers (apps/api's app.ts) — same
+// shape as packages/db/src/services/chart.service.ts since M7-003.
+export type { SessionValidationResult } from '@openpanel/core';
+export {
+ createDemoSession,
+ createSession,
+ EMPTY_SESSION,
+ invalidateSession,
+ validateSessionToken,
+} from '@openpanel/core';
diff --git a/packages/db/src/services/date.service.ts b/packages/db/src/services/date.service.ts
index 19fcd7232..041f8c8ea 100644
--- a/packages/db/src/services/date.service.ts
+++ b/packages/db/src/services/date.service.ts
@@ -1,296 +1,11 @@
-import { DateTime } from '@openpanel/common';
-import type { IChartRange, IReportInput } from '@openpanel/validation';
-
-export function resolveDateRange(
- startDate?: string,
- endDate?: string
-): { startDate: string; endDate: string } {
- const end = endDate ?? new Date().toISOString().slice(0, 10);
- const start =
- startDate ??
- new Date(Date.now() - 30 * 86_400_000).toISOString().slice(0, 10);
- return { startDate: start, endDate: end };
-}
-
-export function getDatesFromRange(range: IChartRange, timezone: string) {
- if (range === '30min' || range === 'lastHour') {
- const minutes = range === '30min' ? 30 : 60;
- const startDate = DateTime.now()
- .minus({ minute: minutes })
- .startOf('minute')
- .setZone(timezone)
- .toFormat('yyyy-MM-dd HH:mm:ss');
- const endDate = DateTime.now()
- .setZone(timezone)
- .endOf('minute')
- .toFormat('yyyy-MM-dd HH:mm:ss');
-
- return {
- startDate,
- endDate,
- };
- }
-
- if (range === 'last24h') {
- const startDate = DateTime.now()
- .minus({ hour: 24 })
- .startOf('minute')
- .setZone(timezone)
- .toFormat('yyyy-MM-dd HH:mm:ss');
- const endDate = DateTime.now()
- .setZone(timezone)
- .endOf('minute')
- .toFormat('yyyy-MM-dd HH:mm:ss');
-
- return {
- startDate,
- endDate,
- };
- }
-
- if (range === 'today') {
- const startDate = DateTime.now()
- .setZone(timezone)
- .startOf('day')
- .toFormat('yyyy-MM-dd HH:mm:ss');
- const endDate = DateTime.now()
- .setZone(timezone)
- .endOf('day')
- .toFormat('yyyy-MM-dd HH:mm:ss');
-
- return {
- startDate,
- endDate,
- };
- }
-
- if (range === 'yesterday') {
- const startDate = DateTime.now()
- .minus({ day: 1 })
- .setZone(timezone)
- .startOf('day')
- .toFormat('yyyy-MM-dd HH:mm:ss');
- const endDate = DateTime.now()
- .minus({ day: 1 })
- .setZone(timezone)
- .endOf('day')
- .toFormat('yyyy-MM-dd HH:mm:ss');
- return {
- startDate,
- endDate,
- };
- }
-
- if (range === '7d') {
- const startDate = DateTime.now()
- .minus({ day: 7 })
- .setZone(timezone)
- .startOf('day')
- .toFormat('yyyy-MM-dd HH:mm:ss');
- const endDate = DateTime.now()
- .setZone(timezone)
- .endOf('day')
- .plus({ millisecond: 1 })
- .toFormat('yyyy-MM-dd HH:mm:ss');
-
- return {
- startDate,
- endDate,
- };
- }
-
- if (range === '3m') {
- const startDate = DateTime.now()
- .minus({ month: 3 })
- .setZone(timezone)
- .startOf('day')
- .toFormat('yyyy-MM-dd HH:mm:ss');
- const endDate = DateTime.now()
- .setZone(timezone)
- .endOf('day')
- .plus({ millisecond: 1 })
- .toFormat('yyyy-MM-dd HH:mm:ss');
-
- return {
- startDate,
- endDate,
- };
- }
-
- if (range === '6m') {
- const startDate = DateTime.now()
- .minus({ month: 6 })
- .setZone(timezone)
- .startOf('day')
- .toFormat('yyyy-MM-dd HH:mm:ss');
- const endDate = DateTime.now()
- .setZone(timezone)
- .endOf('day')
- .plus({ millisecond: 1 })
- .toFormat('yyyy-MM-dd HH:mm:ss');
-
- return {
- startDate,
- endDate,
- };
- }
-
- if (range === '12m') {
- const startDate = DateTime.now()
- .minus({ month: 12 })
- .setZone(timezone)
- .startOf('month')
- .toFormat('yyyy-MM-dd HH:mm:ss');
- const endDate = DateTime.now()
- .setZone(timezone)
- .endOf('month')
- .plus({ millisecond: 1 })
- .toFormat('yyyy-MM-dd HH:mm:ss');
-
- return {
- startDate,
- endDate,
- };
- }
-
- if (range === 'monthToDate') {
- const startDate = DateTime.now()
- .setZone(timezone)
- .startOf('month')
- .toFormat('yyyy-MM-dd HH:mm:ss');
- const endDate = DateTime.now()
- .setZone(timezone)
- .endOf('day')
- .plus({ millisecond: 1 })
- .toFormat('yyyy-MM-dd HH:mm:ss');
-
- return {
- startDate,
- endDate,
- };
- }
-
- if (range === 'lastMonth') {
- const month = DateTime.now()
- .minus({ month: 1 })
- .setZone(timezone)
- .startOf('month');
-
- const startDate = month.toFormat('yyyy-MM-dd HH:mm:ss');
- const endDate = month
- .endOf('month')
- .plus({ millisecond: 1 })
- .toFormat('yyyy-MM-dd HH:mm:ss');
-
- return {
- startDate,
- endDate,
- };
- }
-
- if (range === 'yearToDate') {
- const startDate = DateTime.now()
- .setZone(timezone)
- .startOf('year')
- .toFormat('yyyy-MM-dd HH:mm:ss');
- const endDate = DateTime.now()
- .setZone(timezone)
- .endOf('day')
- .plus({ millisecond: 1 })
- .toFormat('yyyy-MM-dd HH:mm:ss');
-
- return {
- startDate,
- endDate,
- };
- }
-
- if (range === 'lastYear') {
- const year = DateTime.now().minus({ year: 1 }).setZone(timezone);
- const startDate = year.startOf('year').toFormat('yyyy-MM-dd HH:mm:ss');
- const endDate = year.endOf('year').toFormat('yyyy-MM-dd HH:mm:ss');
-
- return {
- startDate,
- endDate,
- };
- }
-
- // range === '30d'
- const startDate = DateTime.now()
- .minus({ day: 30 })
- .setZone(timezone)
- .startOf('day')
- .toFormat('yyyy-MM-dd HH:mm:ss');
- const endDate = DateTime.now()
- .setZone(timezone)
- .endOf('day')
- .plus({ millisecond: 1 })
- .toFormat('yyyy-MM-dd HH:mm:ss');
-
- return {
- startDate,
- endDate,
- };
-}
-
-const DATE_ONLY_REGEX = /^\d{4}-\d{2}-\d{2}$/;
-
-function normalizeBoundary(value: string, boundary: 'start' | 'end'): string {
- if (DATE_ONLY_REGEX.test(value)) {
- return boundary === 'start'
- ? `${value} 00:00:00`
- : `${value} 23:59:59`;
- }
- return value;
-}
-
-export function getChartStartEndDate(
- {
- startDate,
- endDate,
- range,
- }: Pick<IReportInput, 'endDate' | 'startDate' | 'range'>,
- timezone: string
-) {
- const normalizedStart = startDate
- ? normalizeBoundary(startDate, 'start')
- : startDate;
- const normalizedEnd = endDate ? normalizeBoundary(endDate, 'end') : endDate;
-
- if (normalizedStart && normalizedEnd) {
- return { startDate: normalizedStart, endDate: normalizedEnd };
- }
-
- const ranges = getDatesFromRange(range, timezone);
- if (!normalizedStart && normalizedEnd) {
- return { startDate: ranges.startDate, endDate: normalizedEnd };
- }
-
- return ranges;
-}
-
-export function getChartPrevStartEndDate({
- startDate,
- endDate,
-}: {
- startDate: string;
- endDate: string;
-}) {
- let diff = DateTime.fromFormat(endDate, 'yyyy-MM-dd HH:mm:ss').diff(
- DateTime.fromFormat(startDate, 'yyyy-MM-dd HH:mm:ss')
- );
-
- if ((diff.milliseconds / 1000) % 2 !== 0) {
- diff = diff.plus({ millisecond: 1 });
- }
-
- return {
- startDate: DateTime.fromFormat(startDate, 'yyyy-MM-dd HH:mm:ss')
- .minus({ millisecond: diff.milliseconds })
- .toFormat('yyyy-MM-dd HH:mm:ss'),
- endDate: DateTime.fromFormat(endDate, 'yyyy-MM-dd HH:mm:ss')
- .minus({ millisecond: diff.milliseconds })
- .toFormat('yyyy-MM-dd HH:mm:ss'),
- };
-}
+// Chart date-range resolution lives in @openpanel/core now (M8-005):
+// packages/core/src/shared/date.ts. Re-exported here for existing
+// `@openpanel/db` importers (packages/trpc's overview/event routers,
+// apps/api's insights controller, ~40 core modules that still deep-import
+// this exact specifier) — same shape as event.service.ts since M7-002.
+export {
+ getChartPrevStartEndDate,
+ getChartStartEndDate,
+ getDatesFromRange,
+ resolveDateRange,
+} from '@openpanel/core';
diff --git a/packages/db/src/services/filter-where.service.ts b/packages/db/src/services/filter-where.service.ts
index 5920667ea..e44a7d53a 100644
--- a/packages/db/src/services/filter-where.service.ts
+++ b/packages/db/src/services/filter-where.service.ts
@@ -1,373 +1,6 @@
-/** biome-ignore-all lint/style/useDefaultSwitchClause: switch cases are exhaustive by design */
-import {
- getCohortIds,
- type IChartEventFilter,
- type IChartFilterValueType,
-} from '@openpanel/validation';
-import sqlstring from 'sqlstring';
-import { formatClickhouseDate, TABLE_NAMES } from '../clickhouse/client';
-import { buildTypedClause, hasTypedCast, isTypedOperator } from './filter-cast';
-
-export type FilterTableContext = {
- /** Outer query's primary table. */
- selfTable: 'sessions' | 'profiles' | 'events';
- /**
- * Expression on the outer row that yields the owning profile id. For the
- * profiles table this is `id`; for events/sessions it's `profile_id`. Used
- * by cohort + cross-table profile.* filters.
- */
- profileIdExpr: string;
- /**
- * Expression on the outer row that yields the array of group ids. All three
- * canonical tables expose a `groups Array(String)` column today.
- */
- groupsExpr?: string;
- /**
- * Optional date scope passed to subselects that reference the events table
- * (currently only `session.performed_event`). Without it ClickHouse has to
- * scan the entire event history for the project.
- */
- startDate?: Date;
- endDate?: Date;
-};
-
-/** Sentinel sessions columns that the UI may filter on directly. */
-const SESSION_NUMERIC_COLUMNS = new Set([
- 'screen_view_count',
- 'event_count',
- 'duration',
- 'revenue',
-]);
-
-function escape(value: string | number | boolean | null): string {
- return sqlstring.escape(typeof value === 'string' ? value.trim() : value);
-}
-
-function trimVal(value: string | number | boolean | null): string {
- return typeof value === 'string' ? value.trim() : String(value);
-}
-
-/**
- * Build a WHERE-clause fragment for a single non-array column. Mirrors the
- * operator set used by `getEventFiltersWhereClause` so behaviour stays
- * consistent across surfaces.
- */
-function compileScalarClause(
- column: string,
- operator: IChartEventFilter['operator'],
- value: IChartEventFilter['value'],
- options: { numeric?: boolean; type?: IChartFilterValueType } = {},
-): string | null {
- if (
- value.length === 0 &&
- operator !== 'isNull' &&
- operator !== 'isNotNull'
- ) {
- return null;
- }
-
- // Explicit cast type wins over the column-name `numeric` auto-detect. Casts
- // both the column and each value consistently (see filter-cast.ts).
- if (hasTypedCast(options.type) && isTypedOperator(operator)) {
- return buildTypedClause(column, operator, value, options.type!);
- }
-
- const numeric = options.numeric === true;
-
- switch (operator) {
- case 'is': {
- if (numeric) {
- return `(${value
- .map((v) => `toFloat64(${column}) = toFloat64(${escape(v)})`)
- .join(' OR ')})`;
- }
- if (value.length === 1) {
- return `${column} = ${escape(value[0]!)}`;
- }
- return `${column} IN (${value.map(escape).join(', ')})`;
- }
- case 'isNot': {
- if (numeric) {
- return `(${value
- .map((v) => `toFloat64(${column}) != toFloat64(${escape(v)})`)
- .join(' OR ')})`;
- }
- if (value.length === 1) {
- return `${column} != ${escape(value[0]!)}`;
- }
- return `${column} NOT IN (${value.map(escape).join(', ')})`;
- }
- case 'contains': {
- return `(${value
- .map((v) => `${column} ILIKE ${sqlstring.escape(`%${trimVal(v)}%`)}`)
- .join(' OR ')})`;
- }
- case 'doesNotContain': {
- return `(${value
- .map((v) => `${column} NOT ILIKE ${sqlstring.escape(`%${trimVal(v)}%`)}`)
- .join(' AND ')})`;
- }
- case 'startsWith': {
- return `(${value
- .map((v) => `${column} ILIKE ${sqlstring.escape(`${trimVal(v)}%`)}`)
- .join(' OR ')})`;
- }
- case 'endsWith': {
- return `(${value
- .map((v) => `${column} ILIKE ${sqlstring.escape(`%${trimVal(v)}`)}`)
- .join(' OR ')})`;
- }
- case 'regex': {
- return `(${value
- .map((v) => `match(${column}, ${escape(v)})`)
- .join(' OR ')})`;
- }
- case 'isNull':
- return `(${column} = '' OR ${column} IS NULL)`;
- case 'isNotNull':
- return `(${column} != '' AND ${column} IS NOT NULL)`;
- case 'gt': {
- return `(${value
- .map(
- (v) =>
- `${numeric ? `toFloat64(${column})` : column} > ${numeric ? `toFloat64(${escape(v)})` : escape(v)}`,
- )
- .join(' OR ')})`;
- }
- case 'lt': {
- return `(${value
- .map(
- (v) =>
- `${numeric ? `toFloat64(${column})` : column} < ${numeric ? `toFloat64(${escape(v)})` : escape(v)}`,
- )
- .join(' OR ')})`;
- }
- case 'gte': {
- return `(${value
- .map(
- (v) =>
- `${numeric ? `toFloat64(${column})` : column} >= ${numeric ? `toFloat64(${escape(v)})` : escape(v)}`,
- )
- .join(' OR ')})`;
- }
- case 'lte': {
- return `(${value
- .map(
- (v) =>
- `${numeric ? `toFloat64(${column})` : column} <= ${numeric ? `toFloat64(${escape(v)})` : escape(v)}`,
- )
- .join(' OR ')})`;
- }
- }
-
- return null;
-}
-
-/**
- * Profiles columns a `profile.<field>` filter may resolve to. Anything else is
- * not a column name and must not reach the SQL text. Kept in sync with
- * `getProfilePropertySelect` in chart.service.ts, which lists the same set for
- * the SELECT side.
- */
-const PROFILE_COLUMNS = new Set([
- 'id',
- 'first_name',
- 'last_name',
- 'email',
- 'avatar',
- 'created_at',
- 'last_seen_at',
-]);
-
-/**
- * Translate `profile.<field>` into the SQL accessor used when querying the
- * profiles table directly. Bare fields (email, first_name, …) map to columns;
- * `profile.properties.<key>` maps to the JSON `properties[key]` lookup.
- * Returns null for a field that is neither, so the caller can drop the filter.
- */
-function profileColumnSql(name: string): string | null {
- const withoutPrefix = name.replace(/^profile\./, '');
- if (withoutPrefix.startsWith('properties.')) {
- const key = withoutPrefix.replace(/^properties\./, '');
- return `properties[${sqlstring.escape(key)}]`;
- }
- if (PROFILE_COLUMNS.has(withoutPrefix)) {
- return withoutPrefix;
- }
- return null;
-}
-
-/**
- * Translate `group.<field>` into the SQL accessor used when querying the
- * groups table directly (no join alias).
- */
-function groupColumnSql(name: string): string {
- const withoutPrefix = name.replace(/^group\./, '');
- if (withoutPrefix === 'name' || withoutPrefix === 'type' || withoutPrefix === 'id') {
- return withoutPrefix;
- }
- if (withoutPrefix.startsWith('properties.')) {
- const key = withoutPrefix.replace(/^properties\./, '');
- return `properties[${sqlstring.escape(key)}]`;
- }
- return 'id';
-}
-
-/** Translate `session.<field>` to the underlying sessions column. */
-function sessionColumnSql(name: string): string | null {
- const withoutPrefix = name.replace(/^session\./, '');
- if (withoutPrefix === 'is_bounce') return 'is_bounce';
- if (SESSION_NUMERIC_COLUMNS.has(withoutPrefix)) return withoutPrefix;
- // performed_event is handled as a subselect, not a column
- return null;
-}
-
-function buildCohortClause(
- filter: IChartEventFilter,
- projectId: string,
- ctx: FilterTableContext,
-): string | null {
- // `getCohortIds` normalizes the legacy single-value `cohortId` field and
- // the newer `cohortIds` array into one list. Falls back to extracting the
- // id from the `cohort:<id>` filter name when neither is set (older URL
- // formats encoded the id only in the name).
- let cohortIds = getCohortIds(filter);
- if (cohortIds.length === 0 && filter.name.startsWith('cohort:')) {
- cohortIds = [filter.name.slice('cohort:'.length)];
- }
- if (cohortIds.length === 0) return null;
- const negate = filter.operator === 'notInCohort';
- const op = negate ? 'NOT IN' : 'IN';
- const escapedIds = cohortIds.map((id) => sqlstring.escape(id)).join(', ');
- return `${ctx.profileIdExpr} ${op} (SELECT profile_id FROM ${TABLE_NAMES.cohort_members} FINAL WHERE cohort_id IN (${escapedIds}) AND project_id = ${sqlstring.escape(projectId)})`;
-}
-
-function buildGroupClause(
- filter: IChartEventFilter,
- projectId: string,
- ctx: FilterTableContext,
-): string | null {
- if (!ctx.groupsExpr) return null;
- const column = groupColumnSql(filter.name);
- const inner = compileScalarClause(column, filter.operator, filter.value, {
- type: filter.type,
- });
- if (!inner) return null;
- const projectClause = `project_id = ${sqlstring.escape(projectId)}`;
- return `arrayExists(g -> g IN (SELECT id FROM ${TABLE_NAMES.groups} FINAL WHERE ${projectClause} AND ${inner}), ${ctx.groupsExpr})`;
-}
-
-function buildProfileClause(
- filter: IChartEventFilter,
- projectId: string,
- ctx: FilterTableContext,
-): string | null {
- const column = profileColumnSql(filter.name);
- if (!column) return null;
- const numeric = column === 'created_at' || column === 'last_seen_at';
- const inner = compileScalarClause(column, filter.operator, filter.value, {
- numeric,
- type: filter.type,
- });
- if (!inner) return null;
- if (ctx.selfTable === 'profiles') {
- return inner;
- }
- return `${ctx.profileIdExpr} IN (SELECT id FROM ${TABLE_NAMES.profiles} FINAL WHERE project_id = ${sqlstring.escape(projectId)} AND ${inner})`;
-}
-
-function buildSessionClause(
- filter: IChartEventFilter,
- projectId: string,
- ctx: FilterTableContext,
-): string | null {
- if (ctx.selfTable !== 'sessions') return null;
- const fieldName = filter.name.replace(/^session\./, '');
-
- if (fieldName === 'performed_event') {
- if (filter.value.length === 0) return null;
- const inClause =
- filter.value.length === 1
- ? `= ${escape(filter.value[0]!)}`
- : `IN (${filter.value.map(escape).join(', ')})`;
- const op = filter.operator === 'isNot' ? 'NOT IN' : 'IN';
- const dateScope: string[] = [];
- if (ctx.startDate && ctx.endDate) {
- dateScope.push(
- `toDate(created_at) BETWEEN toDate('${formatClickhouseDate(ctx.startDate)}') AND toDate('${formatClickhouseDate(ctx.endDate)}')`,
- );
- }
- const scopeSql = dateScope.length ? `AND ${dateScope.join(' AND ')} ` : '';
- return `id ${op} (SELECT DISTINCT session_id FROM ${TABLE_NAMES.events} WHERE project_id = ${sqlstring.escape(projectId)} ${scopeSql}AND name ${inClause})`;
- }
-
- if (fieldName === 'is_bounce') {
- if (filter.value.length === 0) return null;
- const wants = filter.value.some((v) =>
- typeof v === 'boolean' ? v : String(v).toLowerCase() === 'true',
- );
- const truthy = filter.operator === 'isNot' ? !wants : wants;
- return `is_bounce = ${truthy ? 1 : 0}`;
- }
-
- const column = sessionColumnSql(filter.name);
- if (!column) return null;
- return compileScalarClause(column, filter.operator, filter.value, {
- numeric: SESSION_NUMERIC_COLUMNS.has(column),
- type: filter.type,
- });
-}
-
-/**
- * Translate `IChartEventFilter[]` into a WHERE-clause record suitable for
- * merging into `createSqlBuilder().sb.where`. Handles cohort / group / profile
- * / session prefixes. Event-property (`properties.*`) filters are ignored on
- * non-events tables — they require a subquery on the events table that is
- * better expressed as a cohort.
- */
-export function buildFilterWhere(
- filters: IChartEventFilter[],
- projectId: string,
- ctx: FilterTableContext,
-): Record<string, string> {
- const where: Record<string, string> = {};
- filters.forEach((filter, index) => {
- const id = `f${index}`;
- // Callers concatenate these fragments with AND and no grouping, so each
- // fragment is parenthesized here to keep a top-level OR inside it from
- // rebinding the surrounding conditions.
- const set = (clause: string | null) => {
- if (clause) where[id] = `(${clause})`;
- };
-
- if (filter.operator === 'inCohort' || filter.operator === 'notInCohort') {
- set(buildCohortClause(filter, projectId, ctx));
- return;
- }
-
- if (filter.name.startsWith('cohort:')) {
- set(buildCohortClause(filter, projectId, ctx));
- return;
- }
-
- if (filter.name.startsWith('group.')) {
- set(buildGroupClause(filter, projectId, ctx));
- return;
- }
-
- if (filter.name.startsWith('profile.')) {
- set(buildProfileClause(filter, projectId, ctx));
- return;
- }
-
- if (filter.name.startsWith('session.')) {
- set(buildSessionClause(filter, projectId, ctx));
- return;
- }
-
- // properties.* filters only make sense on the events table; ignore on
- // sessions/profiles queries. Callers that need them should query the
- // events table directly (e.g. via getEventList) or use a cohort.
- });
- return where;
-}
+// The sessions/profiles/events-table filter compiler lives in @openpanel/core
+// now (M8-005): packages/core/src/modules/chart/src/table-filter-where.ts.
+// Re-exported here for existing `@openpanel/db` importers — same shape as
+// packages/db/src/services/chart.service.ts since M7-003.
+export type { FilterTableContext } from '@openpanel/core';
+export { buildFilterWhere } from '@openpanel/core';
diff --git a/packages/db/src/services/id.service.ts b/packages/db/src/services/id.service.ts
index 3060532c8..09adf6e65 100644
--- a/packages/db/src/services/id.service.ts
+++ b/packages/db/src/services/id.service.ts
@@ -1,38 +1,6 @@
-import { slug } from '@openpanel/common';
-
-import { db } from '../prisma-client';
-
-export async function getId(
- tableName: 'project' | 'dashboard' | 'organization',
- name: string,
-) {
- const newId = slug(name);
- if (!db[tableName]) {
- throw new Error('Table does not exists');
- }
-
- if (!('findUnique' in db[tableName])) {
- throw new Error('findUnique does not exists');
- }
-
- // @ts-expect-error
- const existingProject = await db[tableName].findUnique({
- where: {
- id: newId,
- },
- });
-
- function random(str: string) {
- const numbers = Math.floor(1000 + Math.random() * 9000);
- if (str.match(/-\d{4}$/g)) {
- return str.replace(/-\d{4}$/g, `-${numbers}`);
- }
- return `${str}-${numbers}`;
- }
-
- if (existingProject) {
- return getId(tableName, random(name));
- }
-
- return newId;
-}
+// Slug-based id generation lives in @openpanel/core now (M8-005):
+// packages/core/src/shared/slug-id.ts. Re-exported here for existing
+// `@openpanel/db` importers (core's dashboard/project/onboarding services,
+// which deep-import this exact specifier via dynamic import) — same shape as
+// event.service.ts since M7-002.
+export { getId } from '@openpanel/core';
diff --git a/packages/db/src/services/lookback.test.ts b/packages/db/src/services/lookback.test.ts
deleted file mode 100644
index d0c96890a..000000000
--- a/packages/db/src/services/lookback.test.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-import { afterEach, describe, expect, it, vi } from 'vitest';
-import { resolveMaxLookbackDays } from './lookback';
-
-describe('resolveMaxLookbackDays', () => {
- afterEach(() => {
- vi.unstubAllEnvs();
- });
-
- it('returns the caller default when unset', () => {
- vi.stubEnv('EVENT_LIST_MAX_LOOKBACK_DAYS', '');
- expect(resolveMaxLookbackDays('EVENT_LIST_MAX_LOOKBACK_DAYS', 365 * 5)).toBe(
- 365 * 5,
- );
- expect(resolveMaxLookbackDays('SESSION_LIST_MAX_LOOKBACK_DAYS', 365)).toBe(
- 365,
- );
- });
-
- it('replaces the ceiling when set to a positive integer', () => {
- vi.stubEnv('EVENT_LIST_MAX_LOOKBACK_DAYS', '7');
- expect(resolveMaxLookbackDays('EVENT_LIST_MAX_LOOKBACK_DAYS', 365 * 5)).toBe(
- 7,
- );
- // Raising past the default is allowed too — it's a ceiling, not a min.
- vi.stubEnv('SESSION_LIST_MAX_LOOKBACK_DAYS', '3650');
- expect(resolveMaxLookbackDays('SESSION_LIST_MAX_LOOKBACK_DAYS', 365)).toBe(
- 3650,
- );
- });
-
- it('reads each list its own variable — no cross-talk', () => {
- vi.stubEnv('EVENT_LIST_MAX_LOOKBACK_DAYS', '7');
- expect(resolveMaxLookbackDays('SESSION_LIST_MAX_LOOKBACK_DAYS', 365)).toBe(
- 365,
- );
- });
-
- it('falls back to the default for malformed values', () => {
- for (const bad of ['0', '-1', '7.5', '7days', 'junk']) {
- vi.stubEnv('EVENT_LIST_MAX_LOOKBACK_DAYS', bad);
- expect(
- resolveMaxLookbackDays('EVENT_LIST_MAX_LOOKBACK_DAYS', 365),
- ).toBe(365);
- }
- });
-});
diff --git a/packages/db/src/services/lookback.ts b/packages/db/src/services/lookback.ts
index 970ba9fc3..f0ebd096e 100644
--- a/packages/db/src/services/lookback.ts
+++ b/packages/db/src/services/lookback.ts
@@ -1,30 +1,6 @@
-/**
- * Ceiling (in days) for the empty-result lookback expansion on the event and
- * session lists.
- *
- * When a cursor window matches nothing, those lists double the window and
- * retry until the ceiling is reached. The doubling geometry keeps the total
- * cost at roughly 2x the final window, so the ceiling is what actually
- * bounds the worst case: with a filter no index can prune (e.g. a
- * properties value) that matches nothing at all, every step is a full scan
- * of its window, and a multi-year ceiling turns one page view into minutes
- * of scanning.
- *
- * Each list has its own variable (EVENT_LIST_MAX_LOOKBACK_DAYS,
- * SESSION_LIST_MAX_LOOKBACK_DAYS) because their built-in ceilings differ —
- * the surfaces have different cost profiles and a shared knob would couple
- * them. Values are human-sized day counts (1 / 7 / 365 / ...); unset or
- * invalid (non-integer, zero, negative) keeps the caller's default, so
- * behavior is unchanged unless a variable is set.
- */
-export function resolveMaxLookbackDays(
- envName: string,
- defaultDays: number
-): number {
- const raw = process.env[envName];
- if (!raw || !/^\d+$/.test(raw)) {
- return defaultDays;
- }
- const parsed = Number(raw);
- return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : defaultDays;
-}
+// The lookback ceiling lives in @openpanel/core now (M8-005):
+// packages/core/src/shared/lookback.ts. Re-exported here for existing
+// `@openpanel/db` importers (core's event/session services, which
+// dynamic-import this exact specifier to keep one dynamic edge per import
+// cycle) — same shape as event.service.ts since M7-002.
+export { resolveMaxLookbackDays } from '@openpanel/core';
diff --git a/packages/db/src/services/registration.service.ts b/packages/db/src/services/registration.service.ts
index 434254a0e..40a31a88a 100644
--- a/packages/db/src/services/registration.service.ts
+++ b/packages/db/src/services/registration.service.ts
@@ -1,41 +1,6 @@
-import { db } from '../prisma-client';
-
-/**
- * Whether a *new* user may be created right now.
- *
- * This must only be consulted at the point where we know the account does not
- * exist yet. Calling it before an identity is known (e.g. when kicking off an
- * OAuth redirect) would reject returning users too, since we cannot tell a
- * sign-in from a sign-up at that stage.
- */
-export async function getIsRegistrationAllowed(inviteId?: string | null) {
- // ALLOW_REGISTRATION is always undefined in cloud
- if (process.env.ALLOW_REGISTRATION === undefined) {
- return true;
- }
-
- // Self-hosting logic
- // 1. First user is always allowed
- const count = await db.user.count();
- if (count === 0) {
- return true;
- }
-
- // 2. If there is an invite, check if it is valid
- if (inviteId) {
- if (process.env.ALLOW_INVITATION === 'false') {
- return false;
- }
-
- const invite = await db.invite.findUnique({
- where: {
- id: inviteId,
- },
- });
-
- return !!invite;
- }
-
- // 3. Otherwise, check if general registration is allowed
- return process.env.ALLOW_REGISTRATION !== 'false';
-}
+// Registration-allowed policy lives in @openpanel/core now (M8-005):
+// packages/core/src/modules/auth/src/registration.ts. Re-exported here for
+// existing `@openpanel/db` importers (core's auth.service.ts, which
+// dynamic-imports this exact specifier to keep one dynamic edge per import
+// cycle) — same shape as event.service.ts since M7-002.
+export { getIsRegistrationAllowed } from '@openpanel/core';
diff --git a/packages/sdks/sdk/src/index.ts b/packages/sdks/sdk/src/index.ts
index 896dc1b74..c08f700b7 100644
--- a/packages/sdks/sdk/src/index.ts
+++ b/packages/sdks/sdk/src/index.ts
@@ -1,30 +1,86 @@
-// Deep-imported on purpose: rollup-plugin-dts (used by tsup) only inlines
-// types when the import resolves to a single source file. Importing from
-// the package root ('@openpanel/validation') leaves an external reference
-// in dist/index.d.ts, and `@openpanel/validation` is not published so
-// consumers would see a broken import. We tested tsdown too; it hits the
-// same limitation via rolldown-plugin-dts (Oxc/tsc both fail to follow
-// `export *` chains across source-only workspace packages).
-import type {
- IAliasPayload,
- IAssignGroupPayload,
- IDecrementPayload,
- IGroupPayload,
- IIdentifyPayload,
- IIncrementPayload,
- ITrackHandlerPayload,
- ITrackPayload,
-} from '@openpanel/validation/src/track.validation';
+// Hand-duplicated on purpose, not imported: the wire contract's source of
+// truth is @openpanel/core/modules/ingest/ingest.constants.ts (ADR-008,
+// "ingest owns C"), but core's package.json exports map is deliberately
+// narrow (no `./*` wildcard — see packages/core/AGENTS.md) and
+// rollup-plugin-dts (tsup's dts bundler) cannot inline a type that resolves
+// through that map's `*` pattern: it leaves an unresolvable
+// `@openpanel/core/...` reference in dist/index.d.ts, which breaks for every
+// consumer since core isn't published. A plain deep import into
+// `@openpanel/validation` hits the same wall one hop later, since that
+// package now just re-exports core's. Keeping a literal copy here is what
+// keeps this package's shipped .d.ts self-contained. The SDK wire contract
+// tests (verification/contracts/sdk) exercise both sides at runtime, so a
+// drift shows up as a behavioral failure even without a type-level check.
import { Api } from './api';
-export type AliasPayload = IAliasPayload;
-export type AssignGroupPayload = IAssignGroupPayload;
-export type DecrementPayload = IDecrementPayload;
-export type GroupPayload = IGroupPayload;
-export type IdentifyPayload = IIdentifyPayload;
-export type IncrementPayload = IIncrementPayload;
-export type TrackHandlerPayload = ITrackHandlerPayload;
-export type TrackPayload = ITrackPayload;
+export type ProfileId = string | number;
+
+export interface AliasPayload {
+ profileId: ProfileId;
+ alias: string;
+}
+
+export interface AssignGroupPayload {
+ groupIds: string[];
+ profileId?: ProfileId;
+}
+
+export interface DecrementPayload {
+ profileId: ProfileId;
+ property: string;
+ value?: number;
+}
+
+export interface GroupPayload {
+ id: string;
+ type: string;
+ name: string;
+ properties?: Record<string, unknown>;
+}
+
+export interface IdentifyPayload {
+ profileId: ProfileId;
+ firstName?: string;
+ lastName?: string;
+ email?: string;
+ avatar?: string;
+ properties?: Record<string, unknown>;
+}
+
+export interface IncrementPayload {
+ profileId: ProfileId;
+ property: string;
+ value?: number;
+}
+
+export interface TrackPayload {
+ name: string;
+ properties?: Record<string, unknown>;
+ profileId?: ProfileId;
+ groups?: string[] | null;
+}
+
+export interface ReplayPayload {
+ chunk_index: number;
+ events_count: number;
+ is_full_snapshot: boolean;
+ started_at: string;
+ ended_at: string;
+ payload: string;
+ // Server-issued session id (from a prior /track response) the SDK echoes back,
+ // so the chunk is filed under the right session without device resolution.
+ sessionId?: string;
+}
+
+export type TrackHandlerPayload =
+ | { type: 'track'; payload: TrackPayload }
+ | { type: 'identify'; payload: IdentifyPayload }
+ | { type: 'increment'; payload: IncrementPayload }
+ | { type: 'decrement'; payload: DecrementPayload }
+ | { type: 'alias'; payload: AliasPayload }
+ | { type: 'replay'; payload: ReplayPayload }
+ | { type: 'group'; payload: GroupPayload }
+ | { type: 'assign_group'; payload: AssignGroupPayload };
export interface TrackProperties {
[key: string]: unknown;
@@ -174,7 +230,7 @@ export class OpenPanel {
identify(payload: IdentifyPayload) {
this.log('identify user', payload);
if (payload.profileId) {
- this.profileId = payload.profileId
+ this.profileId = payload.profileId;
this.flush();
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 4819409cc..406021958 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1166,6 +1166,9 @@ importers:
ipaddr.js:
specifier: ^2.5.0
version: 2.5.0
+ jiti:
+ specifier: ^2.4.1
+ version: 2.6.1
js-yaml:
specifier: ^4.1.0
version: 4.1.1