Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(metrics): add a shared builder for metrics deep links (#89768)

Daniel Viscaa4154afafaa4
diff --git a/products/metrics/frontend/components/metricsViewerLogic.tsx b/products/metrics/frontend/components/metricsViewerLogic.tsx
index efb7044dd1aa..323a9f50eadf 100644
--- a/products/metrics/frontend/components/metricsViewerLogic.tsx
+++ b/products/metrics/frontend/components/metricsViewerLogic.tsx
@@ -44,6 +44,10 @@ import type { MetricsChartSeries } from './metricsSeries'
export type MetricAggregation = 'sum' | 'avg' | 'count' | 'p95' | 'rate' | 'increase'
export const METRIC_AGGREGATIONS: MetricAggregation[] = ['sum', 'avg', 'count', 'p95', 'rate', 'increase']
+/** Narrows an untrusted value (a URL param, a saved link) to an aggregation the backend accepts. */
+export const isMetricAggregation = (value: unknown): value is MetricAggregation =>
+ typeof value === 'string' && METRIC_AGGREGATIONS.includes(value as MetricAggregation)
+
export type MetricsViewerSeries = _MetricSeriesApi
// Display shape for the "vs baseline" anomaly badge (null = no anomaly / flat metric).
@@ -180,6 +184,7 @@ export interface metricsViewerLogicValues {
pickerServices: string[] // metricNamePickerLogic
currentTeamId: number | null // teamLogic
aggregation: MetricAggregation
+ aggregationExplicitlySet: boolean
anomalyBadge: MetricsAnomalyBadge | null
anomalyReport: _MetricAnomalyReportApi | null
anomalyReportLoading: boolean
@@ -441,6 +446,17 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
setRecommendedAggregation: (_, { aggregation }) => aggregation,
},
],
+ // Whether the current aggregation was picked deliberately (by the user, or named in a
+ // link) rather than recommended from the metric's type. A deliberate pick holds only
+ // until the next metric switch, matching what picking a metric already does.
+ aggregationExplicitlySet: [
+ false,
+ {
+ setAggregation: () => true,
+ setRecommendedAggregation: () => false,
+ setMetricName: () => false,
+ },
+ ],
dateFrom: [DEFAULT_DATE_FROM as string | null, { setDateFrom: (_, { dateFrom }) => dateFrom }],
dateTo: [null as string | null, { setDateTo: (_, { dateTo }) => dateTo }],
liveRefresh: [false, { setLiveRefresh: (_, { liveRefresh }) => liveRefresh }],
@@ -511,22 +527,24 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
actions.setRecommendedAggregation(recommended)
}
},
- // Recovers the type when the metric name was set before the picker's list
- // arrived (initial load); an already-latched type is left alone.
+ // Recovers the type, and the aggregation that follows from it, when the metric name was set
+ // before the picker's list arrived — the shape of a deep link on a cold load. An
+ // already-latched type and an explicitly chosen aggregation are both left alone.
loadItemsSuccess: () => {
- if (values.selectedMetricType !== null || !values.hasMetricName) {
+ if (!values.hasMetricName) {
return
}
const metricType = values.items.find((item) => item.name === values.metricName.trim())?.metric_type
const known = toKnownMetricType(metricType)
- if (known) {
+ if (known && values.selectedMetricType === null) {
actions.setSelectedMetricType(known)
}
- // The name was set before the list arrived, so the pick-time recommendation
- // never ran. Apply it late, but only over the untouched default — an
- // aggregation restored from the URL or picked by the user stays.
+ // Without this a link to a cumulative counter charts the raw running total rather than
+ // its rate: nothing recommended an aggregation while the list was still empty. The
+ // explicit-pick flag, not a compare against the default, is what holds a deliberate
+ // choice — picking the default value is still a choice.
const recommended = metricType ? RECOMMENDED_AGGREGATION_BY_TYPE[metricType] : undefined
- if (recommended && values.aggregation === DEFAULT_AGGREGATION && recommended !== values.aggregation) {
+ if (recommended && !values.aggregationExplicitlySet && recommended !== values.aggregation) {
actions.setRecommendedAggregation(recommended)
}
},
diff --git a/products/metrics/frontend/metricsLinks.test.ts b/products/metrics/frontend/metricsLinks.test.ts
new file mode 100644
index 000000000000..cd368bb113a9
--- /dev/null
+++ b/products/metrics/frontend/metricsLinks.test.ts
@@ -0,0 +1,71 @@
+import { combineUrl } from 'kea-router'
+
+import { FilterLogicalOperator, PropertyFilterType, PropertyOperator } from '~/types'
+
+import { metricUrl, metricsUrlForService } from './metricsLinks'
+
+describe('metricsLinks', () => {
+ const paramsOf = (url: string): Record<string, any> => combineUrl(url).searchParams
+
+ it('links to the bare metrics route when nothing is scoped', () => {
+ expect(metricUrl({})).toBe('/metrics')
+ })
+
+ // The scene opens on Overview. Any link that scopes the viewer has to say so, or it applies
+ // its filters to a tab the user never sees and looks broken.
+ it.each([
+ ['a metric name', { metricName: 'http_requests_total' }],
+ ['a filter group', { filterGroup: { type: FilterLogicalOperator.And, values: [] } }],
+ ['a group-by', { groupBy: ['service_name'] }],
+ ['a time window', { dateFrom: '-7d' }],
+ ])('opens the viewer tab for a link carrying %s', (_name, params) => {
+ expect(paramsOf(metricUrl(params)).activeTab).toBe('viewer')
+ })
+
+ // Param names are the contract with metricsSceneLogic's parser. Spelling one of them
+ // differently here drops it silently on restore, so pin the names, not just the values.
+ it('names the metric with the param the scene reads back', () => {
+ expect(paramsOf(metricUrl({ metricName: 'http_requests_total' }))).toMatchObject({
+ metricName: 'http_requests_total',
+ })
+ })
+
+ it('carries the metric type and aggregation so the link charts exactly one series shape', () => {
+ expect(
+ paramsOf(metricUrl({ metricName: 'http_requests_total', metricType: 'sum', aggregation: 'rate' }))
+ ).toMatchObject({ metricType: 'sum', aggregation: 'rate' })
+ })
+
+ it('carries the time window', () => {
+ expect(paramsOf(metricUrl({ dateFrom: '-7d', dateTo: '-1d' }))).toMatchObject({
+ dateFrom: '-7d',
+ dateTo: '-1d',
+ })
+ })
+
+ it('serializes the filter group as JSON the scene can parse back', () => {
+ const url = metricsUrlForService('checkout', {})
+ expect(JSON.parse(paramsOf(url).filterGroup)).toEqual({
+ type: FilterLogicalOperator.And,
+ values: [
+ {
+ type: FilterLogicalOperator.And,
+ values: [
+ {
+ type: PropertyFilterType.MetricAttribute,
+ key: 'service_name',
+ value: ['checkout'],
+ operator: PropertyOperator.Exact,
+ },
+ ],
+ },
+ ],
+ })
+ })
+
+ it('scopes a service link to the window the caller was looking at', () => {
+ expect(paramsOf(metricsUrlForService('checkout', { dateFrom: '-30m', dateTo: null }))).toMatchObject({
+ dateFrom: '-30m',
+ })
+ })
+})
diff --git a/products/metrics/frontend/metricsLinks.ts b/products/metrics/frontend/metricsLinks.ts
new file mode 100644
index 000000000000..e5d73d05be6e
--- /dev/null
+++ b/products/metrics/frontend/metricsLinks.ts
@@ -0,0 +1,84 @@
+import { combineUrl } from 'kea-router'
+
+import { urls } from 'scenes/urls'
+
+import { FilterLogicalOperator, PropertyFilterType, PropertyOperator, UniversalFiltersGroup } from '~/types'
+
+import { SERVICE_NAME_KEY } from './components/metricsViewerLogic'
+
+/**
+ * The metrics viewer's URL contract, in one place.
+ *
+ * Every product that links into a metric goes through here rather than hand-writing the search
+ * params, so the encoding stays in step with `metricsSceneLogic`'s parser. Mirrors
+ * `products/tracing/frontend/traceLinks.ts`.
+ */
+export interface MetricLinkParams {
+ metricName?: string
+ /** Pins the series shape when one name is reported as several OTel types. */
+ metricType?: string
+ aggregation?: string
+ dateFrom?: string | null
+ dateTo?: string | null
+ groupBy?: string[]
+ filterGroup?: UniversalFiltersGroup
+}
+
+/** Wraps label matchers in the two-level group the filter bar and the scene parser both expect. */
+export const metricsFilterGroup = (
+ filters: { key: string; value: string[]; operator?: PropertyOperator }[]
+): UniversalFiltersGroup => ({
+ type: FilterLogicalOperator.And,
+ values: [
+ {
+ type: FilterLogicalOperator.And,
+ values: filters.map(({ key, value, operator }) => ({
+ type: PropertyFilterType.MetricAttribute,
+ key,
+ value,
+ operator: operator ?? PropertyOperator.Exact,
+ })) as UniversalFiltersGroup['values'],
+ },
+ ],
+})
+
+export const metricUrl = (params: MetricLinkParams): string => {
+ const searchParams: Record<string, string | string[]> = {}
+
+ if (params.metricName) {
+ searchParams.metricName = params.metricName
+ }
+ if (params.metricType) {
+ searchParams.metricType = params.metricType
+ }
+ if (params.aggregation) {
+ searchParams.aggregation = params.aggregation
+ }
+ if (params.dateFrom) {
+ searchParams.dateFrom = params.dateFrom
+ }
+ if (params.dateTo) {
+ searchParams.dateTo = params.dateTo
+ }
+ if (params.groupBy?.length) {
+ searchParams.groupBy = params.groupBy
+ }
+ if (params.filterGroup) {
+ searchParams.filterGroup = JSON.stringify(params.filterGroup)
+ }
+
+ // The scene opens on Overview. Anything that scopes the viewer — a metric, a service filter, a
+ // group-by, a window — means to show the chart, so say so rather than filtering a hidden tab.
+ if (Object.keys(searchParams).length > 0) {
+ searchParams.activeTab = 'viewer'
+ }
+
+ return combineUrl(urls.metrics(), searchParams).url
+}
+
+/** "Show me this service's metrics", the pivot Logs and Tracing offer. */
+export const metricsUrlForService = (serviceName: string, params: Omit<MetricLinkParams, 'filterGroup'> = {}): string =>
+ metricUrl({
+ ...params,
+ filterGroup: metricsFilterGroup([{ key: SERVICE_NAME_KEY, value: [serviceName] }]),
+ })