A modern and elegant dashboard for network traffic visualization and analysis.
fix: bucket daily trends by the viewer's local day (#82)
luolei3b515fc0c2fa
diff --git a/apps/collector/src/database/repositories/timeseries.repository.test.ts b/apps/collector/src/database/repositories/timeseries.repository.test.tsnew file mode 100644index 0000000..25c9d09--- /dev/null+++ b/apps/collector/src/database/repositories/timeseries.repository.test.ts@@ -0,0 +1,89 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { createTestDatabase, createTestBackend } from '../../__tests__/helpers.js';+import type { StatsDatabase } from '../../modules/db/db.js';++describe('TimeseriesRepository daily trend buckets', () => {+ let db: StatsDatabase;+ let cleanup: () => void;+ let backendId: number;+ const start = '2026-10-07T00:00:00Z';+ const end = '2026-10-10T00:00:00Z';++ beforeEach(() => {+ ({ db, cleanup } = createTestDatabase());+ backendId = createTestBackend(db);+ });++ afterEach(() => {+ cleanup();+ });++ function writeTraffic(hour: string, upload = 10, download = 20, targetBackendId = backendId): void {+ db.batchUpdateTrafficStats(targetBackendId, [{+ domain: 'example.com',+ ip: '1.2.3.4',+ chain: 'DIRECT',+ chains: ['DIRECT'],+ rule: 'Match',+ rulePayload: '',+ upload,+ download,+ timestampMs: Date.parse(`${hour}Z`),+ }]);+ }++ function queryTrend(bucketMinutes = 1440, tzOffsetMinutes?: number) {+ return db.repos.timeseries.getTrafficTrendAggregated(+ backendId, 4320, bucketMinutes, start, end, tzOffsetMinutes,+ );+ }++ it.each([+ [480, '2026-10-08T16:00:00'],+ [330, '2026-10-08T18:30:00'],+ [-300, '2026-10-08T05:00:00'],+ [-210, '2026-10-08T03:30:00'],+ ])('returns the UTC start of the local day for offset %i', (offset, time) => {+ writeTraffic('2026-10-08T20:00:00');++ expect(queryTrend(1440, offset)).toEqual([{ time, upload: 10, download: 20 }]);+ });++ it('preserves the UTC bucket and serialized output when the offset is omitted or zero', () => {+ writeTraffic('2026-10-08T20:00:00');+ const expected = [{ time: '2026-10-08T00:00:00', upload: 10, download: 20 }];++ expect(queryTrend()).toEqual(expected);+ expect(JSON.stringify(queryTrend(1440, 0))).toBe(JSON.stringify(expected));+ });++ it('splits at local midnight, sums each day, and isolates backends', () => {+ writeTraffic('2026-10-08T15:00:00', 1, 2);+ writeTraffic('2026-10-08T16:00:00', 3, 4);+ writeTraffic('2026-10-08T20:00:00', 5, 6);+ const otherBackendId = createTestBackend(db, 'other-backend');+ writeTraffic('2026-10-08T20:00:00', 100, 200, otherBackendId);++ expect(queryTrend(1440, 480)).toEqual([+ { time: '2026-10-07T16:00:00', upload: 1, download: 2 },+ { time: '2026-10-08T16:00:00', upload: 8, download: 10 },+ ]);+ });++ it('uses daily boundaries for buckets larger than one day', () => {+ writeTraffic('2026-10-08T20:00:00');++ expect(queryTrend(2880, 480)).toEqual([+ { time: '2026-10-08T16:00:00', upload: 10, download: 20 },+ ]);+ });++ it.each([1, 5, 60, 120, 1439])('ignores offsets for %i-minute buckets', (bucketMinutes) => {+ writeTraffic('2026-10-08T20:00:00');+ const withoutOffset = queryTrend(bucketMinutes);++ expect(withoutOffset).toHaveLength(1);+ expect(JSON.stringify(queryTrend(bucketMinutes, 480))).toBe(JSON.stringify(withoutOffset));+ expect(JSON.stringify(queryTrend(bucketMinutes, -210))).toBe(JSON.stringify(withoutOffset));+ });+});diff --git a/apps/collector/src/database/repositories/timeseries.repository.ts b/apps/collector/src/database/repositories/timeseries.repository.tsindex 2597248..86fc950 100644--- a/apps/collector/src/database/repositories/timeseries.repository.ts+++ b/apps/collector/src/database/repositories/timeseries.repository.ts@@ -122,6 +122,7 @@ export class TimeseriesRepository extends BaseRepository {bucketMinutes = 1,start?: string,end?: string,+ tzOffsetMinutes = 0,): Array<{ time: string; upload: number; download: number }> {const range = this.parseMinuteRange(start, end);const cutoff = new Date(Date.now() - minutes * 60 * 1000);@@ -135,6 +136,28 @@ export class TimeseriesRepository extends BaseRepository {const endHour = this.toHourKey(new Date(endMinute));if (bucketMinutes >= 1440) {+ if (tzOffsetMinutes !== 0) {+ // Shift to the caller's local day, truncate, then return its UTC start.+ const bucketExpr = `strftime('%Y-%m-%dT%H:%M:00', hour, @offset, 'start of day', @reverseOffset)`;+ const stmt = this.db.prepare(`+ SELECT+ ${bucketExpr} as time,+ SUM(upload) as upload,+ SUM(download) as download+ FROM hourly_stats+ WHERE backend_id = @backendId AND hour >= @startHour AND hour <= @endHour+ GROUP BY ${bucketExpr}+ ORDER BY time ASC+ `);+ return stmt.all({+ backendId,+ startHour,+ endHour,+ offset: `${tzOffsetMinutes} minutes`,+ reverseOffset: `${-tzOffsetMinutes} minutes`,+ }) as Array<{ time: string; upload: number; download: number }>;+ }+// Daily bucket: group by dateconst stmt = this.db.prepare(`SELECTdiff --git a/apps/collector/src/modules/clickhouse/clickhouse.reader.test.ts b/apps/collector/src/modules/clickhouse/clickhouse.reader.test.tsnew file mode 100644index 0000000..7640256--- /dev/null+++ b/apps/collector/src/modules/clickhouse/clickhouse.reader.test.ts@@ -0,0 +1,90 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { ClickHouseReader } from './clickhouse.reader.js';++describe('ClickHouseReader daily trend buckets', () => {+ const sampleHour = '2026-10-08T20:00:00Z';+ const fetchMock = vi.fn<typeof fetch>();++ beforeEach(() => {+ vi.stubEnv('CH_ENABLED', '1');+ vi.stubEnv('CH_DATABASE', 'neko_master');+ vi.stubEnv('STATS_QUERY_SOURCE', 'clickhouse');+ vi.stubGlobal('fetch', fetchMock);+ fetchMock.mockReset();+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ vi.unstubAllEnvs();+ });++ function mockBucket(time: string): void {+ fetchMock.mockImplementation(async () => Response.json({+ data: [{ time, upload: '3', download: '4' }],+ }));+ }++ function expectedQuery(bucketExpression: string): string {+ return `+SELECT+ toString(${bucketExpression}) AS time,+ toUInt64(SUM(upload)) AS upload,+ toUInt64(SUM(download)) AS download+FROM neko_master.traffic_agg_buffer+WHERE backend_id = 1+ AND minute >= toDateTime('2026-10-08 20:00:00')+ AND minute <= toDateTime('2026-10-08 20:00:00')+GROUP BY time+ORDER BY time ASC+\nFORMAT JSON`;+ }++ it.each([+ [480, 28800, '2026-10-08 16:00:00'],+ [-300, -18000, '2026-10-08 05:00:00'],+ [330, 19800, '2026-10-08 18:30:00'],+ [-210, -12600, '2026-10-08 03:30:00'],+ ])('aligns the SQL daily bucket for offset %i and returns a UTC minute key', async (offset, seconds, time) => {+ mockBucket(time);+ const result = await new ClickHouseReader().getTrafficTrendAggregated(1, 1440, sampleHour, sampleHour, offset);++ expect(fetchMock).toHaveBeenCalledOnce();+ expect(fetchMock.mock.calls[0][1]?.body).toBe(expectedQuery(+ `toDateTime(toInt64(floor((toInt64(toUnixTimestamp(minute)) + (${seconds})) / 86400) * 86400 - (${seconds})), 'UTC')`,+ ));+ expect(result).toEqual([{ time: time.replace(' ', 'T'), upload: 3, download: 4 }]);+ });++ it.each([1, 60, 1440, 2880])('preserves the existing %i-minute SQL and output with a missing or zero offset', async (bucketMinutes) => {+ mockBucket('2026-10-08 00:00:00');+ const reader = new ClickHouseReader();+ const original = await reader.getTrafficTrendAggregated(1, bucketMinutes, sampleHour, sampleHour);+ const zeroOffset = await reader.getTrafficTrendAggregated(1, bucketMinutes, sampleHour, sampleHour, 0);+ const query = expectedQuery(bucketMinutes <= 1 ? 'minute' : `toStartOfInterval(minute, INTERVAL ${bucketMinutes} MINUTE)`);++ expect(fetchMock.mock.calls[0][1]?.body).toBe(query);+ expect(fetchMock.mock.calls[1][1]?.body).toBe(query);+ expect(original).toEqual([{ time: '2026-10-08 00:00:00', upload: 3, download: 4 }]);+ expect(zeroOffset).toEqual(original);+ });++ it.each([1, 60, 1439])('ignores offsets for %i-minute buckets', async (bucketMinutes) => {+ mockBucket('2026-10-08 20:00:00');+ const reader = new ClickHouseReader();+ const original = await reader.getTrafficTrendAggregated(1, bucketMinutes, sampleHour, sampleHour);+ const shifted = await reader.getTrafficTrendAggregated(1, bucketMinutes, sampleHour, sampleHour, 330);++ expect(fetchMock.mock.calls[1][1]?.body).toBe(fetchMock.mock.calls[0][1]?.body);+ expect(shifted).toEqual(original);+ });++ it('uses a local day when the requested bucket is longer than a day', async () => {+ mockBucket('2026-10-08 16:00:00');+ const result = await new ClickHouseReader().getTrafficTrendAggregated(1, 2880, sampleHour, sampleHour, 480);++ expect(fetchMock.mock.calls[0][1]?.body).toBe(expectedQuery(+ "toDateTime(toInt64(floor((toInt64(toUnixTimestamp(minute)) + (28800)) / 86400) * 86400 - (28800)), 'UTC')",+ ));+ expect(result).toEqual([{ time: '2026-10-08T16:00:00', upload: 3, download: 4 }]);+ });+});diff --git a/apps/collector/src/modules/clickhouse/clickhouse.reader.ts b/apps/collector/src/modules/clickhouse/clickhouse.reader.tsindex c32186f..c5d9b3d 100644--- a/apps/collector/src/modules/clickhouse/clickhouse.reader.ts+++ b/apps/collector/src/modules/clickhouse/clickhouse.reader.ts@@ -300,10 +300,14 @@ ORDER BY minute ASCbucketMinutes: number,start: string,end: string,+ tzOffsetMinutes = 0,): Promise<Array<{ time: string; upload: number; download: number }> | null> {const safeBucket = Math.max(1, Math.floor(bucketMinutes));- const bucketExpr =- safeBucket <= 1+ const useLocalDay = safeBucket >= 1440 && tzOffsetMinutes !== 0;+ const offsetSeconds = tzOffsetMinutes * 60;+ const bucketExpr = useLocalDay+ ? `toDateTime(toInt64(floor((toInt64(toUnixTimestamp(minute)) + (${offsetSeconds})) / 86400) * 86400 - (${offsetSeconds})), 'UTC')`+ : safeBucket <= 1? 'minute': `toStartOfInterval(minute, INTERVAL ${safeBucket} MINUTE)`;@@ -321,7 +325,7 @@ ORDER BY time ASC`);if (!rows) return null;return (rows as Array<any>).map((row) => ({- time: String(row.time || ''),+ time: useLocalDay ? String(row.time || '').replace(' ', 'T') : String(row.time || ''),upload: Number(row.upload || 0),download: Number(row.download || 0),}));diff --git a/apps/collector/src/modules/realtime/realtime.merger.ts b/apps/collector/src/modules/realtime/realtime.merger.tsindex 496d2e0..19a70bc 100644--- a/apps/collector/src/modules/realtime/realtime.merger.ts+++ b/apps/collector/src/modules/realtime/realtime.merger.ts@@ -22,10 +22,15 @@ function toMinuteKey(tsMs: number): string {return `${iso.slice(0, 16)}:00`;}-function bucketMinuteKey(minuteKey: string, bucketMinutes: number): string {+function bucketMinuteKey(minuteKey: string, bucketMinutes: number, tzOffsetMinutes = 0): string {if (bucketMinutes <= 1) return minuteKey;const timestampMs = Date.parse(`${minuteKey}Z`);if (!Number.isFinite(timestampMs)) return minuteKey;+ if (bucketMinutes >= 1440 && tzOffsetMinutes !== 0) {+ const dayMs = 1440 * 60 * 1000;+ const offsetMs = tzOffsetMinutes * 60 * 1000;+ return toMinuteKey(Math.floor((timestampMs + offsetMs) / dayMs) * dayMs - offsetMs);+ }const bucketMs = Math.floor(bucketMinutes) * 60 * 1000;return toMinuteKey(Math.floor(timestampMs / bucketMs) * bucketMs);}@@ -158,6 +163,7 @@ export class RealtimeMerger {minutes: number,bucketMinutes = 1,nowMs = Date.now(),+ tzOffsetMinutes = 0,): TrafficTrendPoint[] {const minuteMap = this.store.minuteByBackend.get(backendId);if (!minuteMap || minuteMap.size === 0) return basePoints;@@ -167,7 +173,7 @@ export class RealtimeMerger {for (const [minuteKey, bucket] of minuteMap) {if (minuteKey < cutoffKey) continue;- const bucketKey = bucketMinuteKey(minuteKey, bucketMinutes);+ const bucketKey = bucketMinuteKey(minuteKey, bucketMinutes, tzOffsetMinutes);const existing = deltaMap.get(bucketKey);if (existing) {existing.upload += bucket.upload;diff --git a/apps/collector/src/modules/realtime/realtime.store.ts b/apps/collector/src/modules/realtime/realtime.store.tsindex 842d658..49de6b4 100644--- a/apps/collector/src/modules/realtime/realtime.store.ts+++ b/apps/collector/src/modules/realtime/realtime.store.ts@@ -117,10 +117,15 @@ function toMinuteKey(tsMs: number): string {return `${iso.slice(0, 16)}:00`;}-function bucketMinuteKey(minuteKey: string, bucketMinutes: number): string {+function bucketMinuteKey(minuteKey: string, bucketMinutes: number, tzOffsetMinutes = 0): string {if (bucketMinutes <= 1) return minuteKey;const timestampMs = Date.parse(`${minuteKey}Z`);if (!Number.isFinite(timestampMs)) return minuteKey;+ if (bucketMinutes >= 1440 && tzOffsetMinutes !== 0) {+ const dayMs = 1440 * 60 * 1000;+ const offsetMs = tzOffsetMinutes * 60 * 1000;+ return toMinuteKey(Math.floor((timestampMs + offsetMs) / dayMs) * dayMs - offsetMs);+ }const bucketMs = Math.floor(bucketMinutes) * 60 * 1000;return toMinuteKey(Math.floor(timestampMs / bucketMs) * bucketMs);}@@ -674,6 +679,7 @@ export class RealtimeStore {minutes: number,bucketMinutes = 1,nowMs = Date.now(),+ tzOffsetMinutes = 0,): TrafficTrendPoint[] {const minuteMap = this.minuteByBackend.get(backendId);if (!minuteMap || minuteMap.size === 0) return basePoints;@@ -683,7 +689,7 @@ export class RealtimeStore {for (const [minuteKey, bucket] of minuteMap) {if (minuteKey < cutoffKey) continue;- const bucketKey = bucketMinuteKey(minuteKey, bucketMinutes);+ const bucketKey = bucketMinuteKey(minuteKey, bucketMinutes, tzOffsetMinutes);const existing = deltaMap.get(bucketKey);if (existing) {existing.upload += bucket.upload;diff --git a/apps/collector/src/modules/realtime/realtime.trend.test.ts b/apps/collector/src/modules/realtime/realtime.trend.test.tsindex 0d1c8f7..785fb43 100644--- a/apps/collector/src/modules/realtime/realtime.trend.test.ts+++ b/apps/collector/src/modules/realtime/realtime.trend.test.ts@@ -32,3 +32,61 @@ describe('realtime trend bucketing', () => {]);});});++describe.each(['store', 'merger'] as const)('realtime %s local daily trend buckets', (mode) => {+ const sampleNowMs = Date.parse('2026-10-09T00:00:00Z');++ function createTrend(minuteKeys = ['2026-10-08T20:00:00']) {+ const store = new RealtimeStore();+ store.minuteByBackend.set(backendId, new Map(minuteKeys.map((minuteKey) => [+ minuteKey,+ { upload: 3, download: 4, lastUpdated: sampleNowMs },+ ])));+ return mode === 'store' ? store : new RealtimeMerger(store);+ }++ it.each([+ [480, '2026-10-08T16:00:00'],+ [-300, '2026-10-08T05:00:00'],+ [330, '2026-10-08T18:30:00'],+ [-210, '2026-10-08T03:30:00'],+ ])('aligns a daily bucket with offset %i to %s', (offset, time) => {+ expect(createTrend().mergeTrend(backendId, [], 1440, 1440, sampleNowMs, offset)).toEqual([+ { time, upload: 3, download: 4 },+ ]);+ });++ it('merges into existing local-day buckets and splits at local midnight', () => {+ const trend = createTrend(['2026-10-08T15:59:00', '2026-10-08T16:00:00', '2026-10-08T20:00:00']);+ const base = [+ { time: '2026-10-07T16:00:00', upload: 10, download: 20 },+ { time: '2026-10-08T16:00:00', upload: 30, download: 40 },+ ];++ expect(trend.mergeTrend(backendId, base, 1440, 1440, sampleNowMs, 480)).toEqual([+ { time: '2026-10-07T16:00:00', upload: 13, download: 24 },+ { time: '2026-10-08T16:00:00', upload: 36, download: 48 },+ ]);+ });++ it('keeps missing and zero offsets identical to the existing UTC daily output', () => {+ const trend = createTrend();+ const expected = [{ time: '2026-10-08T00:00:00', upload: 3, download: 4 }];++ expect(trend.mergeTrend(backendId, [], 1440, 1440, sampleNowMs)).toEqual(expected);+ expect(trend.mergeTrend(backendId, [], 1440, 1440, sampleNowMs, 0)).toEqual(expected);+ });++ it.each([1, 60, 1439])('ignores offsets for %i-minute buckets', (bucketMinutes) => {+ const trend = createTrend();+ const expected = trend.mergeTrend(backendId, [], 1440, bucketMinutes, sampleNowMs);++ expect(trend.mergeTrend(backendId, [], 1440, bucketMinutes, sampleNowMs, 330)).toEqual(expected);+ });++ it('uses a local day when the requested bucket is longer than a day', () => {+ expect(createTrend().mergeTrend(backendId, [], 2880, 2880, sampleNowMs, 480)).toEqual([+ { time: '2026-10-08T16:00:00', upload: 3, download: 4 },+ ]);+ });+});diff --git a/apps/collector/src/modules/stats/stats.controller.test.ts b/apps/collector/src/modules/stats/stats.controller.test.tsindex 78b57b8..1fab104 100644--- a/apps/collector/src/modules/stats/stats.controller.test.ts+++ b/apps/collector/src/modules/stats/stats.controller.test.ts@@ -1,5 +1,5 @@import type { FastifyInstance } from 'fastify';-import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { createTestBackend, createTestDatabase } from '../../__tests__/helpers.js';import { createApp } from '../app/app.js';import type { StatsDatabase } from '../db/db.js';@@ -24,11 +24,81 @@ describe('StatsController', () => {});afterEach(async () => {+ vi.restoreAllMocks();await app.close();realtimeStore.clearBackend(backendId);cleanup();});+ it.each([+ [undefined, 0],+ ['0', 0],+ ['480', 480],+ ['-330', -330],+ ['480.9', 480],+ ['-330.9', -330],+ ['840', 840],+ ['-840', -840],+ ['9999', 840],+ ['-9999', -840],+ ['', 0],+ ['invalid', 0],+ ['480invalid', 0],+ ['NaN', 0],+ ['Infinity', 0],+ ['-Infinity', 0],+ ])('parses daily trend tzOffsetMinutes=%s as %i', async (rawOffset, expectedOffset) => {+ const getTrend = vi.spyOn(app.statsService, 'getTrafficTrendAggregatedWithRouting')+ .mockResolvedValue([]);+ const query = new URLSearchParams({+ backendId: String(backendId),+ minutes: '1440',+ bucketMinutes: '1440',+ });+ if (rawOffset !== undefined) query.set('tzOffsetMinutes', rawOffset);++ const response = await app.inject({+ method: 'GET',+ url: `/api/stats/trend/aggregated?${query}`,+ });++ expect(response.statusCode).toBe(200);+ expect(getTrend).toHaveBeenCalledWith(backendId, { active: false }, 1440, 1440, expectedOffset);+ });++ it('returns local daily buckets without sharing cached results across offsets', async () => {+ db.batchUpdateTrafficStats(backendId, [{+ domain: 'example.com',+ ip: '203.0.113.1',+ chain: 'DIRECT',+ chains: ['DIRECT'],+ rule: 'Match',+ rulePayload: '',+ upload: 3,+ download: 4,+ timestampMs: Date.parse('2026-10-08T20:00:00Z'),+ }]);+ const query = new URLSearchParams({+ backendId: String(backendId),+ start: '2026-10-08T00:00:00Z',+ end: '2026-10-09T12:00:00Z',+ minutes: '1440',+ bucketMinutes: '1440',+ });+ for (const [offset, expectedTime] of [+ [undefined, '2026-10-08T00:00:00'],+ ['480', '2026-10-08T16:00:00'],+ ['-480', '2026-10-08T08:00:00'],+ ['0', '2026-10-08T00:00:00'],+ ] as const) {+ if (offset === undefined) query.delete('tzOffsetMinutes');+ else query.set('tzOffsetMinutes', offset);+ const response = await app.inject({ method: 'GET', url: `/api/stats/trend/aggregated?${query}` });+ expect(response.statusCode).toBe(200);+ expect(response.json()).toEqual([{ time: expectedTime, upload: 3, download: 4 }]);+ }+ });+it('accepts a daily bucket for aggregated traffic trends', async () => {const baseUpdate = {domain: 'example.com',diff --git a/apps/collector/src/modules/stats/stats.controller.ts b/apps/collector/src/modules/stats/stats.controller.tsindex 03b85ac..21c4e11 100644--- a/apps/collector/src/modules/stats/stats.controller.ts+++ b/apps/collector/src/modules/stats/stats.controller.ts@@ -755,14 +755,19 @@ const statsController: FastifyPluginAsync = async (fastify: FastifyInstance): Pr}const query = request.query as Record<string, string | undefined>;- const { minutes = '30', bucketMinutes = '1' } = query;+ const { minutes = '30', bucketMinutes = '1', tzOffsetMinutes } = query;const windowMinutes = service.parseLimit(minutes, 30, 60 * 24 * 7);const bucket = service.parseLimit(bucketMinutes, 1, 24 * 60);+ const parsedOffset = typeof tzOffsetMinutes === 'string' ? Number(tzOffsetMinutes) : 0;+ const timezoneOffset = Number.isFinite(parsedOffset)+ ? Math.max(-840, Math.min(840, Math.trunc(parsedOffset)))+ : 0;return await service.getTrafficTrendAggregatedWithRouting(backendId,timeRange,windowMinutes,bucket,+ timezoneOffset,);});diff --git a/apps/collector/src/modules/stats/stats.service.test.ts b/apps/collector/src/modules/stats/stats.service.test.tsindex 23fa7ab..faa9dc9 100644--- a/apps/collector/src/modules/stats/stats.service.test.ts+++ b/apps/collector/src/modules/stats/stats.service.test.ts@@ -1,8 +1,9 @@-import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';import { createTestDatabase, createTestBackend } from '../../__tests__/helpers.js';import { StatsService } from './stats.service.js';import { realtimeStore } from '../realtime/realtime.store.js';import type { StatsDatabase } from '../db/db.js';+import { ClickHouseReader } from '../clickhouse/clickhouse.reader.js';describe('StatsService', () => {let db: StatsDatabase;@@ -17,6 +18,7 @@ describe('StatsService', () => {});afterEach(() => {+ vi.restoreAllMocks();realtimeStore.clearBackend(backendId);cleanup();});@@ -203,6 +205,46 @@ describe('StatsService', () => {});});+ describe('daily trend timezone routing', () => {+ it.each(['sqlite', 'clickhouse', 'unrouted'] as const)(+ 'merges persisted and realtime data in the same local day through %s',+ async (source) => {+ const nowMs = Date.parse('2026-10-09T12:00:00Z');+ vi.spyOn(Date, 'now').mockReturnValue(nowMs);+ vi.spyOn(ClickHouseReader.prototype, 'shouldUseForRange')+ .mockReturnValue(source === 'clickhouse');+ const chTrend = vi.spyOn(ClickHouseReader.prototype, 'getTrafficTrendAggregated')+ .mockResolvedValue([{ time: '2026-10-08T16:00:00', upload: 3, download: 4 }]);+ db.batchUpdateTrafficStats(backendId, [{+ domain: 'example.com',+ ip: '203.0.113.1',+ chain: 'DIRECT',+ chains: ['DIRECT'],+ rule: 'Match',+ rulePayload: '',+ upload: 3,+ download: 4,+ timestampMs: Date.parse('2026-10-08T19:00:00Z'),+ }]);+ realtimeStore.minuteByBackend.set(backendId, new Map([+ ['2026-10-08T20:00:00', { upload: 5, download: 6, lastUpdated: nowMs }],+ ]));+ const range = { active: true, start: '2026-10-08T00:00:00Z', end: '2026-10-09T12:00:00Z' };++ const result = source === 'unrouted'+ ? service.getTrafficTrendAggregated(backendId, range, 1440, 1440, 480)+ : await service.getTrafficTrendAggregatedWithRouting(backendId, range, 1440, 1440, 480);++ expect(result).toEqual([{ time: '2026-10-08T16:00:00', upload: 8, download: 10 }]);+ if (source === 'clickhouse') {+ expect(chTrend).toHaveBeenCalledWith(backendId, 1440, range.start, range.end, 480);+ } else {+ expect(chTrend).not.toHaveBeenCalled();+ }+ },+ );+ });+describe('strict mode routing', () => {it('should use clickhouse for aggregated trend when range is inactive', async () => {const prevStrict = process.env.CH_STRICT_STATS;diff --git a/apps/collector/src/modules/stats/stats.service.ts b/apps/collector/src/modules/stats/stats.service.tsindex 73dc649..1efa5a0 100644--- a/apps/collector/src/modules/stats/stats.service.ts+++ b/apps/collector/src/modules/stats/stats.service.ts@@ -1474,17 +1474,34 @@ export class StatsService {/*** Get traffic trend aggregated by time buckets for chart display*/+ private getTrafficTrendAggregatedBase(+ backendId: number,+ timeRange: TimeRange,+ minutes: number,+ bucketMinutes: number,+ tzOffsetMinutes: number,+ ): TrafficTrendPoint[] {+ if (bucketMinutes >= 1440 && tzOffsetMinutes !== 0) {+ // The legacy DB facade cache has no timezone dimension.+ return this.db.repos.timeseries.getTrafficTrendAggregated(+ backendId, minutes, bucketMinutes, timeRange.start, timeRange.end, tzOffsetMinutes,+ );+ }+ return this.db.getTrafficTrendAggregated(backendId, minutes, bucketMinutes, timeRange.start, timeRange.end);+ }+getTrafficTrendAggregated(backendId: number,timeRange: TimeRange,minutes: number,bucketMinutes: number,+ tzOffsetMinutes = 0,): TrafficTrendPoint[] {- const base = this.db.getTrafficTrendAggregated(backendId, minutes, bucketMinutes, timeRange.start, timeRange.end);+ const base = this.getTrafficTrendAggregatedBase(backendId, timeRange, minutes, bucketMinutes, tzOffsetMinutes);if (!this.shouldIncludeRealtime(timeRange)) {return base;}- return this.realtimeStore.mergeTrend(backendId, base, minutes, bucketMinutes);+ return this.realtimeStore.mergeTrend(backendId, base, minutes, bucketMinutes, undefined, tzOffsetMinutes);}async getTrafficTrendAggregatedWithRouting(@@ -1492,6 +1509,7 @@ export class StatsService {timeRange: TimeRange,minutes: number,bucketMinutes: number,+ tzOffsetMinutes = 0,): Promise<TrafficTrendPoint[]> {const queryRange = this.resolveQueryRange(timeRange, Math.max(1, minutes));const shouldUseCH =@@ -1505,16 +1523,17 @@ export class StatsService {bucketMinutes,queryRange.start,queryRange.end,+ tzOffsetMinutes,): null;const base =chBase ||- this.db.getTrafficTrendAggregated(+ this.getTrafficTrendAggregatedBase(backendId,+ timeRange,minutes,bucketMinutes,- timeRange.start,- timeRange.end,+ tzOffsetMinutes,);if (!chBase) {this.failIfStrictFallback('trend.aggregated');@@ -1524,7 +1543,7 @@ export class StatsService {if (!this.shouldIncludeRealtime(timeRange)) {return base;}- return this.realtimeStore.mergeTrend(backendId, base, minutes, bucketMinutes);+ return this.realtimeStore.mergeTrend(backendId, base, minutes, bucketMinutes, undefined, tzOffsetMinutes);}/**diff --git a/apps/web/components/overview/index.tsx b/apps/web/components/overview/index.tsxindex f5723ec..b9a79f6 100644--- a/apps/web/components/overview/index.tsx+++ b/apps/web/components/overview/index.tsx@@ -193,6 +193,7 @@ export function OverviewTab({}const bucketMinutes = granularity === "day" ? 24 * 60 : getMinuteBucket(durationMs);+ const tzOffsetMinutes = granularity === "day" ? -new Date().getTimezoneOffset() : undefined;const minutes = Math.max(1, Math.ceil(durationMs / 60000));const realtime = queryEnd.getTime() >= Date.now() - REALTIME_END_TOLERANCE_MS;@@ -202,6 +203,7 @@ export function OverviewTab({durationMs,minutes,bucketMinutes,+ tzOffsetMinutes,granularity,realtime,};@@ -227,7 +229,8 @@ export function OverviewTab({activeBackendId,trendQuery.minutes,trendQuery.bucketMinutes,- { start: trendQuery.start, end: trendQuery.end }+ { start: trendQuery.start, end: trendQuery.end },+ trendQuery.tzOffsetMinutes);queryClient.setQueryData(queryKey, stats.trendStats);@@ -240,6 +243,7 @@ export function OverviewTab({activeBackendId,minutes: trendQuery.minutes,bucketMinutes: trendQuery.bucketMinutes,+ tzOffsetMinutes: trendQuery.tzOffsetMinutes,range: { start: trendQuery.start, end: trendQuery.end },enabled: !!activeBackendId,refetchInterval: wsTrendEnabled && wsTrendConnected ? 90000 : false,diff --git a/apps/web/hooks/api/use-traffic-trend.ts b/apps/web/hooks/api/use-traffic-trend.tsindex a09d3a6..6f0d3ea 100644--- a/apps/web/hooks/api/use-traffic-trend.ts+++ b/apps/web/hooks/api/use-traffic-trend.ts@@ -8,6 +8,7 @@ interface UseTrafficTrendOptions {activeBackendId?: number;minutes?: number;bucketMinutes?: number;+ tzOffsetMinutes?: number;range?: TimeRange;enabled?: boolean;refetchInterval?: number | false | ((query: any) => number | false);@@ -19,19 +20,21 @@ export function useTrafficTrend({activeBackendId,minutes = 30,bucketMinutes = 1,+ tzOffsetMinutes,range,enabled = true,refetchInterval,}: UseTrafficTrendOptions) {return useQuery({- queryKey: getTrafficTrendQueryKey(activeBackendId, minutes, bucketMinutes, range),+ queryKey: getTrafficTrendQueryKey(activeBackendId, minutes, bucketMinutes, range, tzOffsetMinutes),queryFn: async () => {if (!activeBackendId) throw new Error("Backend ID is required");return api.getTrafficTrendAggregated(activeBackendId,minutes,bucketMinutes,- range+ range,+ tzOffsetMinutes);},enabled: !!activeBackendId && enabled,diff --git a/apps/web/lib/api.ts b/apps/web/lib/api.tsindex e2bcf68..dd4f853 100644--- a/apps/web/lib/api.ts+++ b/apps/web/lib/api.ts@@ -286,12 +286,13 @@ export const api = {end: range?.end,})),- getTrafficTrendAggregated: (backendId?: number, minutes = 30, bucketMinutes = 1, range?: TimeRange) =>+ getTrafficTrendAggregated: (backendId?: number, minutes = 30, bucketMinutes = 1, range?: TimeRange, tzOffsetMinutes?: number) =>fetchJson<TrafficTrendPoint[]>(buildUrl(`${API_BASE}/stats/trend/aggregated`, {backendId,minutes,bucketMinutes,+ tzOffsetMinutes: bucketMinutes >= 1440 ? tzOffsetMinutes : undefined,start: range?.start,end: range?.end,})diff --git a/apps/web/lib/stats-query-keys.ts b/apps/web/lib/stats-query-keys.tsindex 4e87e0c..c7cef9d 100644--- a/apps/web/lib/stats-query-keys.ts+++ b/apps/web/lib/stats-query-keys.ts@@ -79,6 +79,7 @@ export function getTrafficTrendQueryKey(minutes = 30,bucketMinutes = 1,range?: TimeRange,+ tzOffsetMinutes?: number,) {return ["stats",@@ -87,6 +88,7 @@ export function getTrafficTrendQueryKey(backendId: backendId ?? null,minutes,bucketMinutes,+ tzOffsetMinutes: bucketMinutes >= 1440 ? (tzOffsetMinutes ?? 0) : 0,...normalizeRange(range),},] as const;