Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Add request-volume timeseries chart to the API logs page. (#4327)

Kiran K93aa72a07589
diff --git a/apps/web/app/api/logs/count/route.ts b/apps/web/app/api/logs/count/route.ts
index 10587da0b1..0d46d204b6 100644
--- a/apps/web/app/api/logs/count/route.ts
+++ b/apps/web/app/api/logs/count/route.ts
@@ -7,7 +7,7 @@ import { NextResponse } from "next/server";
// GET /api/logs/count
export const GET = withWorkspace(
async ({ workspace, searchParams }) => {
- const { start, end, interval, ...filters } =
+ const { start, end, interval, timezone, exactRange, ...filters } =
getApiLogsCountQuerySchema.parse(searchParams);
const { startDate, endDate } = getApiLogsDateRange({
@@ -15,6 +15,8 @@ export const GET = withWorkspace(
start,
end,
interval,
+ timezone,
+ exactRange: Boolean(exactRange),
});
const rows = await getApiLogsCount({
diff --git a/apps/web/app/api/logs/route.ts b/apps/web/app/api/logs/route.ts
index 13a48fcc19..498386d776 100644
--- a/apps/web/app/api/logs/route.ts
+++ b/apps/web/app/api/logs/route.ts
@@ -8,7 +8,7 @@ import { NextResponse } from "next/server";
// GET /api/logs
export const GET = withWorkspace(
async ({ workspace, searchParams }) => {
- const { start, end, interval, ...filters } =
+ const { start, end, interval, timezone, exactRange, ...filters } =
getApiLogsQuerySchema.parse(searchParams);
const { startDate, endDate } = getApiLogsDateRange({
@@ -16,6 +16,8 @@ export const GET = withWorkspace(
start,
end,
interval,
+ timezone,
+ exactRange: Boolean(exactRange),
});
const logs = await getApiLogs({
diff --git a/apps/web/app/api/logs/timeseries/route.ts b/apps/web/app/api/logs/timeseries/route.ts
new file mode 100644
index 0000000000..46bdc59302
--- /dev/null
+++ b/apps/web/app/api/logs/timeseries/route.ts
@@ -0,0 +1,36 @@
+import { getApiLogsDateRange } from "@/lib/api-logs/api-log-retention";
+import { getApiLogsTimeseries } from "@/lib/api-logs/get-api-logs-timeseries";
+import { getApiLogsTimeseriesQuerySchema } from "@/lib/api-logs/schemas";
+import { withWorkspace } from "@/lib/auth/workspace";
+import { NextResponse } from "next/server";
+
+// GET /api/logs/timeseries
+export const GET = withWorkspace(
+ async ({ workspace, searchParams }) => {
+ const { start, end, interval, timezone, exactRange, ...filters } =
+ getApiLogsTimeseriesQuerySchema.parse(searchParams);
+
+ const { startDate, endDate, granularity } = getApiLogsDateRange({
+ plan: workspace.plan,
+ start,
+ end,
+ interval,
+ timezone,
+ exactRange: Boolean(exactRange),
+ });
+
+ const rows = await getApiLogsTimeseries({
+ ...filters,
+ start: startDate,
+ end: endDate,
+ timezone: timezone ?? "UTC",
+ granularity,
+ workspaceId: workspace.id,
+ });
+
+ return NextResponse.json(rows);
+ },
+ {
+ requiredPermissions: ["workspaces.read"],
+ },
+);
diff --git a/apps/web/lib/api-logs/api-log-retention.ts b/apps/web/lib/api-logs/api-log-retention.ts
index 186b447565..caee2a6c4b 100644
--- a/apps/web/lib/api-logs/api-log-retention.ts
+++ b/apps/web/lib/api-logs/api-log-retention.ts
@@ -1,6 +1,8 @@
import { formatUTCDateTimeClickhouse } from "@/lib/analytics/utils/format-utc-datetime-clickhouse";
-import { PlanProps } from "@/lib/types";
-import { subDays } from "date-fns";
+import { sanitizeTimezone } from "@/lib/analytics/utils/sanitize-timezone";
+import { ApiLogsGranularity, PlanProps } from "@/lib/types";
+import { tz, TZDate } from "@date-fns/tz";
+import { differenceInDays, endOfToday, subDays } from "date-fns";
import { getStartEndDates } from "../analytics/utils/get-start-end-dates";
import { API_LOG_RETENTION_DAYS, DEFAULT_RETENTION_DAYS } from "./constants";
@@ -9,43 +11,143 @@ export function getApiLogsDateRange({
start,
end,
interval,
+ timezone,
+ exactRange,
}: {
plan: PlanProps;
start?: string | Date | null;
end?: string | Date | null;
interval?: string;
-}) {
+ timezone?: string;
+ exactRange?: boolean;
+}): {
+ startDate: string;
+ endDate: string;
+ granularity: ApiLogsGranularity;
+} {
+ const tzName = sanitizeTimezone(timezone);
const retentionDays = API_LOG_RETENTION_DAYS[plan] ?? DEFAULT_RETENTION_DAYS;
const retentionBoundary = subDays(new Date(), retentionDays);
- // If interval or custom start/end provided, resolve them
+ // Histogram bar clicks pass exactRange so we keep the bucket's real start/end
+ // (e.g. a single hour). getStartEndDates otherwise snaps custom ranges to
+ // startOfDay/endOfDay, which would expand an hour click to the whole day.
+ if (exactRange && start && end) {
+ let startDate = new Date(start);
+ let endDate = new Date(end);
+
+ if (startDate > endDate) {
+ [startDate, endDate] = [endDate, startDate];
+ }
+
+ const { normalizedStart, normalizedEnd } = clampToRetention({
+ startDate,
+ endDate,
+ retentionBoundary,
+ });
+
+ return {
+ startDate: formatUTCDateTimeClickhouse(normalizedStart),
+ endDate: formatUTCDateTimeClickhouse(normalizedEnd),
+ granularity: granularityFromRange({
+ startDate: normalizedStart,
+ endDate: normalizedEnd,
+ timezone: tzName,
+ }),
+ };
+ }
+
+ if (interval === "60d") {
+ const startDate = subDays(new TZDate(Date.now(), tzName), 60);
+ const endDate = endOfToday({ in: tz(tzName) });
+
+ const { normalizedStart, normalizedEnd } = clampToRetention({
+ startDate,
+ endDate,
+ retentionBoundary,
+ });
+
+ return {
+ startDate: formatUTCDateTimeClickhouse(normalizedStart),
+ endDate: formatUTCDateTimeClickhouse(normalizedEnd),
+ granularity: "day",
+ };
+ }
+
if (interval || (start && end)) {
- const { startDate, endDate } = getStartEndDates({
+ const {
+ startDate,
+ endDate,
+ granularity: resolvedGranularity,
+ } = getStartEndDates({
interval,
start,
end,
+ timezone: tzName,
});
- // Clamp start to retention boundary
- const clampedStart =
- startDate < retentionBoundary ? retentionBoundary : startDate;
- const clampedEnd =
- endDate < retentionBoundary ? retentionBoundary : endDate;
+ const { normalizedStart, normalizedEnd } = clampToRetention({
+ startDate,
+ endDate,
+ retentionBoundary,
+ });
- const normalizedStart =
- clampedStart <= clampedEnd ? clampedStart : clampedEnd;
- const normalizedEnd =
- clampedStart <= clampedEnd ? clampedEnd : clampedStart;
+ const granularity: ApiLogsGranularity =
+ resolvedGranularity === "hour" ? "hour" : "day";
return {
startDate: formatUTCDateTimeClickhouse(normalizedStart),
endDate: formatUTCDateTimeClickhouse(normalizedEnd),
+ granularity,
};
}
- // Default: full retention window
return {
startDate: formatUTCDateTimeClickhouse(retentionBoundary),
endDate: formatUTCDateTimeClickhouse(new Date()),
+ granularity: "day",
+ };
+}
+
+function clampToRetention({
+ startDate,
+ endDate,
+ retentionBoundary,
+}: {
+ startDate: Date;
+ endDate: Date;
+ retentionBoundary: Date;
+}) {
+ const clampedStart =
+ startDate < retentionBoundary ? retentionBoundary : startDate;
+ const clampedEnd = endDate < retentionBoundary ? retentionBoundary : endDate;
+
+ return {
+ normalizedStart: clampedStart <= clampedEnd ? clampedStart : clampedEnd,
+ normalizedEnd: clampedStart <= clampedEnd ? clampedEnd : clampedStart,
};
}
+
+const HOUR_MS = 60 * 60 * 1000;
+
+function granularityFromRange({
+ startDate,
+ endDate,
+ timezone,
+}: {
+ startDate: Date;
+ endDate: Date;
+ timezone: string;
+}): ApiLogsGranularity {
+ const durationMs = endDate.getTime() - startDate.getTime();
+
+ if (durationMs <= 2 * HOUR_MS) {
+ return "minute";
+ }
+
+ const daysDifference = differenceInDays(endDate, startDate, {
+ in: tz(timezone),
+ });
+
+ return daysDifference <= 2 ? "hour" : "day";
+}
diff --git a/apps/web/lib/api-logs/get-api-logs-count.ts b/apps/web/lib/api-logs/get-api-logs-count.ts
index 1308930f7b..966bcf6dab 100644
--- a/apps/web/lib/api-logs/get-api-logs-count.ts
+++ b/apps/web/lib/api-logs/get-api-logs-count.ts
@@ -9,7 +9,7 @@ import {
type GetApiLogsCountParams = Omit<
z.infer<typeof getApiLogsCountQuerySchema>,
- "start" | "end"
+ "start" | "end" | "timezone" | "exactRange"
> & {
workspaceId: string;
start: string;
diff --git a/apps/web/lib/api-logs/get-api-logs-timeseries.ts b/apps/web/lib/api-logs/get-api-logs-timeseries.ts
new file mode 100644
index 0000000000..7ad37bf88c
--- /dev/null
+++ b/apps/web/lib/api-logs/get-api-logs-timeseries.ts
@@ -0,0 +1,57 @@
+import { tb } from "@/lib/tinybird";
+import type { ApiLogsGranularity } from "@/lib/types";
+import * as z from "zod/v4";
+import {
+ apiLogTimeseriesFilterSchemaTB,
+ apiLogTimeseriesRowSchema,
+ getApiLogsTimeseriesQuerySchema,
+} from "./schemas";
+
+type GetApiLogsTimeseriesParams = Omit<
+ z.infer<typeof getApiLogsTimeseriesQuerySchema>,
+ "start" | "end" | "timezone" | "exactRange"
+> & {
+ workspaceId: string;
+ start: string;
+ end: string;
+ timezone: string;
+ granularity: ApiLogsGranularity;
+};
+
+export async function getApiLogsTimeseries(params: GetApiLogsTimeseriesParams) {
+ const {
+ workspaceId,
+ routePattern,
+ method,
+ statusCode,
+ tokenId,
+ requestId,
+ requestType,
+ start,
+ end,
+ timezone,
+ granularity,
+ } = params;
+
+ const pipe = tb.buildPipe({
+ pipe: "get_api_logs_timeseries",
+ parameters: apiLogTimeseriesFilterSchemaTB,
+ data: apiLogTimeseriesRowSchema,
+ });
+
+ const result = await pipe({
+ workspaceId,
+ timezone,
+ granularity,
+ ...(routePattern && { routePattern }),
+ ...(method && { method }),
+ ...(statusCode && { statusCode }),
+ ...(tokenId && { tokenId }),
+ ...(requestId && { requestId }),
+ ...(requestType && { requestType }),
+ ...(start && { start }),
+ ...(end && { end }),
+ });
+
+ return z.array(apiLogTimeseriesRowSchema).parse(result.data);
+}
diff --git a/apps/web/lib/api-logs/get-api-logs.ts b/apps/web/lib/api-logs/get-api-logs.ts
index bc2fe0533b..5967d87610 100644
--- a/apps/web/lib/api-logs/get-api-logs.ts
+++ b/apps/web/lib/api-logs/get-api-logs.ts
@@ -8,7 +8,7 @@ import {
type GetApiLogsParams = Omit<
z.infer<typeof getApiLogsQuerySchema>,
- "start" | "end"
+ "start" | "end" | "timezone" | "exactRange"
> & {
workspaceId: string;
start: string;
diff --git a/apps/web/lib/api-logs/schemas.ts b/apps/web/lib/api-logs/schemas.ts
index 7bbdbb6072..aeba3073a9 100644
--- a/apps/web/lib/api-logs/schemas.ts
+++ b/apps/web/lib/api-logs/schemas.ts
@@ -2,6 +2,7 @@ import { getPaginationQuerySchema } from "@/lib/zod/schemas/misc";
import { tokenSchema } from "@/lib/zod/schemas/token";
import { UserSchema } from "@/lib/zod/schemas/users";
import * as z from "zod/v4";
+import { sanitizeTimezone } from "../analytics/utils/sanitize-timezone";
import { parseDateSchema } from "../zod/schemas/utils";
import { API_LOGS_MAX_PAGE_SIZE } from "./constants";
@@ -105,6 +106,11 @@ export const getApiLogsQuerySchema = z
start: parseDateSchema.optional(),
end: parseDateSchema.optional(),
interval: z.enum(["24h", "7d", "30d", "60d", "90d"]).optional(),
+ timezone: z
+ .string()
+ .optional()
+ .overwrite((v) => (v === undefined ? undefined : sanitizeTimezone(v))),
+ exactRange: z.enum(["1", "true"]).optional(),
})
.extend(
getPaginationQuerySchema({
@@ -117,3 +123,28 @@ export const getApiLogsCountQuerySchema = getApiLogsQuerySchema
.extend({
groupBy: apiLogCountGroupBySchema.optional(),
});
+
+export const getApiLogsTimeseriesQuerySchema = getApiLogsCountQuerySchema.omit({
+ groupBy: true,
+});
+
+export const apiLogTimeseriesGranularitySchema = z.enum(["minute", "hour", "day"]);
+
+export const apiLogTimeseriesFilterSchemaTB = apiLogFilterSchemaTB
+ .omit({
+ limit: true,
+ offset: true,
+ })
+ .extend({
+ timezone: z.string().optional(),
+ granularity: apiLogTimeseriesGranularitySchema.optional(),
+ });
+
+export const apiLogTimeseriesRowSchema = z.object({
+ date: z.string(),
+ dateEnd: z.string(),
+ status2xx: z.number(),
+ status4xx: z.number(),
+ status5xx: z.number(),
+ statusOther: z.number(),
+});
diff --git a/apps/web/lib/swr/use-api-logs-count.ts b/apps/web/lib/swr/use-api-logs-count.ts
index 03eccc29fc..fc6dc2dc2d 100644
--- a/apps/web/lib/swr/use-api-logs-count.ts
+++ b/apps/web/lib/swr/use-api-logs-count.ts
@@ -43,6 +43,7 @@ export function useApiLogsCount({
{
workspaceId,
...(groupBy && { groupBy }),
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
},
{
include: [
@@ -55,6 +56,7 @@ export function useApiLogsCount({
"start",
"end",
"interval",
+ "exactRange",
],
},
);
diff --git a/apps/web/lib/swr/use-api-logs-timeseries.ts b/apps/web/lib/swr/use-api-logs-timeseries.ts
new file mode 100644
index 0000000000..1909333466
--- /dev/null
+++ b/apps/web/lib/swr/use-api-logs-timeseries.ts
@@ -0,0 +1,45 @@
+import type { ApiLogsTimeseriesRow } from "@/lib/types";
+import { useRouterStuff } from "@dub/ui";
+import { fetcher } from "@dub/utils";
+import useSWR from "swr";
+import useWorkspace from "./use-workspace";
+
+export function useApiLogsTimeseries() {
+ const { id: workspaceId } = useWorkspace();
+ const { getQueryString } = useRouterStuff();
+
+ const queryString = getQueryString(
+ {
+ workspaceId,
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
+ },
+ {
+ include: [
+ "method",
+ "statusCode",
+ "routePattern",
+ "tokenId",
+ "requestId",
+ "requestType",
+ "start",
+ "end",
+ "interval",
+ "exactRange",
+ ],
+ },
+ );
+
+ const { data, error, isLoading } = useSWR<ApiLogsTimeseriesRow[]>(
+ workspaceId ? `/api/logs/timeseries${queryString}` : null,
+ fetcher,
+ {
+ keepPreviousData: true,
+ },
+ );
+
+ return {
+ data,
+ error,
+ isLoading: isLoading || (!error && data === undefined),
+ };
+}
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index a81a6a161b..6caa1e933f 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -38,6 +38,8 @@ import {
apiLogCountRowSchemas,
apiLogEnrichedSchema,
apiLogSchemaTB,
+ apiLogTimeseriesGranularitySchema,
+ apiLogTimeseriesRowSchema,
requestTypeSchema,
} from "./api-logs/schemas";
import { PAID_TRAFFIC_PLATFORMS } from "./api/fraud/constants";
@@ -888,6 +890,12 @@ export type RequestType = z.infer<typeof requestTypeSchema>;
export type ApiLogTB = z.infer<typeof apiLogSchemaTB>;
+export type ApiLogsTimeseriesRow = z.infer<typeof apiLogTimeseriesRowSchema>;
+
+export type ApiLogsGranularity = z.infer<
+ typeof apiLogTimeseriesGranularitySchema
+>;
+
// Commission events
export type CommissionAnalyticsQuery = z.infer<
typeof commissionAnalyticsQuerySchema
diff --git a/apps/web/ui/logs/logs-histogram.tsx b/apps/web/ui/logs/logs-histogram.tsx
new file mode 100644
index 0000000000..b69c51533d
--- /dev/null
+++ b/apps/web/ui/logs/logs-histogram.tsx
@@ -0,0 +1,196 @@
+"use client";
+
+import { formatDateTooltip } from "@/lib/analytics/format-date-tooltip";
+import { useApiLogsTimeseries } from "@/lib/swr/use-api-logs-timeseries";
+import { LoadingSpinner, useRouterStuff } from "@dub/ui";
+import { Bars, TimeSeriesChart, XAxis, YAxis } from "@dub/ui/charts";
+import { cn, nFormatter } from "@dub/utils";
+import { useMemo } from "react";
+
+const SERIES = [
+ {
+ id: "status2xx",
+ label: "2xx",
+ colorClassName: "text-content-success",
+ },
+ {
+ id: "status4xx",
+ label: "4xx",
+ colorClassName: "text-content-warning",
+ },
+ {
+ id: "status5xx",
+ label: "5xx",
+ colorClassName: "text-content-error",
+ },
+ {
+ id: "statusOther",
+ label: "Other",
+ colorClassName: "text-content-subtle",
+ },
+] as const;
+
+type HistogramValues = {
+ status2xx: number;
+ status4xx: number;
+ status5xx: number;
+ statusOther: number;
+};
+
+type LogsHistogramDatum = {
+ date: Date;
+ end: Date;
+ values: HistogramValues;
+};
+
+export function LogsHistogram() {
+ const { data, error, isLoading } = useApiLogsTimeseries();
+ const { queryParams, searchParamsObj } = useRouterStuff();
+ const { start, end, interval, exactRange } = searchParamsObj;
+
+ const isMinuteRange = Boolean(
+ exactRange &&
+ start &&
+ end &&
+ new Date(end).getTime() - new Date(start).getTime() <= 2 * 60 * 60 * 1000,
+ );
+
+ const chartData = useMemo(
+ () =>
+ data?.map((row) => ({
+ date: new Date(row.date),
+ end: new Date(row.dateEnd),
+ values: {
+ status2xx: row.status2xx,
+ status4xx: row.status4xx,
+ status5xx: row.status5xx,
+ statusOther: row.statusOther,
+ } satisfies HistogramValues,
+ })) satisfies LogsHistogramDatum[] | undefined,
+ [data],
+ );
+
+ const showOther = useMemo(
+ () => Boolean(chartData?.some((d) => d.values.statusOther > 0)),
+ [chartData],
+ );
+
+ const series = useMemo(
+ () =>
+ SERIES.filter((s) => s.id !== "statusOther" || showOther).map((s) => ({
+ id: s.id,
+ valueAccessor: (d: LogsHistogramDatum) => d.values[s.id],
+ colorClassName: s.colorClassName,
+ isActive: true,
+ })),
+ [showOther],
+ );
+
+ const isAllZero = Boolean(
+ chartData?.every(
+ (d) =>
+ d.values.status2xx +
+ d.values.status4xx +
+ d.values.status5xx +
+ d.values.statusOther ===
+ 0,
+ ),
+ );
+
+ return (
+ <div className="relative h-40 w-full">
+ {chartData && chartData.length > 0 && !isAllZero ? (
+ <div
+ className={cn(
+ "size-full transition-opacity duration-200",
+ isLoading && "pointer-events-none opacity-60",
+ )}
+ >
+ <TimeSeriesChart
+ type="bar"
+ data={chartData}
+ series={series}
+ tooltipClassName="p-0 overflow-hidden"
+ onXValueClick={
+ isMinuteRange
+ ? undefined
+ : (datum) => {
+ const bucket = datum as LogsHistogramDatum;
+
+ // exactRange skips day-snapping so this hour/day bucket is not
+ // expanded to a full calendar day on the server.
+ queryParams({
+ del: ["interval", "page"],
+ set: {
+ start: bucket.date.toISOString(),
+ end: bucket.end.toISOString(),
+ exactRange: "1",
+ },
+ });
+ }
+ }
+ tooltipContent={(d) => {
+ const total =
+ d.values.status2xx +
+ d.values.status4xx +
+ d.values.status5xx +
+ d.values.statusOther;
+
+ const rows = SERIES.filter(
+ (s) => s.id !== "statusOther" || d.values.statusOther > 0,
+ );
+
+ return (
+ <>
+ <div className="flex items-center justify-between gap-4 px-4 py-3 text-xs">
+ <span className="text-content-emphasis font-semibold">
+ {formatDateTooltip(d.date, { interval, start, end })}
+ </span>
+ <span className="text-content-default font-medium">
+ {nFormatter(total, { full: true })}
+ </span>
+ </div>
+ <div className="border-border-subtle grid grid-cols-[minmax(0,1fr),min-content] gap-x-6 gap-y-2 border-t px-4 py-3 text-xs">
+ {rows.map((s) => (
+ <div key={s.id} className="contents">
+ <div className="flex items-center gap-2">
+ <div
+ className={cn(
+ "size-2 shrink-0 rounded-sm bg-current",
+ s.colorClassName,
+ )}
+ />
+ <span className="text-neutral-600">{s.label}</span>
+ </div>
+ <span className="text-right font-medium text-neutral-900">
+ {nFormatter(d.values[s.id], { full: true })}
+ </span>
+ </div>
+ ))}
+ </div>
+ </>
+ );
+ }}
+ >
+ <XAxis
+ highlightLast={false}
+ tickFormat={(d) => formatDateTooltip(d, { interval, start, end })}
+ />
+ <YAxis showGridLines tickFormat={nFormatter} />
+ <Bars />
+ </TimeSeriesChart>
+ </div>
+ ) : (
+ <div className="flex size-full items-center justify-center text-sm text-neutral-500">
+ {isLoading ? (
+ <LoadingSpinner />
+ ) : error ? (
+ <p>Failed to load</p>
+ ) : (
+ <p>No requests in this range</p>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/apps/web/ui/logs/logs-table.tsx b/apps/web/ui/logs/logs-table.tsx
index 0ac22b0ded..f55a0eb682 100644
--- a/apps/web/ui/logs/logs-table.tsx
+++ b/apps/web/ui/logs/logs-table.tsx
@@ -36,6 +36,7 @@ import { useRouter } from "next/navigation";
import { useMemo } from "react";
import useSWR from "swr";
import { getStatusCodeBadgeVariant } from "./log-utils";
+import { LogsHistogram } from "./logs-histogram";
import { useLogFilters } from "./use-log-filters";
const LOGS_TABLE_COLUMNS = {
@@ -308,6 +309,7 @@ export function LogsTable() {
setSelectedFilter={setSelectedFilter}
plan={plan || "free"}
/>
+ <LogsHistogram />
{logs?.length !== 0 ? (
<Table {...tableProps} table={table} />
) : (
diff --git a/apps/web/ui/logs/use-log-filters.ts b/apps/web/ui/logs/use-log-filters.ts
index 43cde3d5fd..652f109df7 100644
--- a/apps/web/ui/logs/use-log-filters.ts
+++ b/apps/web/ui/logs/use-log-filters.ts
@@ -174,6 +174,7 @@ export function useLogFilters() {
"start",
"end",
"interval",
+ "exactRange",
],
}),
[queryParams],
@@ -203,6 +204,12 @@ export function useLogFilters() {
params.interval = searchParamsObj.interval;
}
+ params.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
+
+ if (searchParamsObj.exactRange) {
+ params.exactRange = searchParamsObj.exactRange;
+ }
+
return new URLSearchParams(params).toString();
}, [
activeFilters,
@@ -211,6 +218,7 @@ export function useLogFilters() {
searchParamsObj.start,
searchParamsObj.end,
searchParamsObj.interval,
+ searchParamsObj.exactRange,
]);
return {
diff --git a/apps/web/ui/shared/simple-date-range-picker.tsx b/apps/web/ui/shared/simple-date-range-picker.tsx
index c03be07c23..c276a421dd 100644
--- a/apps/web/ui/shared/simple-date-range-picker.tsx
+++ b/apps/web/ui/shared/simple-date-range-picker.tsx
@@ -47,7 +47,7 @@ export default function SimpleDateRangePicker({
onChange={(range, preset) => {
if (preset) {
queryParams({
- del: ["start", "end"],
+ del: ["start", "end", "exactRange"],
set: {
interval: preset.id,
},
@@ -60,7 +60,7 @@ export default function SimpleDateRangePicker({
if (!range || !range.from || !range.to) return;
queryParams({
- del: "interval",
+ del: ["interval", "exactRange"],
set: {
start: range.from.toISOString(),
end: range.to.toISOString(),
diff --git a/packages/tinybird/pipes/get_api_logs_timeseries.pipe b/packages/tinybird/pipes/get_api_logs_timeseries.pipe
new file mode 100644
index 0000000000..b88e2c8fe1
--- /dev/null
+++ b/packages/tinybird/pipes/get_api_logs_timeseries.pipe
@@ -0,0 +1,141 @@
+DESCRIPTION >
+ API logs request-volume timeseries by status class
+
+
+NODE day_intervals
+SQL >
+
+%
+ WITH
+ toStartOfDay(
+ toDateTime64({{ DateTime64(start, '2024-06-01 00:00:00.000') }}, 3),
+ {{ String(timezone, 'UTC') }}
+ ) AS start,
+ toStartOfDay(
+ toDateTime64({{ DateTime64(end, '2024-06-07 00:00:00.000') }}, 3)
+ - toIntervalMillisecond(1),
+ {{ String(timezone, 'UTC') }}
+ ) AS end,
+ dateDiff('day', start, end) + 1 AS days_diff
+ SELECT
+ arrayJoin(
+ arrayMap(
+ x -> toDateTime64(start + toIntervalDay(x), 3, {{ String(timezone, 'UTC') }}),
+ range(0, days_diff)
+ )
+ ) as interval
+
+
+
+NODE hour_intervals
+SQL >
+
+%
+ WITH
+ toStartOfHour(
+ toDateTime64({{ DateTime64(start, '2024-06-01 00:00:00.000') }}, 3),
+ {{ String(timezone, 'UTC') }}
+ ) AS start,
+ toStartOfHour(
+ toDateTime64({{ DateTime64(end, '2024-06-07 00:00:00.000') }}, 3)
+ - toIntervalMillisecond(1),
+ {{ String(timezone, 'UTC') }}
+ ) AS end,
+ dateDiff('hour', start, end) + 1 AS hours_diff
+ SELECT
+ arrayJoin(
+ arrayMap(
+ x -> toDateTime64(start + toIntervalHour(x), 3, {{ String(timezone, 'UTC') }}),
+ range(0, hours_diff)
+ )
+ ) as interval
+
+
+
+NODE minute_intervals
+SQL >
+
+%
+ WITH
+ toStartOfMinute(
+ toDateTime64({{ DateTime64(start, '2024-06-01 00:00:00.000') }}, 3),
+ {{ String(timezone, 'UTC') }}
+ ) AS start,
+ toStartOfMinute(
+ toDateTime64({{ DateTime64(end, '2024-06-07 00:00:00.000') }}, 3)
+ - toIntervalMillisecond(1),
+ {{ String(timezone, 'UTC') }}
+ ) AS end,
+ dateDiff('minute', start, end) + 1 AS minutes_diff
+ SELECT
+ arrayJoin(
+ arrayMap(
+ x -> toDateTime64(start + toIntervalMinute(x), 3, {{ String(timezone, 'UTC') }}),
+ range(0, minutes_diff)
+ )
+ ) as interval
+
+
+
+NODE counts
+SQL >
+
+%
+ SELECT
+ {% if defined(granularity) and granularity == 'minute' %}
+ toDateTime64(toStartOfMinute(timestamp, {{ String(timezone, 'UTC') }}), 3)
+ {% elif defined(granularity) and granularity == 'hour' %}
+ toDateTime64(toStartOfHour(timestamp, {{ String(timezone, 'UTC') }}), 3)
+ {% else %}
+ toDateTime64(toStartOfDay(timestamp, {{ String(timezone, 'UTC') }}), 3)
+ {% end %} AS interval,
+ countIf(status_code >= 200 AND status_code < 300) AS status2xx,
+ countIf(status_code >= 400 AND status_code < 500) AS status4xx,
+ countIf(status_code >= 500) AS status5xx,
+ countIf(status_code < 200 OR (status_code >= 300 AND status_code < 400)) AS statusOther
+ FROM dub_api_logs
+ WHERE
+ workspace_id = {{ String(workspaceId) }}
+ {% if defined(start) and defined(end) %}
+ AND timestamp >= {{ DateTime(start, '2024-06-01 00:00:00') }}
+ AND timestamp < {{ DateTime(end, '2024-06-07 00:00:00') }}
+ {% end %}
+ {% if defined(routePattern) %} AND route_pattern = {{ String(routePattern) }} {% end %}
+ {% if defined(method) %} AND method = {{ String(method) }} {% end %}
+ {% if defined(statusCode) %} AND status_code = {{ UInt16(statusCode) }} {% end %}
+ {% if defined(tokenId) %} AND token_id = {{ String(tokenId) }} {% end %}
+ {% if defined(requestId) %} AND id = {{ String(requestId) }} {% end %}
+ {% if defined(requestType) %} AND request_type = {{ String(requestType) }} {% end %}
+ GROUP BY interval
+
+
+
+NODE endpoint
+SQL >
+
+%
+ SELECT
+ formatDateTime(interval, '%FT%T.000%z') as date,
+ formatDateTime(
+ {% if defined(granularity) and granularity == 'minute' %}
+ interval + toIntervalMinute(1)
+ {% elif defined(granularity) and granularity == 'hour' %}
+ interval + toIntervalHour(1)
+ {% else %}
+ interval + toIntervalDay(1)
+ {% end %},
+ '%FT%T.000%z'
+ ) as dateEnd,
+ coalesce(status2xx, 0) as status2xx,
+ coalesce(status4xx, 0) as status4xx,
+ coalesce(status5xx, 0) as status5xx,
+ coalesce(statusOther, 0) as statusOther
+ FROM
+ {% if defined(granularity) and granularity == 'minute' %} minute_intervals
+ {% elif defined(granularity) and granularity == 'hour' %} hour_intervals
+ {% else %} day_intervals
+ {% end %}
+ LEFT JOIN counts USING interval
+ ORDER BY interval
+
+TYPE ENDPOINT
diff --git a/packages/ui/src/charts/time-series-chart.tsx b/packages/ui/src/charts/time-series-chart.tsx
index 0f7feee109..5503c982f8 100644
--- a/packages/ui/src/charts/time-series-chart.tsx
+++ b/packages/ui/src/charts/time-series-chart.tsx
@@ -44,6 +44,7 @@ function TimeSeriesChartInner<T extends Datum>({
tooltipClassName = "",
defaultTooltipIndex = null,
onHoverDateChange,
+ onXValueClick,
margin: marginProp = {
top: 12,
right: 5,
@@ -223,6 +224,17 @@ function TimeSeriesChartInner<T extends Datum>({
onTouchMove={handleTooltip}
onMouseMove={handleTooltip}
onMouseLeave={hideTooltip}
+ onClick={() => {
+ if (tooltipData) {
+ onXValueClick?.(tooltipData);
+ }
+ }}
+ onTouchEnd={() => {
+ if (tooltipData) {
+ onXValueClick?.(tooltipData);
+ }
+ }}
+ className={onXValueClick ? "cursor-pointer" : undefined}
fill="transparent"
/>
</Group>
diff --git a/packages/ui/src/charts/types.ts b/packages/ui/src/charts/types.ts
index 91f53ff838..f025343fdf 100644
--- a/packages/ui/src/charts/types.ts
+++ b/packages/ui/src/charts/types.ts
@@ -40,6 +40,11 @@ type ChartOptionalProps<T extends Datum = any> = {
*/
onHoverDateChange?: (date: Date | null) => void;
+ /**
+ * Called when the user clicks the currently hovered x-value (date).
+ */
+ onXValueClick?: (datum: TimeSeriesDatum<T>) => void;
+
/**
* Absolute pixel values for margins around the chart area.
* Default values accommodate axis labels and other expected overflow.
@@ -64,7 +69,7 @@ export type ChartProps<T extends Datum = any> = ChartRequiredProps<T> &
ChartOptionalProps<T>;
export type ChartContext<T extends Datum = any> = Required<
- Omit<ChartProps<T>, "onHoverDateChange">
+ Omit<ChartProps<T>, "onHoverDateChange" | "onXValueClick">
> & {
width: number;
height: number;