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.

fix(metrics): load catalog sparklines on view (#99935)

Frank Hamand59d32a5dad18
diff --git a/products/metrics/frontend/components/MetricsCatalog.test.tsx b/products/metrics/frontend/components/MetricsCatalog.test.tsx
new file mode 100644
index 000000000000..108ec099d472
--- /dev/null
+++ b/products/metrics/frontend/components/MetricsCatalog.test.tsx
@@ -0,0 +1,96 @@
+import '@testing-library/jest-dom'
+
+import { act, cleanup, render, screen } from '@testing-library/react'
+import { Provider } from 'kea'
+
+import { initKeaTests } from '~/test/init'
+import { AccessControlLevel, AccessControlResourceType, AppContext } from '~/types'
+
+import { metricsNamesRetrieve, metricsValuesRetrieve } from '../generated/api'
+import { MetricsCatalog } from './MetricsCatalog'
+
+jest.mock('../generated/api', () => ({
+ ...jest.requireActual('../generated/api'),
+ metricsNamesRetrieve: jest.fn(),
+ metricsValuesRetrieve: jest.fn(),
+ metricsQueryCreate: jest.fn(),
+}))
+
+const CATALOG_ITEMS = [
+ { name: 'http.server.duration', metric_type: 'histogram' },
+ { name: 'queue.depth', metric_type: 'gauge' },
+]
+
+// Stands in for the browser's observer so a test can say which cards are in view.
+class FakeIntersectionObserver {
+ static observers: { callback: IntersectionObserverCallback; elements: Element[] }[] = []
+ private entry: { callback: IntersectionObserverCallback; elements: Element[] }
+
+ constructor(callback: IntersectionObserverCallback) {
+ this.entry = { callback, elements: [] }
+ FakeIntersectionObserver.observers.push(this.entry)
+ }
+
+ observe(element: Element): void {
+ this.entry.elements.push(element)
+ }
+
+ disconnect(): void {
+ this.entry.elements = []
+ }
+
+ unobserve(): void {}
+}
+
+const scrollIntoView = (testId: string): void => {
+ for (const observer of FakeIntersectionObserver.observers) {
+ for (const element of observer.elements) {
+ if (element.getAttribute('data-attr') === testId) {
+ observer.callback([{ isIntersecting: true, target: element } as IntersectionObserverEntry], null as any)
+ }
+ }
+ }
+}
+
+// The catalog only lists names, so each card asks for its own sparkline. That
+// request must wait until the card is near the viewport, or the lazy load is
+// no cheaper than the one query over every metric it replaced.
+describe('MetricsCatalog', () => {
+ beforeEach(() => {
+ window.POSTHOG_APP_CONTEXT = {
+ ...window.POSTHOG_APP_CONTEXT,
+ resource_access_control: {
+ ...window.POSTHOG_APP_CONTEXT?.resource_access_control,
+ [AccessControlResourceType.Metrics]: AccessControlLevel.Viewer,
+ },
+ } as AppContext
+ initKeaTests()
+ FakeIntersectionObserver.observers = []
+ window.IntersectionObserver = FakeIntersectionObserver as unknown as typeof IntersectionObserver
+ jest.mocked(metricsNamesRetrieve).mockResolvedValue({ results: CATALOG_ITEMS } as any)
+ jest.mocked(metricsValuesRetrieve).mockReset()
+ jest.mocked(metricsValuesRetrieve).mockResolvedValue({ results: [] } as any)
+ })
+
+ afterEach(() => cleanup())
+
+ it('requests a card sparkline only once that card scrolls into view', async () => {
+ render(
+ <Provider>
+ <MetricsCatalog />
+ </Provider>
+ )
+ expect(await screen.findByText('queue.depth')).toBeInTheDocument()
+ expect(jest.mocked(metricsValuesRetrieve)).not.toHaveBeenCalled()
+
+ await act(async () => {
+ scrollIntoView('metrics-catalog-card-queue.depth')
+ })
+
+ expect(jest.mocked(metricsValuesRetrieve)).toHaveBeenCalledTimes(1)
+ expect(jest.mocked(metricsValuesRetrieve)).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({ value: 'queue.depth', limit: 1 })
+ )
+ })
+})
diff --git a/products/metrics/frontend/components/MetricsCatalog.tsx b/products/metrics/frontend/components/MetricsCatalog.tsx
index 488bab9fb903..327460a4e7d0 100644
--- a/products/metrics/frontend/components/MetricsCatalog.tsx
+++ b/products/metrics/frontend/components/MetricsCatalog.tsx
@@ -1,7 +1,8 @@
import { useActions, useMountedLogic, useValues } from 'kea'
+import { useEffect, useRef } from 'react'
import { IconSearch } from '@posthog/icons'
-import { LemonInput, LemonSkeleton, LemonTag } from '@posthog/lemon-ui'
+import { LemonButton, LemonInput, LemonSkeleton, LemonTag } from '@posthog/lemon-ui'
import { Sparkline } from 'lib/components/Sparkline'
import { TZLabel } from 'lib/components/TZLabel'
@@ -12,20 +13,20 @@ import { MetricCatalogItem, metricsCatalogLogic } from './metricsCatalogLogic'
// A metric's OTel type says how to read it before it is opened. The one-liner is
// the catalog's main teaching surface: it turns a bare name into a sentence the
// reader can scan, and it matches the recommended aggregation the viewer applies.
-const describeMetric = (item: MetricCatalogItem): string => {
- const unit = item.unit ? ` (${item.unit})` : ''
+const describeMetric = (item: MetricCatalogItem, unit?: string): string => {
+ const unitLabel = unit ? ` (${unit})` : ''
switch (item.metric_type) {
case 'gauge':
- return `A current level, read at each scrape${unit}.`
+ return `A current level, read at each scrape${unitLabel}.`
case 'sum':
- return `A running total that grows over time${unit}.`
+ return `A running total that grows over time${unitLabel}.`
case 'histogram':
case 'exponential_histogram':
- return `A distribution of values; chart a percentile${unit}.`
+ return `A distribution of values; chart a percentile${unitLabel}.`
case 'summary':
- return `A distribution with precomputed percentiles${unit}.`
+ return `A distribution with precomputed percentiles${unitLabel}.`
default:
- return `A metric${unit}.`
+ return `A metric${unitLabel}.`
}
}
@@ -33,36 +34,82 @@ const typeTagLabel = (metricType: string): string =>
metricType === 'sum' ? 'counter' : metricType === 'exponential_histogram' ? 'histogram' : metricType || 'unknown'
const CatalogCard = ({ item }: { item: MetricCatalogItem }): JSX.Element => {
- const { openMetric } = useActions(metricsCatalogLogic)
+ const { openMetric, loadSparkline, retrySparkline } = useActions(metricsCatalogLogic)
+ const { catalogItemDetails, catalogItemDetailsFailed, catalogItemDetailsLoading } = useValues(metricsCatalogLogic)
+ const cardRef = useRef<HTMLButtonElement>(null)
+ const detail = catalogItemDetails[item.name]
+ const failed = catalogItemDetailsFailed[item.name]
+ const loading = catalogItemDetailsLoading[item.name]
+
+ useEffect(() => {
+ const card = cardRef.current
+ if (!card || detail || failed || loading) {
+ return
+ }
+ // Browsers without IntersectionObserver still show a useful catalog;
+ // they fall back to loading the card when it mounts.
+ if (!window.IntersectionObserver) {
+ loadSparkline(item)
+ return
+ }
+ const observer = new IntersectionObserver(
+ ([entry]) => {
+ if (entry?.isIntersecting) {
+ loadSparkline(item)
+ observer.disconnect()
+ }
+ },
+ // Request just before the card enters view so the chart is normally
+ // ready by the time a person reaches it.
+ { rootMargin: '300px' }
+ )
+ observer.observe(card)
+ return () => observer.disconnect()
+ }, [detail, item, loadSparkline, loading])
+
return (
- <button
- type="button"
- onClick={() => openMetric(item)}
- data-attr={`metrics-catalog-card-${item.name}`}
- className="flex flex-col gap-2 border rounded p-3 text-left hover:border-accent-primary focus:border-accent-primary transition-colors bg-bg-3000"
- >
- <div className="flex items-start justify-between gap-2 min-w-0">
- <span className="font-mono text-sm truncate" title={item.name}>
- {item.name}
- </span>
- <LemonTag type="muted" size="small">
- {typeTagLabel(item.metric_type)}
- </LemonTag>
- </div>
- <div className="h-10 w-full">
- {item.sparkline && item.sparkline.length > 1 ? (
- <Sparkline data={item.sparkline} type="line" />
- ) : (
- <div className="h-full flex items-center text-xs text-muted">No recent data to draw</div>
+ <div className="flex flex-col border rounded hover:border-accent-primary focus-within:border-accent-primary transition-colors bg-bg-3000">
+ <button
+ ref={cardRef}
+ type="button"
+ onClick={() => openMetric(item)}
+ data-attr={`metrics-catalog-card-${item.name}`}
+ className="flex flex-col gap-2 p-3 text-left"
+ >
+ <div className="flex items-start justify-between gap-2 min-w-0">
+ <span className="font-mono text-sm truncate" title={item.name}>
+ {item.name}
+ </span>
+ <LemonTag type="muted" size="small">
+ {typeTagLabel(item.metric_type)}
+ </LemonTag>
+ </div>
+ <div className="h-10 w-full">
+ {detail?.sparkline && detail.sparkline.length > 1 ? (
+ <Sparkline data={detail.sparkline} type="line" />
+ ) : loading ? (
+ <LemonSkeleton className="h-full" />
+ ) : failed ? (
+ <div className="h-full flex items-center text-xs text-muted">Could not load recent data</div>
+ ) : (
+ <div className="h-full flex items-center text-xs text-muted">No recent data to draw</div>
+ )}
+ </div>
+ <p className="text-xs text-secondary mb-0">{describeMetric(item, detail?.unit)}</p>
+ {detail?.last_seen && (
+ <span className="text-xs text-muted">
+ Last seen <TZLabel time={detail.last_seen} />
+ </span>
)}
- </div>
- <p className="text-xs text-secondary mb-0">{describeMetric(item)}</p>
- {item.last_seen && (
- <span className="text-xs text-muted">
- Last seen <TZLabel time={item.last_seen} />
- </span>
+ </button>
+ {failed && (
+ <div className="px-3 pb-3">
+ <LemonButton size="xsmall" type="secondary" onClick={() => retrySparkline(item)}>
+ Retry
+ </LemonButton>
+ </div>
)}
- </button>
+ </div>
)
}
diff --git a/products/metrics/frontend/components/metricsCatalogLogic.test.ts b/products/metrics/frontend/components/metricsCatalogLogic.test.ts
index a9b10136ed2d..16fa7dbd3218 100644
--- a/products/metrics/frontend/components/metricsCatalogLogic.test.ts
+++ b/products/metrics/frontend/components/metricsCatalogLogic.test.ts
@@ -20,20 +20,21 @@ const CATALOG_ITEMS = [
{
name: 'http.server.duration',
metric_type: 'histogram',
- unit: 'ms',
- last_seen: '2026-09-03T10:00:00+00:00',
- sparkline: [1, 2, 3],
},
{
name: 'queue.depth',
metric_type: 'gauge',
- unit: '',
- last_seen: '2026-09-03T10:00:00+00:00',
- sparkline: [3, 2, 1],
},
- { name: 'jobs.processed', metric_type: 'sum', unit: '', last_seen: '2026-09-03T09:00:00+00:00', sparkline: [0, 1] },
+ { name: 'jobs.processed', metric_type: 'sum' },
]
+const SPARKLINE_ITEM = {
+ ...CATALOG_ITEMS[0],
+ unit: 'ms',
+ last_seen: '2026-09-03T10:00:00+00:00',
+ sparkline: [1, 2, 3],
+}
+
describe('metricsCatalogLogic', () => {
let logic: ReturnType<typeof metricsCatalogLogic.build>
@@ -47,7 +48,7 @@ describe('metricsCatalogLogic', () => {
} as AppContext
initKeaTests()
jest.mocked(metricsValuesRetrieve).mockReset()
- jest.mocked(metricsValuesRetrieve).mockResolvedValue({ results: CATALOG_ITEMS } as any)
+ jest.mocked(metricsValuesRetrieve).mockResolvedValue({ results: [SPARKLINE_ITEM] } as any)
jest.mocked(metricsNamesRetrieve).mockResolvedValue({ results: CATALOG_ITEMS } as any)
})
@@ -55,7 +56,7 @@ describe('metricsCatalogLogic', () => {
logic?.unmount()
})
- it('loads catalog items from the metric names endpoint', async () => {
+ it('loads catalog names without requesting sparklines', async () => {
logic = metricsCatalogLogic()
logic.mount()
@@ -64,6 +65,91 @@ describe('metricsCatalogLogic', () => {
})
})
+ it('loads a card sparkline only when that card enters view', async () => {
+ logic = metricsCatalogLogic()
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadCatalogSuccess'])
+
+ await expectLogic(logic, () => {
+ logic.actions.loadSparkline(CATALOG_ITEMS[0])
+ }).toDispatchActions(['loadSparklineSuccess'])
+
+ expect(jest.mocked(metricsValuesRetrieve)).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({ value: 'http.server.duration', limit: 1 })
+ )
+ expect(logic.values.catalogItemDetails['http.server.duration']).toEqual(SPARKLINE_ITEM)
+ })
+
+ it('retries a sparkline after a transient failure', async () => {
+ jest.mocked(metricsValuesRetrieve)
+ .mockRejectedValueOnce(new Error('temporary error'))
+ .mockResolvedValueOnce({ results: [SPARKLINE_ITEM] } as any)
+ logic = metricsCatalogLogic()
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadCatalogSuccess'])
+
+ await expectLogic(logic, () => {
+ logic.actions.loadSparkline(CATALOG_ITEMS[0])
+ }).toDispatchActions(['loadSparklineFailure'])
+ expect(logic.values.catalogItemDetailsFailed['http.server.duration']).toBe(true)
+
+ await expectLogic(logic, () => {
+ logic.actions.retrySparkline(CATALOG_ITEMS[0])
+ }).toDispatchActions(['loadSparklineSuccess'])
+
+ expect(logic.values.catalogItemDetailsFailed['http.server.duration']).toBe(false)
+ expect(jest.mocked(metricsValuesRetrieve)).toHaveBeenCalledTimes(2)
+ })
+
+ it('keeps every in-flight card when more cards scroll into view', async () => {
+ // Several cards cross the viewport at once. Each one is its own request,
+ // so a later card must not cancel or fail an earlier one still in flight.
+ jest.mocked(metricsValuesRetrieve).mockImplementation(
+ (_teamId: any, params: any) =>
+ new Promise((resolve) =>
+ setTimeout(() => resolve({ results: [{ ...SPARKLINE_ITEM, name: params.value }] } as any), 0)
+ ) as any
+ )
+ logic = metricsCatalogLogic()
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadCatalogSuccess'])
+
+ await expectLogic(logic, () => {
+ logic.actions.loadSparkline(CATALOG_ITEMS[0])
+ logic.actions.loadSparkline(CATALOG_ITEMS[1])
+ }).toFinishAllListeners()
+
+ expect(logic.values.catalogItemDetailsFailed).toEqual({})
+ expect(Object.keys(logic.values.catalogItemDetails).sort()).toEqual([
+ CATALOG_ITEMS[0].name,
+ CATALOG_ITEMS[1].name,
+ ])
+ })
+
+ it('a rejection from the old service scope does not fail the same card in the new scope', async () => {
+ // A card in scope A fails after the person has entered scope B. The name
+ // can exist in both, and the new card must still get to ask for itself.
+ let rejectFirst: (error: Error) => void = () => {}
+ jest.mocked(metricsValuesRetrieve).mockImplementationOnce(
+ () => new Promise((_resolve, reject) => (rejectFirst = reject)) as any
+ )
+ metricNamePickerLogic.mount()
+ logic = metricsCatalogLogic()
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadCatalogSuccess'])
+
+ logic.actions.loadSparkline(CATALOG_ITEMS[0])
+ metricNamePickerLogic.actions.setServices(['api'])
+ await expectLogic(logic).toDispatchActions(['loadCatalogSuccess'])
+
+ rejectFirst(new Error('boom'))
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.catalogItemDetailsFailed).toEqual({})
+ expect(logic.values.catalogItemDetailsLoading[CATALOG_ITEMS[0].name]).toBeUndefined()
+ })
+
it('narrows the visible cards by a search substring', async () => {
logic = metricsCatalogLogic()
logic.mount()
@@ -86,7 +172,7 @@ describe('metricsCatalogLogic', () => {
await expectLogic(logic).toDispatchActions(['loadCatalogSuccess'])
- expect(jest.mocked(metricsValuesRetrieve)).toHaveBeenCalledWith(
+ expect(jest.mocked(metricsNamesRetrieve)).toHaveBeenCalledWith(
expect.any(String),
expect.objectContaining({ service: 'api' })
)
@@ -98,7 +184,7 @@ describe('metricsCatalogLogic', () => {
await expectLogic(logic).toDispatchActions(['loadCatalogSuccess'])
- const call = jest.mocked(metricsValuesRetrieve).mock.calls[0][1]
+ const call = jest.mocked(metricsNamesRetrieve).mock.calls[0][1]
expect(call).not.toHaveProperty('service')
})
diff --git a/products/metrics/frontend/components/metricsCatalogLogic.tsx b/products/metrics/frontend/components/metricsCatalogLogic.tsx
index 84130f42ecd8..544d7f750099 100644
--- a/products/metrics/frontend/components/metricsCatalogLogic.tsx
+++ b/products/metrics/frontend/components/metricsCatalogLogic.tsx
@@ -3,20 +3,23 @@ import { loaders } from 'kea-loaders'
import { teamLogic } from 'scenes/teamLogic'
-import { metricsValuesRetrieve } from '../generated/api'
-import type { _MetricNameApi } from '../generated/api.schemas'
+import { metricsNamesRetrieve, metricsValuesRetrieve } from '../generated/api'
+import type { _MetricNameApi, _MetricPickerNameApi } from '../generated/api.schemas'
import { canViewMetrics } from '../metricsAccess'
import { metricsSceneLogic } from '../metricsSceneLogic'
import { metricNamePickerLogic } from './metricNamePickerLogic'
import { metricsViewerLogic, toKnownMetricType } from './metricsViewerLogic'
/** One catalog card: a metric name plus what makes it scannable before opening it. */
-export type MetricCatalogItem = _MetricNameApi
+export type MetricCatalogItem = _MetricPickerNameApi
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface metricsCatalogLogicValues {
pickerServices: string[] // metricNamePickerLogic
currentTeamId: number | null // teamLogic
+ catalogItemDetails: Record<string, _MetricNameApi>
+ catalogItemDetailsFailed: Record<string, boolean>
+ catalogItemDetailsLoading: Record<string, boolean>
catalogItems: MetricCatalogItem[]
catalogItemsLoading: boolean
search: string
@@ -46,24 +49,43 @@ export interface metricsCatalogLogicActions {
errorObject?: any
}
loadCatalogSuccess: (
- catalogItems: _MetricNameApi[],
+ catalogItems: _MetricPickerNameApi[],
payload?: any
) => {
- catalogItems: _MetricNameApi[]
+ catalogItems: _MetricPickerNameApi[]
payload?: any
}
- openMetric: (item: MetricCatalogItem) => {
+ loadSparkline: (item: MetricCatalogItem) => {
+ item: _MetricPickerNameApi
+ }
+ loadSparklineFailure: (name: string) => {
+ name: string
+ }
+ loadSparklineSuccess: (
+ name: string,
item: _MetricNameApi
+ ) => {
+ item: _MetricNameApi
+ name: string
+ }
+ openMetric: (item: MetricCatalogItem) => {
+ item: _MetricPickerNameApi
+ }
+ retrySparkline: (item: MetricCatalogItem) => {
+ item: _MetricPickerNameApi
}
setSearch: (search: string) => {
search: string
}
+ setSparklineLoading: (name: string) => {
+ name: string
+ }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface metricsCatalogLogicMeta {
__keaTypeGenInternalSelectorTypes: {
- visibleItems: (catalogItems: _MetricNameApi[], search: string) => MetricCatalogItem[]
+ visibleItems: (catalogItems: _MetricPickerNameApi[], search: string) => MetricCatalogItem[]
}
}
@@ -89,11 +111,43 @@ export const metricsCatalogLogic = kea<metricsCatalogLogicType>([
})),
actions({
setSearch: (search: string) => ({ search }),
+ loadSparkline: (item: MetricCatalogItem) => ({ item }),
+ setSparklineLoading: (name: string) => ({ name }),
+ loadSparklineSuccess: (name: string, item: _MetricNameApi) => ({ name, item }),
+ loadSparklineFailure: (name: string) => ({ name }),
+ retrySparkline: (item: MetricCatalogItem) => ({ item }),
// A card click hands the metric to the viewer and switches to it.
openMetric: (item: MetricCatalogItem) => ({ item }),
}),
reducers({
search: ['' as string, { setSearch: (_, { search }) => search }],
+ // Details depend on the service scope. Drop the old scope as soon as a
+ // replacement name list starts loading, so a late card can never show a
+ // sparkline from the service the person just left.
+ catalogItemDetails: [
+ {} as Record<string, _MetricNameApi>,
+ {
+ loadCatalog: () => ({}),
+ loadSparklineSuccess: (state, { name, item }) => ({ ...state, [name]: item }),
+ },
+ ],
+ catalogItemDetailsFailed: [
+ {} as Record<string, boolean>,
+ {
+ loadCatalog: () => ({}),
+ loadSparklineFailure: (state, { name }) => ({ ...state, [name]: true }),
+ retrySparkline: (state, { item }) => ({ ...state, [item.name]: false }),
+ },
+ ],
+ catalogItemDetailsLoading: [
+ {} as Record<string, boolean>,
+ {
+ loadCatalog: () => ({}),
+ setSparklineLoading: (state, { name }) => ({ ...state, [name]: true }),
+ loadSparklineSuccess: (state, { name }) => ({ ...state, [name]: false }),
+ loadSparklineFailure: (state, { name }) => ({ ...state, [name]: false }),
+ },
+ ],
}),
loaders(({ values }) => ({
catalogItems: [
@@ -106,8 +160,9 @@ export const metricsCatalogLogic = kea<metricsCatalogLogicType>([
// The catalog is scoped to whatever services the picker is
// currently pinned to (a service entered from the overview, or
// the viewer's own scope), so the cards match what the user
- // clicked into. The endpoint returns the sparkline and unit.
- const response = await metricsValuesRetrieve(String(values.currentTeamId), {
+ // clicked into. It returns only names; visible cards load their
+ // own sparkline later instead of one query sampling every metric.
+ const response = await metricsNamesRetrieve(String(values.currentTeamId), {
limit: 500,
...(values.pickerServices.length ? { service: values.pickerServices.join(',') } : {}),
})
@@ -128,12 +183,53 @@ export const metricsCatalogLogic = kea<metricsCatalogLogicType>([
},
],
}),
- listeners(({ actions }) => ({
+ listeners(({ actions, values }) => ({
// Re-scope: entering a service from the overview or a viewer filter change
// re-reads the cards for that scope.
setServices: () => {
actions.loadCatalog()
},
+ // No kea breakpoint here: its counter is per action type, not per card, so
+ // the next card scrolling into view would abort every request still in
+ // flight and leave those cards on an error they never actually hit.
+ loadSparkline: async ({ item }) => {
+ // An IntersectionObserver can notify more than once while a card is
+ // near the viewport. Keep one request per name and retry only after a
+ // failed request or after the catalog scope changes.
+ if (values.catalogItemDetails[item.name] || values.catalogItemDetailsLoading[item.name]) {
+ return
+ }
+ const teamId = values.currentTeamId
+ const services = values.pickerServices
+ // The service scope can change while the query runs. The name list was
+ // reset for that new scope, so neither a late result nor a late
+ // rejection may land on a card that now belongs to another scope.
+ const stillInScope = (): boolean =>
+ teamId === values.currentTeamId && services.join('\u0000') === values.pickerServices.join('\u0000')
+ actions.setSparklineLoading(item.name)
+ try {
+ const response = await metricsValuesRetrieve(String(teamId), {
+ value: item.name,
+ limit: 1,
+ ...(services.length ? { service: services.join(',') } : {}),
+ })
+ if (!stillInScope()) {
+ return
+ }
+ // A name can disappear between the first request and this lazy
+ // lookup. Treat that the same as a metric with no recent points,
+ // which stops an observer retry loop for a stale card.
+ actions.loadSparklineSuccess(item.name, response.results[0] ?? { ...item, sparkline: [] })
+ } catch {
+ if (!stillInScope()) {
+ return
+ }
+ actions.loadSparklineFailure(item.name)
+ }
+ },
+ retrySparkline: ({ item }) => {
+ actions.loadSparkline(item)
+ },
openMetric: ({ item }) => {
// Set the type first so it latches: a metric name reused across OTel
// types (a counter and a gauge) charts only the picked type, and the
diff --git a/products/metrics/frontend/components/metricsHandoff.test.ts b/products/metrics/frontend/components/metricsHandoff.test.ts
index ee1057ba2e12..72222257fccc 100644
--- a/products/metrics/frontend/components/metricsHandoff.test.ts
+++ b/products/metrics/frontend/components/metricsHandoff.test.ts
@@ -3,12 +3,13 @@ import { expectLogic } from 'kea-test-utils'
import { initKeaTests } from '~/test/init'
import { AccessControlLevel, AccessControlResourceType, AppContext } from '~/types'
-import { metricsValuesRetrieve } from '../generated/api'
+import { metricsNamesRetrieve, metricsValuesRetrieve } from '../generated/api'
import { metricsCatalogLogic } from './metricsCatalogLogic'
import { metricsFundamentalsLogic } from './metricsFundamentalsLogic'
jest.mock('../generated/api', () => ({
...jest.requireActual('../generated/api'),
+ metricsNamesRetrieve: jest.fn(),
metricsValuesRetrieve: jest.fn(),
metricsQueryCreate: jest.fn(),
metricsExplainCreate: jest.fn(),
@@ -28,6 +29,7 @@ describe('metrics cross-tab handoffs', () => {
} as unknown as AppContext
initKeaTests()
jest.mocked(metricsValuesRetrieve).mockResolvedValue({ results: [] } as any)
+ jest.mocked(metricsNamesRetrieve).mockResolvedValue({ results: [] } as any)
})
it('explainMetric state survives the viewer tab unmounting', async () => {
@@ -54,8 +56,8 @@ describe('metrics cross-tab handoffs', () => {
})
it('a loaded catalog survives the explore tab unmounting', async () => {
- const items = [{ name: 'jobs.processed', metric_type: 'sum', unit: '', last_seen: null, sparkline: [1] }]
- jest.mocked(metricsValuesRetrieve).mockResolvedValue({ results: items } as any)
+ const items = [{ name: 'jobs.processed', metric_type: 'sum' }]
+ jest.mocked(metricsNamesRetrieve).mockResolvedValue({ results: items } as any)
const sceneHold = metricsCatalogLogic()
sceneHold.mount()