Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

refactor(analytics): one time window, one fill, for every bucketed query (#1119)

Goldflag9c66672b25e2
diff --git a/server/src/api/admin/getAdminServiceEventCount.ts b/server/src/api/admin/getAdminServiceEventCount.ts
index 67dbd19d2..9dcb99892 100644
--- a/server/src/api/admin/getAdminServiceEventCount.ts
+++ b/server/src/api/admin/getAdminServiceEventCount.ts
@@ -1,6 +1,7 @@
import { FastifyReply, FastifyRequest } from "fastify";
-import SqlString from "sqlstring";
+import { DateTime } from "luxon";
import { clickhouse } from "../../db/clickhouse/clickhouse.js";
+import { resolveTimeWindow } from "../analytics/utils/timeWindow.js";
import { processResults } from "../analytics/utils/utils.js";
type ServiceEventCountResponse = {
@@ -27,42 +28,21 @@ export async function getAdminServiceEventCount(
}>,
res: FastifyReply
) {
- const { start_date, end_date, time_zone = "UTC" } = req.query;
+ const { time_zone = "UTC" } = req.query;
try {
- // Build time filter for the query
- let timeFilter = "";
- let fillFromDate = "";
- let fillToDate = "";
+ // No range asked for means the last 30 days, resolved to an explicit pair so
+ // the predicate and the fill come from one window rather than two
+ // hand-written defaults that have to agree.
+ const today = DateTime.now().setZone(time_zone);
+ const start_date = req.query.start_date || today.minus({ days: 30 }).toFormat("yyyy-MM-dd");
+ const end_date = req.query.end_date || today.toFormat("yyyy-MM-dd");
- if (start_date && end_date) {
- timeFilter = `AND event_hour >= toTimeZone(
- toStartOfDay(toDateTime(${SqlString.escape(start_date)}, ${SqlString.escape(time_zone)})),
- 'UTC'
- )
- AND event_hour < if(
- toDate(${SqlString.escape(end_date)}) = toDate(now(), ${SqlString.escape(time_zone)}),
- now(),
- toTimeZone(
- toStartOfDay(toDateTime(${SqlString.escape(end_date)}, ${SqlString.escape(time_zone)})) + INTERVAL 1 DAY,
- 'UTC'
- )
- )`;
-
- // Set up WITH FILL parameters - use UTC midnight boundaries
- fillFromDate = `FROM toStartOfDay(toDateTime(${SqlString.escape(start_date)}))`;
-
- fillToDate = `TO toStartOfDay(toDateTime(${SqlString.escape(end_date)})) + INTERVAL 1 DAY`;
- } else {
- // Default to last 30 days if no date range provided
- timeFilter = "AND event_hour >= toStartOfDay(now()) - INTERVAL 30 DAY";
- fillFromDate = "FROM toStartOfDay(now()) - INTERVAL 30 DAY";
- fillToDate = "TO toStartOfDay(now()) + INTERVAL 1 DAY";
- }
+ const window = resolveTimeWindow({ start_date, end_date, time_zone });
const query = `
SELECT
- toStartOfDay(timestamp) as event_date,
+ ${window.bucketed("timestamp", "day")} as event_date,
countIf(type = 'pageview') as pageview_count,
countIf(type = 'custom_event') as custom_event_count,
countIf(type = 'performance') as performance_count,
@@ -75,10 +55,10 @@ export async function getAdminServiceEventCount(
count() as event_count
FROM events
WHERE type IN ('pageview', 'custom_event', 'performance', 'outbound', 'error', 'button_click', 'copy', 'form_submit', 'input_change')
- ${timeFilter.replace(/event_hour/g, "timestamp")}
+ ${window.where()}
GROUP BY event_date
ORDER BY event_date
- WITH FILL ${fillFromDate} ${fillToDate} STEP INTERVAL 1 DAY
+ ${window.fill("day")}
`;
const result = await clickhouse.query({
diff --git a/server/src/api/analytics/bots/getBotDimension.ts b/server/src/api/analytics/bots/getBotDimension.ts
index 63f5466d7..c91ac1d1f 100644
--- a/server/src/api/analytics/bots/getBotDimension.ts
+++ b/server/src/api/analytics/bots/getBotDimension.ts
@@ -1,6 +1,6 @@
import { FilterParams } from "@rybbit/shared";
import { FastifyReply, FastifyRequest } from "fastify";
-import { getTimeStatement } from "../utils/utils.js";
+import { getTimeStatement } from "../utils/timeWindow.js";
import { analyticsRoute, getPaginationStatements, runPaginatedQuery } from "../utils/analyticsQuery.js";
import {
BOT_DIMENSIONS,
diff --git a/server/src/api/analytics/bots/getBotOverview.ts b/server/src/api/analytics/bots/getBotOverview.ts
index fe8fda674..3a92d68ef 100644
--- a/server/src/api/analytics/bots/getBotOverview.ts
+++ b/server/src/api/analytics/bots/getBotOverview.ts
@@ -1,6 +1,6 @@
import { FilterParams } from "@rybbit/shared";
import { FastifyReply, FastifyRequest } from "fastify";
-import { getTimeStatement } from "../utils/utils.js";
+import { getTimeStatement } from "../utils/timeWindow.js";
import { analyticsRoute, runAnalyticsQuery } from "../utils/analyticsQuery.js";
import { type BotLayerKey, getBotFilterStatement, getBotLayerStatement } from "./utils.js";
diff --git a/server/src/api/analytics/bots/getBotTimeSeries.ts b/server/src/api/analytics/bots/getBotTimeSeries.ts
index 33df5bf84..d6f035f4d 100644
--- a/server/src/api/analytics/bots/getBotTimeSeries.ts
+++ b/server/src/api/analytics/bots/getBotTimeSeries.ts
@@ -1,10 +1,9 @@
import { FilterParams } from "@rybbit/shared";
import { FastifyReply, FastifyRequest } from "fastify";
-import SqlString from "sqlstring";
import { TimeBucket } from "../types.js";
-import { getTimeStatement, TimeBucketToFn } from "../utils/utils.js";
+import { resolveTimeWindow } from "../utils/timeWindow.js";
import { analyticsRoute, runAnalyticsQuery } from "../utils/analyticsQuery.js";
-import { type BotLayerKey, getBotFilterStatement, getBotLayerStatement, getBotTimeStatementFill } from "./utils.js";
+import { type BotLayerKey, getBotFilterStatement, getBotLayerStatement } from "./utils.js";
type BotTimeSeriesPoint = {
time: string;
@@ -22,20 +21,16 @@ export interface BotTimeSeriesRequest {
}
export const buildBotTimeSeriesQuery = (query: BotTimeSeriesRequest["Querystring"]) => {
- const { bucket = "hour", time_zone } = query;
- const timeStatement = getTimeStatement(query);
+ const { bucket = "hour" } = query;
+ const window = resolveTimeWindow(query);
+ const timeStatement = window.where();
const filterStatement = getBotFilterStatement(query.filters);
const layerStatement = getBotLayerStatement(query.layer);
- const hasBoundedTime =
- Boolean(query.start_date && query.end_date) ||
- Boolean(query.start_datetime && query.end_datetime) ||
- (query.past_minutes_start !== undefined && query.past_minutes_end !== undefined);
- const fillClause = hasBoundedTime ? getBotTimeStatementFill(query, bucket) : "";
- const timezone = SqlString.escape(time_zone || "UTC");
+ const fillClause = window.fill(bucket);
return `
SELECT
- toDateTime(${TimeBucketToFn[bucket]}(toTimeZone(timestamp, ${timezone}))) AS time,
+ ${window.bucketed("timestamp", bucket)} AS time,
count() AS bot_requests
FROM bot_events
WHERE site_id = {siteId:Int32}
diff --git a/server/src/api/analytics/bots/utils.test.ts b/server/src/api/analytics/bots/utils.test.ts
index 08605b789..17340a452 100644
--- a/server/src/api/analytics/bots/utils.test.ts
+++ b/server/src/api/analytics/bots/utils.test.ts
@@ -5,19 +5,7 @@ vi.mock("../../../db/postgres/postgres.js", () => ({
sql: {},
}));
-import { TimeBucket } from "../types.js";
-import {
- buildStringFilterCondition,
- getBotFilterStatement,
- getBotLayerStatement,
- getBotSqlParam,
- getBotTimeStatementFill,
-} from "./utils.js";
-
-const normalize = (sql: string) => sql.replace(/\s+/g, " ").trim();
-
-type FillParams = Parameters<typeof getBotTimeStatementFill>[0];
-const fillParams = (p: Record<string, unknown>) => p as unknown as FillParams;
+import { buildStringFilterCondition, getBotFilterStatement, getBotLayerStatement, getBotSqlParam } from "./utils.js";
describe("getBotLayerStatement", () => {
it("should return empty string for undefined layer", () => {
@@ -295,86 +283,3 @@ describe("getBotFilterStatement", () => {
});
});
-describe("getBotTimeStatementFill", () => {
- describe("date range mode", () => {
- it("should build a timezone-aware WITH FILL clause from start_date and end_date", () => {
- const result = getBotTimeStatementFill(
- fillParams({ start_date: "2024-01-01", end_date: "2024-01-31", time_zone: "America/New_York" }),
- "day"
- );
- expect(normalize(result)).toBe(
- "WITH FILL FROM toTimeZone( toDateTime(toStartOfDay(toDateTime('2024-01-01', 'America/New_York'))), 'UTC' ) " +
- "TO if( toDate('2024-01-31') = toDate(now(), 'America/New_York'), toTimeZone(now(), 'UTC'), " +
- "toTimeZone( toDateTime(toStartOfDay(toDateTime('2024-01-31', 'America/New_York'))) + INTERVAL 1 DAY, 'UTC' ) ) " +
- "STEP INTERVAL 1 DAY"
- );
- });
-
- it("should default a missing time_zone to UTC", () => {
- const result = getBotTimeStatementFill(fillParams({ start_date: "2024-01-01", end_date: "2024-01-31" }), "day");
- expect(result).toContain("toDateTime('2024-01-01', 'UTC')");
- });
- });
-
- describe("datetime range mode", () => {
- it("should build a WITH FILL clause from start_datetime and end_datetime", () => {
- const result = getBotTimeStatementFill(
- fillParams({
- start_datetime: "2024-01-01 05:30:00",
- end_datetime: "2024-01-02 06:45:00",
- time_zone: "UTC",
- }),
- "hour"
- );
- expect(normalize(result)).toBe(
- "WITH FILL FROM toTimeZone( toDateTime(toStartOfHour(toTimeZone(toDateTime('2024-01-01 05:30:00', 'UTC'), 'UTC'))), 'UTC' ) " +
- "TO toTimeZone( toDateTime(toStartOfHour(toTimeZone(toDateTime('2024-01-02 06:45:00', 'UTC'), 'UTC'))), 'UTC' ) " +
- "STEP INTERVAL 1 HOUR"
- );
- });
- });
-
- describe("past minutes mode", () => {
- beforeEach(() => {
- vi.useFakeTimers();
- vi.setSystemTime(new Date("2024-06-15T12:00:00Z"));
- });
-
- afterEach(() => {
- vi.useRealTimers();
- });
-
- it("should build a WITH FILL clause from past_minutes_start/end relative to now", () => {
- const result = getBotTimeStatementFill(fillParams({ past_minutes_start: 120, past_minutes_end: 60 }), "hour");
- expect(normalize(result)).toBe(
- "WITH FILL FROM toStartOfHour(toDateTime('2024-06-15 10:00:00')) " +
- "TO toStartOfHour(toDateTime('2024-06-15 11:00:00')) + INTERVAL 1 HOUR " +
- "STEP INTERVAL 1 HOUR"
- );
- });
-
- it("should use MINUTE-based interval for minute buckets", () => {
- const result = getBotTimeStatementFill(
- fillParams({ past_minutes_start: 30, past_minutes_end: 0 }),
- "five_minutes"
- );
- expect(result).toContain("+ INTERVAL 1 MINUTE");
- expect(result).toContain("STEP INTERVAL 5 MINUTES");
- });
- });
-
- describe("validation", () => {
- it("should throw for an invalid bucket", () => {
- expect(() =>
- getBotTimeStatementFill(
- fillParams({ start_date: "2024-01-01", end_date: "2024-01-31", time_zone: "UTC" }),
- "decade" as TimeBucket
- )
- ).toThrow();
- });
-
- it("should throw when no time range params are provided", () => {
- expect(() => getBotTimeStatementFill(fillParams({}), "day")).toThrow();
- });
- });
-});
diff --git a/server/src/api/analytics/bots/utils.ts b/server/src/api/analytics/bots/utils.ts
index d98062b48..727979f0c 100644
--- a/server/src/api/analytics/bots/utils.ts
+++ b/server/src/api/analytics/bots/utils.ts
@@ -1,9 +1,5 @@
-import { FilterParams } from "@rybbit/shared";
-import SqlString from "sqlstring";
-import { FilterParameter, TimeBucket } from "../types.js";
+import { FilterParameter } from "../types.js";
import { getFilterStatement, getSqlParam } from "../utils/getFilterStatement.js";
-import { validateTimeStatementFillParams } from "../utils/query-validation.js";
-import { bucketIntervalMap, normalizeDatetimeForClickhouse, TimeBucketToFn } from "../utils/utils.js";
// Condition rendering is shared with the events surface; re-exported here for
// existing importers and tests.
@@ -87,68 +83,3 @@ export function getBotFilterStatement(filters?: string) {
});
}
-export function getBotTimeStatementFill(params: FilterParams, bucket: TimeBucket) {
- const { params: validatedParams, bucket: validatedBucket } = validateTimeStatementFillParams(params, bucket);
-
- if (validatedParams.start_date && validatedParams.end_date && validatedParams.time_zone) {
- const { start_date, end_date, time_zone } = validatedParams;
- return `WITH FILL FROM toTimeZone(
- toDateTime(${TimeBucketToFn[validatedBucket]}(toDateTime(${SqlString.escape(start_date)}, ${SqlString.escape(
- time_zone
- )}))),
- 'UTC'
- )
- TO if(
- toDate(${SqlString.escape(end_date)}) = toDate(now(), ${SqlString.escape(time_zone)}),
- toTimeZone(now(), 'UTC'),
- toTimeZone(
- toDateTime(${TimeBucketToFn[validatedBucket]}(toDateTime(${SqlString.escape(end_date)}, ${SqlString.escape(
- time_zone
- )}))) + INTERVAL 1 DAY,
- 'UTC'
- )
- ) STEP INTERVAL ${bucketIntervalMap[validatedBucket]}`;
- }
-
- if (validatedParams.start_datetime && validatedParams.end_datetime && validatedParams.time_zone) {
- const { start_datetime, end_datetime, time_zone } = validatedParams;
- const normalizedStartDatetime = normalizeDatetimeForClickhouse(start_datetime);
- const normalizedEndDatetime = normalizeDatetimeForClickhouse(end_datetime);
- return `WITH FILL FROM toTimeZone(
- toDateTime(${TimeBucketToFn[validatedBucket]}(toTimeZone(toDateTime(${SqlString.escape(
- normalizedStartDatetime
- )}, 'UTC'), ${SqlString.escape(time_zone)}))),
- 'UTC'
- )
- TO toTimeZone(
- toDateTime(${TimeBucketToFn[validatedBucket]}(toTimeZone(toDateTime(${SqlString.escape(
- normalizedEndDatetime
- )}, 'UTC'), ${SqlString.escape(time_zone)}))),
- 'UTC'
- ) STEP INTERVAL ${bucketIntervalMap[validatedBucket]}`;
- }
-
- if (validatedParams.past_minutes_start !== undefined && validatedParams.past_minutes_end !== undefined) {
- const { past_minutes_start: start, past_minutes_end: end } = validatedParams;
- const now = new Date();
- const startIso = new Date(now.getTime() - start * 60 * 1000).toISOString().slice(0, 19).replace("T", " ");
- const endIso = new Date(now.getTime() - end * 60 * 1000).toISOString().slice(0, 19).replace("T", " ");
-
- return `WITH FILL
- FROM ${TimeBucketToFn[validatedBucket]}(toDateTime(${SqlString.escape(startIso)}))
- TO ${TimeBucketToFn[validatedBucket]}(toDateTime(${SqlString.escape(endIso)})) + INTERVAL 1 ${
- validatedBucket === "month"
- ? "MONTH"
- : validatedBucket === "week"
- ? "WEEK"
- : validatedBucket === "day"
- ? "DAY"
- : validatedBucket === "hour"
- ? "HOUR"
- : "MINUTE"
- }
- STEP INTERVAL ${bucketIntervalMap[validatedBucket]}`;
- }
-
- return "";
-}
diff --git a/server/src/api/analytics/events/getAutocaptureEvents.ts b/server/src/api/analytics/events/getAutocaptureEvents.ts
index 82c512605..c7ff85b88 100644
--- a/server/src/api/analytics/events/getAutocaptureEvents.ts
+++ b/server/src/api/analytics/events/getAutocaptureEvents.ts
@@ -1,6 +1,6 @@
import { FastifyReply, FastifyRequest } from "fastify";
import SqlString from "sqlstring";
-import { getTimeStatement } from "../utils/utils.js";
+import { getTimeStatement } from "../utils/timeWindow.js";
import { FilterParams } from "@rybbit/shared";
import { getFilterStatement } from "../utils/getFilterStatement.js";
import { AutocaptureTargetType, isAutocaptureTargetType } from "../utils/eventConditions.js";
diff --git a/server/src/api/analytics/events/getAutocaptureValues.ts b/server/src/api/analytics/events/getAutocaptureValues.ts
index 46397cfff..a5ae3cd5a 100644
--- a/server/src/api/analytics/events/getAutocaptureValues.ts
+++ b/server/src/api/analytics/events/getAutocaptureValues.ts
@@ -1,6 +1,6 @@
import { FastifyReply, FastifyRequest } from "fastify";
import SqlString from "sqlstring";
-import { getTimeStatement } from "../utils/utils.js";
+import { getTimeStatement } from "../utils/timeWindow.js";
import { getFilterStatement } from "../utils/getFilterStatement.js";
import { FilterParams } from "@rybbit/shared";
import { AUTOCAPTURE_PATTERN_PROPS, AutocaptureTargetType, isAutocaptureTargetType } from "../utils/eventConditions.js";
diff --git a/server/src/api/analytics/events/getEventBucketed.ts b/server/src/api/analytics/events/getEventBucketed.ts
index 2f3980d13..ecfe93679 100644
--- a/server/src/api/analytics/events/getEventBucketed.ts
+++ b/server/src/api/analytics/events/getEventBucketed.ts
@@ -2,7 +2,7 @@ import { FilterParams } from "@rybbit/shared";
import { FastifyReply, FastifyRequest } from "fastify";
import { TimeBucket } from "../types.js";
import { getFilterStatement } from "../utils/getFilterStatement.js";
-import { getTimeStatement, TimeBucketToFn } from "../utils/utils.js";
+import { getTimeStatement, TimeBucketToFn } from "../utils/timeWindow.js";
import { analyticsRoute, runAnalyticsQuery } from "../utils/analyticsQuery.js";
export type GetEventBucketedResponse = {
diff --git a/server/src/api/analytics/events/getEventNames.ts b/server/src/api/analytics/events/getEventNames.ts
index f9e9a90ca..f87126e93 100644
--- a/server/src/api/analytics/events/getEventNames.ts
+++ b/server/src/api/analytics/events/getEventNames.ts
@@ -1,5 +1,5 @@
import { FastifyReply, FastifyRequest } from "fastify";
-import { getTimeStatement } from "../utils/utils.js";
+import { getTimeStatement } from "../utils/timeWindow.js";
import { FilterParams } from "@rybbit/shared";
import { getFilterStatement } from "../utils/getFilterStatement.js";
import { analyticsRoute, runAnalyticsQuery } from "../utils/analyticsQuery.js";
diff --git a/server/src/api/analytics/events/getEventProperties.ts b/server/src/api/analytics/events/getEventProperties.ts
index 216e6ee20..129546a06 100644
--- a/server/src/api/analytics/events/getEventProperties.ts
+++ b/server/src/api/analytics/events/getEventProperties.ts
@@ -1,5 +1,5 @@
import { FastifyReply, FastifyRequest } from "fastify";
-import { getTimeStatement } from "../utils/utils.js";
+import { getTimeStatement } from "../utils/timeWindow.js";
import { FilterParams } from "@rybbit/shared";
import { getFilterStatement } from "../utils/getFilterStatement.js";
import { analyticsRoute, runAnalyticsQuery } from "../utils/analyticsQuery.js";
diff --git a/server/src/api/analytics/events/getEvents.ts b/server/src/api/analytics/events/getEvents.ts
index 7bcc87a40..f314f95d9 100644
--- a/server/src/api/analytics/events/getEvents.ts
+++ b/server/src/api/analytics/events/getEvents.ts
@@ -1,5 +1,6 @@
import { FastifyReply, FastifyRequest } from "fastify";
-import { enrichWithTraits, getTimeStatement } from "../utils/utils.js";
+import { enrichWithTraits } from "../utils/utils.js";
+import { getTimeStatement } from "../utils/timeWindow.js";
import { FilterParams } from "@rybbit/shared";
import { getFilterStatement } from "../utils/getFilterStatement.js";
import { analyticsRoute, QuerySpec, runAnalyticsQuery } from "../utils/analyticsQuery.js";
diff --git a/server/src/api/analytics/events/getOutboundLinks.ts b/server/src/api/analytics/events/getOutboundLinks.ts
index 2c83a1344..3c8413b98 100644
--- a/server/src/api/analytics/events/getOutboundLinks.ts
+++ b/server/src/api/analytics/events/getOutboundLinks.ts
@@ -1,5 +1,5 @@
import { FastifyReply, FastifyRequest } from "fastify";
-import { getTimeStatement } from "../utils/utils.js";
+import { getTimeStatement } from "../utils/timeWindow.js";
import { FilterParams } from "@rybbit/shared";
import { getFilterStatement } from "../utils/getFilterStatement.js";
import { analyticsRoute, runAnalyticsQuery } from "../utils/analyticsQuery.js";
diff --git a/server/src/api/analytics/events/getSiteEventCount.ts b/server/src/api/analytics/events/getSiteEventCount.ts
index affdd2c6b..9a3a2c3d8 100644
--- a/server/src/api/analytics/events/getSiteEventCount.ts
+++ b/server/src/api/analytics/events/getSiteEventCount.ts
@@ -2,7 +2,7 @@ import { FilterParams } from "@rybbit/shared";
import { FastifyReply, FastifyRequest } from "fastify";
import { TimeBucket } from "../types.js";
import { getFilterStatement } from "../utils/getFilterStatement.js";
-import { getTimeStatement, TimeBucketToFn } from "../utils/utils.js";
+import { getTimeStatement, TimeBucketToFn } from "../utils/timeWindow.js";
import { analyticsRoute, runAnalyticsQuery } from "../utils/analyticsQuery.js";
export type GetSiteEventCountResponse = {
diff --git a/server/src/api/analytics/funnels/getFunnel.ts b/server/src/api/analytics/funnels/getFunnel.ts
index fead99107..aac47d652 100644
--- a/server/src/api/analytics/funnels/getFunnel.ts
+++ b/server/src/api/analytics/funnels/getFunnel.ts
@@ -1,7 +1,7 @@
import { FilterParams } from "@rybbit/shared";
import { FastifyReply, FastifyRequest } from "fastify";
import SqlString from "sqlstring";
-import { getTimeStatement } from "../utils/utils.js";
+import { getTimeStatement } from "../utils/timeWindow.js";
import { getFilterStatement } from "../utils/getFilterStatement.js";
import { AnalyticsQueryError, runAnalyticsQuery } from "../utils/analyticsQuery.js";
import { buildFunnelStepCondition, FunnelStep } from "./funnelSteps.js";
diff --git a/server/src/api/analytics/funnels/getFunnelStepSessions.ts b/server/src/api/analytics/funnels/getFunnelStepSessions.ts
index 6272f5387..285b9dfdd 100644
--- a/server/src/api/analytics/funnels/getFunnelStepSessions.ts
+++ b/server/src/api/analytics/funnels/getFunnelStepSessions.ts
@@ -1,6 +1,7 @@
import { FilterParams } from "@rybbit/shared";
import { FastifyReply, FastifyRequest } from "fastify";
-import { enrichWithTraits, getTimeStatement } from "../utils/utils.js";
+import { enrichWithTraits } from "../utils/utils.js";
+import { getTimeStatement } from "../utils/timeWindow.js";
import { GetSessionsResponse } from "../sessions/getSessions.js";
import { getFilterStatement } from "../utils/getFilterStatement.js";
import { analyticsRoute, runAnalyticsQuery } from "../utils/analyticsQuery.js";
diff --git a/server/src/api/analytics/getErrorBucketed.ts b/server/src/api/analytics/getErrorBucketed.ts
index f46fbd396..b5577c257 100644
--- a/server/src/api/analytics/getErrorBucketed.ts
+++ b/server/src/api/analytics/getErrorBucketed.ts
@@ -1,48 +1,10 @@
import { FilterParams } from "@rybbit/shared";
import { FastifyReply, FastifyRequest } from "fastify";
-import SqlString from "sqlstring";
-import { validateTimeStatementFillParams } from "./utils/query-validation.js";
-import { getTimeStatement, TimeBucketToFn, bucketIntervalMap } from "./utils/utils.js";
+import { resolveTimeWindow } from "./utils/timeWindow.js";
import { TimeBucket } from "./types.js";
import { getFilterStatement } from "./utils/getFilterStatement.js";
import { AnalyticsQueryError, runAnalyticsQuery } from "./utils/analyticsQuery.js";
-function getTimeStatementFill(params: FilterParams, bucket: TimeBucket) {
- const { params: validatedParams, bucket: validatedBucket } = validateTimeStatementFillParams(params, bucket);
-
- if (validatedParams.start_date && validatedParams.end_date && validatedParams.time_zone) {
- const { start_date, end_date, time_zone } = validatedParams;
- return `WITH FILL FROM ${
- TimeBucketToFn[validatedBucket]
- }(toDateTime(${SqlString.escape(start_date)}, ${SqlString.escape(time_zone)}))
- TO if(
- toDate(${SqlString.escape(end_date)}) = toDate(now(), ${SqlString.escape(time_zone)}),
- ${TimeBucketToFn[validatedBucket]}(toTimeZone(now(), ${SqlString.escape(time_zone)})),
- ${TimeBucketToFn[validatedBucket]}(toDateTime(${SqlString.escape(end_date)}, ${SqlString.escape(
- time_zone
- )})) + INTERVAL 1 DAY
- ) STEP INTERVAL ${bucketIntervalMap[validatedBucket]}`;
- }
- if (validatedParams.start_datetime && validatedParams.end_datetime && validatedParams.time_zone) {
- const { start_datetime, end_datetime, time_zone } = validatedParams;
- return `WITH FILL FROM ${TimeBucketToFn[validatedBucket]}(
- toTimeZone(toDateTime(${SqlString.escape(start_datetime)}, 'UTC'), ${SqlString.escape(time_zone)})
- )
- TO ${TimeBucketToFn[validatedBucket]}(
- toTimeZone(toDateTime(${SqlString.escape(end_datetime)}, 'UTC'), ${SqlString.escape(time_zone)})
- )
- STEP INTERVAL ${bucketIntervalMap[validatedBucket]}`;
- }
- // For specific past minutes range - convert to exact timestamps for better performance
- if (validatedParams.past_minutes_start !== undefined && validatedParams.past_minutes_end !== undefined) {
- return `WITH FILL FROM now() - INTERVAL ${validatedParams.past_minutes_start} MINUTE
- TO now() - INTERVAL ${validatedParams.past_minutes_end} MINUTE
- STEP INTERVAL ${bucketIntervalMap[validatedBucket]}`;
- }
-
- throw new Error("Invalid time parameters");
-}
-
interface GetErrorBucketedRequest {
Params: {
siteId: string;
@@ -60,13 +22,14 @@ export type GetErrorBucketedResponse = {
export const buildErrorBucketedQuery = (query: GetErrorBucketedRequest["Querystring"], siteId: number) => {
const { bucket } = query;
- const timeStatement = getTimeStatement(query);
+ const window = resolveTimeWindow(query);
+ const timeStatement = window.where();
const filterStatement = getFilterStatement(query.filters, siteId, timeStatement);
- const timeStatementFill = getTimeStatementFill(query, bucket);
+ const timeStatementFill = window.fill(bucket);
return `
SELECT
- ${TimeBucketToFn[bucket]}(toTimeZone(timestamp, {timeZone:String})) AS time,
+ ${window.bucketed("timestamp", bucket)} AS time,
COUNT(*) AS error_count
FROM events
WHERE
@@ -97,7 +60,6 @@ export async function getErrorBucketed(req: FastifyRequest<GetErrorBucketedReque
params: {
siteId: numericSiteId,
errorMessage: errorMessage,
- timeZone: req.query.time_zone || "UTC",
},
});
diff --git a/server/src/api/analytics/getErrorEvents.ts b/server/src/api/analytics/getErrorEvents.ts
index 7dd923c09..571076255 100644
--- a/server/src/api/analytics/getErrorEvents.ts
+++ b/server/src/api/analytics/getErrorEvents.ts
@@ -1,5 +1,5 @@
import { FastifyReply, FastifyRequest } from "fastify";
-import { getTimeStatement } from "./utils/utils.js";
+import { getTimeStatement } from "./utils/timeWindow.js";
import { FilterParams } from "@rybbit/shared";
import { getFilterStatement } from "./utils/getFilterStatement.js";
import { analyticsRoute, getPaginationStatements, runAnalyticsQuery, runPaginatedQuery } from "./utils/analyticsQuery.js";
diff --git a/server/src/api/analytics/getErrorNames.ts b/server/src/api/analytics/getErrorNames.ts
index bff0056fb..4158daa85 100644
--- a/server/src/api/analytics/getErrorNames.ts
+++ b/server/src/api/analytics/getErrorNames.ts
@@ -1,5 +1,5 @@
import { FastifyReply, FastifyRequest } from "fastify";
-import { getTimeStatement } from "./utils/utils.js";
+import { getTimeStatement } from "./utils/timeWindow.js";
import { FilterParams } from "@rybbit/shared";
import { getFilterStatement } from "./utils/getFilterStatement.js";
import { analyticsRoute, getPaginationStatements, runAnalyticsQuery, runPaginatedQuery } from "./utils/analyticsQuery.js";
diff --git a/server/src/api/analytics/getJourneys.ts b/server/src/api/analytics/getJourneys.ts
index 99024281d..18e72a9e8 100644
--- a/server/src/api/analytics/getJourneys.ts
+++ b/server/src/api/analytics/getJourneys.ts
@@ -3,7 +3,8 @@ import { FastifyReply, FastifyRequest } from "fastify";
import SqlString from "sqlstring";
import { z } from "zod";
import { getFilterStatement } from "./utils/getFilterStatement.js";
-import { getTimeStatement, patternToRegex } from "./utils/utils.js";
+import { patternToRegex } from "./utils/utils.js";
+import { getTimeStatement } from "./utils/timeWindow.js";
import { AnalyticsQueryError, runAnalyticsQuery } from "./utils/analyticsQuery.js";
// stepFilters arrives as a JSON object mapping a (numeric) step index to a path
diff --git a/server/src/api/analytics/getMetric.ts b/server/src/api/analytics/getMetric.ts
index be7ec83f5..f142326a5 100644
--- a/server/src/api/analytics/getMetric.ts
+++ b/server/src/api/analytics/getMetric.ts
@@ -1,6 +1,6 @@
import { FastifyReply, FastifyRequest } from "fastify";
import { FilterParameter } from "./types.js";
-import { getTimeStatement } from "./utils/utils.js";
+import { getTimeStatement } from "./utils/timeWindow.js";
import { getFilterStatement, getSqlParam } from "./utils/getFilterStatement.js";
import { SESSION_CHANNEL_AGG } from "./utils/sessionAttribution.js";
import { FilterParams } from "@rybbit/shared";
diff --git a/server/src/api/analytics/getOrgEventCount.ts b/server/src/api/analytics/getOrgEventCount.ts
index 757bd1027..aae97d6d5 100644
--- a/server/src/api/analytics/getOrgEventCount.ts
+++ b/server/src/api/analytics/getOrgEventCount.ts
@@ -2,6 +2,7 @@ import { FastifyReply, FastifyRequest } from "fastify";
import SqlString from "sqlstring";
import { getSitesUserHasAccessTo } from "../../lib/auth-utils.js";
import { analyticsRoute, runAnalyticsQuery } from "./utils/analyticsQuery.js";
+import { resolveTimeWindow } from "./utils/timeWindow.js";
type OrgEventCountResponse = {
event_date: string;
@@ -29,51 +30,16 @@ interface GetOrgEventCountRequest {
}
export const buildOrgEventCountQuery = (query: GetOrgEventCountRequest["Querystring"], siteIds: number[]) => {
- const { start_date, end_date, time_zone = "UTC" } = query;
-
- // Build time filter for the query
- let timeFilter = "";
- let fillFromDate = "";
- let fillToDate = "";
-
- if (start_date && end_date) {
- timeFilter = `AND event_hour >= toTimeZone(
- toStartOfDay(toDateTime(${SqlString.escape(start_date)}, ${SqlString.escape(time_zone)})),
- 'UTC'
- )
- AND event_hour < if(
- toDate(${SqlString.escape(end_date)}) = toDate(now(), ${SqlString.escape(time_zone)}),
- now(),
- toTimeZone(
- toStartOfDay(toDateTime(${SqlString.escape(end_date)}, ${SqlString.escape(time_zone)})) + INTERVAL 1 DAY,
- 'UTC'
- )
- )`;
-
- // Set up WITH FILL parameters
- fillFromDate = `FROM toTimeZone(
- toStartOfDay(toDateTime(${SqlString.escape(start_date)}, ${SqlString.escape(time_zone)})),
- 'UTC'
- )`;
-
- fillToDate = `TO if(
- toDate(${SqlString.escape(end_date)}) = toDate(now(), ${SqlString.escape(time_zone)}),
- toStartOfDay(now()) + INTERVAL 1 DAY,
- toTimeZone(
- toStartOfDay(toDateTime(${SqlString.escape(end_date)}, ${SqlString.escape(time_zone)})) + INTERVAL 1 DAY,
- 'UTC'
- )
- )`;
- } else {
- // No date range: return all data without WITH FILL
- timeFilter = "";
- fillFromDate = "";
- fillToDate = "";
- }
+ const window = resolveTimeWindow(query);
+ // Days are counted in the caller's timezone, the same one the window is
+ // bounded by. Grouping by `toStartOfDay(timestamp)` counted UTC days instead,
+ // which put the fill's day boundaries hours away from the data's β€” for a
+ // non-UTC caller the filled rows never landed on a real row, so every day
+ // appeared twice, once with its counts and once empty.
return `
SELECT
- toStartOfDay(timestamp) as event_date,
+ ${window.bucketed("timestamp", "day")} as event_date,
countIf(type = 'pageview') as pageview_count,
countIf(type = 'custom_event') as custom_event_count,
countIf(type = 'performance') as performance_count,
@@ -87,10 +53,10 @@ export const buildOrgEventCountQuery = (query: GetOrgEventCountRequest["Querystr
FROM events
WHERE site_id IN (${siteIds.map((id: number) => SqlString.escape(id)).join(", ")})
AND type IN ('pageview', 'custom_event', 'performance', 'outbound', 'error', 'button_click', 'copy', 'form_submit', 'input_change')
- ${timeFilter.replace(/event_hour/g, "timestamp")}
+ ${window.where()}
GROUP BY event_date
ORDER BY event_date
- ${fillFromDate ? `WITH FILL ${fillFromDate} ${fillToDate} STEP INTERVAL 1 DAY` : ""}
+ ${window.fill("day")}
`;
};
diff --git a/server/src/api/analytics/getOverviewBucketed.ts b/server/src/api/analytics/getOverviewBucketed.ts
index f7baeaf57..99b678589 100644
--- a/server/src/api/analytics/getOverviewBucketed.ts
+++ b/server/src/api/analytics/getOverviewBucketed.ts
@@ -1,116 +1,18 @@
import { FilterParams } from "@rybbit/shared";
import { FastifyReply, FastifyRequest } from "fastify";
-import SqlString from "sqlstring";
-import { validateTimeStatementFillParams } from "./utils/query-validation.js";
-import {
- getTimeStatement,
- normalizeDatetimeForClickhouse,
- TimeBucketToFn,
- bucketIntervalMap,
-} from "./utils/utils.js";
+import { resolveTimeWindow } from "./utils/timeWindow.js";
import { getFilterStatement } from "./utils/getFilterStatement.js";
import { TimeBucket } from "./types.js";
import { analyticsRoute, runAnalyticsQuery } from "./utils/analyticsQuery.js";
import { effectiveUserId } from "./utils/effectiveUserId.js";
-function getTimeStatementFill(params: FilterParams, bucket: TimeBucket) {
- const { params: validatedParams, bucket: validatedBucket } = validateTimeStatementFillParams(params, bucket);
-
- if (validatedParams.start_date && validatedParams.end_date && validatedParams.time_zone) {
- const { start_date, end_date, time_zone } = validatedParams;
- return `WITH FILL FROM toTimeZone(
- toDateTime(${TimeBucketToFn[validatedBucket]}(toDateTime(${SqlString.escape(start_date)}, ${SqlString.escape(
- time_zone
- )}))),
- 'UTC'
- )
- TO if(
- toDate(${SqlString.escape(end_date)}) = toDate(now(), ${SqlString.escape(time_zone)}),
- toTimeZone(now(), 'UTC'),
- toTimeZone(
- toDateTime(${TimeBucketToFn[validatedBucket]}(toDateTime(${SqlString.escape(end_date)}, ${SqlString.escape(
- time_zone
- )}))) + INTERVAL 1 DAY,
- 'UTC'
- )
- ) STEP INTERVAL ${bucketIntervalMap[validatedBucket]}`;
- }
- if (validatedParams.start_datetime && validatedParams.end_datetime && validatedParams.time_zone) {
- const { start_datetime, end_datetime, time_zone } = validatedParams;
- const normalizedStartDatetime = normalizeDatetimeForClickhouse(start_datetime);
- const normalizedEndDatetime = normalizeDatetimeForClickhouse(end_datetime);
- return `WITH FILL FROM toTimeZone(
- toDateTime(${TimeBucketToFn[validatedBucket]}(toTimeZone(toDateTime(${SqlString.escape(
- normalizedStartDatetime
- )}, 'UTC'), ${SqlString.escape(time_zone)}))),
- 'UTC'
- )
- TO toTimeZone(
- toDateTime(${TimeBucketToFn[validatedBucket]}(toTimeZone(toDateTime(${SqlString.escape(
- normalizedEndDatetime
- )}, 'UTC'), ${SqlString.escape(time_zone)}))),
- 'UTC'
- ) STEP INTERVAL ${bucketIntervalMap[validatedBucket]}`;
- }
- // For specific past minutes range - convert to exact timestamps for better performance
- if (validatedParams.past_minutes_start !== undefined && validatedParams.past_minutes_end !== undefined) {
- const { past_minutes_start: start, past_minutes_end: end } = validatedParams;
-
- // Calculate exact timestamps in JavaScript to avoid runtime ClickHouse calculations
- const now = new Date();
- const startTimestamp = new Date(now.getTime() - start * 60 * 1000);
- const endTimestamp = new Date(now.getTime() - end * 60 * 1000);
-
- // Format as YYYY-MM-DD HH:MM:SS without milliseconds for ClickHouse
- const startIso = startTimestamp.toISOString().slice(0, 19).replace("T", " ");
- const endIso = endTimestamp.toISOString().slice(0, 19).replace("T", " ");
-
- return ` WITH FILL
- FROM ${TimeBucketToFn[validatedBucket]}(toDateTime(${SqlString.escape(startIso)}))
- TO ${TimeBucketToFn[validatedBucket]}(toDateTime(${SqlString.escape(endIso)})) + INTERVAL 1 ${
- validatedBucket === "minute"
- ? "MINUTE"
- : validatedBucket === "five_minutes"
- ? "MINUTE"
- : validatedBucket === "ten_minutes"
- ? "MINUTE"
- : validatedBucket === "fifteen_minutes"
- ? "MINUTE"
- : validatedBucket === "month"
- ? "MONTH"
- : validatedBucket === "week"
- ? "WEEK"
- : validatedBucket === "day"
- ? "DAY"
- : "HOUR"
- }
- STEP INTERVAL ${bucketIntervalMap[validatedBucket]}`;
- }
- return "";
-}
-
export const buildOverviewBucketedQuery = (params: FilterParams<{ bucket: TimeBucket }>, siteId: number) => {
- const {
- start_date,
- end_date,
- time_zone,
- bucket = "hour",
- filters,
- start_datetime,
- end_datetime,
- past_minutes_start,
- past_minutes_end,
- } = params;
- const timeStatement = getTimeStatement(params);
- const filterStatement = getFilterStatement(filters, siteId, timeStatement);
- const pastMinutesRange =
- past_minutes_start !== undefined && past_minutes_end !== undefined
- ? { start: Number(past_minutes_start), end: Number(past_minutes_end) }
- : undefined;
+ const { bucket = "hour", filters } = params;
- const isAllTime = !start_date && !end_date && !start_datetime && !end_datetime && !pastMinutesRange;
- const fillClause = isAllTime ? "" : getTimeStatementFill(params, bucket);
- const tzEscaped = SqlString.escape(time_zone || "UTC");
+ const window = resolveTimeWindow(params);
+ const timeStatement = window.where();
+ const filterStatement = getFilterStatement(filters, siteId, timeStatement);
+ const fillClause = window.fill(bucket);
return `
WITH
@@ -121,7 +23,7 @@ AllSessionPageviews AS (
FROM events
WHERE
site_id = {siteId:Int32}
- ${getTimeStatement(params)}
+ ${timeStatement}
GROUP BY session_id
),
FilteredSessions AS (
@@ -133,7 +35,7 @@ FilteredSessions AS (
WHERE
site_id = {siteId:Int32}
${filterStatement}
- ${getTimeStatement(params)}
+ ${timeStatement}
GROUP BY session_id
),
SessionsWithPageviews AS (
@@ -156,7 +58,7 @@ SELECT
FROM
(
SELECT
- toDateTime(${TimeBucketToFn[bucket]}(toTimeZone(start_time, ${tzEscaped}))) AS time,
+ ${window.bucketed("start_time", bucket)} AS time,
COUNT() AS sessions,
AVG(total_pageviews_in_session) AS pages_per_session,
sumIf(1, total_pageviews_in_session = 1) / COUNT() AS bounce_rate,
@@ -167,14 +69,14 @@ FROM
FULL JOIN
(
SELECT
- toDateTime(${TimeBucketToFn[bucket]}(toTimeZone(timestamp, ${tzEscaped}))) AS time,
+ ${window.bucketed("timestamp", bucket)} AS time,
countIf(type = 'pageview') AS pageviews,
COUNT(DISTINCT ${effectiveUserId()}) AS users
FROM events
WHERE
site_id = {siteId:Int32}
${filterStatement}
- ${getTimeStatement(params)}
+ ${timeStatement}
GROUP BY time ORDER BY time ${fillClause}
) AS page_stats
USING time
diff --git a/server/src/api/analytics/getPageTitles.ts b/server/src/api/analytics/getPageTitles.ts
index 5d820c1cc..c0ba92ebb 100644
--- a/server/src/api/analytics/getPageTitles.ts
+++ b/server/src/api/analytics/getPageTitles.ts
@@ -1,5 +1,5 @@
import { FastifyReply, FastifyRequest } from "fastify";
-import { getTimeStatement } from "./utils/utils.js";
+import { getTimeStatement } from "./utils/timeWindow.js";
import { FilterParams } from "@rybbit/shared";
import { getFilterStatement } from "./utils/getFilterStatement.js";
import { analyticsRoute, getPaginationStatements, runAnalyticsQuery, runPaginatedQuery } from "./utils/analyticsQuery.js";
diff --git a/server/src/api/analytics/goals/getGoalSessions.ts b/server/src/api/analytics/goals/getGoalSessions.ts
index 275309643..57b95693c 100644
--- a/server/src/api/analytics/goals/getGoalSessions.ts
+++ b/server/src/api/analytics/goals/getGoalSessions.ts
@@ -2,7 +2,7 @@ import { FastifyReply, FastifyRequest } from "fastify";
import { db } from "../../../db/postgres/postgres.js";
import { goals } from "../../../db/postgres/schema.js";
import { eq } from "drizzle-orm";
-import { getTimeStatement } from "../utils/utils.js";
+import { getTimeStatement } from "../utils/timeWindow.js";
import { FilterParams } from "@rybbit/shared";
import { GetSessionsResponse } from "../sessions/getSessions.js";
import { analyticsRoute, runAnalyticsQuery } from "../utils/analyticsQuery.js";
diff --git a/server/src/api/analytics/goals/getGoalTimeSeries.ts b/server/src/api/analytics/goals/getGoalTimeSeries.ts
index d2764b1d3..4b1a0e7ef 100644
--- a/server/src/api/analytics/goals/getGoalTimeSeries.ts
+++ b/server/src/api/analytics/goals/getGoalTimeSeries.ts
@@ -6,7 +6,7 @@ import { db } from "../../../db/postgres/postgres.js";
import { goals } from "../../../db/postgres/schema.js";
import { TimeBucket } from "../types.js";
import { getFilterStatement } from "../utils/getFilterStatement.js";
-import { getTimeStatement, TimeBucketToFn } from "../utils/utils.js";
+import { getTimeStatement, TimeBucketToFn } from "../utils/timeWindow.js";
import { analyticsRoute, runAnalyticsQuery } from "../utils/analyticsQuery.js";
import { buildGoalCondition } from "./goalConditions.js";
diff --git a/server/src/api/analytics/goals/getGoals.ts b/server/src/api/analytics/goals/getGoals.ts
index a0410af9b..3cff75dd0 100644
--- a/server/src/api/analytics/goals/getGoals.ts
+++ b/server/src/api/analytics/goals/getGoals.ts
@@ -2,7 +2,7 @@ import { FastifyReply, FastifyRequest } from "fastify";
import { db } from "../../../db/postgres/postgres.js";
import { goals } from "../../../db/postgres/schema.js";
import { eq, desc, asc, sql } from "drizzle-orm";
-import { getTimeStatement } from "../utils/utils.js";
+import { getTimeStatement } from "../utils/timeWindow.js";
import SqlString from "sqlstring";
import { FilterParams } from "@rybbit/shared";
import { getFilterStatement } from "../utils/getFilterStatement.js";
diff --git a/server/src/api/analytics/lite/getMetricLite.ts b/server/src/api/analytics/lite/getMetricLite.ts
index 923565ff3..688e05353 100644
--- a/server/src/api/analytics/lite/getMetricLite.ts
+++ b/server/src/api/analytics/lite/getMetricLite.ts
@@ -2,7 +2,8 @@ import { FilterParams } from "@rybbit/shared";
import { FastifyReply, FastifyRequest } from "fastify";
import { getMetric } from "../getMetric.js";
import { analyticsRoute, runAnalyticsQuery } from "../utils/analyticsQuery.js";
-import { getLiteSessionFilter, getLiteTimeStatement, hasLiteFilters } from "./utils.js";
+import { getTimeStatement } from "../utils/timeWindow.js";
+import { getLiteSessionFilter, hasLiteDatetimeRange, hasLiteFilters } from "./utils.js";
// Lite metric supports only dimensions backed by MVs:
// - pathname β†’ pathname_hourly_mv_target
@@ -43,7 +44,7 @@ const getLitePagination = (query: GetMetricLiteRequest["Querystring"]) => {
export const buildMetricLiteSessionQuery = (query: GetMetricLiteRequest["Querystring"], filterSql: string) => {
const { parameter } = query;
const { limit, offsetStatement } = getLitePagination(query);
- const sessionsTime = getLiteTimeStatement(query, "start_time");
+ const sessionsTime = getTimeStatement(query, "start_time");
const nonEmpty = parameter === "device_type" ? `AND ${parameter} <> ''` : "";
return `
SELECT
@@ -83,7 +84,7 @@ export const buildMetricLiteSessionQuery = (query: GetMetricLiteRequest["Queryst
export const buildMetricLiteQuery = (query: GetMetricLiteRequest["Querystring"]): string | null => {
const { parameter } = query;
const { limit, offsetStatement } = getLitePagination(query);
- const timeStatement = getLiteTimeStatement(query, "event_hour");
+ const timeStatement = getTimeStatement(query, "event_hour");
// Percentages are computed in an outer pass so the window function
// operates on already-grouped rows. `sum(sum(...)) OVER ()` is illegal
@@ -170,6 +171,12 @@ export const getMetricLite = analyticsRoute<GetMetricLiteRequest>(
"metric",
async (req: FastifyRequest<GetMetricLiteRequest>, res: FastifyReply) => {
const site = Number(req.params.siteId);
+
+ // The hourly rollups can't express a sub-hour window.
+ if (hasLiteDatetimeRange(req.query)) {
+ return getMetric(req as unknown as Parameters<typeof getMetric>[0], res);
+ }
+
const filtersPresent = hasLiteFilters(req.query.filters);
// Pull totalCount off the window column and drop it from the returned rows so
diff --git a/server/src/api/analytics/lite/getOverviewBucketedLite.ts b/server/src/api/analytics/lite/getOverviewBucketedLite.ts
index 48b0cee73..4a8c20421 100644
--- a/server/src/api/analytics/lite/getOverviewBucketedLite.ts
+++ b/server/src/api/analytics/lite/getOverviewBucketedLite.ts
@@ -1,11 +1,10 @@
import { FilterParams } from "@rybbit/shared";
import { FastifyReply, FastifyRequest } from "fastify";
-import SqlString from "sqlstring";
import { getOverviewBucketed } from "../getOverviewBucketed.js";
import { TimeBucket } from "../types.js";
-import { TimeBucketToFn } from "../utils/utils.js";
+import { resolveTimeWindow } from "../utils/timeWindow.js";
import { analyticsRoute, runAnalyticsQuery } from "../utils/analyticsQuery.js";
-import { getLiteFillClause, getLiteSessionFilter, getLiteTimeStatement, hasLiteFilters, liteBucket } from "./utils.js";
+import { getLiteSessionFilter, hasLiteDatetimeRange, hasLiteFilters, liteBucket } from "./utils.js";
type GetOverviewBucketedLiteResponse = {
time: string;
@@ -26,13 +25,12 @@ type GetOverviewBucketedLiteResponse = {
// bucketing is negligible (sessions rarely cross day boundaries), and we get
// all 6 metrics from a single small table.
function buildHourBucketQuery(args: {
- fn: string;
- tz: string;
+ bucketed: (column: string) => string;
overviewTime: string;
sessionsTime: string;
fill: string;
}) {
- const { fn, tz, overviewTime, sessionsTime, fill } = args;
+ const { bucketed, overviewTime, sessionsTime, fill } = args;
return `
SELECT
coalesce(p.time, s.time) AS time,
@@ -44,7 +42,7 @@ function buildHourBucketQuery(args: {
coalesce(s.session_duration, 0) AS session_duration
FROM (
SELECT
- toDateTime(${fn}(toTimeZone(event_hour, ${tz}))) AS time,
+ ${bucketed("event_hour")} AS time,
sum(pageviews) AS pageviews,
uniqMerge(users) AS users
FROM overview_hourly_mv_target
@@ -55,7 +53,7 @@ function buildHourBucketQuery(args: {
) p
FULL JOIN (
SELECT
- toDateTime(${fn}(toTimeZone(session_start, ${tz}))) AS time,
+ ${bucketed("session_start")} AS time,
count() AS sessions,
avg(session_pageviews) AS pages_per_session,
countIf(session_pageviews = 1) / count() * 100 AS bounce_rate,
@@ -79,12 +77,11 @@ function buildHourBucketQuery(args: {
}
function buildDayBucketQuery(args: {
- fn: string;
- tz: string;
+ bucketed: (column: string) => string;
sessionTime: string;
fill: string;
}) {
- const { fn, tz, sessionTime, fill } = args;
+ const { bucketed, sessionTime, fill } = args;
// Aggregate in the inner GROUP BY, then compose ratios in the outer SELECT.
// Aliasing `sum(sessions) AS sessions` would shadow the column inside the
// div-by-zero guard and trigger ILLEGAL_AGGREGATION.
@@ -99,7 +96,7 @@ function buildDayBucketQuery(args: {
if(sessions > 0, total_session_duration_seconds / sessions, 0) AS session_duration
FROM (
SELECT
- toDateTime(${fn}(toTimeZone(session_hour, ${tz}))) AS time,
+ ${bucketed("session_hour")} AS time,
sum(sessions) AS sessions,
sum(pageviews) AS pageviews,
uniqMerge(users) AS users,
@@ -121,13 +118,12 @@ function buildDayBucketQuery(args: {
// MVs. Bucketing by session-start instead of event-time is the same negligible
// approximation the day-bucket path already makes.
function buildSessionMvFilteredQuery(args: {
- fn: string;
- tz: string;
+ bucketed: (column: string) => string;
sessionsTime: string;
fill: string;
filterSql: string;
}) {
- const { fn, tz, sessionsTime, fill, filterSql } = args;
+ const { bucketed, sessionsTime, fill, filterSql } = args;
return `
SELECT
time,
@@ -139,7 +135,7 @@ function buildSessionMvFilteredQuery(args: {
if(sessions > 0, total_session_duration_seconds / sessions, 0) AS session_duration
FROM (
SELECT
- toDateTime(${fn}(toTimeZone(session_start, ${tz}))) AS time,
+ ${bucketed("session_start")} AS time,
count() AS sessions,
sum(session_pageviews) AS pageviews,
uniqExact(user_id) AS users,
@@ -174,16 +170,24 @@ export const getOverviewBucketedLite = analyticsRoute<GetOverviewBucketedLiteReq
"overview",
async (req: FastifyRequest<GetOverviewBucketedLiteRequest>, res: FastifyReply) => {
const site = Number(req.params.siteId);
- const bucket = liteBucket(req.query.bucket);
- const fn = TimeBucketToFn[bucket];
- const tz = SqlString.escape(req.query.time_zone || "UTC");
- const isAllTime =
- !req.query.start_date &&
- !req.query.end_date &&
- req.query.past_minutes_start === undefined &&
- req.query.past_minutes_end === undefined;
- const fill = isAllTime ? "" : getLiteFillClause(req.query, bucket);
+ // The hourly rollups can't express a sub-hour window.
+ if (hasLiteDatetimeRange(req.query)) {
+ return getOverviewBucketed(req, res);
+ }
+
+ const bucket = liteBucket(req.query.bucket);
+ const window = resolveTimeWindow(req.query);
+ // The rollups name their time column differently per table, so the window
+ // renders the bucket expression per column instead of each builder
+ // reassembling it from a function name and a timezone.
+ const bucketed = (column: string) => window.bucketed(column, bucket);
+ const fill = window.fill(bucket);
+ // Every predicate in the query comes off this one window. Resolving it per
+ // column re-read now(), so a past-minutes request built across an hour
+ // boundary could bound the pageview rollup and the session rollup to
+ // different windows and join two different questions together.
+ const where = (column: string) => window.where(column);
const filtersPresent = hasLiteFilters(req.query.filters);
@@ -196,9 +200,8 @@ export const getOverviewBucketedLite = analyticsRoute<GetOverviewBucketedLiteReq
return getOverviewBucketed(req, res);
}
query = buildSessionMvFilteredQuery({
- fn,
- tz,
- sessionsTime: getLiteTimeStatement(req.query, "start_time"),
+ bucketed,
+ sessionsTime: where("start_time"),
fill,
filterSql: filter.sql,
});
@@ -207,16 +210,14 @@ export const getOverviewBucketedLite = analyticsRoute<GetOverviewBucketedLiteReq
query = useDayBucket
? buildDayBucketQuery({
- fn,
- tz,
- sessionTime: getLiteTimeStatement(req.query, "session_hour"),
+ bucketed,
+ sessionTime: where("session_hour"),
fill,
})
: buildHourBucketQuery({
- fn,
- tz,
- overviewTime: getLiteTimeStatement(req.query, "event_hour"),
- sessionsTime: getLiteTimeStatement(req.query, "start_time"),
+ bucketed,
+ overviewTime: where("event_hour"),
+ sessionsTime: where("start_time"),
fill,
});
}
diff --git a/server/src/api/analytics/lite/getOverviewLite.ts b/server/src/api/analytics/lite/getOverviewLite.ts
index 77104757e..3308479fb 100644
--- a/server/src/api/analytics/lite/getOverviewLite.ts
+++ b/server/src/api/analytics/lite/getOverviewLite.ts
@@ -2,7 +2,8 @@ import { FilterParams } from "@rybbit/shared";
import { FastifyReply, FastifyRequest } from "fastify";
import { getOverview } from "../getOverview.js";
import { analyticsRoute, runAnalyticsQuery } from "../utils/analyticsQuery.js";
-import { getLiteSessionFilter, getLiteTimeStatement, hasLiteFilters } from "./utils.js";
+import { getTimeStatement } from "../utils/timeWindow.js";
+import { getLiteSessionFilter, hasLiteDatetimeRange, hasLiteFilters } from "./utils.js";
type GetOverviewLiteResponse = {
sessions: number;
@@ -24,7 +25,7 @@ interface GetOverviewLiteRequest {
// session_hourly_mv_target.
export const buildOverviewLiteQuery = (query: GetOverviewLiteRequest["Querystring"], filterSql: string | null) => {
if (filterSql !== null) {
- const sessionsTime = getLiteTimeStatement(query, "start_time");
+ const sessionsTime = getTimeStatement(query, "start_time");
return `
SELECT
sessions,
@@ -57,7 +58,7 @@ export const buildOverviewLiteQuery = (query: GetOverviewLiteRequest["Querystrin
`;
}
- const timeStatement = getLiteTimeStatement(query, "session_hour");
+ const timeStatement = getTimeStatement(query, "session_hour");
// Single read of the refreshable session_hourly_mv_target β€” ~720 rows/month
// per site instead of millions of session rows. All 6 metrics derive from
@@ -93,6 +94,12 @@ export const getOverviewLite = analyticsRoute<GetOverviewLiteRequest>(
"overview",
async (req: FastifyRequest<GetOverviewLiteRequest>, res: FastifyReply) => {
const site = Number(req.params.siteId);
+
+ // The hourly rollups can't express a sub-hour window.
+ if (hasLiteDatetimeRange(req.query)) {
+ return getOverview(req, res);
+ }
+
const filtersPresent = hasLiteFilters(req.query.filters);
// Filters that touch columns the session rollup doesn't carry (pathname,
diff --git a/server/src/api/analytics/lite/utils.test.ts b/server/src/api/analytics/lite/utils.test.ts
index 3d3fbf2d2..52cf36836 100644
--- a/server/src/api/analytics/lite/utils.test.ts
+++ b/server/src/api/analytics/lite/utils.test.ts
@@ -2,9 +2,8 @@ import { FilterParams } from "@rybbit/shared";
import { afterEach, describe, expect, it, vi } from "vitest";
import { TimeBucket } from "../types.js";
import {
- getLiteFillClause,
getLiteSessionFilter,
- getLiteTimeStatement,
+ hasLiteDatetimeRange,
hasLiteFilters,
liteBucket,
wrapLiteLikeValue,
@@ -175,108 +174,18 @@ describe("getLiteSessionFilter", () => {
});
});
-describe("getLiteTimeStatement", () => {
- afterEach(() => {
- vi.useRealTimers();
- });
-
- it("should build a timezone-aware day range against the given column", () => {
- const result = getLiteTimeStatement(
- { start_date: "2024-01-01", end_date: "2024-01-31", time_zone: "America/New_York" },
- "event_hour"
- );
-
- expect(normalize(result)).toBe(
- normalize(`AND event_hour >= toTimeZone(
- toStartOfDay(toDateTime('2024-01-01', 'America/New_York')),
- 'UTC'
- )
- AND event_hour < if(
- toDate('2024-01-31') = toDate(now(), 'America/New_York'),
- toTimeZone(now(), 'UTC'),
- toTimeZone(
- toStartOfDay(toDateTime('2024-01-31', 'America/New_York')) + INTERVAL 1 DAY,
- 'UTC'
- )
- )`)
- );
- });
-
- it("should default a missing time_zone to UTC", () => {
- const result = getLiteTimeStatement(params({ start_date: "2024-01-01", end_date: "2024-01-31" }), "event_hour");
- expect(result).toContain("toDateTime('2024-01-01', 'UTC')");
- expect(result).not.toBe("");
- });
-
- it("should compute exact timestamps for past minutes", () => {
- vi.useFakeTimers();
- vi.setSystemTime(new Date("2024-06-15T12:00:00Z"));
-
- const result = getLiteTimeStatement(params({ past_minutes_start: 120, past_minutes_end: 0 }), "start_time");
-
- expect(result).toBe(
- "AND start_time > toDateTime('2024-06-15 10:00:00') AND start_time <= toDateTime('2024-06-15 12:00:00')"
- );
- });
-
- it("should return empty string with no time params", () => {
- expect(getLiteTimeStatement(params({}), "event_hour")).toBe("");
- });
-
- it("should return empty string when only one date bound is provided", () => {
- expect(getLiteTimeStatement(params({ start_date: "2024-01-01" }), "event_hour")).toBe("");
- });
-});
-
-describe("getLiteFillClause", () => {
- afterEach(() => {
- vi.useRealTimers();
- });
-
- it("should build a date-range fill clause with the bucket fn and interval", () => {
- const result = getLiteFillClause(
- params({ start_date: "2024-01-01", end_date: "2024-01-31", time_zone: "UTC" }),
- "day"
- );
-
- expect(normalize(result)).toBe(
- normalize(`WITH FILL FROM toTimeZone(
- toDateTime(toStartOfDay(toDateTime('2024-01-01', 'UTC'))),
- 'UTC'
- )
- TO if(
- toDate('2024-01-31') = toDate(now(), 'UTC'),
- toTimeZone(now(), 'UTC'),
- toTimeZone(
- toDateTime(toStartOfDay(toDateTime('2024-01-31', 'UTC'))) + INTERVAL 1 DAY,
- 'UTC'
- )
- ) STEP INTERVAL 1 DAY`)
- );
- });
-
- it("should default a missing time_zone to UTC", () => {
- const result = getLiteFillClause(params({ start_date: "2024-01-01", end_date: "2024-01-31" }), "hour");
- expect(result).toContain("toDateTime('2024-01-01', 'UTC')");
- expect(result).toContain("toStartOfHour");
- expect(result).toContain("STEP INTERVAL 1 HOUR");
- });
-
- it("should build a past-minutes fill clause with exact timestamps", () => {
- vi.useFakeTimers();
- vi.setSystemTime(new Date("2024-06-15T12:00:00Z"));
-
- const result = getLiteFillClause(params({ past_minutes_start: 120, past_minutes_end: 0 }), "hour");
-
- expect(normalize(result)).toBe(
- normalize(`WITH FILL FROM toStartOfHour(toDateTime('2024-06-15 10:00:00'))
- TO toStartOfHour(toDateTime('2024-06-15 12:00:00')) + INTERVAL 1 HOUR
- STEP INTERVAL 1 HOUR`)
- );
- });
-
- it("should return empty string with no time params", () => {
- expect(getLiteFillClause(params({}), "hour")).toBe("");
+describe("hasLiteDatetimeRange", () => {
+ // The hourly rollups can't answer a sub-hour question, so a datetime range
+ // sends the request to the raw-events endpoints. Both the lite time statement
+ // and the lite fill used to ignore these params outright, answering with
+ // all-time data and a 200.
+ it("should be true only when both datetime bounds are present", () => {
+ expect(hasLiteDatetimeRange(params({ start_datetime: "2024-01-01 10:30:00", end_datetime: "2024-01-01 14:45:00" })))
+ .toBe(true);
+ expect(hasLiteDatetimeRange(params({ start_datetime: "2024-01-01 10:30:00" }))).toBe(false);
+ expect(hasLiteDatetimeRange(params({ end_datetime: "2024-01-01 14:45:00" }))).toBe(false);
+ expect(hasLiteDatetimeRange(params({ start_date: "2024-01-01", end_date: "2024-01-31" }))).toBe(false);
+ expect(hasLiteDatetimeRange(params({}))).toBe(false);
});
});
diff --git a/server/src/api/analytics/lite/utils.ts b/server/src/api/analytics/lite/utils.ts
index 863e4d815..f09efce00 100644
--- a/server/src/api/analytics/lite/utils.ts
+++ b/server/src/api/analytics/lite/utils.ts
@@ -1,9 +1,7 @@
import { FilterParams } from "@rybbit/shared";
-import SqlString from "sqlstring";
import { FilterType, TimeBucket } from "../types.js";
-import { TimeBucketToFn, bucketIntervalMap } from "../utils/utils.js";
import { buildStringFilterCondition, wrapLikeValue } from "../utils/getFilterStatement.js";
-import { validateFilters, validateTimeStatementParams } from "../utils/query-validation.js";
+import { validateFilters } from "../utils/query-validation.js";
// Lite endpoints back the simplified high-traffic dashboard. They read from
// hourly materialized views (overview_hourly_mv, sessions_mv, pathname_hourly_mv,
@@ -91,64 +89,6 @@ export function getLiteSessionFilter(filters: string | undefined): { supported:
return { supported: true, sql: conditions.length ? `AND ${conditions.join(" AND ")}` : "" };
}
-export type LiteTimeRange = {
- startStatement: string;
- endStatement: string;
- whereClause: string;
-};
-
-// Build a WHERE-clause fragment that filters an MV's hour-bucket column.
-// The `column` is whichever hour-truncated DateTime column the MV exposes
-// (overview_hourly_mv uses `event_hour`; sessions_mv uses `start_time`).
-export function getLiteTimeStatement(
- params: Pick<FilterParams, "start_date" | "end_date" | "time_zone" | "past_minutes_start" | "past_minutes_end">,
- column: string
-): string {
- const { start_date, end_date, time_zone, past_minutes_start, past_minutes_end } = params;
-
- const pastMinutesRange =
- past_minutes_start !== undefined && past_minutes_end !== undefined
- ? { start: Number(past_minutes_start), end: Number(past_minutes_end) }
- : undefined;
-
- // A missing time_zone must not silently discard the requested date range
- // (that would return all-time data); dates are interpreted as UTC instead.
- const date = start_date && end_date ? { start_date, end_date, time_zone: time_zone || "UTC" } : undefined;
-
- const sanitized = validateTimeStatementParams({ date, pastMinutesRange });
-
- if (sanitized.date) {
- const { start_date, end_date, time_zone } = sanitized.date;
- if (!start_date && !end_date) return "";
-
- return `AND ${column} >= toTimeZone(
- toStartOfDay(toDateTime(${SqlString.escape(start_date)}, ${SqlString.escape(time_zone)})),
- 'UTC'
- )
- AND ${column} < if(
- toDate(${SqlString.escape(end_date)}) = toDate(now(), ${SqlString.escape(time_zone)}),
- toTimeZone(now(), 'UTC'),
- toTimeZone(
- toStartOfDay(toDateTime(${SqlString.escape(end_date)}, ${SqlString.escape(time_zone)})) + INTERVAL 1 DAY,
- 'UTC'
- )
- )`;
- }
-
- if (sanitized.pastMinutesRange) {
- const { start, end } = sanitized.pastMinutesRange;
- const now = new Date();
- const startTimestamp = new Date(now.getTime() - start * 60 * 1000);
- const endTimestamp = new Date(now.getTime() - end * 60 * 1000);
- const startIso = startTimestamp.toISOString().slice(0, 19).replace("T", " ");
- const endIso = endTimestamp.toISOString().slice(0, 19).replace("T", " ");
-
- return `AND ${column} > toDateTime(${SqlString.escape(startIso)}) AND ${column} <= toDateTime(${SqlString.escape(endIso)})`;
- }
-
- return "";
-}
-
// MVs are hour-bucketed, so anything below `hour` gets promoted.
export function liteBucket(bucket: TimeBucket | undefined): TimeBucket {
if (!bucket) return "hour";
@@ -158,37 +98,14 @@ export function liteBucket(bucket: TimeBucket | undefined): TimeBucket {
return bucket;
}
-export function getLiteFillClause(params: FilterParams, bucket: TimeBucket): string {
- const { start_date, end_date, past_minutes_start, past_minutes_end } = params;
- const time_zone = params.time_zone || "UTC";
- const fn = TimeBucketToFn[bucket];
- const interval = bucketIntervalMap[bucket];
-
- if (start_date && end_date) {
- return `WITH FILL FROM toTimeZone(
- toDateTime(${fn}(toDateTime(${SqlString.escape(start_date)}, ${SqlString.escape(time_zone)}))),
- 'UTC'
- )
- TO if(
- toDate(${SqlString.escape(end_date)}) = toDate(now(), ${SqlString.escape(time_zone)}),
- toTimeZone(now(), 'UTC'),
- toTimeZone(
- toDateTime(${fn}(toDateTime(${SqlString.escape(end_date)}, ${SqlString.escape(time_zone)}))) + INTERVAL 1 DAY,
- 'UTC'
- )
- ) STEP INTERVAL ${interval}`;
- }
-
- if (past_minutes_start !== undefined && past_minutes_end !== undefined) {
- const now = new Date();
- const startTs = new Date(now.getTime() - Number(past_minutes_start) * 60 * 1000);
- const endTs = new Date(now.getTime() - Number(past_minutes_end) * 60 * 1000);
- const startIso = startTs.toISOString().slice(0, 19).replace("T", " ");
- const endIso = endTs.toISOString().slice(0, 19).replace("T", " ");
- return `WITH FILL FROM ${fn}(toDateTime(${SqlString.escape(startIso)}))
- TO ${fn}(toDateTime(${SqlString.escape(endIso)})) + INTERVAL ${interval}
- STEP INTERVAL ${interval}`;
- }
-
- return "";
+// The hourly rollups can't answer a sub-hour question: a 10:30 β†’ 14:45 window
+// would have to include the whole of hour 10 and hour 14, over-counting both
+// edges. A datetime range therefore falls back to the raw-events endpoints, the
+// same escape hatch an unsupported filter takes. Before, both the lite time
+// statement and the lite fill simply ignored start_datetime/end_datetime, so the
+// request came back as all-time data with a 200.
+export function hasLiteDatetimeRange(
+ params: Pick<FilterParams, "start_datetime" | "end_datetime">
+): boolean {
+ return Boolean(params.start_datetime && params.end_datetime);
}
diff --git a/server/src/api/analytics/performance/getPerformanceByDimension.ts b/server/src/api/analytics/performance/getPerformanceByDimension.ts
index 9086464cc..6d6959bbc 100644
--- a/server/src/api/analytics/performance/getPerformanceByDimension.ts
+++ b/server/src/api/analytics/performance/getPerformanceByDimension.ts
@@ -1,5 +1,5 @@
import { FastifyReply, FastifyRequest } from "fastify";
-import { getTimeStatement } from "../utils/utils.js";
+import { getTimeStatement } from "../utils/timeWindow.js";
import { FilterParams } from "@rybbit/shared";
import { getFilterStatement } from "../utils/getFilterStatement.js";
import { analyticsRoute, getPaginationStatements, runPaginatedQuery } from "../utils/analyticsQuery.js";
diff --git a/server/src/api/analytics/performance/getPerformanceOverview.ts b/server/src/api/analytics/performance/getPerformanceOverview.ts
index 875c8f15c..e9ddc108c 100644
--- a/server/src/api/analytics/performance/getPerformanceOverview.ts
+++ b/server/src/api/analytics/performance/getPerformanceOverview.ts
@@ -1,5 +1,5 @@
import { FastifyReply, FastifyRequest } from "fastify";
-import { getTimeStatement } from "../utils/utils.js";
+import { getTimeStatement } from "../utils/timeWindow.js";
import { PerformanceOverviewMetrics } from "../types.js";
import { FilterParams } from "@rybbit/shared";
import { getFilterStatement } from "../utils/getFilterStatement.js";
diff --git a/server/src/api/analytics/performance/getPerformanceTimeSeries.ts b/server/src/api/analytics/performance/getPerformanceTimeSeries.ts
index 29f36fc00..75d6f2983 100644
--- a/server/src/api/analytics/performance/getPerformanceTimeSeries.ts
+++ b/server/src/api/analytics/performance/getPerformanceTimeSeries.ts
@@ -1,107 +1,20 @@
import { FastifyReply, FastifyRequest } from "fastify";
-import { getTimeStatement, TimeBucketToFn, bucketIntervalMap } from "../utils/utils.js";
-import SqlString from "sqlstring";
-import { validateTimeStatementFillParams } from "../utils/query-validation.js";
+import { resolveTimeWindow } from "../utils/timeWindow.js";
import { TimeBucket, PerformanceTimeSeriesPoint } from "../types.js";
import { FilterParams } from "@rybbit/shared";
import { getFilterStatement } from "../utils/getFilterStatement.js";
import { analyticsRoute, runAnalyticsQuery } from "../utils/analyticsQuery.js";
-function getTimeStatementFill(params: FilterParams, bucket: TimeBucket) {
- const { params: validatedParams, bucket: validatedBucket } = validateTimeStatementFillParams(params, bucket);
-
- if (validatedParams.start_date && validatedParams.end_date && validatedParams.time_zone) {
- const { start_date, end_date, time_zone } = validatedParams;
- return `WITH FILL FROM toTimeZone(
- toDateTime(${TimeBucketToFn[validatedBucket]}(toDateTime(${SqlString.escape(start_date)}, ${SqlString.escape(
- time_zone
- )}))),
- 'UTC'
- )
- TO if(
- toDate(${SqlString.escape(end_date)}) = toDate(now(), ${SqlString.escape(time_zone)}),
- toTimeZone(now(), 'UTC'),
- toTimeZone(
- toDateTime(${TimeBucketToFn[validatedBucket]}(toDateTime(${SqlString.escape(end_date)}, ${SqlString.escape(
- time_zone
- )}))) + INTERVAL 1 DAY,
- 'UTC'
- )
- ) STEP INTERVAL ${bucketIntervalMap[validatedBucket]}`;
- }
- if (validatedParams.start_datetime && validatedParams.end_datetime && validatedParams.time_zone) {
- const { start_datetime, end_datetime, time_zone } = validatedParams;
- return `WITH FILL FROM toTimeZone(
- toDateTime(${TimeBucketToFn[validatedBucket]}(toTimeZone(toDateTime(${SqlString.escape(
- start_datetime
- )}, 'UTC'), ${SqlString.escape(time_zone)}))),
- 'UTC'
- )
- TO toTimeZone(
- toDateTime(${TimeBucketToFn[validatedBucket]}(toTimeZone(toDateTime(${SqlString.escape(
- end_datetime
- )}, 'UTC'), ${SqlString.escape(time_zone)}))),
- 'UTC'
- ) STEP INTERVAL ${bucketIntervalMap[validatedBucket]}`;
- }
- // For specific past minutes range - convert to exact timestamps for better performance
- if (validatedParams.past_minutes_start !== undefined && validatedParams.past_minutes_end !== undefined) {
- const { past_minutes_start: start, past_minutes_end: end } = validatedParams;
-
- // Calculate exact timestamps in JavaScript to avoid runtime ClickHouse calculations
- const now = new Date();
- const startTimestamp = new Date(now.getTime() - start * 60 * 1000);
- const endTimestamp = new Date(now.getTime() - end * 60 * 1000);
-
- // Format as YYYY-MM-DD HH:MM:SS without milliseconds for ClickHouse
- const startIso = startTimestamp.toISOString().slice(0, 19).replace("T", " ");
- const endIso = endTimestamp.toISOString().slice(0, 19).replace("T", " ");
-
- return ` WITH FILL
- FROM ${TimeBucketToFn[validatedBucket]}(toDateTime(${SqlString.escape(startIso)}))
- TO ${TimeBucketToFn[validatedBucket]}(toDateTime(${SqlString.escape(endIso)})) + INTERVAL 1 ${
- validatedBucket === "minute"
- ? "MINUTE"
- : validatedBucket === "five_minutes"
- ? "MINUTE"
- : validatedBucket === "ten_minutes"
- ? "MINUTE"
- : validatedBucket === "fifteen_minutes"
- ? "MINUTE"
- : validatedBucket === "month"
- ? "MONTH"
- : validatedBucket === "week"
- ? "WEEK"
- : validatedBucket === "day"
- ? "DAY"
- : "HOUR"
- }
- STEP INTERVAL ${bucketIntervalMap[validatedBucket]}`;
- }
- return "";
-}
-
export const buildPerformanceTimeSeriesQuery = (params: FilterParams<{ bucket: TimeBucket }>, siteId: number) => {
- const {
- start_date,
- end_date,
- time_zone,
- bucket = "hour",
- filters,
- start_datetime,
- end_datetime,
- past_minutes_start,
- past_minutes_end,
- } = params;
- const timeStatement = getTimeStatement(params);
- const filterStatement = getFilterStatement(filters, siteId, timeStatement);
+ const { bucket = "hour", filters } = params;
- const isAllTime =
- !start_date && !end_date && !start_datetime && !end_datetime && !past_minutes_start && !past_minutes_end;
+ const window = resolveTimeWindow(params);
+ const timeStatement = window.where();
+ const filterStatement = getFilterStatement(filters, siteId, timeStatement);
const query = `
SELECT
- toDateTime(${TimeBucketToFn[bucket]}(toTimeZone(timestamp, ${SqlString.escape(time_zone || "UTC")}))) AS time,
+ ${window.bucketed("timestamp", bucket)} AS time,
quantile(0.5)(lcp) AS lcp_p50,
quantile(0.75)(lcp) AS lcp_p75,
quantile(0.9)(lcp) AS lcp_p90,
@@ -129,7 +42,7 @@ WHERE
AND type = 'performance'
${filterStatement}
${timeStatement}
-GROUP BY time ORDER BY time ${isAllTime ? "" : getTimeStatementFill(params, bucket)}`;
+GROUP BY time ORDER BY time ${window.fill(bucket)}`;
return query;
};
diff --git a/server/src/api/analytics/runDashboardCardQuery.ts b/server/src/api/analytics/runDashboardCardQuery.ts
index a88fd7a2e..e873fee41 100644
--- a/server/src/api/analytics/runDashboardCardQuery.ts
+++ b/server/src/api/analytics/runDashboardCardQuery.ts
@@ -3,7 +3,8 @@ import SqlString from "sqlstring";
import { z } from "zod";
import { clickhouse } from "../../db/clickhouse/clickhouse.js";
import { MAX_CUSTOM_QUERY_LENGTH, normalizeCustomQuery, validateScopedQuery } from "./utils/customQueryValidation.js";
-import { bucketIntervalMap, getTimeStatement } from "./utils/utils.js";
+import { validateHttpTimeParams } from "./utils/query-validation.js";
+import { bucketIntervalMap, getTimeStatement } from "./utils/timeWindow.js";
const MAX_EXECUTION_TIME_SECONDS = 10;
const MAX_RESULT_ROWS = 1000;
@@ -11,6 +12,11 @@ const MAX_RESULT_ROWS = 1000;
const BUCKET_TOKEN = /\{\{\s*bucket\s*\}\}/gi;
const TZ_TOKEN = /\{\{\s*tz\s*\}\}/gi;
+// Only the two fields the time window doesn't own. The bounds are checked by
+// validateHttpTimeParams below rather than re-described here: a second schema
+// that merely looked similar would accept an unpaired, reversed or impossible
+// bound (`25:00:00` matches the format), which the window then drops β€” silently
+// widening the card to all time.
const requestBodySchema = z.object({
query: z.string().trim().min(1).max(MAX_CUSTOM_QUERY_LENGTH),
startDate: z.string().optional(),
@@ -44,6 +50,23 @@ export async function runDashboardCardQuery(
return reply.status(400).send({ error: body.error.errors[0]?.message ?? "Invalid request body" });
}
+ // The bounds arrive in the body, so validateTimeParams β€” a query-param
+ // preHandler β€” never sees them. Run the same validator the routes run, on the
+ // same param names, so this endpoint rejects exactly what they reject.
+ const timeParams = {
+ start_date: body.data.startDate,
+ end_date: body.data.endDate,
+ time_zone: body.data.timeZone,
+ start_datetime: body.data.startDateTime,
+ end_datetime: body.data.endDateTime,
+ past_minutes_start: body.data.pastMinutesStart,
+ past_minutes_end: body.data.pastMinutesEnd,
+ };
+ const timeError = validateHttpTimeParams(timeParams);
+ if (timeError) {
+ return reply.status(400).send({ error: timeError });
+ }
+
// Substitute {{bucket}} and {{tz}} BEFORE validation so the validator never
// sees the template tokens. {{bucket}} comes from an allowlisted enum mapped
// to a constant interval string; {{tz}} is SqlString-escaped to a quoted
@@ -64,15 +87,7 @@ export async function runDashboardCardQuery(
// Auto-scope the timestamp to the global time range. getTimeStatement returns
// an "AND timestamp >= ... AND timestamp < ..." fragment (or "" for all-time),
// with all values Zod-sanitized and SqlString-escaped internally.
- const timeStatement = getTimeStatement({
- start_date: body.data.startDate ?? "",
- end_date: body.data.endDate ?? "",
- time_zone: body.data.timeZone ?? "",
- start_datetime: body.data.startDateTime,
- end_datetime: body.data.endDateTime,
- past_minutes_start: body.data.pastMinutesStart,
- past_minutes_end: body.data.pastMinutesEnd,
- });
+ const timeStatement = getTimeStatement(timeParams);
const query = `
WITH scoped_events AS (
diff --git a/server/src/api/analytics/sessions/getSessionLocations.ts b/server/src/api/analytics/sessions/getSessionLocations.ts
index 60f27cc83..55403b813 100644
--- a/server/src/api/analytics/sessions/getSessionLocations.ts
+++ b/server/src/api/analytics/sessions/getSessionLocations.ts
@@ -1,6 +1,6 @@
import { FilterParams } from "@rybbit/shared";
import { FastifyReply, FastifyRequest } from "fastify";
-import { getTimeStatement } from "../utils/utils.js";
+import { getTimeStatement } from "../utils/timeWindow.js";
import { getFilterStatement } from "../utils/getFilterStatement.js";
import { analyticsRoute, runAnalyticsQuery } from "../utils/analyticsQuery.js";
diff --git a/server/src/api/analytics/sessions/getSessions.ts b/server/src/api/analytics/sessions/getSessions.ts
index 963f5a46e..50d712ca3 100644
--- a/server/src/api/analytics/sessions/getSessions.ts
+++ b/server/src/api/analytics/sessions/getSessions.ts
@@ -2,7 +2,8 @@ import { FilterParams } from "@rybbit/shared";
import { FastifyReply, FastifyRequest } from "fastify";
import { getFilterStatement } from "../utils/getFilterStatement.js";
import { SESSION_CHANNEL_AGG, SESSION_REFERRER_AGG } from "../utils/sessionAttribution.js";
-import { enrichWithTraits, getTimeStatement } from "../utils/utils.js";
+import { enrichWithTraits } from "../utils/utils.js";
+import { getTimeStatement } from "../utils/timeWindow.js";
import { analyticsRoute, runAnalyticsQuery, QuerySpec } from "../utils/analyticsQuery.js";
import { matchesUser } from "../utils/effectiveUserId.js";
diff --git a/server/src/api/analytics/users/getUserInfo.ts b/server/src/api/analytics/users/getUserInfo.ts
index 876cb40cd..bd43df608 100644
--- a/server/src/api/analytics/users/getUserInfo.ts
+++ b/server/src/api/analytics/users/getUserInfo.ts
@@ -5,7 +5,7 @@ import { db } from "../../../db/postgres/postgres.js";
import { userProfiles, userAliases } from "../../../db/postgres/schema.js";
import { getFilterStatement } from "../utils/getFilterStatement.js";
import { SESSION_CHANNEL_AGG, SESSION_REFERRER_AGG } from "../utils/sessionAttribution.js";
-import { getTimeStatement } from "../utils/utils.js";
+import { getTimeStatement } from "../utils/timeWindow.js";
import { matchesUser } from "../utils/effectiveUserId.js";
import { runAnalyticsQuery } from "../utils/analyticsQuery.js";
diff --git a/server/src/api/analytics/users/getUsers.ts b/server/src/api/analytics/users/getUsers.ts
index 6e3238dfd..b0c0d9fc2 100644
--- a/server/src/api/analytics/users/getUsers.ts
+++ b/server/src/api/analytics/users/getUsers.ts
@@ -1,7 +1,8 @@
import { FastifyReply, FastifyRequest } from "fastify";
import { sql, SQL } from "drizzle-orm";
import { db } from "../../../db/postgres/postgres.js";
-import { enrichWithTraits, getTimeStatement } from "../utils/utils.js";
+import { enrichWithTraits } from "../utils/utils.js";
+import { getTimeStatement } from "../utils/timeWindow.js";
import { FilterParams } from "@rybbit/shared";
import { getFilterStatement } from "../utils/getFilterStatement.js";
import { SESSION_CHANNEL_AGG, SESSION_REFERRER_AGG } from "../utils/sessionAttribution.js";
diff --git a/server/src/api/analytics/utils/analyticsQuery.test.ts b/server/src/api/analytics/utils/analyticsQuery.test.ts
index 3dbd8827f..c6fd62318 100644
--- a/server/src/api/analytics/utils/analyticsQuery.test.ts
+++ b/server/src/api/analytics/utils/analyticsQuery.test.ts
@@ -83,10 +83,21 @@ describe("runAnalyticsQuery", () => {
query: "SELECT 1",
format: "JSONEachRow",
query_params: { siteId: 1 },
+ clickhouse_settings: { max_execution_time: 60 },
});
expect(rows).toEqual([{ value: "Chrome", count: 42 }]);
});
+ // Analytics queries used to run with no settings at all, so a runaway all-time
+ // query could hold a ClickHouse slot indefinitely.
+ it("caps execution time", async () => {
+ mockQuery.mockResolvedValueOnce(resultSet([]));
+
+ await runAnalyticsQuery({ query: "SELECT 1" });
+
+ expect(mockQuery.mock.calls[0][0].clickhouse_settings?.max_execution_time).toBe(60);
+ });
+
it("wraps failures in AnalyticsQueryError carrying the SQL", async () => {
const boom = new Error("boom");
mockQuery.mockRejectedValueOnce(boom);
diff --git a/server/src/api/analytics/utils/analyticsQuery.ts b/server/src/api/analytics/utils/analyticsQuery.ts
index 41fff6245..33d154fed 100644
--- a/server/src/api/analytics/utils/analyticsQuery.ts
+++ b/server/src/api/analytics/utils/analyticsQuery.ts
@@ -23,12 +23,22 @@ export class AnalyticsQueryError extends Error {
}
}
+/**
+ * Every analytics query used to run uncapped while the two custom-SQL endpoints
+ * capped at 10 seconds β€” an all-time query on a large Site could hold a
+ * ClickHouse slot indefinitely. This bound is deliberately far above the 10s the
+ * user-authored endpoints allow: these queries are first-party and a legitimate
+ * all-time range on a busy Site is slow, not runaway.
+ */
+const MAX_EXECUTION_TIME_SECONDS = 60;
+
export async function runAnalyticsQuery<T>(spec: QuerySpec): Promise<T[]> {
try {
const result = await clickhouse.query({
query: spec.query,
format: "JSONEachRow",
query_params: spec.params,
+ clickhouse_settings: { max_execution_time: MAX_EXECUTION_TIME_SECONDS },
});
return await processResults<T>(result);
} catch (error) {
diff --git a/server/src/api/analytics/utils/query-validation.test.ts b/server/src/api/analytics/utils/query-validation.test.ts
index d3b54336e..023af77af 100644
--- a/server/src/api/analytics/utils/query-validation.test.ts
+++ b/server/src/api/analytics/utils/query-validation.test.ts
@@ -1,11 +1,5 @@
import { describe, expect, it } from "vitest";
-import {
- filterParamSchema,
- validateFilters,
- validateHttpTimeParams,
- validateTimeStatementFillParams,
- validateTimeStatementParams,
-} from "./query-validation.js";
+import { filterParamSchema, validateFilters, validateHttpTimeParams } from "./query-validation.js";
// =============================================================================
// validateHttpTimeParams
@@ -178,149 +172,6 @@ describe("validateHttpTimeParams", () => {
});
});
-// =============================================================================
-// validateTimeStatementParams
-// =============================================================================
-
-describe("validateTimeStatementParams", () => {
- const ALL_UNDEFINED = { date: undefined, dateTimeRange: undefined, pastMinutesRange: undefined };
-
- it("accepts a valid date object", () => {
- const params = { date: { start_date: "2025-01-01", end_date: "2025-01-31", time_zone: "UTC" } };
- expect(validateTimeStatementParams(params)).toEqual(params);
- });
-
- it("accepts a valid dateTimeRange", () => {
- const params = { dateTimeRange: { start_datetime: "2025-01-01 00:00:00", end_datetime: "2025-01-02 00:00:00" } };
- expect(validateTimeStatementParams(params)).toEqual(params);
- });
-
- it("accepts a valid pastMinutesRange where start is older (greater) than end", () => {
- const params = { pastMinutesRange: { start: 60, end: 0 } };
- expect(validateTimeStatementParams(params)).toEqual(params);
- });
-
- // PINNED BEHAVIOR: timeStatementParamsSchema ends in .catch({...}), so ANY
- // invalid input β€” malformed dates, bad timezones, reversed ranges, even
- // complete garbage β€” is silently swallowed and replaced with all-undefined
- // fields instead of throwing. Callers (getTimeStatement) treat all-undefined
- // as "no time filter", so invalid input degrades to an all-time query rather
- // than an error. Tests below pin this so a future change is deliberate.
- describe("silently swallows invalid input to all-undefined (.catch)", () => {
- it("empty object (nothing provided) does not throw", () => {
- expect(validateTimeStatementParams({})).toEqual(ALL_UNDEFINED);
- });
-
- it("non-object garbage does not throw", () => {
- expect(validateTimeStatementParams(null)).toEqual(ALL_UNDEFINED);
- expect(validateTimeStatementParams("garbage")).toEqual(ALL_UNDEFINED);
- expect(validateTimeStatementParams(42)).toEqual(ALL_UNDEFINED);
- });
-
- it("invalid time zone is swallowed", () => {
- expect(
- validateTimeStatementParams({
- date: { start_date: "2025-01-01", end_date: "2025-01-31", time_zone: "Not/AZone" },
- })
- ).toEqual(ALL_UNDEFINED);
- });
-
- it("date object missing required time_zone is swallowed", () => {
- expect(
- validateTimeStatementParams({ date: { start_date: "2025-01-01", end_date: "2025-01-31" } })
- ).toEqual(ALL_UNDEFINED);
- });
-
- it("malformed date strings are swallowed", () => {
- expect(
- validateTimeStatementParams({ date: { start_date: "01/01/2025", end_date: "2025-01-31", time_zone: "UTC" } })
- ).toEqual(ALL_UNDEFINED);
- });
-
- it("reversed or equal dateTimeRange is swallowed", () => {
- expect(
- validateTimeStatementParams({
- dateTimeRange: { start_datetime: "2025-01-02 00:00:00", end_datetime: "2025-01-01 00:00:00" },
- })
- ).toEqual(ALL_UNDEFINED);
- });
-
- it("pastMinutesRange with start <= end (wrong ordering) is swallowed", () => {
- expect(validateTimeStatementParams({ pastMinutesRange: { start: 0, end: 60 } })).toEqual(ALL_UNDEFINED);
- expect(validateTimeStatementParams({ pastMinutesRange: { start: 60, end: 60 } })).toEqual(ALL_UNDEFINED);
- });
-
- it("negative pastMinutesRange values are swallowed", () => {
- expect(validateTimeStatementParams({ pastMinutesRange: { start: -10, end: -20 } })).toEqual(ALL_UNDEFINED);
- });
- });
-});
-
-// =============================================================================
-// validateTimeStatementFillParams (bucket enum + fill params schema)
-// =============================================================================
-
-describe("validateTimeStatementFillParams", () => {
- // Cast: validateTimeStatementFillParams is typed for full FilterParams, but
- // the schema only reads the time-related fields, so partial objects are fine.
- const validDateParams = { start_date: "2025-01-01", end_date: "2025-01-31", time_zone: "UTC" } as never;
-
- describe("bucket enum", () => {
- it.each(["minute", "five_minutes", "ten_minutes", "fifteen_minutes", "hour", "day", "week", "month", "year"])(
- "accepts bucket %s",
- bucket => {
- const result = validateTimeStatementFillParams(validDateParams, bucket);
- expect(result.bucket).toBe(bucket);
- }
- );
-
- it("rejects unknown bucket values", () => {
- expect(() => validateTimeStatementFillParams(validDateParams, "quarter")).toThrow();
- expect(() => validateTimeStatementFillParams(validDateParams, undefined)).toThrow();
- });
- });
-
- it("defaults a missing time_zone to UTC instead of dropping the range", () => {
- const result = validateTimeStatementFillParams(
- { start_date: "2025-01-01", end_date: "2025-01-31" } as never,
- "day"
- );
- expect(result.params.time_zone).toBe("UTC");
- expect(result.params.start_date).toBe("2025-01-01");
- });
-
- it("coerces string past_minutes params to numbers", () => {
- const result = validateTimeStatementFillParams(
- { past_minutes_start: "60", past_minutes_end: "0" } as never,
- "minute"
- );
- expect(result.params.past_minutes_start).toBe(60);
- expect(result.params.past_minutes_end).toBe(0);
- });
-
- it("throws when past_minutes_start is not greater than past_minutes_end", () => {
- expect(() =>
- validateTimeStatementFillParams({ past_minutes_start: "0", past_minutes_end: "60" } as never, "minute")
- ).toThrow(/greater than/);
- });
-
- it("throws when no complete time param group is provided", () => {
- expect(() => validateTimeStatementFillParams({} as never, "day")).toThrow(/must be provided/);
- // start_date alone (no end_date) is not a complete group
- expect(() => validateTimeStatementFillParams({ start_date: "2025-01-01" } as never, "day")).toThrow(
- /must be provided/
- );
- });
-
- it("silently turns a non-numeric past_minutes string into undefined, then fails the group check", () => {
- // PINNED: the transform maps NaN to undefined rather than erroring, so the
- // failure surfaces as the "must be provided" refinement, not a type error.
- expect(() =>
- validateTimeStatementFillParams({ past_minutes_start: "abc", past_minutes_end: "0" } as never, "minute")
- ).toThrow(/must be provided/);
- });
-});
-
// =============================================================================
// validateFilters
// =============================================================================
diff --git a/server/src/api/analytics/utils/query-validation.ts b/server/src/api/analytics/utils/query-validation.ts
index 13d4efcc6..14c02e192 100644
--- a/server/src/api/analytics/utils/query-validation.ts
+++ b/server/src/api/analytics/utils/query-validation.ts
@@ -1,234 +1,6 @@
-import { FilterParameter, FilterParams } from "@rybbit/shared";
+import { FilterParameter } from "@rybbit/shared";
import { z } from "zod";
-
-// =============================================================================
-// TIME RELATED SCHEMAS
-// =============================================================================
-
-/**
- * Date validation regex for YYYY-MM-DD format
- */
-const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
-const dateTimeRegex = /^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(Z|[+-]\d{2}:?\d{2})?$/;
-
-const parseDateTimeMs = (value: string) => {
- const normalized = value.includes("T") ? value : value.replace(" ", "T");
- const withZone = /(?:Z|[+-]\d{2}:?\d{2})$/.test(normalized) ? normalized : `${normalized}Z`;
- return Date.parse(withZone);
-};
-
-/**
- * Schema for simplified date parameters without table
- */
-const fillDateParamsSchema = z.object({
- start_date: z
- .string()
- .regex(dateRegex, { message: "Invalid date format. Use YYYY-MM-DD" })
- .optional()
- .refine(date => !date || !isNaN(Date.parse(date)), {
- message: "Invalid date value",
- }),
- end_date: z
- .string()
- .regex(dateRegex, { message: "Invalid date format. Use YYYY-MM-DD" })
- .optional()
- .refine(date => !date || !isNaN(Date.parse(date)), {
- message: "Invalid date value",
- }),
- time_zone: z
- .string()
- .min(1, { message: "Time zone cannot be empty" })
- .refine(
- tz => {
- try {
- // Test if time zone is valid by attempting to format a date with it
- Intl.DateTimeFormat(undefined, { timeZone: tz });
- return true;
- } catch (e) {
- return false;
- }
- },
- { message: "Invalid time zone" }
- ),
-});
-
-const dateTimeRangeSchema = z
- .object({
- start_datetime: z
- .string()
- .regex(dateTimeRegex, { message: "Invalid datetime format. Use YYYY-MM-DD HH:mm:ss" })
- .refine(date => !isNaN(parseDateTimeMs(date)), {
- message: "Invalid datetime value",
- }),
- end_datetime: z
- .string()
- .regex(dateTimeRegex, { message: "Invalid datetime format. Use YYYY-MM-DD HH:mm:ss" })
- .refine(date => !isNaN(parseDateTimeMs(date)), {
- message: "Invalid datetime value",
- }),
- })
- .refine(data => parseDateTimeMs(data.start_datetime) < parseDateTimeMs(data.end_datetime), {
- message: "start_datetime must be before end_datetime",
- });
-
-/**
- * Schema for parameters to getTimeStatement() function
- * Either date or pastMinutesRange must be provided
- */
-const timeStatementParamsSchema = z
- .object({
- date: fillDateParamsSchema.optional(),
- dateTimeRange: dateTimeRangeSchema.optional(),
- pastMinutesRange: z
- .object({
- start: z.number().nonnegative(),
- end: z.number().nonnegative(),
- })
- .optional()
- .refine(data => !data || data.start > data.end, {
- message: "start must be greater than end (start = older, end = newer)",
- }),
- })
- .refine(data => data.date !== undefined || data.dateTimeRange !== undefined || data.pastMinutesRange !== undefined, {
- message: "Either date, dateTimeRange, or pastMinutesRange must be provided",
- })
- // Set default empty objects if schema validation fails
- .catch({
- date: undefined,
- dateTimeRange: undefined,
- pastMinutesRange: undefined,
- });
-
-/**
- * Schema for FilterParams used in getTimeStatementFill() function
- */
-const filterParamsTimeStatementFillSchema = z
- .object({
- start_date: z
- .string()
- .regex(dateRegex, { message: "Invalid date format. Use YYYY-MM-DD" })
- .optional()
- .refine(date => !date || !isNaN(Date.parse(date)), {
- message: "Invalid date value",
- }),
- end_date: z
- .string()
- .regex(dateRegex, { message: "Invalid date format. Use YYYY-MM-DD" })
- .optional()
- .refine(date => !date || !isNaN(Date.parse(date)), {
- message: "Invalid date value",
- }),
- time_zone: z
- .string()
- .min(1, { message: "Time zone cannot be empty" })
- .optional()
- .refine(
- tz => {
- if (!tz) return true;
- try {
- // Test if time zone is valid by attempting to format a date with it
- Intl.DateTimeFormat(undefined, { timeZone: tz });
- return true;
- } catch (e) {
- return false;
- }
- },
- { message: "Invalid time zone" }
- )
- // A missing time_zone must not disable the requested range (all-time
- // fallback) or leak NULL into toTimeZone() SQL; default to UTC.
- .default("UTC"),
- start_datetime: z
- .string()
- .regex(dateTimeRegex, { message: "Invalid datetime format. Use YYYY-MM-DD HH:mm:ss" })
- .optional()
- .refine(date => !date || !isNaN(parseDateTimeMs(date)), {
- message: "Invalid datetime value",
- }),
- end_datetime: z
- .string()
- .regex(dateTimeRegex, { message: "Invalid datetime format. Use YYYY-MM-DD HH:mm:ss" })
- .optional()
- .refine(date => !date || !isNaN(parseDateTimeMs(date)), {
- message: "Invalid datetime value",
- }),
- past_minutes_start: z
- .union([z.string(), z.number()])
- .optional()
- .transform(val => {
- if (val === undefined) return undefined;
- const num = typeof val === "string" ? Number(val) : val;
- return isNaN(num) ? undefined : num;
- })
- .refine(val => val === undefined || val >= 0, {
- message: "past_minutes_start must be non-negative",
- }),
- past_minutes_end: z
- .union([z.string(), z.number()])
- .optional()
- .transform(val => {
- if (val === undefined) return undefined;
- const num = typeof val === "string" ? Number(val) : val;
- return isNaN(num) ? undefined : num;
- })
- .refine(val => val === undefined || val >= 0, {
- message: "past_minutes_end must be non-negative",
- }),
- filters: z.string().optional(),
- })
- .refine(
- data => {
- const hasDateParams = data.start_date && data.end_date && data.time_zone;
- const hasDateTimeParams = data.start_datetime && data.end_datetime && data.time_zone;
- const hasPastMinutesParams = data.past_minutes_start !== undefined && data.past_minutes_end !== undefined;
- return hasDateParams || hasDateTimeParams || hasPastMinutesParams;
- },
- {
- message:
- "Either (start_date, end_date, time_zone), (start_datetime, end_datetime, time_zone), or (past_minutes_start, past_minutes_end) must be provided",
- }
- )
- .refine(
- data => {
- if (data.start_datetime && data.end_datetime) {
- return parseDateTimeMs(data.start_datetime) < parseDateTimeMs(data.end_datetime);
- }
- return true;
- },
- {
- message: "start_datetime must be before end_datetime",
- }
- )
- .refine(
- data => {
- if (data.past_minutes_start !== undefined && data.past_minutes_end !== undefined) {
- return data.past_minutes_start > data.past_minutes_end;
- }
- return true;
- },
- {
- message: "past_minutes_start must be greater than past_minutes_end (start = older, end = newer)",
- }
- );
-
-// =============================================================================
-// BUCKET RELATED SCHEMAS
-// =============================================================================
-
-/**
- * Schema for time bucket values
- */
-const timeBucketSchema = z.enum([
- "minute",
- "five_minutes",
- "ten_minutes",
- "fifteen_minutes",
- "hour",
- "day",
- "week",
- "month",
- "year",
-]);
+import { dateRegex, dateTimeRegex, isValidTimeZone, parseDateTimeMs } from "./timeWindow.js";
// =============================================================================
// FILTER RELATED SCHEMAS
@@ -307,31 +79,6 @@ const filterSchema = z.object({
// SANITIZATION FUNCTIONS
// =============================================================================
-/**
- * Validates and sanitizes parameters for getTimeStatement()
- * @param params Raw input parameters
- * @returns Validated parameters
- */
-export function validateTimeStatementParams(params: unknown) {
- return timeStatementParamsSchema.parse(params);
-}
-
-/**
- * Validates and sanitizes FilterParams for getTimeStatementFill()
- * @param params FilterParams object
- * @param bucket Raw bucket parameter
- * @returns Validated parameters and bucket
- */
-export function validateTimeStatementFillParams(params: FilterParams, bucket: unknown) {
- const validatedBucket = timeBucketSchema.parse(bucket);
- const validatedParams = filterParamsTimeStatementFillSchema.parse(params);
-
- return {
- params: validatedParams,
- bucket: validatedBucket,
- };
-}
-
// =============================================================================
// HTTP-LEVEL TIME PARAM VALIDATION
// =============================================================================
@@ -362,20 +109,7 @@ const httpTimeParamsSchema = z
.regex(dateRegex, { message: "Invalid end_date format. Use YYYY-MM-DD" })
.refine(date => !isNaN(Date.parse(date)), { message: "Invalid end_date value" })
.optional(),
- time_zone: z
- .string()
- .refine(
- tz => {
- try {
- Intl.DateTimeFormat(undefined, { timeZone: tz });
- return true;
- } catch (e) {
- return false;
- }
- },
- { message: "Invalid time_zone" }
- )
- .optional(),
+ time_zone: z.string().refine(isValidTimeZone, { message: "Invalid time_zone" }).optional(),
start_datetime: z
.string()
.regex(dateTimeRegex, { message: "Invalid start_datetime format. Use YYYY-MM-DD HH:mm:ss" })
diff --git a/server/src/api/analytics/utils/timeWindow.test.ts b/server/src/api/analytics/utils/timeWindow.test.ts
new file mode 100644
index 000000000..32b902c13
--- /dev/null
+++ b/server/src/api/analytics/utils/timeWindow.test.ts
@@ -0,0 +1,455 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { TimeBucket } from "../types.js";
+import {
+ bucketIntervalMap,
+ getTimeStatement,
+ normalizeDatetimeForClickhouse,
+ resolveTimeWindow,
+ TimeBucketToFn,
+ TimeWindowParams,
+} from "./timeWindow.js";
+
+const normalize = (sql: string) => sql.replace(/\s+/g, " ").trim();
+
+const getTime = (params: Partial<TimeWindowParams>, column?: string) =>
+ getTimeStatement(params as TimeWindowParams, column);
+const fillOf = (params: Partial<TimeWindowParams>, bucket: TimeBucket) =>
+ normalize(resolveTimeWindow(params as TimeWindowParams).fill(bucket));
+const bucketedOf = (params: Partial<TimeWindowParams>, column: string, bucket: TimeBucket) =>
+ normalize(resolveTimeWindow(params as TimeWindowParams).bucketed(column, bucket));
+
+const ALL_BUCKETS = Object.keys(TimeBucketToFn) as TimeBucket[];
+
+const DATE_RANGE = { start_date: "2024-01-01", end_date: "2024-01-31", time_zone: "America/New_York" };
+const DATETIME_RANGE = { start_datetime: "2024-01-01 05:30:00", end_datetime: "2024-01-02 06:45:00" };
+const PAST_MINUTES = { past_minutes_start: 120, past_minutes_end: 0 };
+
+describe("where()", () => {
+ describe("date range", () => {
+ it("should build a timezone-aware day range from start_date and end_date", () => {
+ expect(normalize(getTime(DATE_RANGE))).toBe(
+ normalize(`AND timestamp >= toTimeZone(
+ toStartOfDay(toDateTime('2024-01-01', 'America/New_York')),
+ 'UTC'
+ )
+ AND timestamp < if(
+ toDate('2024-01-31') = toDate(now(), 'America/New_York'),
+ toTimeZone(now(), 'UTC'),
+ toTimeZone(
+ toStartOfDay(toDateTime('2024-01-31', 'America/New_York')) + INTERVAL 1 DAY,
+ 'UTC'
+ )
+ )`)
+ );
+ });
+
+ it("should default a missing time_zone to UTC instead of dropping the range", () => {
+ const result = getTime({ start_date: "2024-01-01", end_date: "2024-01-31" });
+
+ expect(result).toContain("toDateTime('2024-01-01', 'UTC')");
+ expect(result).toContain("toDateTime('2024-01-31', 'UTC')");
+ expect(result).not.toBe("");
+ });
+
+ it("should defer the 'today' decision to ClickHouse via if(toDate(end) = toDate(now))", () => {
+ const result = getTime({ start_date: "2024-06-15", end_date: "2024-06-15", time_zone: "UTC" });
+
+ expect(normalize(result)).toContain("toDate('2024-06-15') = toDate(now(), 'UTC')");
+ expect(normalize(result)).toContain("toTimeZone(now(), 'UTC')");
+ });
+
+ it("should take precedence over datetime range and past minutes", () => {
+ const result = getTime({
+ start_date: "2024-01-01",
+ end_date: "2024-01-31",
+ time_zone: "UTC",
+ ...DATETIME_RANGE,
+ ...PAST_MINUTES,
+ });
+
+ expect(result).toContain("toStartOfDay(toDateTime('2024-01-01', 'UTC'))");
+ expect(result).not.toContain("2024-01-02");
+ });
+
+ it("should fall through to the datetime range when the dates are malformed", () => {
+ const result = getTime({ start_date: "01/01/2024", end_date: "2024-01-31", ...DATETIME_RANGE });
+
+ expect(normalize(result)).toBe(
+ "AND timestamp >= toDateTime('2024-01-01 05:30:00', 'UTC') AND timestamp < toDateTime('2024-01-02 06:45:00', 'UTC')"
+ );
+ });
+
+ it("should return empty string for an invalid date format", () => {
+ expect(getTime({ start_date: "01/01/2024", end_date: "2024-01-31", time_zone: "UTC" })).toBe("");
+ });
+ });
+
+ describe("datetime range", () => {
+ it("should build a UTC datetime range", () => {
+ const result = getTime({ start_datetime: "2024-01-01 00:00:00", end_datetime: "2024-01-02 12:30:00" });
+
+ expect(normalize(result)).toBe(
+ "AND timestamp >= toDateTime('2024-01-01 00:00:00', 'UTC') AND timestamp < toDateTime('2024-01-02 12:30:00', 'UTC')"
+ );
+ });
+
+ it("should normalize offset datetimes to UTC", () => {
+ const result = getTime({
+ start_datetime: "2024-01-01T05:00:00+02:00",
+ end_datetime: "2024-01-02T05:00:00+02:00",
+ });
+
+ expect(normalize(result)).toBe(
+ "AND timestamp >= toDateTime('2024-01-01 03:00:00', 'UTC') AND timestamp < toDateTime('2024-01-02 03:00:00', 'UTC')"
+ );
+ });
+
+ it("should return empty string when start_datetime is not before end_datetime", () => {
+ expect(getTime({ start_datetime: "2024-01-02 00:00:00", end_datetime: "2024-01-01 00:00:00" })).toBe("");
+ expect(getTime({ start_datetime: "2024-01-01 00:00:00", end_datetime: "2024-01-01 00:00:00" })).toBe("");
+ });
+ });
+
+ describe("past minutes range", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2024-06-15T12:00:00Z"));
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("should compute exact UTC timestamps from past minutes", () => {
+ expect(getTime({ past_minutes_start: 60, past_minutes_end: 0 })).toBe(
+ "AND timestamp > toDateTime('2024-06-15 11:00:00', 'UTC') AND timestamp <= toDateTime('2024-06-15 12:00:00', 'UTC')"
+ );
+ });
+
+ it("should accept numeric strings for past minutes", () => {
+ const result = getTime({
+ past_minutes_start: "30" as unknown as number,
+ past_minutes_end: "0" as unknown as number,
+ });
+
+ expect(result).toBe(
+ "AND timestamp > toDateTime('2024-06-15 11:30:00', 'UTC') AND timestamp <= toDateTime('2024-06-15 12:00:00', 'UTC')"
+ );
+ });
+
+ it("should return empty string when start is not greater than end", () => {
+ expect(getTime({ past_minutes_start: 0, past_minutes_end: 60 })).toBe("");
+ expect(getTime({ past_minutes_start: 30, past_minutes_end: 30 })).toBe("");
+ });
+
+ it("should ignore an unpaired past_minutes param", () => {
+ expect(getTime({ past_minutes_start: 60 })).toBe("");
+ });
+
+ // past_minutes_end = 0 is the realtime dashboard's "up to now". A truthiness
+ // test on the bound treats it as absent, which is how the performance
+ // endpoint used to decide it was an all-time query and drop its fill.
+ it("should treat a zero end bound as a real bound", () => {
+ expect(resolveTimeWindow(PAST_MINUTES as TimeWindowParams).isAllTime).toBe(false);
+ expect(getTime(PAST_MINUTES)).not.toBe("");
+ });
+ });
+
+ describe("column", () => {
+ it("should bound whichever column the caller names", () => {
+ // The replay tables key on start_time and the hourly rollups on
+ // event_hour; callers used to regex-rewrite a statement built for
+ // `timestamp`.
+ expect(getTime(DATE_RANGE, "start_time")).toContain("AND start_time >=");
+ expect(getTime(DATE_RANGE, "start_time")).not.toContain("timestamp");
+ expect(getTime(PAST_MINUTES, "event_hour")).toContain("AND event_hour >");
+ expect(getTime(DATETIME_RANGE, "session_hour")).toContain("AND session_hour >=");
+ });
+
+ it("should default to timestamp", () => {
+ expect(getTime(DATE_RANGE)).toContain("AND timestamp >=");
+ });
+ });
+
+ describe("empty params", () => {
+ it("should return empty string when no time params are provided", () => {
+ expect(getTime({})).toBe("");
+ });
+
+ it("should return empty string when only one date bound is provided", () => {
+ expect(getTime({ start_date: "2024-01-01", time_zone: "UTC" })).toBe("");
+ expect(getTime({ end_date: "2024-01-31", time_zone: "UTC" })).toBe("");
+ });
+
+ // An unusable timezone makes every mode meaningless, so the window degrades
+ // to all-time rather than silently reporting UTC days as local ones.
+ // validateHttpTimeParams rejects it before any HTTP request gets here.
+ it("should return empty string for an invalid time zone", () => {
+ expect(getTime({ ...DATE_RANGE, time_zone: "Not/AZone" })).toBe("");
+ expect(getTime({ ...DATETIME_RANGE, time_zone: "Not/AZone" })).toBe("");
+ expect(getTime({ ...PAST_MINUTES, time_zone: "Not/AZone" })).toBe("");
+ });
+ });
+});
+
+describe("fill()", () => {
+ describe("date range", () => {
+ it("should build a timezone-aware WITH FILL clause bucketed at the range start", () => {
+ expect(fillOf(DATE_RANGE, "day")).toBe(
+ "WITH FILL FROM toTimeZone(toDateTime(toStartOfDay(toTimeZone(toDateTime('2024-01-01', 'America/New_York'), " +
+ "'America/New_York'))), 'UTC') " +
+ "TO if( toDate('2024-01-31') = toDate(now(), 'America/New_York'), toTimeZone(now(), 'UTC'), " +
+ "toTimeZone(toDateTime(toStartOfDay(toTimeZone(toDateTime('2024-01-31', 'America/New_York'), " +
+ "'America/New_York'))) + INTERVAL 1 DAY, 'UTC') ) " +
+ "STEP INTERVAL 1 DAY"
+ );
+ });
+
+ it("should default a missing time_zone to UTC", () => {
+ expect(fillOf({ start_date: "2024-01-01", end_date: "2024-01-31" }, "day")).toContain(
+ "toDateTime('2024-01-01', 'UTC')"
+ );
+ });
+ });
+
+ describe("datetime range", () => {
+ it("should bucket-align both bounds in the window's timezone", () => {
+ const alignedEnd = "toDateTime(toStartOfHour(toTimeZone(toDateTime('2024-01-02 06:45:00', 'UTC'), 'UTC')))";
+
+ expect(fillOf({ ...DATETIME_RANGE, time_zone: "UTC" }, "hour")).toBe(
+ "WITH FILL FROM toDateTime(toStartOfHour(toTimeZone(toDateTime('2024-01-01 05:30:00', 'UTC'), 'UTC'))) " +
+ `TO if(${alignedEnd} = toDateTime('2024-01-02 06:45:00', 'UTC'), ` +
+ `${alignedEnd}, ${alignedEnd} + INTERVAL 1 HOUR) ` +
+ "STEP INTERVAL 1 HOUR"
+ );
+ });
+
+ // Regression: the accepted datetime format allows a Z or +02:00 suffix and
+ // ClickHouse's toDateTime rejects both. The error and performance fills
+ // interpolated the raw value, so a datetime-range request 500'd.
+ it("should normalize a zoned datetime before interpolating it", () => {
+ const result = fillOf(
+ { start_datetime: "2024-01-01T05:30:00Z", end_datetime: "2024-01-02T06:45:00+02:00" },
+ "hour"
+ );
+
+ expect(result).toContain("'2024-01-01 05:30:00'");
+ expect(result).toContain("'2024-01-02 04:45:00'");
+ expect(result).not.toContain("Z'");
+ expect(result).not.toContain("+02:00");
+ });
+
+ // TO is exclusive. Where the upper bound falls decides whether stopping at
+ // it is right: on a boundary it names a bucket the window excludes, so the
+ // fill must stop short of it; mid-bucket it names a bucket the window
+ // partly covers, so the fill must reach one step past it or an empty final
+ // bucket is dropped and the chart ends early. The clause resolves that in
+ // SQL rather than assuming one case, which is what it used to do.
+ // Regression (found in review): the fill used to stop at the truncated end
+ // unconditionally for a datetime range. For [10:30, 14:45) at hour buckets
+ // the rows from 14:00–14:45 are inside the window and bucket to 14:00, but
+ // TO 14:00 is exclusive β€” so the 14:00 bucket appeared only when it had
+ // real rows, and an empty one silently ended the chart an hour early.
+ it("should reach the bucket a mid-bucket upper bound falls in", () => {
+ const result = fillOf({ start_datetime: "2024-01-01 10:30:00", end_datetime: "2024-01-01 14:45:00" }, "hour");
+
+ expect(result).toContain("+ INTERVAL 1 HOUR)");
+ expect(result).toContain("'2024-01-01 14:45:00'");
+ });
+
+ it("should not fill past an upper bound already on a bucket boundary", () => {
+ expect(
+ fillOf({ start_datetime: "2024-01-01 00:00:00", end_datetime: "2024-01-01 04:00:00" }, "hour")
+ ).toContain("TO if(");
+ });
+ });
+
+ describe("past minutes range", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2024-06-15T12:34:00Z"));
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ // Regression: the error fill ran `FROM now() - INTERVAL n MINUTE`, which is
+ // not on a bucket boundary, so filled rows landed at :34 between real rows
+ // at :00 instead of on top of them.
+ it("should align the lower bound to a bucket boundary", () => {
+ const alignedEnd = "toDateTime(toStartOfHour(toTimeZone(toDateTime('2024-06-15 12:34:00', 'UTC'), 'UTC')))";
+
+ expect(fillOf(PAST_MINUTES, "hour")).toBe(
+ "WITH FILL FROM toDateTime(toStartOfHour(toTimeZone(toDateTime('2024-06-15 10:34:00', 'UTC'), 'UTC'))) " +
+ `TO if(${alignedEnd} = toDateTime('2024-06-15 12:34:00', 'UTC'), ` +
+ `${alignedEnd}, ${alignedEnd} + INTERVAL 1 HOUR) ` +
+ "STEP INTERVAL 1 HOUR"
+ );
+ });
+
+ // Regression: the fill bucketed in the server timezone while the SELECT it
+ // is attached to buckets in the Site's, so on a half-hour offset every
+ // filled row landed 30 minutes off the real ones.
+ it("should align in the window's timezone, not the server's", () => {
+ expect(fillOf({ ...PAST_MINUTES, time_zone: "Asia/Kolkata" }, "hour")).toContain(
+ "toDateTime(toStartOfHour(toTimeZone(toDateTime('2024-06-15 10:34:00', 'UTC'), 'Asia/Kolkata')))"
+ );
+ });
+
+ // The window ends mid-bucket, so the final bucket does hold rows: one step
+ // past the aligned end is what makes it appear when it is empty.
+ it("should extend one step past the aligned upper bound", () => {
+ expect(fillOf(PAST_MINUTES, "five_minutes")).toContain("+ INTERVAL 5 MINUTES) STEP INTERVAL 5 MINUTES");
+ });
+
+ it("should read now() once for the predicate and the fill", () => {
+ const window = resolveTimeWindow(PAST_MINUTES as TimeWindowParams);
+
+ vi.setSystemTime(new Date("2024-06-15T18:00:00Z"));
+
+ expect(window.where()).toContain("2024-06-15 12:34:00");
+ expect(window.fill("hour")).toContain("2024-06-15 12:34:00");
+ });
+ });
+
+ describe("buckets", () => {
+ it.each(ALL_BUCKETS)("should use the matching fn and interval for %s", bucket => {
+ const result = fillOf(DATE_RANGE, bucket);
+
+ expect(result).toContain(TimeBucketToFn[bucket]);
+ expect(result).toContain(`STEP INTERVAL ${bucketIntervalMap[bucket]}`);
+ });
+ });
+
+ describe("all-time", () => {
+ // Regression: the fill builders threw when handed no time params and the
+ // error handler called its builder unconditionally, so an all-time error
+ // time-series answered 500.
+ it("should return empty string rather than throwing when no window is bounded", () => {
+ expect(fillOf({}, "day")).toBe("");
+ expect(fillOf({ start_date: "2024-01-01" }, "day")).toBe("");
+ expect(fillOf({ past_minutes_start: 0, past_minutes_end: 60 }, "hour")).toBe("");
+ });
+ });
+});
+
+describe("bucketed()", () => {
+ it("should truncate the named column in the window's timezone", () => {
+ expect(bucketedOf(DATE_RANGE, "timestamp", "hour")).toBe(
+ "toDateTime(toStartOfHour(toTimeZone(timestamp, 'America/New_York')))"
+ );
+ });
+
+ it("should bucket any column the rollups name their time by", () => {
+ for (const column of ["timestamp", "start_time", "event_hour", "session_hour", "session_start"]) {
+ expect(bucketedOf(DATE_RANGE, column, "day")).toContain(`toTimeZone(${column}, 'America/New_York')`);
+ }
+ });
+
+ // ClickHouse rejects a WITH FILL whose bounds are not the same type as the
+ // column being filled, and toStartOfWeek/Month/Year return Date where the
+ // other bucket functions return DateTime. Every bucketed query but the error
+ // time-series already wrapped the truncation in toDateTime to flatten that,
+ // which is why one shared fill builder could not serve both β€” the fill and
+ // the column now come from the same expression.
+ it("should render every bucket size as a DateTime", () => {
+ for (const bucket of ALL_BUCKETS) {
+ expect(bucketedOf(DATE_RANGE, "timestamp", bucket)).toMatch(/^toDateTime\(/);
+ expect(fillOf(DATE_RANGE, bucket)).toContain(`toDateTime(${TimeBucketToFn[bucket]}(`);
+ }
+ });
+
+ it("should still bucket when the window is all-time", () => {
+ const window = resolveTimeWindow({ time_zone: "Asia/Kolkata" } as TimeWindowParams);
+
+ expect(window.isAllTime).toBe(true);
+ expect(window.bucketed("timestamp", "day")).toContain("'Asia/Kolkata'");
+ });
+
+ it("should fall back to UTC for an unusable timezone", () => {
+ expect(bucketedOf({ time_zone: "Not/AZone" }, "timestamp", "day")).toContain("toTimeZone(timestamp, 'UTC')");
+ });
+});
+
+describe("isAllTime", () => {
+ it("should agree with where() on every shape of params", () => {
+ const cases: Partial<TimeWindowParams>[] = [
+ {},
+ DATE_RANGE,
+ DATETIME_RANGE,
+ PAST_MINUTES,
+ { start_date: "2024-01-01" },
+ { end_date: "2024-01-31" },
+ { start_datetime: "2024-01-01 00:00:00" },
+ { past_minutes_start: 60 },
+ { past_minutes_start: 0, past_minutes_end: 60 },
+ { start_date: "01/01/2024", end_date: "2024-01-31" },
+ { ...DATE_RANGE, time_zone: "Not/AZone" },
+ ];
+
+ // The predicate and the fill used to be gated by separately written
+ // presence checks, so a fill could be emitted for a window the WHERE clause
+ // had silently dropped.
+ for (const params of cases) {
+ const window = resolveTimeWindow(params as TimeWindowParams);
+ expect(window.isAllTime).toBe(window.where() === "");
+ expect(window.isAllTime).toBe(window.fill("hour") === "");
+ }
+ });
+});
+
+describe("normalizeDatetimeForClickhouse", () => {
+ it("should strip the Z suffix from ISO UTC datetimes", () => {
+ expect(normalizeDatetimeForClickhouse("2024-01-15T10:30:00Z")).toBe("2024-01-15 10:30:00");
+ });
+
+ it("should convert positive offsets to UTC", () => {
+ expect(normalizeDatetimeForClickhouse("2024-01-15T10:30:00+02:00")).toBe("2024-01-15 08:30:00");
+ });
+
+ it("should convert negative offsets to UTC", () => {
+ expect(normalizeDatetimeForClickhouse("2024-01-15T10:30:00-05:00")).toBe("2024-01-15 15:30:00");
+ });
+
+ it("should treat zoneless datetimes as UTC", () => {
+ expect(normalizeDatetimeForClickhouse("2024-01-15T10:30:00")).toBe("2024-01-15 10:30:00");
+ });
+
+ it("should accept space-separated datetimes without a zone", () => {
+ expect(normalizeDatetimeForClickhouse("2024-01-15 10:30:00")).toBe("2024-01-15 10:30:00");
+ });
+
+ it("should accept space-separated datetimes with an offset", () => {
+ expect(normalizeDatetimeForClickhouse("2024-01-15 10:30:00+02:00")).toBe("2024-01-15 08:30:00");
+ });
+
+ it("should expand date-only input to midnight UTC", () => {
+ expect(normalizeDatetimeForClickhouse("2024-01-15")).toBe("2024-01-15 00:00:00");
+ });
+
+ it("should truncate milliseconds", () => {
+ expect(normalizeDatetimeForClickhouse("2024-01-15T10:30:00.999Z")).toBe("2024-01-15 10:30:00");
+ });
+
+ // Unparseable input reaches toISOString() on an Invalid Date and throws;
+ // callers only pass values already validated by the datetime regex.
+ it("should throw on unparseable input", () => {
+ expect(() => normalizeDatetimeForClickhouse("not-a-date")).toThrow(RangeError);
+ });
+});
+
+describe("SQL injection", () => {
+ it("should reject values that do not match the accepted formats", () => {
+ expect(getTime({ start_date: "2024-01-01'; DROP TABLE events;--", end_date: "2024-01-31" })).toBe("");
+ expect(getTime({ start_datetime: "2024-01-01 00:00:00' OR '1'='1", end_datetime: "2024-01-02 00:00:00" })).toBe("");
+ expect(getTime({ past_minutes_start: "60; DROP TABLE events" as unknown as number, past_minutes_end: 0 })).toBe("");
+ });
+
+ it("should escape the timezone rather than interpolating it raw", () => {
+ // An invalid zone degrades to all-time, so the escaping below is a second
+ // line of defence rather than the only one.
+ expect(getTime({ ...DATE_RANGE, time_zone: "UTC'; DROP TABLE events;--" })).toBe("");
+ expect(fillOf({ ...DATE_RANGE, time_zone: "UTC'; DROP TABLE events;--" }, "day")).toBe("");
+ });
+});
diff --git a/server/src/api/analytics/utils/timeWindow.ts b/server/src/api/analytics/utils/timeWindow.ts
new file mode 100644
index 000000000..1de99df49
--- /dev/null
+++ b/server/src/api/analytics/utils/timeWindow.ts
@@ -0,0 +1,379 @@
+import { FilterParams, TimeBucket } from "@rybbit/shared";
+import SqlString from "sqlstring";
+import { z } from "zod";
+
+/**
+ * The one answer to "what slice of time is this query about?".
+ *
+ * A request expresses its window one of three ways β€” a date range in the Site's
+ * timezone, a range of absolute datetimes, or a trailing past-minutes window β€”
+ * and every bucketed query needs two SQL fragments out of it: a `WHERE`
+ * predicate and a `WITH FILL` clause that puts a zero row in every empty bucket.
+ *
+ * Those fragments used to be built by three `WHERE` builders and five `WITH
+ * FILL` builders, hand-copied across the overview, error, performance, bot and
+ * lite endpoints, with five separate "is this an all-time query?" predicates
+ * deciding whether to emit a fill at all. They had drifted:
+ *
+ * - the error fill ran `FROM now() - INTERVAL n MINUTE`, which is not aligned
+ * to a bucket boundary, so a realtime error chart got filled rows at
+ * :56:47 interleaved with real rows at :00:00
+ * - the error and performance fills interpolated `start_datetime` raw. The
+ * accepted format allows a `Z` or `+02:00` suffix, and ClickHouse's
+ * `toDateTime` rejects both β€” a datetime-range request 500'd
+ * - the error handler called its fill builder unconditionally and the builder
+ * threw on missing time params, so an all-time error time-series 500'd
+ * - the lite fill and the lite predicate ignored `start_datetime`/`end_datetime`
+ * entirely, silently answering a datetime request with all-time data
+ * - past-minutes fills bucketed in the server timezone while the surrounding
+ * `SELECT` bucketed in the Site's, so on a half-hour offset (`Asia/Kolkata`)
+ * the filled rows landed 30 minutes off the real ones
+ *
+ * Callers that need only the predicate keep using {@link getTimeStatement}.
+ * Callers that need both resolve the window once with {@link resolveTimeWindow}
+ * and ask it for each fragment, which is what makes the two agree by
+ * construction: a fill can no longer be emitted for a window the `WHERE` clause
+ * didn't bound, and `now()` for a past-minutes window is read once instead of
+ * once per fragment.
+ *
+ * Resolution is total. Params that are missing, incomplete or malformed resolve
+ * to the all-time window β€” the same forgiving behaviour `getTimeStatement` has
+ * always had, and legitimate for the report jobs, which supply one mode and
+ * leave the others undefined. Rejecting *malformed* params is the HTTP layer's
+ * job: `validateHttpTimeParams` runs in front of every route that takes them.
+ */
+
+// Time bucket mapping constants
+export const TimeBucketToFn = {
+ minute: "toStartOfMinute",
+ five_minutes: "toStartOfFiveMinutes",
+ ten_minutes: "toStartOfTenMinutes",
+ fifteen_minutes: "toStartOfFifteenMinutes",
+ hour: "toStartOfHour",
+ day: "toStartOfDay",
+ week: "toStartOfWeek",
+ month: "toStartOfMonth",
+ year: "toStartOfYear",
+} as const;
+
+export const bucketIntervalMap = {
+ minute: "1 MINUTE",
+ five_minutes: "5 MINUTES",
+ ten_minutes: "10 MINUTES",
+ fifteen_minutes: "15 MINUTES",
+ hour: "1 HOUR",
+ day: "1 DAY",
+ week: "7 DAY",
+ month: "1 MONTH",
+ year: "1 YEAR",
+} as const;
+
+/**
+ * ClickHouse's `toDateTime(String)` parses `YYYY-MM-DD hh:mm:ss` and the `T`
+ * variant, but throws on a trailing `Z` or `+02:00` β€” both of which the accepted
+ * datetime format allows. Normalise to the instant's plain UTC rendering.
+ */
+export const normalizeDatetimeForClickhouse = (value: string) => {
+ const normalized = value.includes("T") ? value : value.replace(" ", "T");
+ const withZone = /(?:Z|[+-]\d{2}:?\d{2})$/.test(normalized) ? normalized : `${normalized}Z`;
+ return new Date(withZone).toISOString().slice(0, 19).replace("T", " ");
+};
+
+/**
+ * Every field is optional: a date range, a datetime range and a past-minutes
+ * window are three alternative ways to say the same thing, and callers outside
+ * HTTP (the report jobs) supply only one of them. No time params at all is a
+ * legitimate all-time query.
+ */
+export type TimeWindowParams = Partial<
+ Pick<
+ FilterParams,
+ | "start_date"
+ | "end_date"
+ | "time_zone"
+ | "start_datetime"
+ | "end_datetime"
+ | "past_minutes_start"
+ | "past_minutes_end"
+ >
+>;
+
+/**
+ * The accepted wire formats, exported so that the HTTP validator in
+ * query-validation.ts accepts exactly what {@link normalizeDatetimeForClickhouse}
+ * knows how to render. The `Z` / `+02:00` suffix drifted between the two once
+ * already β€” accepted at the door, unparseable by ClickHouse downstream.
+ */
+export const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
+export const dateTimeRegex = /^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(Z|[+-]\d{2}:?\d{2})?$/;
+
+export const parseDateTimeMs = (value: string) => {
+ const normalized = value.includes("T") ? value : value.replace(" ", "T");
+ const withZone = /(?:Z|[+-]\d{2}:?\d{2})$/.test(normalized) ? normalized : `${normalized}Z`;
+ return Date.parse(withZone);
+};
+
+export const isValidTimeZone = (tz: string) => {
+ try {
+ Intl.DateTimeFormat(undefined, { timeZone: tz });
+ return true;
+ } catch {
+ return false;
+ }
+};
+
+const dateSchema = z
+ .string()
+ .regex(dateRegex)
+ .refine(date => !isNaN(Date.parse(date)));
+
+const dateTimeSchema = z
+ .string()
+ .regex(dateTimeRegex)
+ .refine(value => !isNaN(parseDateTimeMs(value)));
+
+const minutesSchema = z
+ .union([z.string(), z.number()])
+ .transform(value => Number(value))
+ .refine(value => !isNaN(value) && value >= 0);
+
+const dateWindowSchema = z.object({ start_date: dateSchema, end_date: dateSchema });
+
+const dateTimeWindowSchema = z
+ .object({ start_datetime: dateTimeSchema, end_datetime: dateTimeSchema })
+ .refine(data => parseDateTimeMs(data.start_datetime) < parseDateTimeMs(data.end_datetime));
+
+// start is the older bound: "from 60 minutes ago to 0 minutes ago".
+const pastMinutesWindowSchema = z
+ .object({ start: minutesSchema, end: minutesSchema })
+ .refine(data => data.start > data.end);
+
+/**
+ * A window that has been validated and reduced to one of four shapes. The
+ * `date` shape stays symbolic because its bounds mean "midnight in `timeZone`",
+ * which only ClickHouse can resolve; the instant shapes are already absolute.
+ */
+type ResolvedWindow =
+ | { kind: "all" }
+ | { kind: "date"; startDate: string; endDate: string; timeZone: string }
+ | { kind: "datetime"; start: string; end: string; timeZone: string }
+ | { kind: "pastMinutes"; start: string; end: string; timeZone: string };
+
+/** Formats an instant the way ClickHouse's `toDateTime` wants it. */
+const toClickhouseInstant = (date: Date) => date.toISOString().slice(0, 19).replace("T", " ");
+
+function resolve(params: TimeWindowParams): ResolvedWindow {
+ const timeZone = params.time_zone || "UTC";
+
+ // An unusable timezone makes every window meaningless β€” a date range means
+ // "midnight where the Site is", and the instant ranges still bucket in it β€” so
+ // it degrades to all-time rather than silently reporting UTC days as local
+ // ones. HTTP callers never get here: validateHttpTimeParams rejects it first.
+ if (!isValidTimeZone(timeZone)) {
+ return { kind: "all" };
+ }
+
+ if (params.start_date && params.end_date) {
+ const parsed = dateWindowSchema.safeParse(params);
+ if (parsed.success) {
+ return { kind: "date", startDate: parsed.data.start_date, endDate: parsed.data.end_date, timeZone };
+ }
+ }
+
+ if (params.start_datetime && params.end_datetime) {
+ const parsed = dateTimeWindowSchema.safeParse(params);
+ if (parsed.success) {
+ return {
+ kind: "datetime",
+ start: normalizeDatetimeForClickhouse(parsed.data.start_datetime),
+ end: normalizeDatetimeForClickhouse(parsed.data.end_datetime),
+ timeZone,
+ };
+ }
+ }
+
+ if (params.past_minutes_start !== undefined && params.past_minutes_end !== undefined) {
+ const parsed = pastMinutesWindowSchema.safeParse({
+ start: params.past_minutes_start,
+ end: params.past_minutes_end,
+ });
+ if (parsed.success) {
+ // Resolved to absolute instants here, once, so the predicate and the fill
+ // describe the same window: `now()` used to be read separately by each
+ // builder β€” and four times over inside the overview query alone.
+ const now = Date.now();
+ return {
+ kind: "pastMinutes",
+ start: toClickhouseInstant(new Date(now - parsed.data.start * 60 * 1000)),
+ end: toClickhouseInstant(new Date(now - parsed.data.end * 60 * 1000)),
+ timeZone,
+ };
+ }
+ }
+
+ return { kind: "all" };
+}
+
+/** A resolved window, ready to render either SQL fragment. */
+export interface TimeWindow {
+ /**
+ * True when the request named no usable window. Both fragments are empty:
+ * the query spans the Site's whole history and there is nothing to fill
+ * between.
+ */
+ readonly isAllTime: boolean;
+
+ /**
+ * The `WHERE` fragment bounding `column`, already prefixed with `AND`, or ""
+ * for an all-time window.
+ *
+ * `column` is a parameter because the same window is applied to `timestamp`
+ * on `events`, `start_time` on the replay tables and `event_hour` /
+ * `session_hour` on the hourly rollups. Callers used to build the fragment for
+ * `timestamp` and rewrite it downstream with a regex.
+ */
+ where(column?: string): string;
+
+ /**
+ * The expression to SELECT and GROUP BY when bucketing `column`, truncated to
+ * `bucket` in the window's timezone.
+ *
+ * Pairs with {@link fill}: ClickHouse rejects a `WITH FILL` whose bounds are
+ * not the same type as the column it is filling, and `toStartOfWeek`,
+ * `toStartOfMonth` and `toStartOfYear` return `Date` where every other bucket
+ * function returns `DateTime`. Every bucketed query but one already wrapped
+ * the truncation in `toDateTime` to flatten that; the error time-series did
+ * not, which is why no single fill builder could serve both. Emitting the
+ * bucket expression from the same module as the fill is what makes the two
+ * types agree by construction.
+ */
+ bucketed(column: string, bucket: TimeBucket): string;
+
+ /**
+ * The `WITH FILL FROM … TO … STEP …` clause for `bucket`, or "" for an
+ * all-time window. Belongs directly after the `ORDER BY` of a query that
+ * groups by {@link bucketed}; the bounds are bucket-aligned in the same
+ * timezone so filled rows land on the real ones.
+ */
+ fill(bucket: TimeBucket): string;
+}
+
+/**
+ * Truncates `expression` to `bucket` in `timeZone`, always as a `DateTime`.
+ *
+ * The `toDateTime` wrapper is what keeps a bucket column one type across bucket
+ * sizes: `toStartOfWeek`/`Month`/`Year` return `Date`, the rest `DateTime`, and
+ * a `WITH FILL` whose bounds differ in type from the column it fills is an
+ * INVALID_WITH_FILL_EXPRESSION error, not a silently wrong result. Both the
+ * SELECT expression and the fill bounds are built from here so they cannot
+ * disagree.
+ */
+const truncate = (expression: string, bucket: TimeBucket, timeZone: string) =>
+ `toDateTime(${TimeBucketToFn[bucket]}(toTimeZone(${expression}, ${SqlString.escape(timeZone)})))`;
+
+/** Bucket-aligns an absolute instant, matching the SELECT's bucket expression. */
+const alignInstant = (instant: string, bucket: TimeBucket, timeZone: string) =>
+ truncate(`toDateTime(${SqlString.escape(instant)}, 'UTC')`, bucket, timeZone);
+
+function whereClause(window: ResolvedWindow, column: string): string {
+ switch (window.kind) {
+ case "all":
+ return "";
+
+ case "date": {
+ const { startDate, endDate, timeZone } = window;
+ const tz = SqlString.escape(timeZone);
+ // The upper bound is the end date's midnight *tomorrow*, except when the
+ // end date is today β€” then it is now, so a partial final day is not
+ // reported as a whole one.
+ return `AND ${column} >= toTimeZone(
+ toStartOfDay(toDateTime(${SqlString.escape(startDate)}, ${tz})),
+ 'UTC'
+ )
+ AND ${column} < if(
+ toDate(${SqlString.escape(endDate)}) = toDate(now(), ${tz}),
+ toTimeZone(now(), 'UTC'),
+ toTimeZone(
+ toStartOfDay(toDateTime(${SqlString.escape(endDate)}, ${tz})) + INTERVAL 1 DAY,
+ 'UTC'
+ )
+ )`;
+ }
+
+ case "datetime":
+ return `AND ${column} >= toDateTime(${SqlString.escape(window.start)}, 'UTC')
+ AND ${column} < toDateTime(${SqlString.escape(window.end)}, 'UTC')`;
+
+ case "pastMinutes":
+ return `AND ${column} > toDateTime(${SqlString.escape(window.start)}, 'UTC') AND ${column} <= toDateTime(${SqlString.escape(window.end)}, 'UTC')`;
+ }
+}
+
+function fillClause(window: ResolvedWindow, bucket: TimeBucket): string {
+ if (window.kind === "all") {
+ return "";
+ }
+
+ const step = bucketIntervalMap[bucket];
+
+ if (window.kind === "date") {
+ const { startDate, endDate, timeZone } = window;
+ const tz = SqlString.escape(timeZone);
+ // A date bound means midnight in `timeZone`, which only ClickHouse can
+ // resolve, so the bound stays symbolic and gets truncated in SQL.
+ const midnight = (date: string) => truncate(`toDateTime(${SqlString.escape(date)}, ${tz})`, bucket, timeZone);
+ return `WITH FILL FROM toTimeZone(${midnight(startDate)}, 'UTC')
+ TO if(
+ toDate(${SqlString.escape(endDate)}) = toDate(now(), ${tz}),
+ toTimeZone(now(), 'UTC'),
+ toTimeZone(${midnight(endDate)} + INTERVAL 1 DAY, 'UTC')
+ ) STEP INTERVAL ${step}`;
+ }
+
+ const from = alignInstant(window.start, bucket, window.timeZone);
+ const end = `toDateTime(${SqlString.escape(window.end)}, 'UTC')`;
+ const alignedEnd = alignInstant(window.end, bucket, window.timeZone);
+
+ // `TO` is exclusive, so the last bucket it generates is the one before it.
+ //
+ // Whether that is right depends on where the upper bound falls. On a bucket
+ // boundary the bound is the first instant of a bucket the window excludes, so
+ // that bucket holds no rows and stopping short of it is correct β€” extending
+ // would invent a trailing zero. Mid-bucket, the bucket the bound lands in
+ // does hold rows (the window covers its beginning), so the fill has to reach
+ // one step past it or an empty final bucket is silently dropped and the chart
+ // ends early. A past-minutes window ends at `now` and so is almost always the
+ // second case; a datetime range can be either.
+ const to = `if(${alignedEnd} = ${end}, ${alignedEnd}, ${alignedEnd} + INTERVAL ${step})`;
+
+ return `WITH FILL FROM ${from} TO ${to} STEP INTERVAL ${step}`;
+}
+
+/**
+ * Validates the six time params once and returns the window they describe.
+ *
+ * Precedence is date range, then datetime range, then past minutes β€” the order
+ * the endpoints have always applied. A mode whose params are incomplete or
+ * malformed is skipped rather than failing the whole resolution.
+ */
+export function resolveTimeWindow(params: TimeWindowParams): TimeWindow {
+ const window = resolve(params);
+ // An all-time window still buckets β€” it just doesn't fill β€” so the display
+ // timezone has to survive a window that resolved to no bounds.
+ const timeZone = window.kind === "all" ? params.time_zone || "UTC" : window.timeZone;
+ return {
+ isAllTime: window.kind === "all",
+ where: (column = "timestamp") => whereClause(window, column),
+ bucketed: (column: string, bucket: TimeBucket) =>
+ truncate(column, bucket, isValidTimeZone(timeZone) ? timeZone : "UTC"),
+ fill: (bucket: TimeBucket) => fillClause(window, bucket),
+ };
+}
+
+/**
+ * The `WHERE` fragment alone, for the many callers that never fill. Equivalent
+ * to `resolveTimeWindow(params).where(column)`.
+ */
+export function getTimeStatement(params: TimeWindowParams, column = "timestamp"): string {
+ return resolveTimeWindow(params).where(column);
+}
diff --git a/server/src/api/analytics/utils/utils.test.ts b/server/src/api/analytics/utils/utils.test.ts
index e8608ae8b..91b33bfe8 100644
--- a/server/src/api/analytics/utils/utils.test.ts
+++ b/server/src/api/analytics/utils/utils.test.ts
@@ -1,213 +1,13 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { getTimeStatement, normalizeDatetimeForClickhouse, patternToRegex, processResults } from "./utils.js";
+import { describe, expect, it, vi } from "vitest";
+import { patternToRegex, processResults } from "./utils.js";
vi.mock("../../../db/postgres/postgres.js", () => ({
db: {},
sql: {},
}));
-const normalize = (sql: string) => sql.replace(/\s+/g, " ").trim();
-
-type TimeParams = Parameters<typeof getTimeStatement>[0];
-const getTime = (params: Partial<TimeParams>) => getTimeStatement(params as TimeParams);
-
const makeResultSet = <T>(rows: T[]) => ({ json: async () => rows }) as unknown as Parameters<typeof processResults>[0];
-describe("getTimeStatement", () => {
- describe("date range", () => {
- it("should build a timezone-aware day range from start_date and end_date", () => {
- const result = getTime({
- start_date: "2024-01-01",
- end_date: "2024-01-31",
- time_zone: "America/New_York",
- });
-
- expect(normalize(result)).toBe(
- normalize(`AND timestamp >= toTimeZone(
- toStartOfDay(toDateTime('2024-01-01', 'America/New_York')),
- 'UTC'
- )
- AND timestamp < if(
- toDate('2024-01-31') = toDate(now(), 'America/New_York'),
- toTimeZone(now(), 'UTC'),
- toTimeZone(
- toStartOfDay(toDateTime('2024-01-31', 'America/New_York')) + INTERVAL 1 DAY,
- 'UTC'
- )
- )`)
- );
- });
-
- it("should default a missing time_zone to UTC instead of dropping the range", () => {
- const result = getTime({ start_date: "2024-01-01", end_date: "2024-01-31" });
-
- expect(result).toContain("toDateTime('2024-01-01', 'UTC')");
- expect(result).toContain("toDateTime('2024-01-31', 'UTC')");
- expect(result).not.toBe("");
- });
-
- it("should defer the 'today' decision to ClickHouse via if(toDate(end) = toDate(now))", () => {
- vi.useFakeTimers();
- vi.setSystemTime(new Date("2024-06-15T12:00:00Z"));
-
- const result = getTime({
- start_date: "2024-06-15",
- end_date: "2024-06-15",
- time_zone: "UTC",
- });
-
- expect(normalize(result)).toContain("toDate('2024-06-15') = toDate(now(), 'UTC')");
- expect(normalize(result)).toContain("toTimeZone(now(), 'UTC')");
-
- vi.useRealTimers();
- });
-
- it("should take precedence over datetime range and past minutes", () => {
- const result = getTime({
- start_date: "2024-01-01",
- end_date: "2024-01-31",
- time_zone: "UTC",
- start_datetime: "2024-02-01 00:00:00",
- end_datetime: "2024-02-02 00:00:00",
- past_minutes_start: 60,
- past_minutes_end: 0,
- });
-
- expect(result).toContain("toStartOfDay(toDateTime('2024-01-01', 'UTC'))");
- expect(result).not.toContain("2024-02-01");
- });
-
- it("should return empty string for an invalid date format", () => {
- expect(getTime({ start_date: "01/01/2024", end_date: "2024-01-31", time_zone: "UTC" })).toBe("");
- });
-
- // Potential footgun: an invalid time zone silently degrades to all-time
- // (empty statement) rather than throwing; callers validate upstream.
- it("should return empty string for an invalid time zone", () => {
- expect(getTime({ start_date: "2024-01-01", end_date: "2024-01-31", time_zone: "Not/AZone" })).toBe("");
- });
- });
-
- describe("datetime range", () => {
- it("should build a UTC datetime range", () => {
- const result = getTime({
- start_datetime: "2024-01-01 00:00:00",
- end_datetime: "2024-01-02 12:30:00",
- });
-
- expect(normalize(result)).toBe(
- "AND timestamp >= toDateTime('2024-01-01 00:00:00', 'UTC') AND timestamp < toDateTime('2024-01-02 12:30:00', 'UTC')"
- );
- });
-
- it("should normalize offset datetimes to UTC", () => {
- const result = getTime({
- start_datetime: "2024-01-01T05:00:00+02:00",
- end_datetime: "2024-01-02T05:00:00+02:00",
- });
-
- expect(normalize(result)).toBe(
- "AND timestamp >= toDateTime('2024-01-01 03:00:00', 'UTC') AND timestamp < toDateTime('2024-01-02 03:00:00', 'UTC')"
- );
- });
-
- it("should return empty string when start_datetime is not before end_datetime", () => {
- expect(getTime({ start_datetime: "2024-01-02 00:00:00", end_datetime: "2024-01-01 00:00:00" })).toBe("");
- expect(getTime({ start_datetime: "2024-01-01 00:00:00", end_datetime: "2024-01-01 00:00:00" })).toBe("");
- });
- });
-
- describe("past minutes range", () => {
- beforeEach(() => {
- vi.useFakeTimers();
- vi.setSystemTime(new Date("2024-06-15T12:00:00Z"));
- });
-
- afterEach(() => {
- vi.useRealTimers();
- });
-
- it("should compute exact UTC timestamps from past minutes", () => {
- const result = getTime({ past_minutes_start: 60, past_minutes_end: 0 });
-
- expect(result).toBe(
- "AND timestamp > toDateTime('2024-06-15 11:00:00') AND timestamp <= toDateTime('2024-06-15 12:00:00')"
- );
- });
-
- it("should accept numeric strings for past minutes", () => {
- const result = getTime({
- past_minutes_start: "30" as unknown as number,
- past_minutes_end: "0" as unknown as number,
- });
-
- expect(result).toBe(
- "AND timestamp > toDateTime('2024-06-15 11:30:00') AND timestamp <= toDateTime('2024-06-15 12:00:00')"
- );
- });
-
- it("should return empty string when start is not greater than end", () => {
- expect(getTime({ past_minutes_start: 0, past_minutes_end: 60 })).toBe("");
- expect(getTime({ past_minutes_start: 30, past_minutes_end: 30 })).toBe("");
- });
-
- it("should ignore an unpaired past_minutes param", () => {
- expect(getTime({ past_minutes_start: 60 })).toBe("");
- });
- });
-
- describe("empty params", () => {
- it("should return empty string when no time params are provided", () => {
- expect(getTime({})).toBe("");
- });
-
- it("should return empty string when only one date bound is provided", () => {
- expect(getTime({ start_date: "2024-01-01", time_zone: "UTC" })).toBe("");
- expect(getTime({ end_date: "2024-01-31", time_zone: "UTC" })).toBe("");
- });
- });
-});
-
-describe("normalizeDatetimeForClickhouse", () => {
- it("should strip the Z suffix from ISO UTC datetimes", () => {
- expect(normalizeDatetimeForClickhouse("2024-01-15T10:30:00Z")).toBe("2024-01-15 10:30:00");
- });
-
- it("should convert positive offsets to UTC", () => {
- expect(normalizeDatetimeForClickhouse("2024-01-15T10:30:00+02:00")).toBe("2024-01-15 08:30:00");
- });
-
- it("should convert negative offsets to UTC", () => {
- expect(normalizeDatetimeForClickhouse("2024-01-15T10:30:00-05:00")).toBe("2024-01-15 15:30:00");
- });
-
- it("should treat zoneless datetimes as UTC", () => {
- expect(normalizeDatetimeForClickhouse("2024-01-15T10:30:00")).toBe("2024-01-15 10:30:00");
- });
-
- it("should accept space-separated datetimes without a zone", () => {
- expect(normalizeDatetimeForClickhouse("2024-01-15 10:30:00")).toBe("2024-01-15 10:30:00");
- });
-
- it("should accept space-separated datetimes with an offset", () => {
- expect(normalizeDatetimeForClickhouse("2024-01-15 10:30:00+02:00")).toBe("2024-01-15 08:30:00");
- });
-
- it("should expand date-only input to midnight UTC", () => {
- expect(normalizeDatetimeForClickhouse("2024-01-15")).toBe("2024-01-15 00:00:00");
- });
-
- it("should truncate milliseconds", () => {
- expect(normalizeDatetimeForClickhouse("2024-01-15T10:30:00.999Z")).toBe("2024-01-15 10:30:00");
- });
-
- // Unparseable input reaches toISOString() on an Invalid Date and throws;
- // callers only pass values already validated by the datetime regex.
- it("should throw on unparseable input", () => {
- expect(() => normalizeDatetimeForClickhouse("not-a-date")).toThrow(RangeError);
- });
-});
-
describe("patternToRegex", () => {
it("should convert a single * to a one-segment matcher", () => {
expect(patternToRegex("/blog/*")).toBe("^/blog/[^/]+$");
diff --git a/server/src/api/analytics/utils/utils.ts b/server/src/api/analytics/utils/utils.ts
index f1e78f371..3c69c54a1 100644
--- a/server/src/api/analytics/utils/utils.ts
+++ b/server/src/api/analytics/utils/utils.ts
@@ -1,104 +1,7 @@
import { ResultSet } from "@clickhouse/client";
-import { FilterParams } from "@rybbit/shared";
import { and, eq, inArray } from "drizzle-orm";
-import SqlString from "sqlstring";
import { db } from "../../../db/postgres/postgres.js";
import { userProfiles } from "../../../db/postgres/schema.js";
-import { validateTimeStatementParams } from "./query-validation.js";
-
-export const normalizeDatetimeForClickhouse = (value: string) => {
- const normalized = value.includes("T") ? value : value.replace(" ", "T");
- const withZone = /(?:Z|[+-]\d{2}:?\d{2})$/.test(normalized) ? normalized : `${normalized}Z`;
- return new Date(withZone).toISOString().slice(0, 19).replace("T", " ");
-};
-
-/**
- * Every field is optional: a date range, a datetime range and a past-minutes
- * window are three alternative ways to say the same thing, and callers outside
- * HTTP (the report jobs) supply only one of them. No time params at all is a
- * legitimate all-time query and yields an empty statement.
- */
-type TimeParams = Partial<
- Pick<
- FilterParams,
- | "start_date"
- | "end_date"
- | "time_zone"
- | "start_datetime"
- | "end_datetime"
- | "past_minutes_start"
- | "past_minutes_end"
- >
->;
-
-export function getTimeStatement(params: TimeParams) {
- const { start_date, end_date, time_zone, start_datetime, end_datetime, past_minutes_start, past_minutes_end } =
- params;
-
- // Construct the legacy format for validation
- const pastMinutesRange =
- past_minutes_start !== undefined && past_minutes_end !== undefined
- ? { start: Number(past_minutes_start), end: Number(past_minutes_end) }
- : undefined;
-
- // A missing time_zone must not silently discard the requested date range
- // (that would return all-time data); dates are interpreted as UTC instead.
- const date = start_date && end_date ? { start_date, end_date, time_zone: time_zone || "UTC" } : undefined;
- const dateTimeRange = start_datetime && end_datetime ? { start_datetime, end_datetime } : undefined;
-
- // Sanitize inputs with Zod
- const sanitized = validateTimeStatementParams({
- date,
- dateTimeRange,
- pastMinutesRange,
- });
-
- if (sanitized.date) {
- const { start_date, end_date, time_zone } = sanitized.date;
- if (!start_date && !end_date) {
- return "";
- }
-
- // Use SqlString.escape for date and timeZone values
- return `AND timestamp >= toTimeZone(
- toStartOfDay(toDateTime(${SqlString.escape(start_date)}, ${SqlString.escape(time_zone)})),
- 'UTC'
- )
- AND timestamp < if(
- toDate(${SqlString.escape(end_date)}) = toDate(now(), ${SqlString.escape(time_zone)}),
- toTimeZone(now(), 'UTC'),
- toTimeZone(
- toStartOfDay(toDateTime(${SqlString.escape(end_date)}, ${SqlString.escape(time_zone)})) + INTERVAL 1 DAY,
- 'UTC'
- )
- )`;
- }
-
- if (sanitized.dateTimeRange) {
- const { start_datetime, end_datetime } = sanitized.dateTimeRange;
- return `AND timestamp >= toDateTime(${SqlString.escape(normalizeDatetimeForClickhouse(start_datetime))}, 'UTC')
- AND timestamp < toDateTime(${SqlString.escape(normalizeDatetimeForClickhouse(end_datetime))}, 'UTC')`;
- }
-
- // Handle specific range of past minutes - convert to exact timestamps for better performance
- if (sanitized.pastMinutesRange) {
- const { start, end } = sanitized.pastMinutesRange;
-
- // Calculate exact timestamps in JavaScript to avoid runtime ClickHouse calculations
- const now = new Date();
- const startTimestamp = new Date(now.getTime() - start * 60 * 1000);
- const endTimestamp = new Date(now.getTime() - end * 60 * 1000);
-
- // Format as YYYY-MM-DD HH:MM:SS without milliseconds for ClickHouse
- const startIso = startTimestamp.toISOString().slice(0, 19).replace("T", " ");
- const endIso = endTimestamp.toISOString().slice(0, 19).replace("T", " ");
-
- return `AND timestamp > toDateTime(${SqlString.escape(startIso)}) AND timestamp <= toDateTime(${SqlString.escape(endIso)})`;
- }
-
- // If no valid time parameters were provided, return empty string
- return "";
-}
export async function processResults<T>(results: ResultSet<"JSONEachRow">): Promise<T[]> {
const data: T[] = await results.json();
@@ -149,31 +52,6 @@ export function patternToRegex(pattern: string): string {
return `^${finalRegex}$`;
}
-// Time bucket mapping constants
-export const TimeBucketToFn = {
- minute: "toStartOfMinute",
- five_minutes: "toStartOfFiveMinutes",
- ten_minutes: "toStartOfTenMinutes",
- fifteen_minutes: "toStartOfFifteenMinutes",
- hour: "toStartOfHour",
- day: "toStartOfDay",
- week: "toStartOfWeek",
- month: "toStartOfMonth",
- year: "toStartOfYear",
-} as const;
-
-export const bucketIntervalMap = {
- minute: "1 MINUTE",
- five_minutes: "5 MINUTES",
- ten_minutes: "10 MINUTES",
- fifteen_minutes: "15 MINUTES",
- hour: "1 HOUR",
- day: "1 DAY",
- week: "7 DAY",
- month: "1 MONTH",
- year: "1 YEAR",
-} as const;
-
/**
* Enriches data with user traits from Postgres for identified users.
* This is a shared utility to avoid duplicating the traits fetching logic.
diff --git a/server/src/api/experiments/getExperimentResults.ts b/server/src/api/experiments/getExperimentResults.ts
index de5bcefcf..a0048fcb4 100644
--- a/server/src/api/experiments/getExperimentResults.ts
+++ b/server/src/api/experiments/getExperimentResults.ts
@@ -5,7 +5,8 @@ import { z } from "zod";
import { clickhouse } from "../../db/clickhouse/clickhouse.js";
import { buildGoalCondition } from "../analytics/goals/goalConditions.js";
import { getFilterStatement } from "../analytics/utils/getFilterStatement.js";
-import { getTimeStatement, processResults } from "../analytics/utils/utils.js";
+import { processResults } from "../analytics/utils/utils.js";
+import { getTimeStatement } from "../analytics/utils/timeWindow.js";
import type { ExperimentResultRow } from "./types.js";
import {
buildExperimentResults,
diff --git a/server/src/index.ts b/server/src/index.ts
index 14803c93b..00402dd07 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -203,6 +203,11 @@ const validateTimeParams = async (request: FastifyRequest, reply: FastifyReply)
// Each scoped chain names the resource:action a BEARER credential (API key or
// OAuth token) must be granted; unrestricted legacy credentials and cookie
// sessions always pass. See lib/scopes.ts for the taxonomy.
+//
+// validateTimeParams is on every chain rather than only the ones that currently
+// host a time-taking route: absent params always pass, and the two chains that
+// went without it were how /org-event-count and /admin/service-event-count came
+// to answer a malformed date with all-time data and a 200.
const publicSiteScoped = (resource: ScopeResource, action: ScopeAction) => ({
preHandler: [resolveSiteId, allowPublicSiteAccess({ resource, action }), validateTimeParams] as any,
});
@@ -210,16 +215,16 @@ const authSiteScoped = (resource: ScopeResource, action: ScopeAction) => ({
preHandler: [resolveSiteId, requireSiteAccess({ resource, action }), validateTimeParams] as any,
});
const adminSiteScoped = (resource: ScopeResource, action: ScopeAction) => ({
- preHandler: [resolveSiteId, requireSiteAdminAccess({ resource, action })] as any,
+ preHandler: [resolveSiteId, requireSiteAdminAccess({ resource, action }), validateTimeParams] as any,
});
const orgMemberScoped = (resource: ScopeResource, action: ScopeAction) => ({
- preHandler: [requireOrgMember({ resource, action })] as any,
+ preHandler: [requireOrgMember({ resource, action }), validateTimeParams] as any,
});
const orgAdminScoped = (resource: ScopeResource, action: ScopeAction) => ({
- preHandler: [requireOrgAdminFromParams({ resource, action })] as any,
+ preHandler: [requireOrgAdminFromParams({ resource, action }), validateTimeParams] as any,
});
const authOnlyScoped = (resource: ScopeResource, action: ScopeAction) => ({
- preHandler: [requireAuth({ resource, action })] as any,
+ preHandler: [requireAuth({ resource, action }), validateTimeParams] as any,
});
// Reused scoped chains
@@ -258,7 +263,7 @@ const authOrgWrite = authOnlyScoped("org", "write");
// Scope-exempt / non-bearer chains. "deny-scoped" rejects scoped credentials
// on surfaces with no taxonomy resource (account settings, billing).
-const adminOnly = { preHandler: [requireAdmin] as any };
+const adminOnly = { preHandler: [requireAdmin, validateTimeParams] as any };
const authOnlyNoScopedKeys = { preHandler: [requireAuth("deny-scoped")] as any };
const orgAdminNoScopedKeys = { preHandler: [requireOrgAdminFromParams("deny-scoped")] as any };
diff --git a/server/src/services/pdfReports/pdfReportService.ts b/server/src/services/pdfReports/pdfReportService.ts
index 5bcb29b93..36e91bef0 100644
--- a/server/src/services/pdfReports/pdfReportService.ts
+++ b/server/src/services/pdfReports/pdfReportService.ts
@@ -5,7 +5,8 @@ import { eq } from "drizzle-orm";
import { db } from "../../db/postgres/postgres.js";
import { sites } from "../../db/postgres/schema.js";
import { clickhouse } from "../../db/clickhouse/clickhouse.js";
-import { getTimeStatement, processResults } from "../../api/analytics/utils/utils.js";
+import { processResults } from "../../api/analytics/utils/utils.js";
+import { getTimeStatement } from "../../api/analytics/utils/timeWindow.js";
import { createServiceLogger } from "../../lib/logger/logger.js";
import {
BreakdownDimension,
diff --git a/server/src/services/replay/sessionReplayQueryService.ts b/server/src/services/replay/sessionReplayQueryService.ts
index 0a09ff932..419bb0fb8 100644
--- a/server/src/services/replay/sessionReplayQueryService.ts
+++ b/server/src/services/replay/sessionReplayQueryService.ts
@@ -4,7 +4,8 @@ import {
SessionReplayListItem,
GetSessionReplayEventsResponse,
} from "../../types/sessionReplay.js";
-import { processResults, getTimeStatement } from "../../api/analytics/utils/utils.js";
+import { processResults } from "../../api/analytics/utils/utils.js";
+import { getTimeStatement } from "../../api/analytics/utils/timeWindow.js";
import { FilterParams } from "@rybbit/shared";
import { r2Storage } from "../storage/r2StorageService.js";
import { getFilterStatement } from "../../api/analytics/utils/getFilterStatement.js";
@@ -26,7 +27,7 @@ export class SessionReplayQueryService {
): Promise<SessionReplayListItem[]> {
const { limit = 50, offset = 0, userId, minDuration } = options;
- const timeStatement = getTimeStatement(options).replace(/timestamp/g, "start_time");
+ const timeStatement = getTimeStatement(options, "start_time");
const filterStatement = getFilterStatement(options.filters || "");
diff --git a/server/src/services/siteMetrics/siteMetrics.test.ts b/server/src/services/siteMetrics/siteMetrics.test.ts
index 27dc8e370..641aa618c 100644
--- a/server/src/services/siteMetrics/siteMetrics.test.ts
+++ b/server/src/services/siteMetrics/siteMetrics.test.ts
@@ -8,7 +8,7 @@ vi.mock("../../db/postgres/postgres.js", () => ({
}));
import { FilterParams } from "@rybbit/shared";
-import { getTimeStatement } from "../../api/analytics/utils/utils.js";
+import { getTimeStatement } from "../../api/analytics/utils/timeWindow.js";
import { buildOverviewQuery as buildDashboardOverviewQuery } from "../../api/analytics/getOverview.js";
import {
BreakdownDimension,
diff --git a/server/src/services/siteMetrics/siteMetrics.ts b/server/src/services/siteMetrics/siteMetrics.ts
index 8a65e2664..1fc32175e 100644
--- a/server/src/services/siteMetrics/siteMetrics.ts
+++ b/server/src/services/siteMetrics/siteMetrics.ts
@@ -1,7 +1,7 @@
import { FilterParams } from "@rybbit/shared";
import { EFFECTIVE_SESSION_USER_ID } from "../../api/analytics/utils/effectiveUserId.js";
import { getFilterStatement } from "../../api/analytics/utils/getFilterStatement.js";
-import { getTimeStatement } from "../../api/analytics/utils/utils.js";
+import { getTimeStatement } from "../../api/analytics/utils/timeWindow.js";
/**
* The definition of a Site's headline metrics β€” sessions, pageviews, users,
diff --git a/server/src/services/weekyReports/weeklyReportService.ts b/server/src/services/weekyReports/weeklyReportService.ts
index 88546ad62..8f8d4a68e 100644
--- a/server/src/services/weekyReports/weeklyReportService.ts
+++ b/server/src/services/weekyReports/weeklyReportService.ts
@@ -4,7 +4,8 @@ import { eq } from "drizzle-orm";
import { db } from "../../db/postgres/postgres.js";
import { organization, member, user, sites } from "../../db/postgres/schema.js";
import { clickhouse } from "../../db/clickhouse/clickhouse.js";
-import { getTimeStatement, processResults } from "../../api/analytics/utils/utils.js";
+import { processResults } from "../../api/analytics/utils/utils.js";
+import { getTimeStatement } from "../../api/analytics/utils/timeWindow.js";
import { createServiceLogger } from "../../lib/logger/logger.js";
import { sendWeeklyReportEmail } from "../../lib/email/email.js";
import { filterSitesByMemberAccess } from "../../lib/access.js";