A modern and elegant dashboard for network traffic visualization and analysis.
feat: Implement ClickHouse integration for statistics storage, including migration and comparison tools.
luoleia234b992e210
diff --git a/.gitignore b/.gitignoreindex bcaed76..06a5c6e 100644--- a/.gitignore+++ b/.gitignore@@ -24,6 +24,7 @@ out/*.sqlite*.sqlite3geoip/+data/# Logslogs/diff --git a/README.en.md b/README.en.mdindex 3023445..857cffe 100644--- a/README.en.md+++ b/README.en.md@@ -598,6 +598,36 @@ If you forgot the token, temporarily set `FORCE_ACCESS_CONTROL_OFF=true` to ente3. Reset token, then remove this flag and restart normally.+### ClickHouse Migration (Docker Users)++If you want to migrate stats from SQLite to ClickHouse (while keeping control/config in SQLite), use the one-command helper:++```bash+./scripts/ch-migrate-docker.sh+```++The script automatically:++1. Starts services with the `clickhouse` profile+2. Migrates SQLite stats into ClickHouse+3. Verifies SQLite vs ClickHouse consistency (default threshold: 1%)++Common options:++```bash+# Append import without truncating CH tables+./scripts/ch-migrate-docker.sh --append++# Migrate a specific time window+./scripts/ch-migrate-docker.sh --from 2026-02-01T00:00:00Z --to 2026-02-20T00:00:00Z+```++After migration, set `STATS_QUERY_SOURCE=auto` and restart:++```bash+docker compose up -d+```+## ❓ FAQ### Q: Can I run normally with only `3000:3000` exposed?diff --git a/README.md b/README.mdindex e6ad819..b166741 100644--- a/README.md+++ b/README.md@@ -590,6 +590,36 @@ COOKIE_SECRET=<至少32字节随机字符串>3. 重置密码后,再次停止容器,去除该参数并重启,恢复正常保护模式。+### ClickHouse 迁移(Docker 用户)++如果你准备从 SQLite 统计迁移到 ClickHouse(保留配置仍在 SQLite),推荐直接使用一键脚本:++```bash+./scripts/ch-migrate-docker.sh+```++脚本会自动执行:++1. 启动 `clickhouse` profile 容器+2. 迁移 SQLite 数据到 ClickHouse+3. 对账验证(默认阈值 1%)++常用参数:++```bash+# 不清空 CH 历史数据,做追加导入+./scripts/ch-migrate-docker.sh --append++# 指定时间窗口迁移+./scripts/ch-migrate-docker.sh --from 2026-02-01T00:00:00Z --to 2026-02-20T00:00:00Z+```++迁移完成后,建议将 `STATS_QUERY_SOURCE=auto` 并重启:++```bash+docker compose up -d+```+## ❓ 常见问题### Q: 只映射 `3000:3000` 可以正常使用吗?diff --git a/apps/collector/package.json b/apps/collector/package.jsonindex 0eca181..a851a23 100644--- a/apps/collector/package.json+++ b/apps/collector/package.json@@ -6,6 +6,8 @@"dev": "tsx watch src/index.ts","build": "tsc","start": "node dist/index.js",+ "migrate:sqlite-to-ch": "tsx src/scripts/migrate-sqlite-to-clickhouse.ts",+ "verify:sqlite-vs-ch": "tsx src/scripts/verify-sqlite-clickhouse.ts","lint": "eslint src/","test": "vitest run","test:watch": "vitest"diff --git a/apps/collector/src/app.ts b/apps/collector/src/app.tsindex a35b9cc..df9f7f9 100644--- a/apps/collector/src/app.ts+++ b/apps/collector/src/app.ts@@ -132,6 +132,46 @@ export async function createApp(options: AppOptions) {return buildGatewayHeaders(backend);};+ const parseNonNegativeInt = (value: unknown): number | null => {+ const parsed = Number.parseInt(String(value), 10);+ if (!Number.isFinite(parsed) || parsed < 0) return null;+ return parsed;+ };++ const loadRuleSetSizeByProvider = async (+ gatewayBaseUrl: string,+ headers: Record<string, string>,+ ): Promise<Map<string, number>> => {+ const map = new Map<string, number>();+ try {+ const res = await fetch(`${gatewayBaseUrl}/providers/rules`, {+ headers: { ...headers, 'Content-Type': 'application/json' },+ signal: AbortSignal.timeout(5000),+ });+ if (!res.ok) {+ return map;+ }++ const payload = (await res.json()) as {+ providers?: Record<string, Record<string, unknown>>;+ };+ const providers = payload.providers || {};+ for (const [name, data] of Object.entries(providers)) {+ const ruleCount =+ parseNonNegativeInt(data.ruleCount) ??+ parseNonNegativeInt(data.rule_count) ??+ parseNonNegativeInt(data.size) ??+ parseNonNegativeInt(data.rules);+ if (ruleCount !== null) {+ map.set(name.toLowerCase(), ruleCount);+ }+ }+ } catch {+ // Best-effort enrichment only; ignore provider endpoint failures.+ }+ return map;+ };+const parseAgentToken = (request: { headers: Record<string, unknown> }): string => {const authHeader = request.headers.authorization;if (typeof authHeader === 'string' && authHeader.startsWith('Bearer ')) {@@ -756,7 +796,44 @@ export async function createApp(options: AppOptions) {if (!res.ok) {return reply.status(res.status).send({ error: `Gateway API error: ${res.status}` });}- return res.json();+ const data = (await res.json()) as {+ rules?: Array<Record<string, unknown>>;+ [key: string]: unknown;+ };++ const rules = Array.isArray(data.rules) ? data.rules : [];+ if (rules.length === 0) {+ return data;+ }++ const providerSizeMap = await loadRuleSetSizeByProvider(gatewayBaseUrl, headers);+ if (providerSizeMap.size === 0) {+ return data;+ }++ const enrichedRules = rules.map((rule) => {+ const type = String(rule.type || '');+ const payload = String(rule.payload || '').toLowerCase();+ const size = parseNonNegativeInt(rule.size);+ if (type !== 'RuleSet' || size !== null || !payload) {+ return rule;+ }++ const enrichedSize = providerSizeMap.get(payload);+ if (enrichedSize === undefined) {+ return rule;+ }++ return {+ ...rule,+ size: enrichedSize,+ };+ });++ return {+ ...data,+ rules: enrichedRules,+ };}} catch (error: unknown) {const message = error instanceof Error ? error.message : 'Failed to reach Gateway API';diff --git a/apps/collector/src/batch-buffer.ts b/apps/collector/src/batch-buffer.tsindex a52e42e..57b1fa2 100644--- a/apps/collector/src/batch-buffer.ts+++ b/apps/collector/src/batch-buffer.ts@@ -6,6 +6,7 @@*/import type { StatsDatabase } from "./db.js";import type { GeoIPService } from "./geo-service.js";+import { getClickHouseWriter } from "./clickhouse-writer.js";export interface TrafficUpdate {domain: string;@@ -96,6 +97,7 @@ export class BatchBuffer {backendId: number,logPrefix = "Collector",): FlushResult {+ const clickHouseWriter = getClickHouseWriter();const updates = Array.from(this.buffer.values());const geoResults = [...this.geoQueue];@@ -118,6 +120,9 @@ export class BatchBuffer {if (updates.length > 0) {try {db.batchUpdateTrafficStats(backendId, updates);+ if (clickHouseWriter.isEnabled()) {+ clickHouseWriter.writeTrafficBatch(backendId, updates);+ }} catch (err) {trafficOk = false;console.error(`[${logPrefix}:${backendId}] Batch write failed:`, err);@@ -144,6 +149,9 @@ export class BatchBuffer {timestampMs: r.timestampMs,}));db.batchUpdateCountryStats(backendId, countryUpdates);+ if (clickHouseWriter.isEnabled()) {+ clickHouseWriter.writeCountryBatch(backendId, countryUpdates);+ }} catch (err) {countryOk = false;console.error(diff --git a/apps/collector/src/clickhouse-compare.ts b/apps/collector/src/clickhouse-compare.tsnew file mode 100644index 0000000..0889003--- /dev/null+++ b/apps/collector/src/clickhouse-compare.ts@@ -0,0 +1,138 @@+import type { StatsDatabase } from './db.js';+import { loadClickHouseConfig } from './clickhouse.js';++export class ClickHouseCompareService {+ private readonly config = loadClickHouseConfig();+ private timer: NodeJS.Timeout | null = null;+ private readonly enabled =+ this.config.enabled && process.env.CH_COMPARE_ENABLED === '1';+ private readonly intervalMs = Math.max(+ 30_000,+ Number.parseInt(process.env.CH_COMPARE_INTERVAL_MS || '120000', 10) || 120_000,+ );+ private readonly windowMinutes = Math.max(+ 1,+ Number.parseInt(process.env.CH_COMPARE_WINDOW_MINUTES || '10', 10) || 10,+ );+ private readonly timeoutMs = Math.max(+ 1000,+ Number.parseInt(process.env.CH_COMPARE_TIMEOUT_MS || '8000', 10) || 8000,+ );+ private readonly startDelayMs = Math.max(+ 0,+ Number.parseInt(process.env.CH_COMPARE_START_DELAY_MS || '120000', 10) || 120_000,+ );+ private startedAt = Date.now();++ constructor(private readonly db: StatsDatabase) {}++ start(): void {+ if (!this.enabled) {+ return;+ }+ if (this.timer) return;++ console.info(+ `[ClickHouse Compare] Started interval=${this.intervalMs}ms window=${this.windowMinutes}m start_delay=${this.startDelayMs}ms`,+ );+ void this.runOnce();+ this.timer = setInterval(() => {+ void this.runOnce();+ }, this.intervalMs);+ }++ stop(): void {+ if (this.timer) {+ clearInterval(this.timer);+ this.timer = null;+ console.info('[ClickHouse Compare] Stopped');+ }+ }++ private async runOnce(): Promise<void> {+ if (Date.now() - this.startedAt < this.startDelayMs) {+ return;+ }++ const backends = this.db+ .getListeningBackends()+ .filter((backend) => !backend.url.startsWith('agent://'));+ if (backends.length === 0) return;++ const end = new Date();+ const start = new Date(end.getTime() - this.windowMinutes * 60_000);+ const startIso = start.toISOString();+ const endIso = end.toISOString();++ for (const backend of backends) {+ try {+ const sqlite = this.db.getTrafficInRange(backend.id, startIso, endIso);+ const ch = await this.queryClickHouseTraffic(backend.id, start);++ const uploadDelta = this.ratioDelta(sqlite.upload, ch.upload);+ const downloadDelta = this.ratioDelta(sqlite.download, ch.download);++ console.info(+ `[ClickHouse Compare] backend=${backend.id} window=${this.windowMinutes}m sqlite_upload=${sqlite.upload} ch_upload=${ch.upload} upload_delta=${uploadDelta.toFixed(2)}% sqlite_download=${sqlite.download} ch_download=${ch.download} download_delta=${downloadDelta.toFixed(2)}%`,+ );+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ console.warn(`[ClickHouse Compare] backend=${backend.id} compare failed: ${message}`);+ }+ }+ }++ private async queryClickHouseTraffic(+ backendId: number,+ start: Date,+ ): Promise<{ upload: number; download: number }> {+ const baseUrl = `${this.config.protocol}://${this.config.host}:${this.config.port}`;+ const authHeader =+ this.config.password.length > 0+ ? `Basic ${Buffer.from(`${this.config.user}:${this.config.password}`).toString('base64')}`+ : '';+ const query = `+SELECT+ toUInt64(COALESCE(SUM(upload), 0)) as upload,+ toUInt64(COALESCE(SUM(download), 0)) as download+FROM ${this.config.database}.traffic_minute+WHERE backend_id = ${backendId}+ AND minute >= toDateTime('${this.toClickHouseDateTime(start)}')+FORMAT JSON+`;++ const response = await fetch(+ `${baseUrl}/?database=${encodeURIComponent(this.config.database)}&query=${encodeURIComponent(query)}`,+ {+ method: 'POST',+ headers: {+ ...(authHeader ? { Authorization: authHeader } : {}),+ },+ signal: AbortSignal.timeout(this.timeoutMs),+ },+ );+ if (!response.ok) {+ const body = await response.text();+ throw new Error(`status=${response.status} body=${body.slice(0, 160)}`);+ }+ const json = (await response.json()) as {+ data?: Array<{ upload: number; download: number }>;+ };+ const row = json.data?.[0] || { upload: 0, download: 0 };+ return {+ upload: Number(row.upload || 0),+ download: Number(row.download || 0),+ };+ }++ private ratioDelta(a: number, b: number): number {+ if (a === 0 && b === 0) return 0;+ const denom = Math.max(1, Math.abs(a));+ return ((b - a) / denom) * 100;+ }++ private toClickHouseDateTime(value: Date): string {+ const iso = value.toISOString();+ return `${iso.slice(0, 19).replace('T', ' ')}`;+ }+}diff --git a/apps/collector/src/clickhouse-reader.ts b/apps/collector/src/clickhouse-reader.tsnew file mode 100644index 0000000..c119967--- /dev/null+++ b/apps/collector/src/clickhouse-reader.ts@@ -0,0 +1,688 @@+import type { DomainStats, HourlyStats, IPStats } from '@neko-master/shared';+import { loadClickHouseConfig } from './clickhouse.js';++type StatsQuerySource = 'sqlite' | 'clickhouse' | 'auto';++export type ClickHouseSummary = {+ totalConnections: number;+ totalUpload: number;+ totalDownload: number;+ uniqueDomains: number;+ uniqueIPs: number;+};++export class ClickHouseReader {+ private readonly config = loadClickHouseConfig();+ private readonly source = this.parseSource(process.env.STATS_QUERY_SOURCE);++ shouldUseForRange(start?: string, end?: string): boolean {+ if (!this.config.enabled) return false;+ if (this.source === 'sqlite') return false;+ if (!start || !end) return false;+ const startMs = new Date(start).getTime();+ const endMs = new Date(end).getTime();+ return Number.isFinite(startMs) && Number.isFinite(endMs) && startMs <= endMs;+ }++ async getSummary(+ backendId: number,+ start: string,+ end: string,+ ): Promise<ClickHouseSummary | null> {+ const rows = await this.query<ClickHouseSummary>(`+SELECT+ toUInt64(COALESCE(SUM(connections), 0)) AS totalConnections,+ toUInt64(COALESCE(SUM(upload), 0)) AS totalUpload,+ toUInt64(COALESCE(SUM(download), 0)) AS totalDownload,+ toUInt64(uniqExactIf(domain, domain != '')) AS uniqueDomains,+ toUInt64(uniqExactIf(ip, ip != '')) AS uniqueIPs+FROM ${this.config.database}.traffic_minute+WHERE backend_id = ${backendId}+ AND minute >= toDateTime('${this.toDateTime(start)}')+ AND minute <= toDateTime('${this.toDateTime(end)}')+`);+ return rows?.[0] || null;+ }++ async getTopDomainsLight(+ backendId: number,+ limit: number,+ start: string,+ end: string,+ ): Promise<DomainStats[] | null> {+ const rows = await this.query<Record<string, unknown>>(`+SELECT+ domain,+ toUInt64(SUM(upload)) AS totalUpload,+ toUInt64(SUM(download)) AS totalDownload,+ toUInt64(SUM(connections)) AS totalConnections,+ toString(max(minute)) AS lastSeen+FROM ${this.config.database}.traffic_minute+WHERE backend_id = ${backendId}+ AND minute >= toDateTime('${this.toDateTime(start)}')+ AND minute <= toDateTime('${this.toDateTime(end)}')+ AND domain != ''+GROUP BY domain+ORDER BY (SUM(upload) + SUM(download)) DESC+LIMIT ${Math.max(1, limit)}+`);+ if (!rows) return null;+ return (rows as Array<any>).map((row) => ({+ domain: String(row.domain || ''),+ totalUpload: Number(row.totalUpload || 0),+ totalDownload: Number(row.totalDownload || 0),+ totalConnections: Number(row.totalConnections || 0),+ lastSeen: String(row.lastSeen || ''),+ ips: [],+ rules: [],+ chains: [],+ }));+ }++ async getTopIPsLight(+ backendId: number,+ limit: number,+ start: string,+ end: string,+ ): Promise<IPStats[] | null> {+ const rows = await this.query<Record<string, unknown>>(`+SELECT+ ip,+ toUInt64(SUM(upload)) AS totalUpload,+ toUInt64(SUM(download)) AS totalDownload,+ toUInt64(SUM(connections)) AS totalConnections,+ toString(max(minute)) AS lastSeen+FROM ${this.config.database}.traffic_minute+WHERE backend_id = ${backendId}+ AND minute >= toDateTime('${this.toDateTime(start)}')+ AND minute <= toDateTime('${this.toDateTime(end)}')+ AND ip != ''+GROUP BY ip+ORDER BY (SUM(upload) + SUM(download)) DESC+LIMIT ${Math.max(1, limit)}+`);+ if (!rows) return null;+ return (rows as Array<any>).map((row) => ({+ ip: String(row.ip || ''),+ totalUpload: Number(row.totalUpload || 0),+ totalDownload: Number(row.totalDownload || 0),+ totalConnections: Number(row.totalConnections || 0),+ lastSeen: String(row.lastSeen || ''),+ domains: [],+ chains: [],+ }));+ }++ async getHourlyStats(+ backendId: number,+ hours: number,+ start: string,+ end: string,+ ): Promise<HourlyStats[] | null> {+ const rows = await this.query<Record<string, unknown>>(`+SELECT+ toString(toStartOfHour(minute)) AS hour,+ toUInt64(SUM(upload)) AS upload,+ toUInt64(SUM(download)) AS download,+ toUInt64(SUM(connections)) AS connections+FROM ${this.config.database}.traffic_minute+WHERE backend_id = ${backendId}+ AND minute >= toDateTime('${this.toDateTime(start)}')+ AND minute <= toDateTime('${this.toDateTime(end)}')+GROUP BY hour+ORDER BY hour DESC+LIMIT ${Math.max(1, hours)}+`);+ if (!rows) return null;+ return (rows as Array<any>).map((row) => ({+ hour: String(row.hour || ''),+ upload: Number(row.upload || 0),+ download: Number(row.download || 0),+ connections: Number(row.connections || 0),+ }));+ }++ async getCountryStats(+ backendId: number,+ limit: number,+ start: string,+ end: string,+ ): Promise<+ Array<{+ country: string;+ countryName: string;+ continent: string;+ totalUpload: number;+ totalDownload: number;+ totalConnections: number;+ }> | null+ > {+ const rows = await this.query<Record<string, unknown>>(`+SELECT+ country,+ any(country_name) AS countryName,+ any(continent) AS continent,+ toUInt64(SUM(upload)) AS totalUpload,+ toUInt64(SUM(download)) AS totalDownload,+ toUInt64(SUM(connections)) AS totalConnections+FROM ${this.config.database}.country_minute+WHERE backend_id = ${backendId}+ AND minute >= toDateTime('${this.toDateTime(start)}')+ AND minute <= toDateTime('${this.toDateTime(end)}')+GROUP BY country+ORDER BY (SUM(upload) + SUM(download)) DESC+LIMIT ${Math.max(1, limit)}+`);+ if (!rows) return null;+ return (rows as Array<any>).map((row) => ({+ country: String(row.country || 'UNKNOWN'),+ countryName: String(row.countryName || row.country || 'Unknown'),+ continent: String(row.continent || 'Unknown'),+ totalUpload: Number(row.totalUpload || 0),+ totalDownload: Number(row.totalDownload || 0),+ totalConnections: Number(row.totalConnections || 0),+ }));+ }++ async getTrafficInRange(+ backendId: number,+ start: string,+ end: string,+ ): Promise<{ upload: number; download: number } | null> {+ const rows = await this.query<Record<string, unknown>>(`+SELECT+ toUInt64(COALESCE(SUM(upload), 0)) AS upload,+ toUInt64(COALESCE(SUM(download), 0)) AS download+FROM ${this.config.database}.traffic_minute+WHERE backend_id = ${backendId}+ AND minute >= toDateTime('${this.toDateTime(start)}')+ AND minute <= toDateTime('${this.toDateTime(end)}')+`);+ if (!rows || rows.length === 0) return null;+ const first = rows[0] as Record<string, unknown>;+ return {+ upload: Number(first.upload || 0),+ download: Number(first.download || 0),+ };+ }++ async getTrafficTrend(+ backendId: number,+ start: string,+ end: string,+ ): Promise<Array<{ time: string; upload: number; download: number }> | null> {+ const rows = await this.query<Record<string, unknown>>(`+SELECT+ toString(minute) AS time,+ toUInt64(SUM(upload)) AS upload,+ toUInt64(SUM(download)) AS download+FROM ${this.config.database}.traffic_minute+WHERE backend_id = ${backendId}+ AND minute >= toDateTime('${this.toDateTime(start)}')+ AND minute <= toDateTime('${this.toDateTime(end)}')+GROUP BY minute+ORDER BY minute ASC+`);+ if (!rows) return null;+ return (rows as Array<any>).map((row) => ({+ time: String(row.time || ''),+ upload: Number(row.upload || 0),+ download: Number(row.download || 0),+ }));+ }++ async getTrafficTrendAggregated(+ backendId: number,+ bucketMinutes: number,+ start: string,+ end: string,+ ): Promise<Array<{ time: string; upload: number; download: number }> | null> {+ const safeBucket = Math.max(1, Math.floor(bucketMinutes));+ const bucketExpr =+ safeBucket <= 1+ ? 'minute'+ : `toStartOfInterval(minute, INTERVAL ${safeBucket} MINUTE)`;++ const rows = await this.query<Record<string, unknown>>(`+SELECT+ toString(${bucketExpr}) AS time,+ toUInt64(SUM(upload)) AS upload,+ toUInt64(SUM(download)) AS download+FROM ${this.config.database}.traffic_minute+WHERE backend_id = ${backendId}+ AND minute >= toDateTime('${this.toDateTime(start)}')+ AND minute <= toDateTime('${this.toDateTime(end)}')+GROUP BY time+ORDER BY time ASC+`);+ if (!rows) return null;+ return (rows as Array<any>).map((row) => ({+ time: String(row.time || ''),+ upload: Number(row.upload || 0),+ download: Number(row.download || 0),+ }));+ }++ async getDomainStatsPaginated(+ backendId: number,+ start: string,+ end: string,+ opts: {+ offset?: number;+ limit?: number;+ sortBy?: string;+ sortOrder?: string;+ search?: string;+ },+ ): Promise<{ data: DomainStats[]; total: number } | null> {+ const offset = Math.max(0, opts.offset || 0);+ const limit = Math.max(1, Math.min(200, opts.limit || 50));+ const sortOrder = opts.sortOrder === 'asc' ? 'ASC' : 'DESC';+ const sortExprMap: Record<string, string> = {+ domain: 'domain',+ totalUpload: 'totalUpload',+ totalDownload: 'totalDownload',+ totalTraffic: '(totalUpload + totalDownload)',+ totalConnections: 'totalConnections',+ lastSeen: 'lastSeen',+ };+ const sortExpr = sortExprMap[opts.sortBy || 'totalDownload'] || 'totalDownload';+ const searchClause = opts.search+ ? ` AND positionCaseInsensitive(domain, '${this.esc(opts.search)}') > 0`+ : '';++ const totalRows = await this.query<Record<string, unknown>>(`+SELECT toUInt64(COUNT()) AS total+FROM (+ SELECT domain+ FROM ${this.config.database}.traffic_minute+ WHERE backend_id = ${backendId}+ AND minute >= toDateTime('${this.toDateTime(start)}')+ AND minute <= toDateTime('${this.toDateTime(end)}')+ AND domain != '' ${searchClause}+ GROUP BY domain+)+`);++ const rows = await this.query<Record<string, unknown>>(`+SELECT+ domain,+ arrayDistinct(groupArrayIf(ip, ip != '')) AS ips,+ toUInt64(SUM(upload)) AS totalUpload,+ toUInt64(SUM(download)) AS totalDownload,+ toUInt64(SUM(connections)) AS totalConnections,+ toString(max(minute)) AS lastSeen,+ arrayDistinct(groupArrayIf(rule, rule != '')) AS rules,+ arrayDistinct(groupArrayIf(chain, chain != '')) AS chains+FROM ${this.config.database}.traffic_minute+WHERE backend_id = ${backendId}+ AND minute >= toDateTime('${this.toDateTime(start)}')+ AND minute <= toDateTime('${this.toDateTime(end)}')+ AND domain != '' ${searchClause}+GROUP BY domain+ORDER BY ${sortExpr} ${sortOrder}+LIMIT ${limit} OFFSET ${offset}+`);+ if (!rows || !totalRows) return null;++ const total = Number(totalRows[0]?.total || 0);+ const data = (rows as Array<any>).map((row) => ({+ domain: String(row.domain || ''),+ ips: Array.isArray(row.ips) ? row.ips.map(String) : [],+ totalUpload: Number(row.totalUpload || 0),+ totalDownload: Number(row.totalDownload || 0),+ totalConnections: Number(row.totalConnections || 0),+ lastSeen: String(row.lastSeen || ''),+ rules: Array.isArray(row.rules) ? row.rules.map(String) : [],+ chains: Array.isArray(row.chains) ? row.chains.map(String) : [],+ })) as DomainStats[];++ return { data, total };+ }++ async getIPStatsPaginated(+ backendId: number,+ start: string,+ end: string,+ opts: {+ offset?: number;+ limit?: number;+ sortBy?: string;+ sortOrder?: string;+ search?: string;+ },+ ): Promise<{ data: IPStats[]; total: number } | null> {+ const offset = Math.max(0, opts.offset || 0);+ const limit = Math.max(1, Math.min(200, opts.limit || 50));+ const sortOrder = opts.sortOrder === 'asc' ? 'ASC' : 'DESC';+ const sortExprMap: Record<string, string> = {+ ip: 'ip',+ totalUpload: 'totalUpload',+ totalDownload: 'totalDownload',+ totalTraffic: '(totalUpload + totalDownload)',+ totalConnections: 'totalConnections',+ lastSeen: 'lastSeen',+ };+ const sortExpr = sortExprMap[opts.sortBy || 'totalDownload'] || 'totalDownload';+ const searchClause = opts.search+ ? ` AND (positionCaseInsensitive(ip, '${this.esc(opts.search)}') > 0 OR positionCaseInsensitive(domain, '${this.esc(opts.search)}') > 0)`+ : '';++ const totalRows = await this.query<Record<string, unknown>>(`+SELECT toUInt64(COUNT()) AS total+FROM (+ SELECT ip+ FROM ${this.config.database}.traffic_minute+ WHERE backend_id = ${backendId}+ AND minute >= toDateTime('${this.toDateTime(start)}')+ AND minute <= toDateTime('${this.toDateTime(end)}')+ AND ip != '' ${searchClause}+ GROUP BY ip+)+`);++ const rows = await this.query<Record<string, unknown>>(`+SELECT+ ip,+ arrayDistinct(groupArrayIf(domain, domain != '')) AS domains,+ toUInt64(SUM(upload)) AS totalUpload,+ toUInt64(SUM(download)) AS totalDownload,+ toUInt64(SUM(connections)) AS totalConnections,+ toString(max(minute)) AS lastSeen,+ arrayDistinct(groupArrayIf(chain, chain != '')) AS chains+FROM ${this.config.database}.traffic_minute+WHERE backend_id = ${backendId}+ AND minute >= toDateTime('${this.toDateTime(start)}')+ AND minute <= toDateTime('${this.toDateTime(end)}')+ AND ip != '' ${searchClause}+GROUP BY ip+ORDER BY ${sortExpr} ${sortOrder}+LIMIT ${limit} OFFSET ${offset}+`);+ if (!rows || !totalRows) return null;++ const total = Number(totalRows[0]?.total || 0);+ const data = (rows as Array<any>).map((row) => ({+ ip: String(row.ip || ''),+ domains: Array.isArray(row.domains) ? row.domains.map(String) : [],+ totalUpload: Number(row.totalUpload || 0),+ totalDownload: Number(row.totalDownload || 0),+ totalConnections: Number(row.totalConnections || 0),+ lastSeen: String(row.lastSeen || ''),+ chains: Array.isArray(row.chains) ? row.chains.map(String) : [],+ })) as IPStats[];++ return { data, total };+ }++ async getProxyStats(backendId: number, start: string, end: string): Promise<any[] | null> {+ const rows = await this.query<any>(`+SELECT+ chain,+ toUInt64(SUM(upload)) AS totalUpload,+ toUInt64(SUM(download)) AS totalDownload,+ toUInt64(SUM(connections)) AS totalConnections,+ toString(max(minute)) AS lastSeen+FROM ${this.config.database}.traffic_minute+WHERE backend_id = ${backendId}+ AND minute >= toDateTime('${this.toDateTime(start)}')+ AND minute <= toDateTime('${this.toDateTime(end)}')+GROUP BY chain+ORDER BY (SUM(upload) + SUM(download)) DESC+`);+ if (!rows) return null;+ return rows.map((row: any) => ({+ chain: String(row.chain || ''),+ totalUpload: Number(row.totalUpload || 0),+ totalDownload: Number(row.totalDownload || 0),+ totalConnections: Number(row.totalConnections || 0),+ lastSeen: String(row.lastSeen || ''),+ }));+ }++ async getRuleStats(backendId: number, start: string, end: string): Promise<any[] | null> {+ const rows = await this.query<any>(`+SELECT+ rule,+ any(chain) AS finalProxy,+ toUInt64(SUM(upload)) AS totalUpload,+ toUInt64(SUM(download)) AS totalDownload,+ toUInt64(SUM(connections)) AS totalConnections,+ toString(max(minute)) AS lastSeen+FROM ${this.config.database}.traffic_minute+WHERE backend_id = ${backendId}+ AND minute >= toDateTime('${this.toDateTime(start)}')+ AND minute <= toDateTime('${this.toDateTime(end)}')+GROUP BY rule+ORDER BY (SUM(upload) + SUM(download)) DESC+`);+ if (!rows) return null;+ return rows.map((row: any) => ({+ rule: String(row.rule || ''),+ finalProxy: String(row.finalProxy || ''),+ totalUpload: Number(row.totalUpload || 0),+ totalDownload: Number(row.totalDownload || 0),+ totalConnections: Number(row.totalConnections || 0),+ lastSeen: String(row.lastSeen || ''),+ }));+ }++ async getDeviceStats(backendId: number, start: string, end: string, limit: number): Promise<any[] | null> {+ const rows = await this.query<any>(`+SELECT+ source_ip AS sourceIP,+ toUInt64(SUM(upload)) AS totalUpload,+ toUInt64(SUM(download)) AS totalDownload,+ toUInt64(SUM(connections)) AS totalConnections,+ toString(max(minute)) AS lastSeen+FROM ${this.config.database}.traffic_minute+WHERE backend_id = ${backendId}+ AND minute >= toDateTime('${this.toDateTime(start)}')+ AND minute <= toDateTime('${this.toDateTime(end)}')+ AND source_ip != ''+GROUP BY source_ip+ORDER BY (SUM(upload) + SUM(download)) DESC+LIMIT ${Math.max(1, limit)}+`);+ if (!rows) return null;+ return rows.map((row: any) => ({+ sourceIP: String(row.sourceIP || ''),+ totalUpload: Number(row.totalUpload || 0),+ totalDownload: Number(row.totalDownload || 0),+ totalConnections: Number(row.totalConnections || 0),+ lastSeen: String(row.lastSeen || ''),+ }));+ }++ async getGroupedDomains(+ backendId: number,+ start: string,+ end: string,+ limit: number,+ filters: {+ chain?: string;+ rule?: string;+ sourceIP?: string;+ domain?: string;+ ip?: string;+ },+ ): Promise<DomainStats[] | null> {+ const clauses = this.buildFilters(filters);+ const rows = await this.query<any>(`+SELECT+ domain,+ arrayDistinct(groupArrayIf(ip, ip != '')) AS ips,+ toUInt64(SUM(upload)) AS totalUpload,+ toUInt64(SUM(download)) AS totalDownload,+ toUInt64(SUM(connections)) AS totalConnections,+ toString(max(minute)) AS lastSeen,+ arrayDistinct(groupArrayIf(rule, rule != '')) AS rules,+ arrayDistinct(groupArrayIf(chain, chain != '')) AS chains+FROM ${this.config.database}.traffic_minute+WHERE backend_id = ${backendId}+ AND minute >= toDateTime('${this.toDateTime(start)}')+ AND minute <= toDateTime('${this.toDateTime(end)}')+ AND domain != '' ${clauses}+GROUP BY domain+ORDER BY (SUM(upload) + SUM(download)) DESC+LIMIT ${Math.max(1, limit)}+`);+ if (!rows) return null;+ return rows.map((row: any) => ({+ domain: String(row.domain || ''),+ ips: Array.isArray(row.ips) ? row.ips.map(String) : [],+ totalUpload: Number(row.totalUpload || 0),+ totalDownload: Number(row.totalDownload || 0),+ totalConnections: Number(row.totalConnections || 0),+ lastSeen: String(row.lastSeen || ''),+ rules: Array.isArray(row.rules) ? row.rules.map(String) : [],+ chains: Array.isArray(row.chains) ? row.chains.map(String) : [],+ }));+ }++ async getGroupedIPs(+ backendId: number,+ start: string,+ end: string,+ limit: number,+ filters: {+ chain?: string;+ rule?: string;+ sourceIP?: string;+ domain?: string;+ ip?: string;+ },+ ): Promise<IPStats[] | null> {+ const clauses = this.buildFilters(filters);+ const rows = await this.query<any>(`+SELECT+ ip,+ arrayDistinct(groupArrayIf(domain, domain != '')) AS domains,+ toUInt64(SUM(upload)) AS totalUpload,+ toUInt64(SUM(download)) AS totalDownload,+ toUInt64(SUM(connections)) AS totalConnections,+ toString(max(minute)) AS lastSeen,+ arrayDistinct(groupArrayIf(chain, chain != '')) AS chains+FROM ${this.config.database}.traffic_minute+WHERE backend_id = ${backendId}+ AND minute >= toDateTime('${this.toDateTime(start)}')+ AND minute <= toDateTime('${this.toDateTime(end)}')+ AND ip != '' ${clauses}+GROUP BY ip+ORDER BY (SUM(upload) + SUM(download)) DESC+LIMIT ${Math.max(1, limit)}+`);+ if (!rows) return null;+ return rows.map((row: any) => ({+ ip: String(row.ip || ''),+ domains: Array.isArray(row.domains) ? row.domains.map(String) : [],+ totalUpload: Number(row.totalUpload || 0),+ totalDownload: Number(row.totalDownload || 0),+ totalConnections: Number(row.totalConnections || 0),+ lastSeen: String(row.lastSeen || ''),+ chains: Array.isArray(row.chains) ? row.chains.map(String) : [],+ }));+ }++ async getGroupedProxyStats(+ backendId: number,+ start: string,+ end: string,+ filters: {+ chain?: string;+ rule?: string;+ sourceIP?: string;+ domain?: string;+ ip?: string;+ },+ ): Promise<any[] | null> {+ const clauses = this.buildFilters(filters);+ const rows = await this.query<any>(`+SELECT+ chain,+ toUInt64(SUM(upload)) AS totalUpload,+ toUInt64(SUM(download)) AS totalDownload,+ toUInt64(SUM(connections)) AS totalConnections+FROM ${this.config.database}.traffic_minute+WHERE backend_id = ${backendId}+ AND minute >= toDateTime('${this.toDateTime(start)}')+ AND minute <= toDateTime('${this.toDateTime(end)}')+ AND chain != '' ${clauses}+GROUP BY chain+ORDER BY (SUM(upload) + SUM(download)) DESC+`);+ if (!rows) return null;+ return rows.map((row: any) => ({+ chain: String(row.chain || ''),+ totalUpload: Number(row.totalUpload || 0),+ totalDownload: Number(row.totalDownload || 0),+ totalConnections: Number(row.totalConnections || 0),+ }));+ }++ private async query<T>(query: string): Promise<T[] | null> {+ if (!this.config.enabled) return null;+ const baseUrl = `${this.config.protocol}://${this.config.host}:${this.config.port}`;+ const authHeader =+ this.config.password.length > 0+ ? `Basic ${Buffer.from(`${this.config.user}:${this.config.password}`).toString('base64')}`+ : '';++ try {+ const response = await fetch(+ `${baseUrl}/?database=${encodeURIComponent(this.config.database)}&query=${encodeURIComponent(`${query}\nFORMAT JSON`)}`,+ {+ method: 'POST',+ headers: {+ ...(authHeader ? { Authorization: authHeader } : {}),+ },+ signal: AbortSignal.timeout(this.config.timeoutMs),+ },+ );+ if (!response.ok) {+ const body = await response.text();+ throw new Error(`status=${response.status} body=${body.slice(0, 160)}`);+ }+ const json = (await response.json()) as { data?: T[] };+ return json.data || [];+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ if (this.source === 'clickhouse') {+ throw new Error(`[ClickHouse Reader] strict mode query failed: ${message}`);+ }+ console.warn(`[ClickHouse Reader] query failed, fallback to sqlite: ${message}`);+ return null;+ }+ }++ private toDateTime(value: string): string {+ const date = new Date(value);+ if (Number.isNaN(date.getTime())) {+ return '1970-01-01 00:00:00';+ }+ return date.toISOString().slice(0, 19).replace('T', ' ');+ }++ private buildFilters(filters: Record<string, string | undefined>): string {+ const clauses: string[] = [];+ if (filters.chain) clauses.push(`chain = '${this.esc(filters.chain)}'`);+ if (filters.rule) clauses.push(`rule = '${this.esc(filters.rule)}'`);+ if (filters.sourceIP) clauses.push(`source_ip = '${this.esc(filters.sourceIP)}'`);+ if (filters.domain) clauses.push(`domain = '${this.esc(filters.domain)}'`);+ if (filters.ip) clauses.push(`ip = '${this.esc(filters.ip)}'`);+ if (clauses.length === 0) return '';+ return ` AND ${clauses.join(' AND ')}`;+ }++ private esc(value: string): string {+ return value.replace(/'/g, "''");+ }++ private parseSource(value: string | undefined): StatsQuerySource {+ const normalized = String(value || 'sqlite').trim().toLowerCase();+ if (normalized === 'clickhouse' || normalized === 'auto') {+ return normalized;+ }+ return 'sqlite';+ }+}diff --git a/apps/collector/src/clickhouse-writer.ts b/apps/collector/src/clickhouse-writer.tsnew file mode 100644index 0000000..b1e8b9e--- /dev/null+++ b/apps/collector/src/clickhouse-writer.ts@@ -0,0 +1,179 @@+import type { TrafficUpdate } from './batch-buffer.js';+import { loadClickHouseConfig } from './clickhouse.js';++interface CountryMinuteUpdate {+ country: string;+ countryName: string;+ continent: string;+ upload: number;+ download: number;+ timestampMs?: number;+}++class ClickHouseWriter {+ private readonly config = loadClickHouseConfig();+ private readonly writeEnabled =+ this.config.enabled && process.env.CH_WRITE_ENABLED === '1';+ private readonly metricsIntervalMs = Math.max(+ 1000,+ Number.parseInt(process.env.CH_METRICS_LOG_INTERVAL_MS || '60000', 10) || 60000,+ );+ private readonly maxPendingBatches = Math.max(+ 10,+ Number.parseInt(process.env.CH_WRITE_MAX_PENDING_BATCHES || '200', 10) || 200,+ );+ private writeChain: Promise<void> = Promise.resolve();+ private pendingBatches = 0;+ private metricsWindowStartedAt = Date.now();+ private metrics = {+ trafficBatches: 0,+ trafficRows: 0,+ countryBatches: 0,+ countryRows: 0,+ failures: 0,+ };++ isEnabled(): boolean {+ return this.writeEnabled;+ }++ writeTrafficBatch(backendId: number, updates: TrafficUpdate[]): void {+ if (!this.writeEnabled || updates.length === 0) return;++ const rows = updates.map((item) => ({+ backend_id: backendId,+ minute: this.toMinuteDateTime(item.timestampMs),+ domain: item.domain || '',+ ip: item.ip || '',+ source_ip: item.sourceIP || '',+ chain: item.chains.join(' > ') || item.chain || 'DIRECT',+ rule:+ item.chains.length > 1+ ? item.chains[item.chains.length - 1]+ : item.rulePayload+ ? `${item.rule}(${item.rulePayload})`+ : item.rule,+ upload: Math.max(0, Math.floor(item.upload)),+ download: Math.max(0, Math.floor(item.download)),+ connections: 1,+ }));++ this.enqueue(() => this.insertRows('traffic_minute', rows, 'traffic'));+ }++ writeCountryBatch(backendId: number, updates: CountryMinuteUpdate[]): void {+ if (!this.writeEnabled || updates.length === 0) return;++ const rows = updates.map((item) => ({+ backend_id: backendId,+ minute: this.toMinuteDateTime(item.timestampMs),+ country: item.country || '',+ country_name: item.countryName || '',+ continent: item.continent || '',+ upload: Math.max(0, Math.floor(item.upload)),+ download: Math.max(0, Math.floor(item.download)),+ connections: 1,+ }));++ this.enqueue(() => this.insertRows('country_minute', rows, 'country'));+ }++ private enqueue(task: () => Promise<void>): void {+ if (this.pendingBatches >= this.maxPendingBatches) {+ this.metrics.failures += 1;+ this.maybeLogMetrics();+ console.warn(+ `[ClickHouse Writer] Dropped batch because pending queue is full (${this.pendingBatches}/${this.maxPendingBatches})`,+ );+ return;+ }++ this.pendingBatches += 1;+ this.writeChain = this.writeChain+ .then(() => task())+ .catch((error) => {+ const message = error instanceof Error ? error.message : String(error);+ console.warn(`[ClickHouse Writer] Queue task failed: ${message}`);+ })+ .finally(() => {+ this.pendingBatches = Math.max(0, this.pendingBatches - 1);+ });+ }++ private async insertRows(+ table: 'traffic_minute' | 'country_minute',+ rows: Array<Record<string, unknown>>,+ metricType: 'traffic' | 'country',+ ): Promise<void> {+ const authHeader =+ this.config.password.length > 0+ ? `Basic ${Buffer.from(`${this.config.user}:${this.config.password}`).toString('base64')}`+ : '';+ const body = rows.map((row) => JSON.stringify(row)).join('\n');+ const url = `${this.config.protocol}://${this.config.host}:${this.config.port}/?database=${encodeURIComponent(this.config.database)}&query=${encodeURIComponent(`INSERT INTO ${this.config.database}.${table} FORMAT JSONEachRow`)}`;++ try {+ const response = await fetch(url, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ ...(authHeader ? { Authorization: authHeader } : {}),+ },+ body,+ signal: AbortSignal.timeout(this.config.timeoutMs),+ });++ if (!response.ok) {+ const text = await response.text();+ throw new Error(`status=${response.status} body=${text.slice(0, 200)}`);+ }++ if (metricType === 'traffic') {+ this.metrics.trafficBatches += 1;+ this.metrics.trafficRows += rows.length;+ } else {+ this.metrics.countryBatches += 1;+ this.metrics.countryRows += rows.length;+ }+ this.maybeLogMetrics();+ } catch (error) {+ this.metrics.failures += 1;+ this.maybeLogMetrics();+ const message = error instanceof Error ? error.message : String(error);+ console.warn(`[ClickHouse Writer] Failed to insert ${metricType} batch rows=${rows.length}: ${message}`);+ }+ }++ private toMinuteDateTime(timestampMs?: number): string {+ const date = new Date(timestampMs ?? Date.now()).toISOString();+ return `${date.slice(0, 16).replace('T', ' ')}:00`;+ }++ private maybeLogMetrics(): void {+ const now = Date.now();+ const elapsedMs = now - this.metricsWindowStartedAt;+ if (elapsedMs < this.metricsIntervalMs) {+ return;+ }++ const elapsedSec = Math.max(1, elapsedMs / 1000);+ console.info(+ `[ClickHouse Writer] traffic_batches=${this.metrics.trafficBatches} traffic_rows=${this.metrics.trafficRows} country_batches=${this.metrics.countryBatches} country_rows=${this.metrics.countryRows} failures=${this.metrics.failures} pending_batches=${this.pendingBatches} rows_per_sec=${((this.metrics.trafficRows + this.metrics.countryRows) / elapsedSec).toFixed(1)} window_sec=${elapsedSec.toFixed(1)}`,+ );++ this.metricsWindowStartedAt = now;+ this.metrics = {+ trafficBatches: 0,+ trafficRows: 0,+ countryBatches: 0,+ countryRows: 0,+ failures: 0,+ };+ }+}++const writer = new ClickHouseWriter();++export function getClickHouseWriter(): ClickHouseWriter {+ return writer;+}diff --git a/apps/collector/src/clickhouse.ts b/apps/collector/src/clickhouse.tsnew file mode 100644index 0000000..ce1f957--- /dev/null+++ b/apps/collector/src/clickhouse.ts@@ -0,0 +1,200 @@+type ClickHouseProtocol = 'http' | 'https';++export interface ClickHouseConfig {+ enabled: boolean;+ required: boolean;+ protocol: ClickHouseProtocol;+ host: string;+ port: number;+ database: string;+ user: string;+ password: string;+ timeoutMs: number;+ maxRetries: number;+ retryDelayMs: number;+}++export function loadClickHouseConfig(): ClickHouseConfig {+ const enabled = process.env.CH_ENABLED === '1';+ const required = process.env.CH_REQUIRED === '1';+ const secure = process.env.CH_SECURE === '1';+ return {+ enabled,+ required,+ protocol: secure ? 'https' : 'http',+ host: process.env.CH_HOST || 'clickhouse',+ port: parsePositiveInt(process.env.CH_PORT, 8123),+ database: process.env.CH_DATABASE || 'neko_master',+ user: process.env.CH_USER || 'default',+ password: process.env.CH_PASSWORD || '',+ timeoutMs: parsePositiveInt(process.env.CH_CONNECT_TIMEOUT_MS, 5000),+ maxRetries: parsePositiveInt(process.env.CH_CONNECT_MAX_RETRIES, 5),+ retryDelayMs: parsePositiveInt(process.env.CH_CONNECT_RETRY_DELAY_MS, 2000),+ };+}++function parsePositiveInt(value: string | undefined, fallback: number): number {+ const parsed = Number.parseInt(value || '', 10);+ if (!Number.isFinite(parsed) || parsed <= 0) {+ return fallback;+ }+ return parsed;+}++function maskSecret(secret: string): string {+ if (!secret) return '(empty)';+ if (secret.length <= 4) return '****';+ return `${secret.slice(0, 2)}****${secret.slice(-2)}`;+}++function buildBaseUrl(config: ClickHouseConfig): string {+ return `${config.protocol}://${config.host}:${config.port}`;+}++export function formatClickHouseConfigForLog(config: ClickHouseConfig): string {+ return `enabled=${config.enabled ? '1' : '0'} required=${config.required ? '1' : '0'} endpoint=${buildBaseUrl(config)} database=${config.database} user=${config.user} password=${maskSecret(config.password)}`;+}++export async function ensureClickHouseReady(config: ClickHouseConfig): Promise<void> {+ if (!config.enabled) {+ console.info('[ClickHouse] Integration disabled (CH_ENABLED != 1)');+ return;+ }++ const baseUrl = buildBaseUrl(config);+ const authHeader =+ config.password.length > 0+ ? `Basic ${Buffer.from(`${config.user}:${config.password}`).toString('base64')}`+ : '';++ for (let attempt = 1; attempt <= config.maxRetries; attempt += 1) {+ try {+ const response = await fetch(`${baseUrl}/ping`, {+ method: 'GET',+ headers: {+ ...(authHeader ? { Authorization: authHeader } : {}),+ },+ signal: AbortSignal.timeout(config.timeoutMs),+ });+ const body = await response.text();+ if (!response.ok || body.trim() !== 'Ok.') {+ throw new Error(`unexpected /ping response: status=${response.status} body=${body.slice(0, 120)}`);+ }++ const dbCheck = await fetch(+ `${baseUrl}/?database=${encodeURIComponent(config.database)}&query=${encodeURIComponent('SELECT 1')}`,+ {+ method: 'GET',+ headers: {+ ...(authHeader ? { Authorization: authHeader } : {}),+ },+ signal: AbortSignal.timeout(config.timeoutMs),+ },+ );+ if (!dbCheck.ok) {+ const dbBody = await dbCheck.text();+ throw new Error(`database check failed: status=${dbCheck.status} body=${dbBody.slice(0, 160)}`);+ }++ console.info(`[ClickHouse] Ready at ${baseUrl}, database=${config.database}`);+ return;+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ if (attempt >= config.maxRetries) {+ if (config.required) {+ throw new Error(`[ClickHouse] Not ready after ${attempt} attempts: ${message}`);+ }+ console.warn(`[ClickHouse] Not ready after ${attempt} attempts, continue with fallback: ${message}`);+ return;+ }++ console.warn(+ `[ClickHouse] Attempt ${attempt}/${config.maxRetries} failed: ${message}. Retry in ${config.retryDelayMs}ms`,+ );+ await new Promise((resolve) => setTimeout(resolve, config.retryDelayMs));+ }+ }+}++export async function runClickHouseQuery(+ config: ClickHouseConfig,+ query: string,+): Promise<void> {+ const baseUrl = buildBaseUrl(config);+ const authHeader =+ config.password.length > 0+ ? `Basic ${Buffer.from(`${config.user}:${config.password}`).toString('base64')}`+ : '';++ const response = await fetch(+ `${baseUrl}/?database=${encodeURIComponent(config.database)}&query=${encodeURIComponent(query)}`,+ {+ method: 'POST',+ headers: {+ ...(authHeader ? { Authorization: authHeader } : {}),+ },+ signal: AbortSignal.timeout(config.timeoutMs),+ },+ );++ if (!response.ok) {+ const body = await response.text();+ throw new Error(`query failed: status=${response.status} body=${body.slice(0, 160)}`);+ }+}++export async function ensureClickHouseSchema(config: ClickHouseConfig): Promise<void> {+ if (!config.enabled) {+ return;+ }+ if (process.env.CH_AUTO_CREATE_TABLES === '0') {+ console.info('[ClickHouse] Auto schema creation disabled (CH_AUTO_CREATE_TABLES=0)');+ return;+ }++ await runClickHouseQuery(config, `CREATE DATABASE IF NOT EXISTS ${config.database}`);++ await runClickHouseQuery(+ config,+ `+CREATE TABLE IF NOT EXISTS ${config.database}.traffic_minute (+ backend_id UInt32,+ minute DateTime,+ domain String,+ ip String,+ source_ip String,+ chain String,+ rule String,+ upload UInt64,+ download UInt64,+ connections UInt32+) ENGINE = SummingMergeTree+PARTITION BY toYYYYMM(minute)+ORDER BY (backend_id, minute, domain, ip, source_ip, chain, rule)+TTL minute + INTERVAL 90 DAY+SETTINGS index_granularity = 8192+`,+ );++ await runClickHouseQuery(+ config,+ `+CREATE TABLE IF NOT EXISTS ${config.database}.country_minute (+ backend_id UInt32,+ minute DateTime,+ country String,+ country_name String,+ continent String,+ upload UInt64,+ download UInt64,+ connections UInt32+) ENGINE = SummingMergeTree+PARTITION BY toYYYYMM(minute)+ORDER BY (backend_id, minute, country)+TTL minute + INTERVAL 90 DAY+SETTINGS index_granularity = 8192+`,+ );++ console.info('[ClickHouse] Schema ensured (traffic_minute, country_minute)');+}diff --git a/apps/collector/src/index.ts b/apps/collector/src/index.tsindex 5009ee6..3b569f4 100644--- a/apps/collector/src/index.ts+++ b/apps/collector/src/index.ts@@ -23,6 +23,13 @@ let wsServer: StatsWebSocketServer;import { APIServer } from './app.js';import { GeoIPService } from './geo-service.js';+import {+ ensureClickHouseReady,+ ensureClickHouseSchema,+ formatClickHouseConfigForLog,+ loadClickHouseConfig,+} from './clickhouse.js';+import { ClickHouseCompareService } from './clickhouse-compare.js';const COLLECTOR_WS_PORT = parseInt(process.env.COLLECTOR_WS_PORT || '3002');const API_PORT = parseInt(process.env.API_PORT || '3001');@@ -35,6 +42,7 @@ let db: StatsDatabase;let apiServer: APIServer;let geoService: GeoIPService;let policySyncService: SurgePolicySyncService;+let clickHouseCompareService: ClickHouseCompareService;// Track last known backend configs to detect changeslet lastBackendConfigs: Map<number, BackendConfig> = new Map();@@ -42,10 +50,18 @@ let lastBackendConfigs: Map<number, BackendConfig> = new Map();async function main() {console.log('[Main] Starting collector service...');+ const clickHouseConfig = loadClickHouseConfig();+ console.info(`[Main] ClickHouse config: ${formatClickHouseConfigForLog(clickHouseConfig)}`);+ await ensureClickHouseReady(clickHouseConfig);+ await ensureClickHouseSchema(clickHouseConfig);+// Initialize databaseconsole.log('[Main] Initializing database at:', DB_PATH);db = new StatsDatabase(DB_PATH);+ clickHouseCompareService = new ClickHouseCompareService(db);+ clickHouseCompareService.start();+// Initialize GeoIP servicegeoService = new GeoIPService(db);@@ -256,6 +272,7 @@ function shutdown() {// Stop serverswsServer?.stop();apiServer?.stop();+ clickHouseCompareService?.stop();geoService?.destroy();// Close databasediff --git a/apps/collector/src/modules/stats/stats.controller.ts b/apps/collector/src/modules/stats/stats.controller.tsindex ac7e949..fefc852 100644--- a/apps/collector/src/modules/stats/stats.controller.ts+++ b/apps/collector/src/modules/stats/stats.controller.ts@@ -120,7 +120,7 @@ const statsController: FastifyPluginAsync = async (fastify: FastifyInstance): Pr}try {- const result = service.getSummary(backendId, timeRange);+ const result = await service.getSummaryWithRouting(backendId, timeRange);return result;} catch (error: unknown) {if (error instanceof Error && error.message === 'Backend not found') {@@ -132,7 +132,7 @@ const statsController: FastifyPluginAsync = async (fastify: FastifyInstance): Pr// Get global summary across all backendsfastify.get('/global', async () => {- return service.getGlobalSummary();+ return service.getGlobalSummaryWithRouting();});// Get domain statistics for a specific backend (paginated)@@ -153,7 +153,7 @@ const statsController: FastifyPluginAsync = async (fastify: FastifyInstance): Prconst parsedOffset = parseOffset(offset);const parsedLimit = service.parseLimit(limit, 50, 200);- return service.getDomainStatsPaginated(backendId, timeRange, {+ return await service.getDomainStatsPaginatedWithRouting(backendId, timeRange, {offset: parsedOffset,limit: parsedLimit,sortBy,@@ -180,7 +180,7 @@ const statsController: FastifyPluginAsync = async (fastify: FastifyInstance): Prconst parsedOffset = parseOffset(offset);const parsedLimit = service.parseLimit(limit, 50, 200);- return service.getIPStatsPaginated(backendId, timeRange, {+ return await service.getIPStatsPaginatedWithRouting(backendId, timeRange, {offset: parsedOffset,limit: parsedLimit,sortBy,@@ -208,7 +208,12 @@ const statsController: FastifyPluginAsync = async (fastify: FastifyInstance): Prreturn reply.status(400).send({ error: 'Domain parameter is required' });}- return service.getDomainProxyStats(backendId, domain, timeRange, sourceIP, sourceChain);+ return await service.getDomainProxyStatsWithRouting(+ backendId,+ domain,+ timeRange,+ sourceIP,+ );});// Get IP details for a specific domain@@ -231,7 +236,13 @@ const statsController: FastifyPluginAsync = async (fastify: FastifyInstance): Pr}const effectiveLimit = service.parseLimit(limit, 100, 2000);- return service.getDomainIPDetails(backendId, domain, timeRange, effectiveLimit, sourceIP, sourceChain);+ return await service.getDomainIPDetailsWithRouting(+ backendId,+ domain,+ timeRange,+ effectiveLimit,+ sourceIP,+ );});// Get per-proxy traffic breakdown for a specific IP@@ -253,7 +264,12 @@ const statsController: FastifyPluginAsync = async (fastify: FastifyInstance): Prreturn reply.status(400).send({ error: 'IP parameter is required' });}- return service.getIPProxyStats(backendId, ip, timeRange, sourceIP, sourceChain);+ return await service.getIPProxyStatsWithRouting(+ backendId,+ ip,+ timeRange,+ sourceIP,+ );});// Get domain details for a specific IP@@ -276,7 +292,13 @@ const statsController: FastifyPluginAsync = async (fastify: FastifyInstance): Pr}const effectiveLimit = service.parseLimit(limit, 100, 2000);- return service.getIPDomainDetails(backendId, ip, timeRange, effectiveLimit, sourceIP, sourceChain);+ return await service.getIPDomainDetailsWithRouting(+ backendId,+ ip,+ timeRange,+ effectiveLimit,+ sourceIP,+ );});// Get domains for a specific proxy/chain@@ -299,7 +321,12 @@ const statsController: FastifyPluginAsync = async (fastify: FastifyInstance): Pr}const effectiveLimit = service.parseLimit(limit, 5000, 20000);- return service.getProxyDomains(backendId, chain, timeRange, effectiveLimit);+ return await service.getProxyDomainsWithRouting(+ backendId,+ chain,+ timeRange,+ effectiveLimit,+ );});// Get IPs for a specific proxy/chain@@ -322,7 +349,12 @@ const statsController: FastifyPluginAsync = async (fastify: FastifyInstance): Pr}const effectiveLimit = service.parseLimit(limit, 5000, 20000);- return service.getProxyIPs(backendId, chain, timeRange, effectiveLimit);+ return await service.getProxyIPsWithRouting(+ backendId,+ chain,+ timeRange,+ effectiveLimit,+ );});// Get proxy/chain statistics for a specific backend@@ -338,7 +370,7 @@ const statsController: FastifyPluginAsync = async (fastify: FastifyInstance): Prreturn reply.status(404).send({ error: 'No backend specified or active' });}- return service.getProxyStats(backendId, timeRange);+ return await service.getProxyStatsWithRouting(backendId, timeRange);});// Get rule statistics for a specific backend@@ -354,7 +386,7 @@ const statsController: FastifyPluginAsync = async (fastify: FastifyInstance): Prreturn reply.status(404).send({ error: 'No backend specified or active' });}- return service.getRuleStats(backendId, timeRange);+ return await service.getRuleStatsWithRouting(backendId, timeRange);});// Get domains for a specific rule@@ -377,7 +409,12 @@ const statsController: FastifyPluginAsync = async (fastify: FastifyInstance): Pr}const effectiveLimit = service.parseLimit(limit, 5000, 20000);- return service.getRuleDomains(backendId, rule, timeRange, effectiveLimit);+ return await service.getRuleDomainsWithRouting(+ backendId,+ rule,+ timeRange,+ effectiveLimit,+ );});// Get IPs for a specific rule@@ -400,7 +437,12 @@ const statsController: FastifyPluginAsync = async (fastify: FastifyInstance): Pr}const effectiveLimit = service.parseLimit(limit, 5000, 20000);- return service.getRuleIPs(backendId, rule, timeRange, effectiveLimit);+ return await service.getRuleIPsWithRouting(+ backendId,+ rule,+ timeRange,+ effectiveLimit,+ );});// Get per-proxy traffic breakdown for a specific domain under a specific rule@@ -422,7 +464,12 @@ const statsController: FastifyPluginAsync = async (fastify: FastifyInstance): Prreturn reply.status(400).send({ error: 'Rule and domain parameters are required' });}- return service.getRuleDomainProxyStats(backendId, rule, domain, timeRange);+ return await service.getRuleDomainProxyStatsWithRouting(+ backendId,+ rule,+ domain,+ timeRange,+ );});// Get IP details for a specific domain under a specific rule@@ -445,7 +492,13 @@ const statsController: FastifyPluginAsync = async (fastify: FastifyInstance): Pr}const effectiveLimit = service.parseLimit(limit, 100, 2000);- return service.getRuleDomainIPDetails(backendId, rule, domain, timeRange, effectiveLimit);+ return await service.getRuleDomainIPDetailsWithRouting(+ backendId,+ rule,+ domain,+ timeRange,+ effectiveLimit,+ );});// Get per-proxy traffic breakdown for a specific IP under a specific rule@@ -467,7 +520,12 @@ const statsController: FastifyPluginAsync = async (fastify: FastifyInstance): Prreturn reply.status(400).send({ error: 'Rule and IP parameters are required' });}- return service.getRuleIPProxyStats(backendId, rule, ip, timeRange);+ return await service.getRuleIPProxyStatsWithRouting(+ backendId,+ rule,+ ip,+ timeRange,+ );});// Get domain details for a specific IP under a specific rule@@ -490,7 +548,13 @@ const statsController: FastifyPluginAsync = async (fastify: FastifyInstance): Pr}const effectiveLimit = service.parseLimit(limit, 100, 2000);- return service.getRuleIPDomainDetails(backendId, rule, ip, timeRange, effectiveLimit);+ return await service.getRuleIPDomainDetailsWithRouting(+ backendId,+ rule,+ ip,+ timeRange,+ effectiveLimit,+ );});// Get rule chain flow for a specific rule@@ -512,7 +576,7 @@ const statsController: FastifyPluginAsync = async (fastify: FastifyInstance): Prreturn reply.status(400).send({ error: 'Rule parameter is required' });}- return service.getRuleChainFlow(backendId, rule, timeRange);+ return service.getRuleChainFlowWithRouting(backendId, rule, timeRange);});// Get all rule chain flows merged into unified DAG@@ -528,7 +592,7 @@ const statsController: FastifyPluginAsync = async (fastify: FastifyInstance): Prreturn reply.status(404).send({ error: 'No backend specified or active' });}- return service.getAllRuleChainFlows(backendId, timeRange);+ return service.getAllRuleChainFlowsWithRouting(backendId, timeRange);});// Get rule to proxy mapping for a specific backend@@ -539,7 +603,7 @@ const statsController: FastifyPluginAsync = async (fastify: FastifyInstance): Prreturn reply.status(404).send({ error: 'No backend specified or active' });}- return service.getRuleProxyMap(backendId);+ return service.getRuleProxyMapWithRouting(backendId);});// Get country traffic statistics for a specific backend@@ -559,7 +623,7 @@ const statsController: FastifyPluginAsync = async (fastify: FastifyInstance): Prconst { limit } = query;const limitNum = service.parseLimit(limit, 50, 2000);- return service.getCountryStats(backendId, timeRange, limitNum);+ return await service.getCountryStatsWithRouting(backendId, timeRange, limitNum);});// Get device statistics for a specific backend@@ -578,7 +642,11 @@ const statsController: FastifyPluginAsync = async (fastify: FastifyInstance): Prconst { limit } = query;const effectiveLimit = service.parseLimit(limit, 50, 2000);- return service.getDeviceStats(backendId, timeRange, effectiveLimit);+ return await service.getDeviceStatsWithRouting(+ backendId,+ timeRange,+ effectiveLimit,+ );});// Get domains for a specific device@@ -597,7 +665,12 @@ const statsController: FastifyPluginAsync = async (fastify: FastifyInstance): Prconst { sourceIP, limit } = query;const effectiveLimit = service.parseLimit(limit, 5000, 20000);- return service.getDeviceDomains(backendId, sourceIP || '', timeRange, effectiveLimit);+ return await service.getDeviceDomainsWithRouting(+ backendId,+ sourceIP || '',+ timeRange,+ effectiveLimit,+ );});// Get IPs for a specific device@@ -616,7 +689,12 @@ const statsController: FastifyPluginAsync = async (fastify: FastifyInstance): Prconst { sourceIP, limit } = query;const effectiveLimit = service.parseLimit(limit, 5000, 20000);- return service.getDeviceIPs(backendId, sourceIP || '', timeRange, effectiveLimit);+ return await service.getDeviceIPsWithRouting(+ backendId,+ sourceIP || '',+ timeRange,+ effectiveLimit,+ );});// Get hourly statistics for a specific backend@@ -635,7 +713,7 @@ const statsController: FastifyPluginAsync = async (fastify: FastifyInstance): Prconst query = request.query as Record<string, string | undefined>;const { hours = '24' } = query;const hoursNum = service.parseLimit(hours, 24, 24 * 30);- return service.getHourlyStats(backendId, timeRange, hoursNum);+ return await service.getHourlyStatsWithRouting(backendId, timeRange, hoursNum);});// Get traffic trend for a specific backend@@ -654,7 +732,7 @@ const statsController: FastifyPluginAsync = async (fastify: FastifyInstance): Prconst query = request.query as Record<string, string | undefined>;const { minutes = '30' } = query;const windowMinutes = service.parseLimit(minutes, 30, 60 * 24 * 7);- return service.getTrafficTrend(backendId, timeRange, windowMinutes);+ return await service.getTrafficTrendWithRouting(backendId, timeRange, windowMinutes);});// Get traffic trend aggregated by time buckets for chart display@@ -674,7 +752,12 @@ const statsController: FastifyPluginAsync = async (fastify: FastifyInstance): Prconst { minutes = '30', bucketMinutes = '1' } = query;const windowMinutes = service.parseLimit(minutes, 30, 60 * 24 * 7);const bucket = service.parseLimit(bucketMinutes, 1, 60);- return service.getTrafficTrendAggregated(backendId, timeRange, windowMinutes, bucket);+ return await service.getTrafficTrendAggregatedWithRouting(+ backendId,+ timeRange,+ windowMinutes,+ bucket,+ );});// Get recent connections for a specific backend@@ -688,7 +771,7 @@ const statsController: FastifyPluginAsync = async (fastify: FastifyInstance): Prconst query = request.query as Record<string, string | undefined>;const { limit = '100' } = query;const limitNum = service.parseLimit(limit, 100, 2000);- return service.getRecentConnections(backendId, limitNum);+ return service.getRecentConnectionsWithRouting(backendId, limitNum);});};diff --git a/apps/collector/src/modules/stats/stats.service.ts b/apps/collector/src/modules/stats/stats.service.tsindex 043d6c7..1ee0655 100644--- a/apps/collector/src/modules/stats/stats.service.ts+++ b/apps/collector/src/modules/stats/stats.service.ts@@ -19,6 +19,7 @@ import type {HourlyStats,DeviceStats,} from './stats.types.js';+import { ClickHouseReader } from '../../clickhouse-reader.js';interface PaginatedStatsOptions {offset?: number;@@ -30,11 +31,59 @@ interface PaginatedStatsOptions {end?: string;}+type RoutedSource = 'clickhouse' | 'sqlite';+export class StatsService {+ private clickHouseReader: ClickHouseReader;+ private routeMetricsIntervalMs = Math.max(+ 1000,+ Number.parseInt(process.env.STATS_ROUTE_METRICS_LOG_INTERVAL_MS || '60000', 10) || 60000,+ );+ private routeMetricsWindowStartedAt = Date.now();+ private routeMetrics: Record<string, { clickhouse: number; sqlite: number }> = {};+constructor(private db: StatsDatabase,private realtimeStore: RealtimeStore,- ) {}+ ) {+ this.clickHouseReader = new ClickHouseReader();+ }++ private shouldUseClickHouse(timeRange: TimeRange): boolean {+ return (+ timeRange.active &&+ this.clickHouseReader.shouldUseForRange(timeRange.start, timeRange.end)+ );+ }++ private recordRoute(route: string, source: RoutedSource): void {+ const existing = this.routeMetrics[route] || { clickhouse: 0, sqlite: 0 };+ existing[source] += 1;+ this.routeMetrics[route] = existing;+ this.maybeLogRouteMetrics();+ }++ private maybeLogRouteMetrics(): void {+ if (this.routeMetricsIntervalMs <= 0) return;+ const now = Date.now();+ const elapsedMs = now - this.routeMetricsWindowStartedAt;+ if (elapsedMs < this.routeMetricsIntervalMs) return;++ const entries = Object.entries(this.routeMetrics);+ if (entries.length > 0) {+ const parts = entries+ .map(([name, counts]) => {+ const total = counts.clickhouse + counts.sqlite;+ const chRate = total > 0 ? (counts.clickhouse / total) * 100 : 0;+ return `${name}=ch:${counts.clickhouse},sqlite:${counts.sqlite},ch_rate:${chRate.toFixed(1)}%`;+ })+ .join(' | ');+ console.info(`[Stats Route Metrics] ${parts} window_sec=${(elapsedMs / 1000).toFixed(1)}`);+ }++ this.routeMetricsWindowStartedAt = now;+ this.routeMetrics = {};+ }/*** Resolve backend ID from query param or active backend fallback@@ -155,6 +204,119 @@ export class StatsService {};}+ async getSummaryWithRouting(+ backendId: number,+ timeRange: TimeRange,+ ): Promise<SummaryResponse> {+ const backend = this.db.getBackend(backendId);+ if (!backend) {+ throw new Error('Backend not found');+ }++ const includeRealtime = this.shouldIncludeRealtime(timeRange);+ const shouldUseCH =+ timeRange.active &&+ this.clickHouseReader.shouldUseForRange(timeRange.start, timeRange.end);++ if (!shouldUseCH || !timeRange.start || !timeRange.end) {+ this.recordRoute('summary', 'sqlite');+ return this.getSummary(backendId, timeRange);+ }++ const [summaryCH, topDomainsCH, topIPsCH, hourlyStatsCH, trafficInRangeCH] =+ await Promise.all([+ this.clickHouseReader.getSummary(backendId, timeRange.start, timeRange.end),+ this.clickHouseReader.getTopDomainsLight(+ backendId,+ 10,+ timeRange.start,+ timeRange.end,+ ),+ this.clickHouseReader.getTopIPsLight(+ backendId,+ 10,+ timeRange.start,+ timeRange.end,+ ),+ this.clickHouseReader.getHourlyStats(+ backendId,+ 24,+ timeRange.start,+ timeRange.end,+ ),+ this.clickHouseReader.getTrafficInRange(+ backendId,+ timeRange.start,+ timeRange.end,+ ),+ ]);++ const summary =+ summaryCH || this.db.getSummary(backendId, timeRange.start, timeRange.end);+ const summaryWithRealtime = includeRealtime+ ? this.realtimeStore.applySummaryDelta(backendId, summary)+ : summary;++ const dbTopDomains =+ topDomainsCH ||+ this.db.getTopDomainsLight(backendId, 10, timeRange.start, timeRange.end);+ const topDomains = includeRealtime+ ? this.realtimeStore.mergeTopDomains(backendId, dbTopDomains, 10)+ : dbTopDomains;++ const dbTopIPs =+ topIPsCH || this.db.getTopIPsLight(backendId, 10, timeRange.start, timeRange.end);+ const topIPs = includeRealtime+ ? this.realtimeStore.mergeTopIPs(backendId, dbTopIPs, 10)+ : dbTopIPs;++ const dbProxyStats = this.db.getProxyStats(backendId, timeRange.start, timeRange.end);+ const proxyStats = includeRealtime+ ? this.realtimeStore.mergeProxyStats(backendId, dbProxyStats)+ : dbProxyStats;++ const dbRuleStats = this.db.getRuleStats(backendId, timeRange.start, timeRange.end);+ const ruleStats = includeRealtime+ ? this.realtimeStore.mergeRuleStats(backendId, dbRuleStats)+ : dbRuleStats;++ const hourlyStats =+ hourlyStatsCH ||+ this.db.getHourlyStats(backendId, 24, timeRange.start, timeRange.end);+ const todayTraffic =+ trafficInRangeCH ||+ this.db.getTrafficInRange(backendId, timeRange.start, timeRange.end);+ const todayDelta = includeRealtime+ ? this.realtimeStore.getTodayDelta(backendId)+ : { upload: 0, download: 0 };+ const usedCH =+ !!summaryCH || !!topDomainsCH || !!topIPsCH || !!hourlyStatsCH || !!trafficInRangeCH;+ this.recordRoute('summary', usedCH ? 'clickhouse' : 'sqlite');++ return {+ backend: {+ id: backend.id,+ name: backend.name,+ isActive: backend.is_active,+ listening: backend.listening,+ },+ totalConnections: summaryWithRealtime.totalConnections,+ totalUpload: summaryWithRealtime.totalUpload,+ totalDownload: summaryWithRealtime.totalDownload,+ totalDomains: summary.uniqueDomains,+ totalIPs: summary.uniqueIPs,+ totalRules: ruleStats.length,+ totalProxies: proxyStats.length,+ todayUpload: todayTraffic.upload + todayDelta.upload,+ todayDownload: todayTraffic.download + todayDelta.download,+ topDomains,+ topIPs,+ proxyStats,+ ruleStats,+ hourlyStats,+ };+ }+/*** Get global summary across all backends*/@@ -162,6 +324,11 @@ export class StatsService {return this.db.getGlobalSummary();}+ getGlobalSummaryWithRouting(): GlobalSummary {+ this.recordRoute('global', 'sqlite');+ return this.db.getGlobalSummary();+ }+/*** Get domain statistics for a specific backend (paginated)*/@@ -188,6 +355,47 @@ export class StatsService {return stats;}+ async getDomainStatsPaginatedWithRouting(+ backendId: number,+ timeRange: TimeRange,+ options: PaginatedStatsOptions,+ ): Promise<PaginatedDomainStats> {+ const shouldUseCH = this.shouldUseClickHouse(timeRange);+ const stats =+ shouldUseCH && timeRange.start && timeRange.end+ ? await this.clickHouseReader.getDomainStatsPaginated(+ backendId,+ timeRange.start,+ timeRange.end,+ options,+ )+ : null;++ const resolvedStats =+ stats ||+ this.db.getDomainStatsPaginated(backendId, {+ offset: options.offset,+ limit: options.limit,+ sortBy: options.sortBy,+ sortOrder: options.sortOrder,+ search: options.search,+ start: timeRange.start,+ end: timeRange.end,+ });+ this.recordRoute('domains', stats ? 'clickhouse' : 'sqlite');++ if (this.shouldIncludeRealtime(timeRange)) {+ return this.realtimeStore.mergeDomainStatsPaginated(backendId, resolvedStats, {+ offset: options.offset,+ limit: options.limit,+ sortBy: options.sortBy,+ sortOrder: options.sortOrder,+ search: options.search,+ });+ }+ return resolvedStats;+ }+/*** Get IP statistics for a specific backend (paginated)*/@@ -214,6 +422,47 @@ export class StatsService {return stats;}+ async getIPStatsPaginatedWithRouting(+ backendId: number,+ timeRange: TimeRange,+ options: PaginatedStatsOptions,+ ): Promise<PaginatedIPStats> {+ const shouldUseCH = this.shouldUseClickHouse(timeRange);+ const stats =+ shouldUseCH && timeRange.start && timeRange.end+ ? await this.clickHouseReader.getIPStatsPaginated(+ backendId,+ timeRange.start,+ timeRange.end,+ options,+ )+ : null;++ const resolvedStats =+ stats ||+ this.db.getIPStatsPaginated(backendId, {+ offset: options.offset,+ limit: options.limit,+ sortBy: options.sortBy,+ sortOrder: options.sortOrder,+ search: options.search,+ start: timeRange.start,+ end: timeRange.end,+ });+ this.recordRoute('ips', stats ? 'clickhouse' : 'sqlite');++ if (this.shouldIncludeRealtime(timeRange)) {+ return this.realtimeStore.mergeIPStatsPaginated(backendId, resolvedStats, {+ offset: options.offset,+ limit: options.limit,+ sortBy: options.sortBy,+ sortOrder: options.sortOrder,+ search: options.search,+ });+ }+ return resolvedStats;+ }+/*** Get per-proxy traffic breakdown for a specific domain*/@@ -227,6 +476,29 @@ export class StatsService {return this.db.getDomainProxyStats(backendId, domain, timeRange.start, timeRange.end, sourceIP, sourceChain);}+ async getDomainProxyStatsWithRouting(+ backendId: number,+ domain: string,+ timeRange: TimeRange,+ sourceIP?: string,+ ): Promise<any[]> {+ const shouldUseCH = this.shouldUseClickHouse(timeRange);+ if (shouldUseCH && timeRange.start && timeRange.end) {+ const ch = await this.clickHouseReader.getGroupedProxyStats(+ backendId,+ timeRange.start,+ timeRange.end,+ { domain, sourceIP },+ );+ if (ch) {+ this.recordRoute('domains.proxy-stats', 'clickhouse');+ return ch;+ }+ }+ this.recordRoute('domains.proxy-stats', 'sqlite');+ return this.db.getDomainProxyStats(backendId, domain, timeRange.start, timeRange.end, sourceIP);+ }+/*** Get IP details for a specific domain*/@@ -241,6 +513,31 @@ export class StatsService {return this.db.getDomainIPDetails(backendId, domain, timeRange.start, timeRange.end, limit, sourceIP, sourceChain);}+ async getDomainIPDetailsWithRouting(+ backendId: number,+ domain: string,+ timeRange: TimeRange,+ limit: number,+ sourceIP?: string,+ ): Promise<IPStats[]> {+ const shouldUseCH = this.shouldUseClickHouse(timeRange);+ if (shouldUseCH && timeRange.start && timeRange.end) {+ const ch = await this.clickHouseReader.getGroupedIPs(+ backendId,+ timeRange.start,+ timeRange.end,+ limit,+ { domain, sourceIP },+ );+ if (ch) {+ this.recordRoute('domains.ip-details', 'clickhouse');+ return ch;+ }+ }+ this.recordRoute('domains.ip-details', 'sqlite');+ return this.db.getDomainIPDetails(backendId, domain, timeRange.start, timeRange.end, limit, sourceIP);+ }+/*** Get per-proxy traffic breakdown for a specific IP*/@@ -254,6 +551,29 @@ export class StatsService {return this.db.getIPProxyStats(backendId, ip, timeRange.start, timeRange.end, sourceIP, sourceChain);}+ async getIPProxyStatsWithRouting(+ backendId: number,+ ip: string,+ timeRange: TimeRange,+ sourceIP?: string,+ ): Promise<any[]> {+ const shouldUseCH = this.shouldUseClickHouse(timeRange);+ if (shouldUseCH && timeRange.start && timeRange.end) {+ const ch = await this.clickHouseReader.getGroupedProxyStats(+ backendId,+ timeRange.start,+ timeRange.end,+ { ip, sourceIP },+ );+ if (ch) {+ this.recordRoute('ips.proxy-stats', 'clickhouse');+ return ch;+ }+ }+ this.recordRoute('ips.proxy-stats', 'sqlite');+ return this.db.getIPProxyStats(backendId, ip, timeRange.start, timeRange.end, sourceIP);+ }+/*** Get domain details for a specific IP*/@@ -268,6 +588,31 @@ export class StatsService {return this.db.getIPDomainDetails(backendId, ip, timeRange.start, timeRange.end, limit, sourceIP, sourceChain);}+ async getIPDomainDetailsWithRouting(+ backendId: number,+ ip: string,+ timeRange: TimeRange,+ limit: number,+ sourceIP?: string,+ ): Promise<DomainStats[]> {+ const shouldUseCH = this.shouldUseClickHouse(timeRange);+ if (shouldUseCH && timeRange.start && timeRange.end) {+ const ch = await this.clickHouseReader.getGroupedDomains(+ backendId,+ timeRange.start,+ timeRange.end,+ limit,+ { ip, sourceIP },+ );+ if (ch) {+ this.recordRoute('ips.domain-details', 'clickhouse');+ return ch;+ }+ }+ this.recordRoute('ips.domain-details', 'sqlite');+ return this.db.getIPDomainDetails(backendId, ip, timeRange.start, timeRange.end, limit, sourceIP);+ }+/*** Get domains for a specific proxy/chain*/@@ -279,6 +624,32 @@ export class StatsService {return stats;}+ async getProxyDomainsWithRouting(+ backendId: number,+ chain: string,+ timeRange: TimeRange,+ limit: number,+ ): Promise<DomainStats[]> {+ const shouldUseCH = this.shouldUseClickHouse(timeRange);+ const stats =+ shouldUseCH && timeRange.start && timeRange.end+ ? await this.clickHouseReader.getGroupedDomains(+ backendId,+ timeRange.start,+ timeRange.end,+ limit,+ { chain },+ )+ : null;+ const resolvedStats =+ stats || this.db.getProxyDomains(backendId, chain, limit, timeRange.start, timeRange.end);+ this.recordRoute('proxies.domains', stats ? 'clickhouse' : 'sqlite');+ if (this.shouldIncludeRealtime(timeRange)) {+ return this.realtimeStore.mergeProxyDomains(backendId, chain, resolvedStats, limit);+ }+ return resolvedStats;+ }+/*** Get IPs for a specific proxy/chain*/@@ -290,6 +661,32 @@ export class StatsService {return stats;}+ async getProxyIPsWithRouting(+ backendId: number,+ chain: string,+ timeRange: TimeRange,+ limit: number,+ ): Promise<IPStats[]> {+ const shouldUseCH = this.shouldUseClickHouse(timeRange);+ const stats =+ shouldUseCH && timeRange.start && timeRange.end+ ? await this.clickHouseReader.getGroupedIPs(+ backendId,+ timeRange.start,+ timeRange.end,+ limit,+ { chain },+ )+ : null;+ const resolvedStats =+ stats || this.db.getProxyIPs(backendId, chain, limit, timeRange.start, timeRange.end);+ this.recordRoute('proxies.ips', stats ? 'clickhouse' : 'sqlite');+ if (this.shouldIncludeRealtime(timeRange)) {+ return this.realtimeStore.mergeProxyIPs(backendId, chain, resolvedStats, limit);+ }+ return resolvedStats;+ }+/*** Get proxy/chain statistics for a specific backend*/@@ -301,6 +698,29 @@ export class StatsService {return stats;}+ async getProxyStatsWithRouting(+ backendId: number,+ timeRange: TimeRange,+ ): Promise<ProxyStats[]> {+ const shouldUseCH = this.shouldUseClickHouse(timeRange);+ const stats =+ shouldUseCH && timeRange.start && timeRange.end+ ? await this.clickHouseReader.getProxyStats(+ backendId,+ timeRange.start,+ timeRange.end,+ )+ : null;+ const resolvedStats =+ (stats as ProxyStats[] | null) ||+ this.db.getProxyStats(backendId, timeRange.start, timeRange.end);+ this.recordRoute('proxies', stats ? 'clickhouse' : 'sqlite');+ if (this.shouldIncludeRealtime(timeRange)) {+ return this.realtimeStore.mergeProxyStats(backendId, resolvedStats);+ }+ return resolvedStats;+ }+/*** Get rule statistics for a specific backend*/@@ -312,6 +732,29 @@ export class StatsService {return stats;}+ async getRuleStatsWithRouting(+ backendId: number,+ timeRange: TimeRange,+ ): Promise<RuleStats[]> {+ const shouldUseCH = this.shouldUseClickHouse(timeRange);+ const stats =+ shouldUseCH && timeRange.start && timeRange.end+ ? await this.clickHouseReader.getRuleStats(+ backendId,+ timeRange.start,+ timeRange.end,+ )+ : null;+ const resolvedStats =+ (stats as RuleStats[] | null) ||+ this.db.getRuleStats(backendId, timeRange.start, timeRange.end);+ this.recordRoute('rules', stats ? 'clickhouse' : 'sqlite');+ if (this.shouldIncludeRealtime(timeRange)) {+ return this.realtimeStore.mergeRuleStats(backendId, resolvedStats);+ }+ return resolvedStats;+ }+/*** Get domains for a specific rule*/@@ -323,6 +766,32 @@ export class StatsService {return stats;}+ async getRuleDomainsWithRouting(+ backendId: number,+ rule: string,+ timeRange: TimeRange,+ limit: number,+ ): Promise<DomainStats[]> {+ const shouldUseCH = this.shouldUseClickHouse(timeRange);+ const stats =+ shouldUseCH && timeRange.start && timeRange.end+ ? await this.clickHouseReader.getGroupedDomains(+ backendId,+ timeRange.start,+ timeRange.end,+ limit,+ { rule },+ )+ : null;+ const resolvedStats =+ stats || this.db.getRuleDomains(backendId, rule, limit, timeRange.start, timeRange.end);+ this.recordRoute('rules.domains', stats ? 'clickhouse' : 'sqlite');+ if (this.shouldIncludeRealtime(timeRange)) {+ return this.realtimeStore.mergeRuleDomains(backendId, rule, resolvedStats, limit);+ }+ return resolvedStats;+ }+/*** Get IPs for a specific rule*/@@ -334,6 +803,32 @@ export class StatsService {return stats;}+ async getRuleIPsWithRouting(+ backendId: number,+ rule: string,+ timeRange: TimeRange,+ limit: number,+ ): Promise<IPStats[]> {+ const shouldUseCH = this.shouldUseClickHouse(timeRange);+ const stats =+ shouldUseCH && timeRange.start && timeRange.end+ ? await this.clickHouseReader.getGroupedIPs(+ backendId,+ timeRange.start,+ timeRange.end,+ limit,+ { rule },+ )+ : null;+ const resolvedStats =+ stats || this.db.getRuleIPs(backendId, rule, limit, timeRange.start, timeRange.end);+ this.recordRoute('rules.ips', stats ? 'clickhouse' : 'sqlite');+ if (this.shouldIncludeRealtime(timeRange)) {+ return this.realtimeStore.mergeRuleIPs(backendId, rule, resolvedStats, limit);+ }+ return resolvedStats;+ }+/*** Get per-proxy traffic breakdown for a specific domain under a specific rule*/@@ -341,6 +836,29 @@ export class StatsService {return this.db.getRuleDomainProxyStats(backendId, rule, domain, timeRange.start, timeRange.end);}+ async getRuleDomainProxyStatsWithRouting(+ backendId: number,+ rule: string,+ domain: string,+ timeRange: TimeRange,+ ): Promise<any[]> {+ const shouldUseCH = this.shouldUseClickHouse(timeRange);+ if (shouldUseCH && timeRange.start && timeRange.end) {+ const ch = await this.clickHouseReader.getGroupedProxyStats(+ backendId,+ timeRange.start,+ timeRange.end,+ { rule, domain },+ );+ if (ch) {+ this.recordRoute('rules.domains.proxy-stats', 'clickhouse');+ return ch;+ }+ }+ this.recordRoute('rules.domains.proxy-stats', 'sqlite');+ return this.db.getRuleDomainProxyStats(backendId, rule, domain, timeRange.start, timeRange.end);+ }+/*** Get IP details for a specific domain under a specific rule*/@@ -348,6 +866,31 @@ export class StatsService {return this.db.getRuleDomainIPDetails(backendId, rule, domain, timeRange.start, timeRange.end, limit);}+ async getRuleDomainIPDetailsWithRouting(+ backendId: number,+ rule: string,+ domain: string,+ timeRange: TimeRange,+ limit: number,+ ): Promise<IPStats[]> {+ const shouldUseCH = this.shouldUseClickHouse(timeRange);+ if (shouldUseCH && timeRange.start && timeRange.end) {+ const ch = await this.clickHouseReader.getGroupedIPs(+ backendId,+ timeRange.start,+ timeRange.end,+ limit,+ { rule, domain },+ );+ if (ch) {+ this.recordRoute('rules.domains.ip-details', 'clickhouse');+ return ch;+ }+ }+ this.recordRoute('rules.domains.ip-details', 'sqlite');+ return this.db.getRuleDomainIPDetails(backendId, rule, domain, timeRange.start, timeRange.end, limit);+ }+/*** Get per-proxy traffic breakdown for a specific IP under a specific rule*/@@ -355,6 +898,29 @@ export class StatsService {return this.db.getRuleIPProxyStats(backendId, rule, ip, timeRange.start, timeRange.end);}+ async getRuleIPProxyStatsWithRouting(+ backendId: number,+ rule: string,+ ip: string,+ timeRange: TimeRange,+ ): Promise<any[]> {+ const shouldUseCH = this.shouldUseClickHouse(timeRange);+ if (shouldUseCH && timeRange.start && timeRange.end) {+ const ch = await this.clickHouseReader.getGroupedProxyStats(+ backendId,+ timeRange.start,+ timeRange.end,+ { rule, ip },+ );+ if (ch) {+ this.recordRoute('rules.ips.proxy-stats', 'clickhouse');+ return ch;+ }+ }+ this.recordRoute('rules.ips.proxy-stats', 'sqlite');+ return this.db.getRuleIPProxyStats(backendId, rule, ip, timeRange.start, timeRange.end);+ }+/*** Get domain details for a specific IP under a specific rule*/@@ -362,6 +928,31 @@ export class StatsService {return this.db.getRuleIPDomainDetails(backendId, rule, ip, timeRange.start, timeRange.end, limit);}+ async getRuleIPDomainDetailsWithRouting(+ backendId: number,+ rule: string,+ ip: string,+ timeRange: TimeRange,+ limit: number,+ ): Promise<DomainStats[]> {+ const shouldUseCH = this.shouldUseClickHouse(timeRange);+ if (shouldUseCH && timeRange.start && timeRange.end) {+ const ch = await this.clickHouseReader.getGroupedDomains(+ backendId,+ timeRange.start,+ timeRange.end,+ limit,+ { rule, ip },+ );+ if (ch) {+ this.recordRoute('rules.ips.domain-details', 'clickhouse');+ return ch;+ }+ }+ this.recordRoute('rules.ips.domain-details', 'sqlite');+ return this.db.getRuleIPDomainDetails(backendId, rule, ip, timeRange.start, timeRange.end, limit);+ }+/*** Get rule chain flow for a specific rule*/@@ -369,6 +960,11 @@ export class StatsService {return this.db.getRuleChainFlow(backendId, rule, timeRange.start, timeRange.end);}+ getRuleChainFlowWithRouting(backendId: number, rule: string, timeRange: TimeRange): any {+ this.recordRoute('rules.chain-flow', 'sqlite');+ return this.db.getRuleChainFlow(backendId, rule, timeRange.start, timeRange.end);+ }+/*** Get all rule chain flows merged into unified DAG*/@@ -376,6 +972,11 @@ export class StatsService {return this.db.getAllRuleChainFlows(backendId, timeRange.start, timeRange.end);}+ getAllRuleChainFlowsWithRouting(backendId: number, timeRange: TimeRange): any {+ this.recordRoute('rules.chain-flow-all', 'sqlite');+ return this.db.getAllRuleChainFlows(backendId, timeRange.start, timeRange.end);+ }+/*** Get rule to proxy mapping for a specific backend*/@@ -383,6 +984,11 @@ export class StatsService {return this.db.getRuleProxyMap(backendId);}+ getRuleProxyMapWithRouting(backendId: number): any {+ this.recordRoute('rule-proxy-map', 'sqlite');+ return this.db.getRuleProxyMap(backendId);+ }+/*** Get country traffic statistics for a specific backend*/@@ -394,6 +1000,34 @@ export class StatsService {return stats;}+ async getCountryStatsWithRouting(+ backendId: number,+ timeRange: TimeRange,+ limit: number,+ ): Promise<CountryStats[]> {+ const shouldUseCH =+ timeRange.active &&+ this.clickHouseReader.shouldUseForRange(timeRange.start, timeRange.end);++ const stats =+ shouldUseCH && timeRange.start && timeRange.end+ ? await this.clickHouseReader.getCountryStats(+ backendId,+ limit,+ timeRange.start,+ timeRange.end,+ )+ : null;+ const resolvedStats =+ stats || this.db.getCountryStats(backendId, limit, timeRange.start, timeRange.end);+ this.recordRoute('countries', stats ? 'clickhouse' : 'sqlite');++ if (this.shouldIncludeRealtime(timeRange)) {+ return this.realtimeStore.mergeCountryStats(backendId, resolvedStats);+ }+ return resolvedStats;+ }+/*** Get device statistics for a specific backend*/@@ -405,6 +1039,31 @@ export class StatsService {return stats;}+ async getDeviceStatsWithRouting(+ backendId: number,+ timeRange: TimeRange,+ limit: number,+ ): Promise<DeviceStats[]> {+ const shouldUseCH = this.shouldUseClickHouse(timeRange);+ const stats =+ shouldUseCH && timeRange.start && timeRange.end+ ? await this.clickHouseReader.getDeviceStats(+ backendId,+ timeRange.start,+ timeRange.end,+ limit,+ )+ : null;+ const resolvedStats =+ (stats as DeviceStats[] | null) ||+ this.db.getDevices(backendId, limit, timeRange.start, timeRange.end);+ this.recordRoute('devices', stats ? 'clickhouse' : 'sqlite');+ if (this.shouldIncludeRealtime(timeRange)) {+ return this.realtimeStore.mergeDeviceStats(backendId, resolvedStats, limit);+ }+ return resolvedStats;+ }+/*** Get domains for a specific device*/@@ -417,6 +1076,33 @@ export class StatsService {return stats;}+ async getDeviceDomainsWithRouting(+ backendId: number,+ sourceIP: string,+ timeRange: TimeRange,+ limit: number,+ ): Promise<DomainStats[]> {+ if (!sourceIP) return [];+ const shouldUseCH = this.shouldUseClickHouse(timeRange);+ const stats =+ shouldUseCH && timeRange.start && timeRange.end+ ? await this.clickHouseReader.getGroupedDomains(+ backendId,+ timeRange.start,+ timeRange.end,+ limit,+ { sourceIP },+ )+ : null;+ const resolvedStats =+ stats || this.db.getDeviceDomains(backendId, sourceIP, limit, timeRange.start, timeRange.end);+ this.recordRoute('devices.domains', stats ? 'clickhouse' : 'sqlite');+ if (this.shouldIncludeRealtime(timeRange)) {+ return this.realtimeStore.mergeDeviceDomains(backendId, sourceIP, resolvedStats, limit);+ }+ return resolvedStats;+ }+/*** Get IPs for a specific device*/@@ -429,6 +1115,33 @@ export class StatsService {return stats;}+ async getDeviceIPsWithRouting(+ backendId: number,+ sourceIP: string,+ timeRange: TimeRange,+ limit: number,+ ): Promise<IPStats[]> {+ if (!sourceIP) return [];+ const shouldUseCH = this.shouldUseClickHouse(timeRange);+ const stats =+ shouldUseCH && timeRange.start && timeRange.end+ ? await this.clickHouseReader.getGroupedIPs(+ backendId,+ timeRange.start,+ timeRange.end,+ limit,+ { sourceIP },+ )+ : null;+ const resolvedStats =+ stats || this.db.getDeviceIPs(backendId, sourceIP, limit, timeRange.start, timeRange.end);+ this.recordRoute('devices.ips', stats ? 'clickhouse' : 'sqlite');+ if (this.shouldIncludeRealtime(timeRange)) {+ return this.realtimeStore.mergeDeviceIPs(backendId, sourceIP, resolvedStats, limit);+ }+ return resolvedStats;+ }+/*** Get hourly statistics for a specific backend*/@@ -436,6 +1149,30 @@ export class StatsService {return this.db.getHourlyStats(backendId, hours, timeRange.start, timeRange.end);}+ async getHourlyStatsWithRouting(+ backendId: number,+ timeRange: TimeRange,+ hours: number,+ ): Promise<HourlyStats[]> {+ const shouldUseCH =+ timeRange.active &&+ this.clickHouseReader.shouldUseForRange(timeRange.start, timeRange.end);+ if (shouldUseCH && timeRange.start && timeRange.end) {+ const chStats = await this.clickHouseReader.getHourlyStats(+ backendId,+ hours,+ timeRange.start,+ timeRange.end,+ );+ if (chStats) {+ this.recordRoute('hourly', 'clickhouse');+ return chStats;+ }+ }+ this.recordRoute('hourly', 'sqlite');+ return this.db.getHourlyStats(backendId, hours, timeRange.start, timeRange.end);+ }+/*** Get traffic trend for a specific backend*/@@ -447,6 +1184,34 @@ export class StatsService {return this.realtimeStore.mergeTrend(backendId, base, minutes, 1);}+ async getTrafficTrendWithRouting(+ backendId: number,+ timeRange: TimeRange,+ minutes: number,+ ): Promise<TrafficTrendPoint[]> {+ const shouldUseCH =+ timeRange.active &&+ this.clickHouseReader.shouldUseForRange(timeRange.start, timeRange.end);++ const chBase =+ shouldUseCH && timeRange.start && timeRange.end+ ? await this.clickHouseReader.getTrafficTrend(+ backendId,+ timeRange.start,+ timeRange.end,+ )+ : null;+ const base =+ chBase ||+ this.db.getTrafficTrend(backendId, minutes, timeRange.start, timeRange.end);+ this.recordRoute('trend', chBase ? 'clickhouse' : 'sqlite');++ if (!this.shouldIncludeRealtime(timeRange)) {+ return base;+ }+ return this.realtimeStore.mergeTrend(backendId, base, minutes, 1);+ }+/*** Get traffic trend aggregated by time buckets for chart display*/@@ -463,10 +1228,51 @@ export class StatsService {return this.realtimeStore.mergeTrend(backendId, base, minutes, bucketMinutes);}+ async getTrafficTrendAggregatedWithRouting(+ backendId: number,+ timeRange: TimeRange,+ minutes: number,+ bucketMinutes: number,+ ): Promise<TrafficTrendPoint[]> {+ const shouldUseCH =+ timeRange.active &&+ this.clickHouseReader.shouldUseForRange(timeRange.start, timeRange.end);++ const chBase =+ shouldUseCH && timeRange.start && timeRange.end+ ? await this.clickHouseReader.getTrafficTrendAggregated(+ backendId,+ bucketMinutes,+ timeRange.start,+ timeRange.end,+ )+ : null;+ const base =+ chBase ||+ this.db.getTrafficTrendAggregated(+ backendId,+ minutes,+ bucketMinutes,+ timeRange.start,+ timeRange.end,+ );+ this.recordRoute('trend.aggregated', chBase ? 'clickhouse' : 'sqlite');++ if (!this.shouldIncludeRealtime(timeRange)) {+ return base;+ }+ return this.realtimeStore.mergeTrend(backendId, base, minutes, bucketMinutes);+ }+/*** Get recent connections for a specific backend*/getRecentConnections(backendId: number, limit: number): any[] {return this.db.getRecentConnections(backendId, limit);}++ getRecentConnectionsWithRouting(backendId: number, limit: number): any[] {+ this.recordRoute('connections', 'sqlite');+ return this.db.getRecentConnections(backendId, limit);+ }}diff --git a/apps/collector/src/scripts/migrate-sqlite-to-clickhouse.ts b/apps/collector/src/scripts/migrate-sqlite-to-clickhouse.tsnew file mode 100644index 0000000..fb35fa4--- /dev/null+++ b/apps/collector/src/scripts/migrate-sqlite-to-clickhouse.ts@@ -0,0 +1,342 @@+import Database from 'better-sqlite3';+import {+ ensureClickHouseReady,+ ensureClickHouseSchema,+ loadClickHouseConfig,+ runClickHouseQuery,+} from '../clickhouse.js';++type CliOptions = {+ sqlitePath: string;+ from?: string;+ to?: string;+ batchSize: number;+ truncate: boolean;+};++type MinuteDimRow = {+ _rid: number;+ backend_id: number;+ minute: string;+ domain: string;+ ip: string;+ source_ip: string;+ chain: string;+ rule: string;+ upload: number;+ download: number;+ connections: number;+};++type MinuteCountryRow = {+ _rid: number;+ backend_id: number;+ minute: string;+ country: string;+ country_name: string;+ continent: string;+ upload: number;+ download: number;+ connections: number;+};++function parseArgs(argv: string[]): CliOptions {+ const options: CliOptions = {+ sqlitePath: process.env.DB_PATH || './stats.db',+ batchSize: 5000,+ truncate: false,+ };++ for (let i = 0; i < argv.length; i += 1) {+ const arg = argv[i];+ const next = argv[i + 1];++ if (arg === '--sqlite' && next) {+ options.sqlitePath = next;+ i += 1;+ continue;+ }+ if (arg === '--from' && next) {+ options.from = next;+ i += 1;+ continue;+ }+ if (arg === '--to' && next) {+ options.to = next;+ i += 1;+ continue;+ }+ if (arg === '--batch-size' && next) {+ const parsed = Number.parseInt(next, 10);+ if (Number.isFinite(parsed) && parsed > 0) {+ options.batchSize = parsed;+ }+ i += 1;+ continue;+ }+ if (arg === '--truncate') {+ options.truncate = true;+ continue;+ }+ }++ return options;+}++function toClickHouseDateTime(value: string): string {+ const text = String(value || '').trim();+ if (!text) return '1970-01-01 00:00:00';++ if (text.includes('T')) {+ return text.replace('T', ' ').replace('Z', '').slice(0, 19);+ }+ return text.slice(0, 19);+}++async function insertJsonRows(+ endpoint: string,+ authHeader: string,+ database: string,+ table: string,+ rows: Array<Record<string, unknown>>,+): Promise<void> {+ if (rows.length === 0) return;++ const body = rows.map((row) => JSON.stringify(row)).join('\n');+ const query = `INSERT INTO ${database}.${table} FORMAT JSONEachRow`;+ const response = await fetch(+ `${endpoint}/?database=${encodeURIComponent(database)}&query=${encodeURIComponent(query)}`,+ {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ ...(authHeader ? { Authorization: authHeader } : {}),+ },+ body,+ signal: AbortSignal.timeout(20000),+ },+ );++ if (!response.ok) {+ const text = await response.text();+ throw new Error(+ `insert ${table} failed: status=${response.status} body=${text.slice(0, 200)}`,+ );+ }+}++async function migrateMinuteDim(+ db: Database.Database,+ options: CliOptions,+ endpoint: string,+ authHeader: string,+ database: string,+): Promise<number> {+ const filters: string[] = [];+ const baseParams: Array<string> = [];+ if (options.from) {+ filters.push('minute >= ?');+ baseParams.push(toClickHouseDateTime(options.from));+ }+ if (options.to) {+ filters.push('minute <= ?');+ baseParams.push(toClickHouseDateTime(options.to));+ }+ const filterClause = filters.length > 0 ? ` AND ${filters.join(' AND ')}` : '';++ const countStmt = db.prepare(+ `SELECT COUNT(*) as total FROM minute_dim_stats WHERE 1=1${+ filters.length > 0 ? ` AND ${filters.join(' AND ')}` : ''+ }`,+ );+ const total = Number((countStmt.get(...baseParams) as { total: number }).total || 0);+ console.info(`[Migrate] minute_dim_stats rows to migrate: ${total}`);++ const selectStmt = db.prepare(+ `SELECT+ rowid as _rid,+ backend_id,+ minute,+ domain,+ ip,+ source_ip,+ chain,+ rule,+ upload,+ download,+ connections+ FROM minute_dim_stats+ WHERE rowid > ?${filterClause}+ ORDER BY rowid ASC+ LIMIT ?`,+ );++ let lastRowId = 0;+ let migrated = 0;+ while (true) {+ const rows = selectStmt.all(+ lastRowId,+ ...baseParams,+ options.batchSize,+ ) as MinuteDimRow[];+ if (rows.length === 0) break;++ const payload = rows.map((row) => ({+ backend_id: row.backend_id,+ minute: toClickHouseDateTime(row.minute),+ domain: row.domain || '',+ ip: row.ip || '',+ source_ip: row.source_ip || '',+ chain: row.chain || '',+ rule: row.rule || '',+ upload: Math.max(0, Number(row.upload || 0)),+ download: Math.max(0, Number(row.download || 0)),+ connections: Math.max(0, Number(row.connections || 0)),+ }));++ await insertJsonRows(endpoint, authHeader, database, 'traffic_minute', payload);+ migrated += payload.length;+ lastRowId = rows[rows.length - 1]._rid;++ if (migrated % (options.batchSize * 5) === 0 || migrated === total) {+ console.info(`[Migrate] traffic_minute migrated=${migrated}/${total}`);+ }+ }++ return migrated;+}++async function migrateMinuteCountry(+ db: Database.Database,+ options: CliOptions,+ endpoint: string,+ authHeader: string,+ database: string,+): Promise<number> {+ const filters: string[] = [];+ const baseParams: Array<string> = [];+ if (options.from) {+ filters.push('minute >= ?');+ baseParams.push(toClickHouseDateTime(options.from));+ }+ if (options.to) {+ filters.push('minute <= ?');+ baseParams.push(toClickHouseDateTime(options.to));+ }+ const filterClause = filters.length > 0 ? ` AND ${filters.join(' AND ')}` : '';++ const countStmt = db.prepare(+ `SELECT COUNT(*) as total FROM minute_country_stats WHERE 1=1${+ filters.length > 0 ? ` AND ${filters.join(' AND ')}` : ''+ }`,+ );+ const total = Number((countStmt.get(...baseParams) as { total: number }).total || 0);+ console.info(`[Migrate] minute_country_stats rows to migrate: ${total}`);++ const selectStmt = db.prepare(+ `SELECT+ rowid as _rid,+ backend_id,+ minute,+ country,+ country_name,+ continent,+ upload,+ download,+ connections+ FROM minute_country_stats+ WHERE rowid > ?${filterClause}+ ORDER BY rowid ASC+ LIMIT ?`,+ );++ let lastRowId = 0;+ let migrated = 0;+ while (true) {+ const rows = selectStmt.all(+ lastRowId,+ ...baseParams,+ options.batchSize,+ ) as MinuteCountryRow[];+ if (rows.length === 0) break;++ const payload = rows.map((row) => ({+ backend_id: row.backend_id,+ minute: toClickHouseDateTime(row.minute),+ country: row.country || 'UNKNOWN',+ country_name: row.country_name || row.country || 'Unknown',+ continent: row.continent || 'Unknown',+ upload: Math.max(0, Number(row.upload || 0)),+ download: Math.max(0, Number(row.download || 0)),+ connections: Math.max(0, Number(row.connections || 0)),+ }));++ await insertJsonRows(endpoint, authHeader, database, 'country_minute', payload);+ migrated += payload.length;+ lastRowId = rows[rows.length - 1]._rid;++ if (migrated % (options.batchSize * 5) === 0 || migrated === total) {+ console.info(`[Migrate] country_minute migrated=${migrated}/${total}`);+ }+ }++ return migrated;+}++async function main(): Promise<void> {+ const options = parseArgs(process.argv.slice(2));+ const config = loadClickHouseConfig();++ if (!config.enabled) {+ throw new Error('CH_ENABLED must be 1 when running migration script');+ }++ console.info(+ `[Migrate] start sqlite=${options.sqlitePath} from=${options.from || '-'} to=${options.to || '-'} batch_size=${options.batchSize} truncate=${options.truncate}`,+ );++ await ensureClickHouseReady(config);+ await ensureClickHouseSchema(config);++ if (options.truncate) {+ console.warn('[Migrate] --truncate enabled: clearing ClickHouse target tables');+ await runClickHouseQuery(config, `TRUNCATE TABLE ${config.database}.traffic_minute`);+ await runClickHouseQuery(config, `TRUNCATE TABLE ${config.database}.country_minute`);+ }++ const db = new Database(options.sqlitePath, { readonly: true });+ const endpoint = `${config.protocol}://${config.host}:${config.port}`;+ const authHeader =+ config.password.length > 0+ ? `Basic ${Buffer.from(`${config.user}:${config.password}`).toString('base64')}`+ : '';++ try {+ const migratedTraffic = await migrateMinuteDim(+ db,+ options,+ endpoint,+ authHeader,+ config.database,+ );+ const migratedCountry = await migrateMinuteCountry(+ db,+ options,+ endpoint,+ authHeader,+ config.database,+ );++ console.info(+ `[Migrate] completed traffic_minute=${migratedTraffic} country_minute=${migratedCountry}`,+ );+ } finally {+ db.close();+ }+}++void main().catch((error) => {+ const message = error instanceof Error ? error.message : String(error);+ console.error(`[Migrate] failed: ${message}`);+ process.exit(1);+});diff --git a/apps/collector/src/scripts/verify-sqlite-clickhouse.ts b/apps/collector/src/scripts/verify-sqlite-clickhouse.tsnew file mode 100644index 0000000..87d4bda--- /dev/null+++ b/apps/collector/src/scripts/verify-sqlite-clickhouse.ts@@ -0,0 +1,229 @@+import Database from 'better-sqlite3';+import { ensureClickHouseReady, loadClickHouseConfig } from '../clickhouse.js';++type CliOptions = {+ sqlitePath: string;+ from?: string;+ to?: string;+ maxDeltaPercent: number;+ failOnDelta: boolean;+};++type BackendRow = { id: number; name: string };++type Summary = {+ upload: number;+ download: number;+ connections: number;+ uniqueDomains: number;+ uniqueIPs: number;+};++function parseArgs(argv: string[]): CliOptions {+ const options: CliOptions = {+ sqlitePath: process.env.DB_PATH || './stats.db',+ maxDeltaPercent: Number.parseFloat(process.env.CH_VERIFY_MAX_DELTA_PERCENT || '1') || 1,+ failOnDelta: process.env.CH_VERIFY_FAIL_ON_DELTA === '1',+ };++ for (let i = 0; i < argv.length; i += 1) {+ const arg = argv[i];+ const next = argv[i + 1];+ if (arg === '--sqlite' && next) {+ options.sqlitePath = next;+ i += 1;+ continue;+ }+ if (arg === '--from' && next) {+ options.from = next;+ i += 1;+ continue;+ }+ if (arg === '--to' && next) {+ options.to = next;+ i += 1;+ continue;+ }+ if (arg === '--max-delta' && next) {+ const parsed = Number.parseFloat(next);+ if (Number.isFinite(parsed) && parsed >= 0) {+ options.maxDeltaPercent = parsed;+ }+ i += 1;+ continue;+ }+ if (arg === '--fail-on-delta') {+ options.failOnDelta = true;+ continue;+ }+ }++ return options;+}++function toDateTime(value: string): string {+ const date = new Date(value);+ if (Number.isNaN(date.getTime())) {+ throw new Error(`invalid datetime: ${value}`);+ }+ return date.toISOString().slice(0, 19).replace('T', ' ');+}++function pctDelta(sqliteValue: number, chValue: number): number {+ if (sqliteValue === 0 && chValue === 0) return 0;+ const denom = Math.max(1, Math.abs(sqliteValue));+ return ((chValue - sqliteValue) / denom) * 100;+}++async function queryClickHouseSummary(+ endpoint: string,+ authHeader: string,+ database: string,+ backendId: number,+ from: string,+ to: string,+ timeoutMs: number,+): Promise<Summary> {+ const query = `+SELECT+ toUInt64(COALESCE(SUM(upload), 0)) AS upload,+ toUInt64(COALESCE(SUM(download), 0)) AS download,+ toUInt64(COALESCE(SUM(connections), 0)) AS connections,+ toUInt64(uniqExactIf(domain, domain != '')) AS uniqueDomains,+ toUInt64(uniqExactIf(ip, ip != '')) AS uniqueIPs+FROM ${database}.traffic_minute+WHERE backend_id = ${backendId}+ AND minute >= toDateTime('${from}')+ AND minute <= toDateTime('${to}')+FORMAT JSON+`;++ const response = await fetch(+ `${endpoint}/?database=${encodeURIComponent(database)}&query=${encodeURIComponent(query)}`,+ {+ method: 'POST',+ headers: {+ ...(authHeader ? { Authorization: authHeader } : {}),+ },+ signal: AbortSignal.timeout(timeoutMs),+ },+ );++ if (!response.ok) {+ const body = await response.text();+ throw new Error(`status=${response.status} body=${body.slice(0, 160)}`);+ }++ const json = (await response.json()) as { data?: Array<Record<string, unknown>> };+ const row = json.data?.[0] || {};+ return {+ upload: Number(row.upload || 0),+ download: Number(row.download || 0),+ connections: Number(row.connections || 0),+ uniqueDomains: Number(row.uniqueDomains || 0),+ uniqueIPs: Number(row.uniqueIPs || 0),+ };+}++function querySqliteSummary(+ db: Database.Database,+ backendId: number,+ from: string,+ to: string,+): Summary {+ const stmt = db.prepare(`+ SELECT+ COALESCE(SUM(upload), 0) AS upload,+ COALESCE(SUM(download), 0) AS download,+ COALESCE(SUM(connections), 0) AS connections,+ COUNT(DISTINCT CASE WHEN domain != '' THEN domain END) AS uniqueDomains,+ COUNT(DISTINCT CASE WHEN ip != '' THEN ip END) AS uniqueIPs+ FROM minute_dim_stats+ WHERE backend_id = ? AND minute >= ? AND minute <= ?+ `);+ const row = stmt.get(backendId, from, to) as Record<string, unknown>;+ return {+ upload: Number(row.upload || 0),+ download: Number(row.download || 0),+ connections: Number(row.connections || 0),+ uniqueDomains: Number(row.uniqueDomains || 0),+ uniqueIPs: Number(row.uniqueIPs || 0),+ };+}++async function main(): Promise<void> {+ const options = parseArgs(process.argv.slice(2));+ const config = loadClickHouseConfig();+ if (!config.enabled) {+ throw new Error('CH_ENABLED must be 1 when running verification');+ }++ await ensureClickHouseReady(config);++ const from = toDateTime(options.from || new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString());+ const to = toDateTime(options.to || new Date().toISOString());++ const db = new Database(options.sqlitePath, { readonly: true });+ const backends = db+ .prepare(`SELECT id, name FROM backend_configs ORDER BY id ASC`)+ .all() as BackendRow[];++ const endpoint = `${config.protocol}://${config.host}:${config.port}`;+ const authHeader =+ config.password.length > 0+ ? `Basic ${Buffer.from(`${config.user}:${config.password}`).toString('base64')}`+ : '';++ let hasExceeded = false;+ try {+ console.info(+ `[Verify] sqlite=${options.sqlitePath} window=${from}..${to} max_delta=${options.maxDeltaPercent}% fail_on_delta=${options.failOnDelta ? '1' : '0'}`,+ );++ for (const backend of backends) {+ const sqlite = querySqliteSummary(db, backend.id, from, to);+ const ch = await queryClickHouseSummary(+ endpoint,+ authHeader,+ config.database,+ backend.id,+ from,+ to,+ config.timeoutMs,+ );++ const deltas = {+ upload: pctDelta(sqlite.upload, ch.upload),+ download: pctDelta(sqlite.download, ch.download),+ connections: pctDelta(sqlite.connections, ch.connections),+ uniqueDomains: pctDelta(sqlite.uniqueDomains, ch.uniqueDomains),+ uniqueIPs: pctDelta(sqlite.uniqueIPs, ch.uniqueIPs),+ };++ const exceeded = Object.values(deltas).some(+ (delta) => Math.abs(delta) > options.maxDeltaPercent,+ );+ if (exceeded) {+ hasExceeded = true;+ }++ console.info(+ `[Verify] backend=${backend.id}:${backend.name} sqlite(upload=${sqlite.upload},download=${sqlite.download},conn=${sqlite.connections},domains=${sqlite.uniqueDomains},ips=${sqlite.uniqueIPs}) ch(upload=${ch.upload},download=${ch.download},conn=${ch.connections},domains=${ch.uniqueDomains},ips=${ch.uniqueIPs}) delta(upload=${deltas.upload.toFixed(2)}%,download=${deltas.download.toFixed(2)}%,conn=${deltas.connections.toFixed(2)}%,domains=${deltas.uniqueDomains.toFixed(2)}%,ips=${deltas.uniqueIPs.toFixed(2)}%) status=${exceeded ? 'WARN' : 'OK'}`,+ );+ }+ } finally {+ db.close();+ }++ if (options.failOnDelta && hasExceeded) {+ throw new Error(+ `delta exceeded max threshold ${options.maxDeltaPercent}% for at least one backend`,+ );+ }+}++void main().catch((error) => {+ const message = error instanceof Error ? error.message : String(error);+ console.error(`[Verify] failed: ${message}`);+ process.exit(1);+});diff --git a/docker-compose.yml b/docker-compose.ymlindex b9aec4a..db575e2 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -25,6 +25,28 @@ services:- COOKIE_SECRET=${COOKIE_SECRET:-}- GEOIP_LOOKUP_PROVIDER=${GEOIP_LOOKUP_PROVIDER:-}- GEOIP_ONLINE_API_URL=${GEOIP_ONLINE_API_URL:-}+ - CH_ENABLED=${CH_ENABLED:-0}+ - CH_REQUIRED=${CH_REQUIRED:-0}+ - CH_SECURE=${CH_SECURE:-0}+ - CH_HOST=${CH_HOST:-clickhouse}+ - CH_PORT=${CH_PORT:-8123}+ - CH_DATABASE=${CH_DATABASE:-neko_master}+ - CH_USER=${CH_USER:-neko}+ - CH_PASSWORD=${CH_PASSWORD:-neko_master}+ - CH_WRITE_ENABLED=${CH_WRITE_ENABLED:-0}+ - CH_WRITE_MAX_PENDING_BATCHES=${CH_WRITE_MAX_PENDING_BATCHES:-200}+ - CH_AUTO_CREATE_TABLES=${CH_AUTO_CREATE_TABLES:-1}+ - CH_METRICS_LOG_INTERVAL_MS=${CH_METRICS_LOG_INTERVAL_MS:-60000}+ - CH_COMPARE_ENABLED=${CH_COMPARE_ENABLED:-0}+ - CH_COMPARE_INTERVAL_MS=${CH_COMPARE_INTERVAL_MS:-120000}+ - CH_COMPARE_WINDOW_MINUTES=${CH_COMPARE_WINDOW_MINUTES:-10}+ - CH_COMPARE_TIMEOUT_MS=${CH_COMPARE_TIMEOUT_MS:-8000}+ - CH_COMPARE_START_DELAY_MS=${CH_COMPARE_START_DELAY_MS:-120000}+ - STATS_QUERY_SOURCE=${STATS_QUERY_SOURCE:-sqlite}+ - STATS_ROUTE_METRICS_LOG_INTERVAL_MS=${STATS_ROUTE_METRICS_LOG_INTERVAL_MS:-60000}+ - CH_CONNECT_TIMEOUT_MS=${CH_CONNECT_TIMEOUT_MS:-5000}+ - CH_CONNECT_MAX_RETRIES=${CH_CONNECT_MAX_RETRIES:-5}+ - CH_CONNECT_RETRY_DELAY_MS=${CH_CONNECT_RETRY_DELAY_MS:-2000}networks:- neko-master-network# 健康检查@@ -35,6 +57,30 @@ services:retries: 3start_period: 40s+ clickhouse:+ image: clickhouse/clickhouse-server:24.8+ container_name: neko-master-clickhouse+ restart: unless-stopped+ profiles: ["clickhouse"]+ ports:+ - "${CH_EXTERNAL_HTTP_PORT:-8123}:8123"+ - "${CH_EXTERNAL_NATIVE_PORT:-9000}:9000"+ volumes:+ - ./data/clickhouse:/var/lib/clickhouse+ environment:+ - CLICKHOUSE_DB=${CH_DATABASE:-neko_master}+ - CLICKHOUSE_USER=${CH_USER:-neko}+ - CLICKHOUSE_PASSWORD=${CH_PASSWORD:-neko_master}+ - CLICKHOUSE_DEFAULT_ACCESS_MANAGEMENT=1+ networks:+ - neko-master-network+ healthcheck:+ test: ["CMD-SHELL", "wget -q --spider http://127.0.0.1:8123/ping || exit 1"]+ interval: 30s+ timeout: 10s+ retries: 3+ start_period: 40s+networks:neko-master-network:driver: bridgediff --git a/docs/README.md b/docs/README.mdindex 3f96c45..1e13a06 100644--- a/docs/README.md+++ b/docs/README.md@@ -4,6 +4,7 @@- Chinese: `docs/architecture.md`- English: `docs/architecture.en.md`+- ClickHouse Refactor Plan: `docs/clickhouse-refactor-plan.md`## Agentdiff --git a/docs/clickhouse-refactor-plan.md b/docs/clickhouse-refactor-plan.mdnew file mode 100644index 0000000..03132c8--- /dev/null+++ b/docs/clickhouse-refactor-plan.md@@ -0,0 +1,313 @@+# ClickHouse Refactor Plan (Homelab Balanced)++## Goal++- Reduce collector disk read pressure caused by SQLite UPSERT read amplification.+- Keep existing product behavior and API contracts stable during migration.+- Use a homelab-friendly architecture: minimal new components, simple rollback.++## Scope++- In scope:+ - Stats storage/query path migration (summary, trend, domains, IPs, proxies, rules, countries, hourly).+ - Collector dual-write support (SQLite + ClickHouse) with feature flags.+ - Query routing with gradual cutover and instant fallback.+- Out of scope:+ - Auth/session/backend management schema migration.+ - Agent protocol changes.+ - Frontend major redesign.++## Target Architecture (Phase End State)++- `web` (Next.js)+- `collector-api` (Fastify API + WS)+- `collector-ingest` (traffic ingest/flush worker, can remain in same process at first)+- `clickhouse` (stats store/query)+- SQLite remains for control-plane and fallback reads.++## Why This Path++- Current bottleneck is not GeoIP query frequency anymore; it is write-path index lookups from heavy SQLite UPSERTs.+- ClickHouse is better suited for high-frequency append/aggregate workloads.+- Dual-write + staged read cutover gives low-risk migration and quick rollback.++## Migration Principles++- No big-bang switch.+- Every phase has measurable acceptance criteria.+- Any failure must be recoverable by env flag change.+- Keep API response shape unchanged for frontend.++## Delivery Phases++### Phase 0: Design and Baseline++- Produce table mapping and query mapping from SQLite to ClickHouse.+- Capture baseline metrics (3 runs recommended):+ - `Avg Read Speed`, `P95 Read Speed`, `Avg Write Speed`+ - API latency P95 for core endpoints+ - Data consistency delta for key stats+- Deliverables:+ - This plan + mapping section completed+ - Baseline benchmark notes++### Phase 1: Infrastructure and Config++- Add ClickHouse service to docker-compose (single node).+- Add env flags (default disabled):+ - `CH_ENABLED=0`+ - `CH_HOST`, `CH_PORT`, `CH_DATABASE`, `CH_USER`, `CH_PASSWORD`+ - `CH_WRITE_ENABLED=0`+ - `STATS_QUERY_SOURCE=sqlite` (`sqlite|clickhouse|auto`)+- Add startup health logs and connection retry.+- Acceptance:+ - Service boots with CH disabled and unchanged behavior.+ - CH enabled but write disabled does not impact current flow.++### Phase 2: Schema and Write Path (Dual Write)++- Create ClickHouse tables for minute-level aggregated facts and dimensions.+- Implement batched insert from existing flush path.+- Keep SQLite write as primary; CH write is best-effort and isolated.+- Add write metrics logs:+ - `ch_write_rows`, `ch_write_batches`, `ch_write_failures`, `ch_write_latency_ms`+- Acceptance:+ - CH row growth matches expected ingest rate.+ - SQLite remains healthy when CH is degraded.++### Phase 3: Query Routing (Read Gray Release)++- Implement repository/router layer for stats reads.+- Route low-risk endpoints first:+ - summary, trend, top domains, top IPs, hourly stats+- Add consistency checker (same time window compare SQLite vs CH).+- Acceptance:+ - Delta within tolerance (default < 1%).+ - API latency stable or improved.++### Phase 4: Default Cutover++- Switch `STATS_QUERY_SOURCE=auto` or `clickhouse` for target endpoints.+- Keep SQLite query path as fallback.+- Tune retention/TTL in CH.+- Acceptance:+ - Disk read drop meets target.+ - No functional regression in dashboard.++### Phase 5: Cleanup and Docs++- Document operations, backup, troubleshooting, rollback.+- Keep feature flags for one release cycle.++## Data Model Draft (Initial)++### 1) `traffic_minute`++- Purpose: minute-level aggregated traffic by core dimensions.+- Suggested columns:+ - `backend_id UInt32`+ - `minute DateTime`+ - `domain LowCardinality(String)`+ - `ip String`+ - `source_ip String`+ - `chain String`+ - `rule String`+ - `upload UInt64`+ - `download UInt64`+ - `connections UInt32`+- Engine: `SummingMergeTree`+- Partition: by month (`toYYYYMM(minute)`)+- Order key: `(backend_id, minute, domain, ip, source_ip, chain, rule)`++### 2) `country_minute`++- Purpose: country/continent aggregates.+- Suggested columns:+ - `backend_id UInt32`+ - `minute DateTime`+ - `country LowCardinality(String)`+ - `country_name String`+ - `continent LowCardinality(String)`+ - `upload UInt64`+ - `download UInt64`+ - `connections UInt32`++### 3) Optional Materialized Views++- hourly rollups for faster dashboard hourly charts.+- top-k helper views for common ranking queries.++## Feature Flags and Rollback++- Flags:+ - `CH_ENABLED`+ - `CH_WRITE_ENABLED`+ - `STATS_QUERY_SOURCE`+- Rollback:+ - Set `STATS_QUERY_SOURCE=sqlite`+ - Set `CH_WRITE_ENABLED=0`+ - Keep service up without data loss on control-plane path.++## Risks and Mitigations++- Risk: dual-write overhead.+ - Mitigation: bounded batch size, async write, non-blocking fallback.+- Risk: temporary data inconsistency.+ - Mitigation: consistency checker + alert threshold.+- Risk: homelab resource spikes.+ - Mitigation: single-node CH with memory caps and retention TTL.++## Estimated Complexity (Homelab)++- Infra complexity: medium (+1 core service).+- Code complexity: medium (new write adapter + query router).+- Ops complexity: medium (add CH backup/health checks).++## Acceptance Criteria (Go/No-Go)++- `Avg Read Speed` reduced by at least 30% in 3 comparable runs.+- Dashboard core endpoints no regression in p95 latency.+- Data consistency delta under 1% for selected windows.+- Rollback tested and documented.++## Execution Checklist (Pre-Start)++- [ ] Confirm final scope and endpoints for first cutover.+- [ ] Confirm retention policy in CH (days/months).+- [ ] Confirm whether to keep ingest in collector process or separate worker container.+- [ ] Confirm resource limits for CH container (CPU/RAM/disk).++## Current Implementation Status++- Completed:+ - Phase 1 infra wiring (optional ClickHouse service + connectivity checks).+ - Phase 2 baseline dual-write scaffolding (SQLite primary, CH best-effort writes behind flags).+ - Auto schema bootstrap for `traffic_minute` and `country_minute`.+ - Compare service for SQLite vs ClickHouse traffic windows (non-blocking logs).+ - Initial read routing for core stats endpoints:+ - `/api/stats/summary`+ - `/api/stats/domains`+ - `/api/stats/ips`+ - `/api/stats/domains/proxy-stats`+ - `/api/stats/domains/ip-details`+ - `/api/stats/ips/proxy-stats`+ - `/api/stats/ips/domain-details`+ - `/api/stats/proxies`+ - `/api/stats/proxies/domains`+ - `/api/stats/proxies/ips`+ - `/api/stats/rules`+ - `/api/stats/rules/domains`+ - `/api/stats/rules/ips`+ - `/api/stats/rules/domains/proxy-stats`+ - `/api/stats/rules/domains/ip-details`+ - `/api/stats/rules/ips/proxy-stats`+ - `/api/stats/rules/ips/domain-details`+ - `/api/stats/countries`+ - `/api/stats/devices`+ - `/api/stats/devices/domains`+ - `/api/stats/devices/ips`+ - `/api/stats/hourly`+ - `/api/stats/trend`+ - `/api/stats/trend/aggregated`+- Not completed yet:+ - Keep SQLite-only for non-aggregated or graph-specific endpoints:+ - `/api/stats/rules/chain-flow`+ - `/api/stats/rules/chain-flow-all`+ - `/api/stats/rule-proxy-map`+ - `/api/stats/connections`+ - `/api/stats/global`++## Homelab Trial Run (Current)++1. Start with ClickHouse profile:+ - `CH_ENABLED=1 docker compose --profile clickhouse up -d`+2. Verify readiness logs:+ - `[ClickHouse] Ready ...`+ - `[ClickHouse] Schema ensured ...`+3. Enable dual-write in collector:+ - `CH_WRITE_ENABLED=1`+4. Observe writer metrics:+ - `[ClickHouse Writer] ... failures=0 ...`+5. (Optional) Enable compare logs:+ - `CH_COMPARE_ENABLED=1`+ - Observe: `[ClickHouse Compare] backend=... upload_delta=... download_delta=...`+5. Rollback instantly if needed:+ - `CH_WRITE_ENABLED=0` (keeps SQLite path unchanged)++## SQLite -> ClickHouse Data Migration Script++To help existing SQLite users transfer historical data before cutover, collector now includes:++- Script: `apps/collector/src/scripts/migrate-sqlite-to-clickhouse.ts`+- Command:+ - `pnpm --filter @neko-master/collector migrate:sqlite-to-ch`++Common examples:++- Append-import from current SQLite DB:+ - `CH_ENABLED=1 pnpm --filter @neko-master/collector migrate:sqlite-to-ch -- --sqlite ./apps/collector/stats.db`+- Replace target tables and re-import:+ - `CH_ENABLED=1 pnpm --filter @neko-master/collector migrate:sqlite-to-ch -- --sqlite ./apps/collector/stats.db --truncate`+- Import a time window only:+ - `CH_ENABLED=1 pnpm --filter @neko-master/collector migrate:sqlite-to-ch -- --sqlite ./apps/collector/stats.db --from 2026-02-01T00:00:00Z --to 2026-02-20T00:00:00Z`++Validation command after migration:++- Compare SQLite vs CH over a time window:+ - `CH_ENABLED=1 pnpm --filter @neko-master/collector verify:sqlite-vs-ch -- --sqlite ./apps/collector/stats.db --from 2026-02-01T00:00:00Z --to 2026-02-20T00:00:00Z`+- Fail CI/automation when delta is above threshold:+ - `CH_ENABLED=1 pnpm --filter @neko-master/collector verify:sqlite-vs-ch -- --sqlite ./apps/collector/stats.db --max-delta 1 --fail-on-delta`++Current migration coverage:++- `minute_dim_stats` -> `traffic_minute`+- `minute_country_stats` -> `country_minute`++Notes:++- Script is idempotent only when importing disjoint windows, or when using `--truncate` before full re-import.+- For now, rule graph specific tables are still read from SQLite and do not require CH migration.++## Docker Users (Minimal Steps)++Default compose now uses one-click interop credentials for ClickHouse:++- `CH_USER=neko`+- `CH_PASSWORD=neko_master`++So most Docker users do not need manual credential edits.++Recommended migration sequence:++1. Start with ClickHouse enabled but keep SQLite reads:+ - `CH_ENABLED=1 CH_WRITE_ENABLED=1 STATS_QUERY_SOURCE=sqlite docker compose --profile clickhouse up -d`+2. Migrate historical data inside container:+ - `docker exec -it neko-master node /app/apps/collector/dist/scripts/migrate-sqlite-to-clickhouse.js --sqlite /app/data/stats.db --truncate`+3. Verify SQLite vs ClickHouse consistency:+ - `docker exec -it neko-master node /app/apps/collector/dist/scripts/verify-sqlite-clickhouse.js --sqlite /app/data/stats.db --max-delta 1 --fail-on-delta`+4. Switch to routed reads after verification:+ - `STATS_QUERY_SOURCE=auto docker compose up -d`++Rollback:++- `STATS_QUERY_SOURCE=sqlite CH_WRITE_ENABLED=0 docker compose up -d`++## Active Environment Flags++- `CH_ENABLED` (0/1): enable CH integration+- `CH_REQUIRED` (0/1): fail startup if CH unavailable+- `CH_HOST`, `CH_PORT`, `CH_DATABASE`, `CH_USER`, `CH_PASSWORD`+- `CH_WRITE_ENABLED` (0/1): enable dual-write+- `CH_WRITE_MAX_PENDING_BATCHES` (default 200)+- `CH_AUTO_CREATE_TABLES` (default 1)+- `CH_METRICS_LOG_INTERVAL_MS` (default 60000)+- `CH_COMPARE_ENABLED` (default 0)+- `CH_COMPARE_INTERVAL_MS` (default 120000)+- `CH_COMPARE_WINDOW_MINUTES` (default 10)+- `CH_COMPARE_TIMEOUT_MS` (default 8000)+- `CH_COMPARE_START_DELAY_MS` (default 120000)+- `STATS_QUERY_SOURCE` (default sqlite, reserved for next phase)+- `STATS_ROUTE_METRICS_LOG_INTERVAL_MS` (default 60000, set 0 to disable)+- `CH_CONNECT_TIMEOUT_MS` (default 5000)+- `CH_CONNECT_MAX_RETRIES` (default 5)+- `CH_CONNECT_RETRY_DELAY_MS` (default 2000)diff --git a/scripts/ch-migrate-docker.sh b/scripts/ch-migrate-docker.shnew file mode 100755index 0000000..d12c888--- /dev/null+++ b/scripts/ch-migrate-docker.sh@@ -0,0 +1,84 @@+#!/usr/bin/env bash++set -euo pipefail++SQLITE_PATH="/app/data/stats.db"+MAX_DELTA="1"+TRUNCATE_FLAG="--truncate"+FROM_ARG=""+TO_ARG=""++while [[ $# -gt 0 ]]; do+ case "$1" in+ --sqlite-path)+ SQLITE_PATH="$2"+ shift 2+ ;;+ --from)+ FROM_ARG="--from $2"+ shift 2+ ;;+ --to)+ TO_ARG="--to $2"+ shift 2+ ;;+ --max-delta)+ MAX_DELTA="$2"+ shift 2+ ;;+ --append)+ TRUNCATE_FLAG=""+ shift+ ;;+ -h | --help)+ cat <<'EOF'+Usage: scripts/ch-migrate-docker.sh [options]++Options:+ --sqlite-path <path> SQLite path inside container (default: /app/data/stats.db)+ --from <iso-time> Optional migration start time (e.g. 2026-02-01T00:00:00Z)+ --to <iso-time> Optional migration end time+ --max-delta <percent> Verify threshold percent (default: 1)+ --append Do not truncate ClickHouse tables before import+ -h, --help Show this help++Examples:+ scripts/ch-migrate-docker.sh+ scripts/ch-migrate-docker.sh --append+ scripts/ch-migrate-docker.sh --from 2026-02-01T00:00:00Z --to 2026-02-20T00:00:00Z+EOF+ exit 0+ ;;+ *)+ echo "Unknown argument: $1" >&2+ exit 1+ ;;+ esac+done++echo "[1/4] Starting containers (including ClickHouse profile)..."+docker compose --profile clickhouse up -d++echo "[2/4] Migrating SQLite -> ClickHouse..."+docker compose exec -T \+ -e CH_ENABLED=1 \+ neko-master \+ node /app/apps/collector/dist/scripts/migrate-sqlite-to-clickhouse.js \+ --sqlite "$SQLITE_PATH" \+ $TRUNCATE_FLAG \+ $FROM_ARG \+ $TO_ARG++echo "[3/4] Verifying SQLite vs ClickHouse..."+docker compose exec -T \+ -e CH_ENABLED=1 \+ neko-master \+ node /app/apps/collector/dist/scripts/verify-sqlite-clickhouse.js \+ --sqlite "$SQLITE_PATH" \+ --max-delta "$MAX_DELTA" \+ --fail-on-delta \+ $FROM_ARG \+ $TO_ARG++echo "[4/4] Done. Recommended next step: set STATS_QUERY_SOURCE=auto and restart"+echo " docker compose up -d"