mirror of
https://github.com/supabase/supabase.git
synced 2026-12-04 23:49:03 +00:00
feat(studio): add Warehouse report date controls (#53494)
## Problem The Warehouse report only shows the last hour. ## Solution Add date selection and refresh using the shared report controls. Respect the organisation’s log retention limits and the metrics API’s 30-day maximum. | After | | --- | | <img width="1688" height="1050" alt="CleanShot 2026-11-18 at 11 35 24@2x" src="https://github.com/user-attachments/assets/88267bf8-1054-480b-ac26-c0c2b58386bc" /> | | _The new controls._ | | <img width="2420" height="1028" alt="CleanShot 2026-11-18 at 11 47 52@2x" src="https://github.com/user-attachments/assets/383c06a0-5470-4748-b9a6-fe80647a1399" /> | | _The standard retention upgrade prompt follow tapping either of these on a Pro plan._ | ## Review instructions 1. Open the [Studio staging preview](https://studio-staging-git-dnywh-warehouse-metrics-range-supabase.vercel.app) and select a staging project with Warehouse access. 2. Open **Observability > Warehouse**, or `/project/<ref>/observability/warehouse` ([example](https://studio-staging-git-dnywh-warehouse-metrics-range-supabase.vercel.app/dashboard/project/yirnfrgkxmnqgexikhfc/observability/warehouse)). Change Last 60 minutes to Last 24 hours and check that the chart or no-data state reflects the selected period. 3. Refresh the report. Check that the selected period stays selected. 4. On a paid staging organisation, select a period beyond its log retention (for example, Last 14 days with 7-day retention). Check that the retention upgrade prompt appears and the current period stays selected. --------- Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
This commit is contained in:
1 parent
48c90094d9
commit
8fcd5e7f65
18 files changed
+669
-88
No files matched your search
+117
@@ -0,0 +1,117 @@
|
||||
import dayjs from 'dayjs'
|
||||
import { describe, expect, test } from 'vitest'
|
||||
|
||||
import { getWarehouseMetricsInterval, resolveWarehouseMetricsRange } from './WarehouseMetrics.range'
|
||||
import { REPORTS_DATEPICKER_HELPERS } from '@/components/interfaces/Reports/Reports.constants'
|
||||
|
||||
describe('getWarehouseMetricsInterval', () => {
|
||||
const interval = (hours: number) => {
|
||||
const start = '2026-01-01T00:00:00.000Z'
|
||||
return getWarehouseMetricsInterval(start, dayjs(start).add(hours, 'hour').toISOString())
|
||||
}
|
||||
|
||||
test.each([
|
||||
[0.5, '1m'],
|
||||
[3, '1m'],
|
||||
[3.01, '5m'],
|
||||
[24, '5m'],
|
||||
[24.5, '30m'],
|
||||
[120, '30m'],
|
||||
[121, '1h'],
|
||||
[24 * 30, '1h'],
|
||||
])('%s hours uses %s', (hours, expected) => {
|
||||
expect(interval(hours)).toBe(expected)
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveWarehouseMetricsRange', () => {
|
||||
const now = dayjs('2026-11-05T12:34:56.789Z')
|
||||
const flooredNow = '2026-11-05T12:34:00.000Z'
|
||||
const earliest = '2026-10-06T12:39:00.000Z'
|
||||
|
||||
test('leaves in-range values untouched', () => {
|
||||
const start = '2026-11-05T11:34:56.789Z'
|
||||
const end = '2026-11-05T12:30:10.000Z'
|
||||
expect(resolveWarehouseMetricsRange({ start, end, now })).toEqual({
|
||||
status: 'ok',
|
||||
startDate: start,
|
||||
endDate: end,
|
||||
interval: '1m',
|
||||
isClamped: false,
|
||||
})
|
||||
})
|
||||
|
||||
test('normalizes offsets to ISO without marking the range as clamped', () => {
|
||||
const result = resolveWarehouseMetricsRange({
|
||||
start: '2026-11-05T11:00:00+01:00',
|
||||
end: '2026-11-05T11:30:00+01:00',
|
||||
now,
|
||||
})
|
||||
expect(result).toMatchObject({
|
||||
status: 'ok',
|
||||
startDate: '2026-11-05T10:00:00.000Z',
|
||||
endDate: '2026-11-05T10:30:00.000Z',
|
||||
isClamped: false,
|
||||
})
|
||||
})
|
||||
|
||||
test('clamps a start older than 30 days and keeps the end', () => {
|
||||
const end = '2026-11-05T12:00:00.000Z'
|
||||
expect(resolveWarehouseMetricsRange({ start: '2026-09-01T00:00:00Z', end, now })).toEqual({
|
||||
status: 'ok',
|
||||
startDate: earliest,
|
||||
endDate: end,
|
||||
interval: '1h',
|
||||
isClamped: true,
|
||||
})
|
||||
})
|
||||
|
||||
test('clamps an end in the future to the current minute', () => {
|
||||
const start = '2026-11-05T11:34:00.000Z'
|
||||
expect(resolveWarehouseMetricsRange({ start, end: '2026-11-05T13:00:00Z', now })).toEqual({
|
||||
status: 'ok',
|
||||
startDate: start,
|
||||
endDate: flooredNow,
|
||||
interval: '1m',
|
||||
isClamped: true,
|
||||
})
|
||||
})
|
||||
|
||||
test('is out of range when the whole range is older than the window', () => {
|
||||
expect(
|
||||
resolveWarehouseMetricsRange({
|
||||
start: '2026-08-01T00:00:00Z',
|
||||
end: '2026-09-01T00:00:00Z',
|
||||
now,
|
||||
})
|
||||
).toEqual({ status: 'out_of_range' })
|
||||
})
|
||||
|
||||
test('is out of range when the whole range is in the future', () => {
|
||||
expect(
|
||||
resolveWarehouseMetricsRange({
|
||||
start: '2026-11-06T00:00:00Z',
|
||||
end: '2026-11-07T00:00:00Z',
|
||||
now,
|
||||
})
|
||||
).toEqual({ status: 'out_of_range' })
|
||||
})
|
||||
|
||||
test('is out of range when end is not after start', () => {
|
||||
const same = '2026-11-05T10:00:00.000Z'
|
||||
expect(resolveWarehouseMetricsRange({ start: same, end: same, now })).toEqual({
|
||||
status: 'out_of_range',
|
||||
})
|
||||
})
|
||||
|
||||
test.each(REPORTS_DATEPICKER_HELPERS.map((helper) => [helper.text, helper] as const))(
|
||||
'the "%s" date picker option resolves without clamping',
|
||||
(_text, helper) => {
|
||||
const result = resolveWarehouseMetricsRange({
|
||||
start: helper.calcFrom(),
|
||||
end: helper.calcTo(),
|
||||
})
|
||||
expect(result).toMatchObject({ status: 'ok', isClamped: false })
|
||||
}
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,56 @@
|
||||
import dayjs, { type Dayjs } from 'dayjs'
|
||||
|
||||
const WAREHOUSE_METRICS_MAX_RANGE_DAYS = 30
|
||||
|
||||
/** Keeps every series under ~720 points so a batch with many labeled series stays under the API's response cap. */
|
||||
export const getWarehouseMetricsInterval = (
|
||||
startIso: string,
|
||||
endIso: string
|
||||
): '1m' | '5m' | '30m' | '1h' => {
|
||||
const hours = dayjs(endIso).diff(dayjs(startIso), 'hour', true)
|
||||
if (hours <= 3) return '1m'
|
||||
if (hours <= 24) return '5m'
|
||||
if (hours <= 24 * 5) return '30m'
|
||||
return '1h'
|
||||
}
|
||||
|
||||
export type WarehouseMetricsRange =
|
||||
| {
|
||||
status: 'ok'
|
||||
startDate: string
|
||||
endDate: string
|
||||
interval: ReturnType<typeof getWarehouseMetricsInterval>
|
||||
isClamped: boolean
|
||||
}
|
||||
| { status: 'out_of_range' }
|
||||
|
||||
export const resolveWarehouseMetricsRange = ({
|
||||
start,
|
||||
end,
|
||||
now = dayjs(),
|
||||
}: {
|
||||
start: string
|
||||
end: string
|
||||
now?: Dayjs
|
||||
}): WarehouseMetricsRange => {
|
||||
const latest = now.startOf('minute')
|
||||
// Counted in hours, not calendar days, so a DST change doesn't shift the bound
|
||||
// A few minutes of slack so the oldest bound doesn't fall out of range while the page is open
|
||||
const earliest = latest.subtract(WAREHOUSE_METRICS_MAX_RANGE_DAYS * 24, 'hour').add(5, 'minute')
|
||||
|
||||
const isStartTooEarly = dayjs(start).isBefore(earliest)
|
||||
const isEndInFuture = dayjs(end).isAfter(now)
|
||||
|
||||
const startDate = (isStartTooEarly ? earliest : dayjs(start)).toISOString()
|
||||
const endDate = (isEndInFuture ? latest : dayjs(end)).toISOString()
|
||||
|
||||
if (!dayjs(endDate).isAfter(dayjs(startDate))) return { status: 'out_of_range' }
|
||||
|
||||
return {
|
||||
status: 'ok',
|
||||
startDate,
|
||||
endDate,
|
||||
interval: getWarehouseMetricsInterval(startDate, endDate),
|
||||
isClamped: isStartTooEarly || isEndInFuture,
|
||||
}
|
||||
}
|
||||
+111
-13
@@ -1,6 +1,8 @@
|
||||
import { QueryClient } from '@tanstack/react-query'
|
||||
import { screen } from '@testing-library/react'
|
||||
import { screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import type { platformComponents as components } from 'api-types'
|
||||
import dayjs from 'dayjs'
|
||||
import { HttpResponse } from 'msw'
|
||||
import { beforeEach, expect, test, vi } from 'vitest'
|
||||
|
||||
@@ -67,15 +69,22 @@ const renderReport = (enabled = true) => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false, staleTime: Infinity } },
|
||||
})
|
||||
queryClient.setQueryData(['warehouse-configcat-flag', 'default'], enabled ? ['free-org'] : [])
|
||||
queryClient.setQueryData(projectKeys.detail('default'), { organization_id: 1 })
|
||||
queryClient.setQueryData(organizationKeys.list(), [{ id: 1, slug: 'warehouse-org' }])
|
||||
queryClient.setQueryData(
|
||||
['warehouse-configcat-flag', 'default'],
|
||||
enabled ? ['warehouse-org'] : []
|
||||
)
|
||||
return customRender(<WarehouseMetricsReport />, { queryClient })
|
||||
queryClient.setQueryData(organizationKeys.list(), [
|
||||
{ id: 1, slug: 'free-org', plan: { id: 'free' } },
|
||||
])
|
||||
queryClient.setQueryData(organizationKeys.entitlements('free-org'), {
|
||||
entitlements: [
|
||||
{
|
||||
feature: { key: 'log.retention_days' },
|
||||
type: 'numeric',
|
||||
config: { enabled: true, unlimited: false, value: 1 },
|
||||
},
|
||||
],
|
||||
})
|
||||
return customRender(<WarehouseMetricsReport />, { queryClient, nuqs: { hasMemory: true } })
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
mockSetup()
|
||||
addAPIMock({
|
||||
@@ -84,12 +93,12 @@ beforeEach(() => {
|
||||
response: () => HttpResponse.json<APIErrorBody>({ message: 'Not found' }, { status: 404 }),
|
||||
})
|
||||
})
|
||||
test('shows an explicit last-hour empty state', async () => {
|
||||
test('shows no data for the selected period', async () => {
|
||||
mockMetrics(null)
|
||||
renderReport()
|
||||
expect(await screen.findByText('No data in the last 60 minutes')).toBeInTheDocument()
|
||||
expect(screen.getByRole('status')).toHaveTextContent(
|
||||
'Warehouse report: No data in the last 60 minutes'
|
||||
expect(await screen.findByText('No data in the selected period')).toBeInTheDocument()
|
||||
expect(screen.getByRole('status', { name: 'Report status' })).toHaveTextContent(
|
||||
'Warehouse report: No data in the selected period'
|
||||
)
|
||||
})
|
||||
test('renders measured zero as query activity', async () => {
|
||||
@@ -98,7 +107,7 @@ test('renders measured zero as query activity', async () => {
|
||||
expect(
|
||||
await screen.findByText('Queries started per second. Not a count of SQL statements.')
|
||||
).toBeInTheDocument()
|
||||
expect(screen.queryByText('No data in the last 60 minutes')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('No data in the selected period')).not.toBeInTheDocument()
|
||||
})
|
||||
test.each(['not_started', 'disabled'] as const)(
|
||||
'offers setup when Warehouse is %s',
|
||||
@@ -122,6 +131,68 @@ test('shows a request failure rather than a no-data state', async () => {
|
||||
expect(await screen.findByText('Failed to retrieve Warehouse metrics')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('requests the period selected in the date picker', async () => {
|
||||
const requests: URL[] = []
|
||||
addAPIMock({
|
||||
method: 'get',
|
||||
path: '/platform/warehouse/:ref/metrics',
|
||||
response: ({ request }) => {
|
||||
requests.push(new URL(request.url))
|
||||
return HttpResponse.json<WarehouseMetricsResponse>(response(null))
|
||||
},
|
||||
})
|
||||
renderReport()
|
||||
await screen.findByText('No data in the selected period')
|
||||
await userEvent.click(screen.getByRole('button', { name: /Last 60 minutes/ }))
|
||||
await userEvent.click(screen.getByText('Last 24 hours'))
|
||||
await waitFor(() => expect(requests.at(-1)?.searchParams.get('interval')).toBe('5m'))
|
||||
const lastRequest = requests.at(-1)!
|
||||
expect(
|
||||
dayjs(lastRequest.searchParams.get('endDate')).diff(
|
||||
dayjs(lastRequest.searchParams.get('startDate')),
|
||||
'hour',
|
||||
true
|
||||
)
|
||||
).toBeCloseTo(24, 2)
|
||||
})
|
||||
|
||||
test('refreshes report measurements without changing the selected period', async () => {
|
||||
let requests = 0
|
||||
addAPIMock({
|
||||
method: 'get',
|
||||
path: '/platform/warehouse/:ref/metrics',
|
||||
response: () => {
|
||||
requests += 1
|
||||
return HttpResponse.json<WarehouseMetricsResponse>(response(requests > 2 ? 4 : null))
|
||||
},
|
||||
})
|
||||
renderReport()
|
||||
await screen.findByText('No data in the selected period')
|
||||
await userEvent.click(screen.getByRole('button', { name: /Last 60 minutes/ }))
|
||||
await userEvent.click(screen.getByText('Last 24 hours'))
|
||||
await waitFor(() => expect(requests).toBe(2))
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: 'Refresh report' })).toBeEnabled())
|
||||
const before = requests
|
||||
await userEvent.keyboard('{Shift>}R{/Shift}')
|
||||
expect(
|
||||
await screen.findByText('Queries started per second. Not a count of SQL statements.')
|
||||
).toBeInTheDocument()
|
||||
expect(requests).toBeGreaterThan(before)
|
||||
expect(screen.getByRole('button', { name: /Last 24 hours/ })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('shows the retention upgrade prompt instead of requesting seven days on a free plan', async () => {
|
||||
const metricsRequest = vi.fn(() => HttpResponse.json<WarehouseMetricsResponse>(response(null)))
|
||||
addAPIMock({ method: 'get', path: '/platform/warehouse/:ref/metrics', response: metricsRequest })
|
||||
renderReport()
|
||||
await screen.findByText('No data in the selected period')
|
||||
await userEvent.click(screen.getByRole('button', { name: /Last 60 minutes/ }))
|
||||
const requestsBefore = metricsRequest.mock.calls.length
|
||||
await userEvent.click(screen.getByText('Last 7 days'))
|
||||
expect(await screen.findByRole('dialog')).toHaveTextContent('Report date range')
|
||||
expect(metricsRequest).toHaveBeenCalledTimes(requestsBefore)
|
||||
})
|
||||
|
||||
test('does not request Warehouse data without access', async () => {
|
||||
const setupRequest = vi.fn(() => HttpResponse.json<Setup>(setup))
|
||||
const metricsRequest = vi.fn(() => HttpResponse.json<WarehouseMetricsResponse>(response(null)))
|
||||
@@ -148,3 +219,30 @@ test('shows setup status failures when metrics cannot establish activity', async
|
||||
renderReport()
|
||||
expect(await screen.findByText('Failed to retrieve Warehouse status')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('refresh recovers a failed setup status request', async () => {
|
||||
let requests = 0
|
||||
addAPIMock({
|
||||
method: 'get',
|
||||
path: '/platform/warehouse/:ref/setup-status',
|
||||
response: () => {
|
||||
requests += 1
|
||||
return requests === 1
|
||||
? HttpResponse.json<APIErrorBody>({ message: 'Failed' }, { status: 500 })
|
||||
: HttpResponse.json<Setup>(setup)
|
||||
},
|
||||
})
|
||||
mockMetrics(null)
|
||||
renderReport()
|
||||
await screen.findByText('Failed to retrieve Warehouse status')
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Refresh report' }))
|
||||
expect(await screen.findByText('No data in the selected period')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('opens the date picker with its report shortcut', async () => {
|
||||
mockMetrics(null)
|
||||
renderReport()
|
||||
await screen.findByText('No data in the selected period')
|
||||
await userEvent.keyboard('{Shift>}P{/Shift}')
|
||||
expect(await screen.findByText('Last 24 hours')).toBeVisible()
|
||||
})
|
||||
+128
-23
@@ -1,7 +1,7 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useParams } from 'common'
|
||||
import dayjs from 'dayjs'
|
||||
import { WarehouseIcon } from 'lucide-react'
|
||||
import { RefreshCwIcon, WarehouseIcon } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import { Button, Card, CardContent } from 'ui'
|
||||
import { Admonition } from 'ui-patterns/Admonition'
|
||||
@@ -9,6 +9,7 @@ import { ChartLine } from 'ui-patterns/Chart'
|
||||
import { EmptyStatePresentational } from 'ui-patterns/EmptyStatePresentational'
|
||||
import { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader'
|
||||
|
||||
import { resolveWarehouseMetricsRange } from './WarehouseMetrics.range'
|
||||
import {
|
||||
getEmptyMessage,
|
||||
getReportStatus,
|
||||
@@ -19,13 +20,22 @@ import {
|
||||
type ReportView,
|
||||
} from './WarehouseMetricsReport.utils'
|
||||
import { ReportHeader } from '@/components/interfaces/Reports/ReportHeader'
|
||||
import { REPORT_DATERANGE_HELPER_LABELS } from '@/components/interfaces/Reports/Reports.constants'
|
||||
import ReportStickyNav from '@/components/interfaces/Reports/ReportStickyNav'
|
||||
import { LogsDatePicker } from '@/components/interfaces/Settings/Logs/Logs.DatePickers'
|
||||
import UpgradePrompt from '@/components/interfaces/Settings/Logs/UpgradePrompt'
|
||||
import { AlertError } from '@/components/ui/AlertError'
|
||||
import { NoDataPlaceholder } from '@/components/ui/Charts/NoDataPlaceholder'
|
||||
import { InlineLink } from '@/components/ui/InlineLink'
|
||||
import { ShortcutTooltip } from '@/components/ui/ShortcutTooltip'
|
||||
import { warehouseKeys } from '@/data/warehouse/keys'
|
||||
import { warehouseMetricsQueryOptions } from '@/data/warehouse/warehouse-metrics-query'
|
||||
import { useWarehouseSetupStatusQuery } from '@/data/warehouse/warehouse-setup-status-query'
|
||||
import { useIsWarehouseEnabled } from '@/hooks/misc/useIsWarehouseEnabled'
|
||||
import { useRefreshHandler, useReportDateRange } from '@/hooks/misc/useReportDateRange'
|
||||
import { IS_PLATFORM } from '@/lib/constants'
|
||||
import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
|
||||
import { useShortcut } from '@/state/shortcuts/useShortcut'
|
||||
|
||||
export const WarehouseMetricsReport = () => {
|
||||
const isWarehouseEnabled = useIsWarehouseEnabled()
|
||||
@@ -44,30 +54,57 @@ export const WarehouseMetricsReport = () => {
|
||||
|
||||
const WarehouseMetricsReportContent = () => {
|
||||
const { ref } = useParams()
|
||||
const [range] = useState(() => {
|
||||
const end = dayjs().startOf('minute')
|
||||
return { startDate: end.subtract(1, 'hour').toISOString(), endDate: end.toISOString() }
|
||||
const queryClient = useQueryClient()
|
||||
const [showDatePicker, setShowDatePicker] = useState(false)
|
||||
const {
|
||||
selectedDateRange,
|
||||
datePickerValue,
|
||||
datePickerHelpers,
|
||||
handleDatePickerChange,
|
||||
showUpgradePrompt,
|
||||
setShowUpgradePrompt,
|
||||
} = useReportDateRange()
|
||||
const range = resolveWarehouseMetricsRange({
|
||||
start: selectedDateRange.period_start.date,
|
||||
end: selectedDateRange.period_end.date,
|
||||
})
|
||||
|
||||
const isRangeOk = range.status === 'ok'
|
||||
const setup = useWarehouseSetupStatusQuery({ projectRef: ref }, { enabled: IS_PLATFORM })
|
||||
|
||||
const query = useQuery(
|
||||
warehouseMetricsQueryOptions({
|
||||
projectRef: ref,
|
||||
attributes: ['query_rate'],
|
||||
...range,
|
||||
interval: '1m',
|
||||
startDate: isRangeOk ? range.startDate : '',
|
||||
endDate: isRangeOk ? range.endDate : '',
|
||||
interval: isRangeOk ? range.interval : '1m',
|
||||
enabled: isRangeOk,
|
||||
})
|
||||
)
|
||||
const handleRefresh = useRefreshHandler(
|
||||
datePickerValue,
|
||||
datePickerHelpers,
|
||||
handleDatePickerChange,
|
||||
async () => {
|
||||
await Promise.all([
|
||||
queryClient.invalidateQueries({ queryKey: warehouseKeys.metricsAll(ref) }),
|
||||
queryClient.invalidateQueries({ queryKey: warehouseKeys.setupStatus(ref) }),
|
||||
])
|
||||
}
|
||||
)
|
||||
useShortcut(SHORTCUT_IDS.OBSERVABILITY_REFRESH, handleRefresh, { enabled: !query.isFetching })
|
||||
useShortcut(SHORTCUT_IDS.OBSERVABILITY_TOGGLE_DATE_PICKER, () => {
|
||||
setShowDatePicker((open) => !open)
|
||||
})
|
||||
const metric = query.data?.metrics.find((item) => item.metric === 'query_rate')
|
||||
const hasLiveTables = setup.data?.tables.some((table) => table.state === 'live') ?? false
|
||||
const hasValues = hasAnyValues(metric)
|
||||
const points = toChartPoints(metric)
|
||||
const hasChartValues = points.some((point) => typeof point.value === 'number')
|
||||
const emptyMessage = getEmptyMessage(metric)
|
||||
const emptyMessage = getEmptyMessage(metric, 'No data in the selected period')
|
||||
|
||||
const view = getReportView({
|
||||
isPlatform: IS_PLATFORM,
|
||||
isRangeValid: isRangeOk,
|
||||
isLoading: query.isPending || (setup.isPending && !hasValues),
|
||||
setupError: setup.isError && !hasValues ? setup.error : null,
|
||||
setupPrompt: getSetupPrompt({
|
||||
@@ -79,21 +116,78 @@ const WarehouseMetricsReportContent = () => {
|
||||
hasChartValues,
|
||||
})
|
||||
|
||||
const handleResetRange = () => {
|
||||
const helper = datePickerHelpers.find(
|
||||
(item) => item.text === REPORT_DATERANGE_HELPER_LABELS.LAST_60_MINUTES
|
||||
)
|
||||
if (!helper) return
|
||||
handleDatePickerChange({
|
||||
from: helper.calcFrom(),
|
||||
to: helper.calcTo(),
|
||||
isHelper: true,
|
||||
text: helper.text,
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<p className="text-sm text-foreground-light">Query activity in the last 60 minutes.</p>
|
||||
<div className="relative">
|
||||
<p role="status" className="sr-only">
|
||||
{getReportStatus(view, emptyMessage)}
|
||||
</p>
|
||||
<WarehouseMetricsBody
|
||||
view={view}
|
||||
projectRef={ref}
|
||||
points={points}
|
||||
emptyMessage={emptyMessage}
|
||||
isPartial={metric?.availability === 'partial'}
|
||||
/>
|
||||
</div>
|
||||
<ReportStickyNav
|
||||
content={
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<ShortcutTooltip shortcutId={SHORTCUT_IDS.OBSERVABILITY_REFRESH} label="Refresh report">
|
||||
<Button
|
||||
type="button"
|
||||
aria-label="Refresh report"
|
||||
disabled={query.isFetching}
|
||||
icon={
|
||||
<RefreshCwIcon className={query.isFetching ? 'motion-safe:animate-spin' : ''} />
|
||||
}
|
||||
onClick={handleRefresh}
|
||||
/>
|
||||
</ShortcutTooltip>
|
||||
<LogsDatePicker
|
||||
value={datePickerValue}
|
||||
helpers={datePickerHelpers}
|
||||
onSubmit={handleDatePickerChange}
|
||||
open={showDatePicker}
|
||||
onOpenChange={setShowDatePicker}
|
||||
shortcutId={SHORTCUT_IDS.OBSERVABILITY_TOGGLE_DATE_PICKER}
|
||||
/>
|
||||
<p className="text-xs text-foreground-light">
|
||||
{dayjs(selectedDateRange.period_start.date).format('MMM D, h:mma')} to{' '}
|
||||
{dayjs(selectedDateRange.period_end.date).format('MMM D, h:mma')}
|
||||
</p>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div role="status">
|
||||
{isRangeOk && range.isClamped && (
|
||||
<p className="text-sm text-foreground-light">
|
||||
The selected period was adjusted to fit the available metrics window.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="relative">
|
||||
<p role="status" aria-label="Report status" className="sr-only">
|
||||
{getReportStatus(view, emptyMessage)}
|
||||
</p>
|
||||
<WarehouseMetricsBody
|
||||
view={view}
|
||||
projectRef={ref}
|
||||
points={points}
|
||||
emptyMessage={emptyMessage}
|
||||
isPartial={metric?.availability === 'partial'}
|
||||
onResetRange={handleResetRange}
|
||||
/>
|
||||
</div>
|
||||
</ReportStickyNav>
|
||||
<UpgradePrompt
|
||||
show={showUpgradePrompt}
|
||||
setShowUpgradePrompt={setShowUpgradePrompt}
|
||||
title="Report date range"
|
||||
description="Warehouse metrics follow your organization's log retention limits, up to 30 days."
|
||||
source="warehouseReportDateRange"
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -104,12 +198,14 @@ const WarehouseMetricsBody = ({
|
||||
points,
|
||||
emptyMessage,
|
||||
isPartial,
|
||||
onResetRange,
|
||||
}: {
|
||||
view: ReportView
|
||||
projectRef?: string
|
||||
points: Record<string, string | number>[]
|
||||
emptyMessage: string
|
||||
isPartial: boolean
|
||||
onResetRange: () => void
|
||||
}) => {
|
||||
switch (view.kind) {
|
||||
case 'unsupported':
|
||||
@@ -120,6 +216,15 @@ const WarehouseMetricsBody = ({
|
||||
description="Warehouse metrics are only available on the Supabase platform."
|
||||
/>
|
||||
)
|
||||
case 'out-of-range':
|
||||
return (
|
||||
<Admonition
|
||||
layout="responsive"
|
||||
title="This period is outside the available metrics history"
|
||||
description="Warehouse metrics cover the last 30 days. Choose a more recent period."
|
||||
actions={<Button onClick={onResetRange}>Show last 60 minutes</Button>}
|
||||
/>
|
||||
)
|
||||
case 'loading':
|
||||
return <GenericSkeletonLoader aria-label="Loading Warehouse report" />
|
||||
case 'setup-error':
|
||||
|
||||
+7
@@ -30,6 +30,7 @@ describe('getReportView', () => {
|
||||
it.each([
|
||||
['not on platform', { isPlatform: false, isLoading: true }, 'unsupported'],
|
||||
['loading', { isLoading: true, setupError: error }, 'loading'],
|
||||
['invalid range', { isRangeValid: false, isLoading: true }, 'out-of-range'],
|
||||
[
|
||||
'setup error',
|
||||
{ setupError: error, setupPrompt: 'disabled', metricsError: error },
|
||||
@@ -44,6 +45,12 @@ describe('getReportView', () => {
|
||||
})
|
||||
|
||||
describe('getReportStatus', () => {
|
||||
it('announces the invalid-range fallback', () => {
|
||||
expect(getReportStatus({ kind: 'out-of-range' }, '')).toBe(
|
||||
'This period is outside the available metrics history'
|
||||
)
|
||||
})
|
||||
|
||||
it('announces the empty message when there is nothing to chart', () => {
|
||||
const view = getReportView({
|
||||
isPlatform: true,
|
||||
|
||||
+11
-2
@@ -7,6 +7,7 @@ export type SetupPrompt = 'not_started' | 'disabled'
|
||||
export type ReportView =
|
||||
| { kind: 'unsupported' }
|
||||
| { kind: 'loading' }
|
||||
| { kind: 'out-of-range' }
|
||||
| { kind: 'setup-error'; error: ErrorLike }
|
||||
| { kind: 'setup'; prompt: SetupPrompt }
|
||||
| { kind: 'metrics-error'; error: ErrorLike }
|
||||
@@ -52,6 +53,7 @@ export function getSetupPrompt({
|
||||
// Order matters: the first matching state wins.
|
||||
export function getReportView({
|
||||
isPlatform,
|
||||
isRangeValid = true,
|
||||
isLoading,
|
||||
setupError,
|
||||
setupPrompt,
|
||||
@@ -59,6 +61,7 @@ export function getReportView({
|
||||
hasChartValues,
|
||||
}: {
|
||||
isPlatform: boolean
|
||||
isRangeValid?: boolean
|
||||
isLoading: boolean
|
||||
setupError: ErrorLike | null
|
||||
setupPrompt: SetupPrompt | undefined
|
||||
@@ -66,6 +69,7 @@ export function getReportView({
|
||||
hasChartValues: boolean
|
||||
}): ReportView {
|
||||
if (!isPlatform) return { kind: 'unsupported' }
|
||||
if (!isRangeValid) return { kind: 'out-of-range' }
|
||||
if (isLoading) return { kind: 'loading' }
|
||||
if (setupError) return { kind: 'setup-error', error: setupError }
|
||||
if (setupPrompt) return { kind: 'setup', prompt: setupPrompt }
|
||||
@@ -77,6 +81,8 @@ export function getReportStatus(view: ReportView, emptyMessage: string) {
|
||||
switch (view.kind) {
|
||||
case 'unsupported':
|
||||
return 'Warehouse metrics are unavailable'
|
||||
case 'out-of-range':
|
||||
return 'This period is outside the available metrics history'
|
||||
case 'loading':
|
||||
return 'Loading Warehouse report'
|
||||
case 'setup-error':
|
||||
@@ -90,7 +96,10 @@ export function getReportStatus(view: ReportView, emptyMessage: string) {
|
||||
}
|
||||
}
|
||||
|
||||
export function getEmptyMessage(metric?: WarehouseMetric) {
|
||||
export function getEmptyMessage(
|
||||
metric?: WarehouseMetric,
|
||||
noDataMessage = 'No data in the last 60 minutes'
|
||||
) {
|
||||
if (!metric || metric.series.length > 1) return 'Metrics are temporarily unavailable'
|
||||
switch (metric.availability) {
|
||||
case 'stale':
|
||||
@@ -102,6 +111,6 @@ export function getEmptyMessage(metric?: WarehouseMetric) {
|
||||
case 'not_provisioned':
|
||||
return 'Metrics are temporarily unavailable'
|
||||
default:
|
||||
return 'No data in the last 60 minutes'
|
||||
return noDataMessage
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
|
||||
import { datePickerValueToLogTimeRange, logTimeRangesEqual } from './LogTimeRange.utils'
|
||||
import { EXPLORER_DATEPICKER_HELPERS } from '@/components/interfaces/Settings/Logs/Logs.constants'
|
||||
import { maybeShowUpgradePromptIfNotEntitled } from '@/components/interfaces/Settings/Logs/Logs.utils'
|
||||
import { isStartOutsideRetention } from '@/components/interfaces/Settings/Logs/Logs.utils'
|
||||
import type { TimeRange } from '@/data/content/notebooks/notebook-schema'
|
||||
import { useCheckEntitlements } from '@/hooks/misc/useCheckEntitlements'
|
||||
|
||||
@@ -55,7 +55,7 @@ export const LogsTimeRangeSubMenu = ({
|
||||
<DropdownMenuSubContent className="w-52">
|
||||
{presets.map(({ helper, range: presetRange }) => {
|
||||
const isSelected = !isCustomRange && logTimeRangesEqual(range, presetRange)
|
||||
const isLocked = maybeShowUpgradePromptIfNotEntitled(helper.calcFrom(), entitledToLogDays)
|
||||
const isLocked = isStartOutsideRetention(helper.calcFrom(), entitledToLogDays)
|
||||
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useState } from 'react'
|
||||
|
||||
import { customDateRangeToLogTimeRange } from './LogTimeRange.utils'
|
||||
import { maybeShowUpgradePromptIfNotEntitled } from '@/components/interfaces/Settings/Logs/Logs.utils'
|
||||
import { isStartOutsideRetention } from '@/components/interfaces/Settings/Logs/Logs.utils'
|
||||
import type { TimeRange } from '@/data/content/notebooks/notebook-schema'
|
||||
import { useCheckEntitlements } from '@/hooks/misc/useCheckEntitlements'
|
||||
|
||||
@@ -17,7 +17,7 @@ export function useLogsCustomRange({
|
||||
|
||||
const handleApplyCustomRange = ({ from, to }: { from: Date; to: Date }) => {
|
||||
const range = customDateRangeToLogTimeRange({ from, to })
|
||||
if (maybeShowUpgradePromptIfNotEntitled(range.start, entitledToLogDays)) {
|
||||
if (isStartOutsideRetention(range.start, entitledToLogDays)) {
|
||||
setShowUpgradePrompt(true)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import dayjs from 'dayjs'
|
||||
import { describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { LogsTableName } from './Logs.constants'
|
||||
@@ -14,6 +15,7 @@ import {
|
||||
genCountQuery,
|
||||
genDefaultQuery,
|
||||
getAuthLogSeverity,
|
||||
isStartOutsideRetention,
|
||||
parseMultigresEventMessage,
|
||||
} from './Logs.utils'
|
||||
|
||||
@@ -25,6 +27,24 @@ const createLog = (overrides: Partial<LogData> = {}): LogData => ({
|
||||
})
|
||||
|
||||
describe('Logs.utils', () => {
|
||||
describe('isStartOutsideRetention', () => {
|
||||
const hoursAgo = (hours: number) => dayjs().subtract(hours, 'hour').toISOString()
|
||||
|
||||
test('prompts for a start 36 hours ago with a one-day entitlement', () => {
|
||||
expect(isStartOutsideRetention(hoursAgo(36), 1)).toBe(true)
|
||||
})
|
||||
|
||||
test('does not prompt within the entitlement, including presets computed just before the check', () => {
|
||||
expect(isStartOutsideRetention(hoursAgo(12), 1)).toBe(false)
|
||||
expect(isStartOutsideRetention(hoursAgo(24), 1)).toBe(false)
|
||||
expect(isStartOutsideRetention(hoursAgo(24 * 7), 7)).toBe(false)
|
||||
})
|
||||
|
||||
test('does not prompt without an entitlement value', () => {
|
||||
expect(isStartOutsideRetention(hoursAgo(24 * 30), undefined)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatLogsAsJson', () => {
|
||||
test('formats single log as JSON', () => {
|
||||
const rows: LogData[] = [createLog({ id: '1', event_message: 'test message' })]
|
||||
|
||||
@@ -3,6 +3,7 @@ import { IS_PLATFORM } from 'common'
|
||||
import dayjs, { Dayjs } from 'dayjs'
|
||||
import { get } from 'lodash'
|
||||
import uniqBy from 'lodash/uniqBy'
|
||||
import type { editor, IPosition, languages } from 'monaco-editor'
|
||||
import { useEffect } from 'react'
|
||||
import logConstants from 'shared-data/log-constants'
|
||||
|
||||
@@ -13,7 +14,7 @@ import {
|
||||
SQL_FILTER_TEMPLATES,
|
||||
type SqlFilterEntry,
|
||||
} from './Logs.constants'
|
||||
import type { Filters, LogData, LogsEndpointParams, QueryType } from './Logs.types'
|
||||
import type { Filters, LogData, LogsEndpointParams, Metadata, QueryType } from './Logs.types'
|
||||
import { convertResultsToCSV } from '@/components/interfaces/SQLEditor/UtilityPanel/Results.utils'
|
||||
import BackwardIterator from '@/components/ui/CodeEditor/Providers/BackwardIterator'
|
||||
import { parseOtelTimestamp } from '@/data/logs/otel-inspection.utils'
|
||||
@@ -60,8 +61,9 @@ const getDotKeys = (obj: { [k: string]: unknown }, parent?: string): string[] =>
|
||||
const keys = Object.keys(obj).filter((k) => obj[k])
|
||||
return keys.flatMap((k) => {
|
||||
const currKey = parent ? `${parent}.${k}` : k
|
||||
if (typeof obj[k] === 'object') {
|
||||
return getDotKeys(obj[k] as any, currKey)
|
||||
const value = obj[k]
|
||||
if (typeof value === 'object' && value !== null) {
|
||||
return getDotKeys({ ...value }, currKey)
|
||||
} else {
|
||||
return [currKey]
|
||||
}
|
||||
@@ -351,16 +353,24 @@ export const parseMultigresEventMessage = (
|
||||
}
|
||||
}
|
||||
|
||||
// Presets like "Last 24 hours" compute their start moments before this check runs,
|
||||
// so allow a small grace window past the exact cutoff instead of locking them out.
|
||||
const ENTITLEMENT_CUTOFF_GRACE_MS = 60 * 1000
|
||||
|
||||
/**
|
||||
* Determine if we should show the user an upgrade prompt while browsing logs
|
||||
*
|
||||
* [Joshen] Tbh this should be a guard from API, and not UI to ensure that the checks are
|
||||
* consistent. To investigate separately - e.g upgrade prompt should show if API for logs
|
||||
* returns a error regarding the date range
|
||||
*/
|
||||
export const maybeShowUpgradePromptIfNotEntitled = (
|
||||
export const isStartOutsideRetention = (
|
||||
from: string | null | undefined,
|
||||
entitledToDays: number | undefined
|
||||
) => {
|
||||
if (!entitledToDays) return false
|
||||
const day = Math.abs(dayjs().diff(dayjs(from), 'day'))
|
||||
return day > entitledToDays
|
||||
const cutoff = dayjs().subtract(entitledToDays, 'day').subtract(ENTITLEMENT_CUTOFF_GRACE_MS, 'ms')
|
||||
return dayjs(from).isBefore(cutoff)
|
||||
}
|
||||
|
||||
export const genCountQuery = (table: LogsTableName, filters: Filters): SafeLogSqlFragment => {
|
||||
@@ -388,7 +398,7 @@ const calcChartStart = (
|
||||
): [Dayjs, 'minute' | 'hour' | 'day'] => {
|
||||
const ite = resolveLogTimestamp(params.iso_timestamp_end)
|
||||
// todo @TzeYiing needs typing
|
||||
const its: any = resolveLogTimestamp(params.iso_timestamp_start)
|
||||
const its = resolveLogTimestamp(params.iso_timestamp_start)
|
||||
|
||||
let trunc: 'minute' | 'hour' | 'day' = 'minute'
|
||||
let extendValue = 60 * 6
|
||||
@@ -489,12 +499,23 @@ export const useEditorHints = () => {
|
||||
|
||||
useEffect(() => {
|
||||
if (monaco) {
|
||||
const competionProvider = {
|
||||
const competionProvider: languages.CompletionItemProvider = {
|
||||
triggerCharacters: ['`', ' ', '.'],
|
||||
provideCompletionItems: function (model: any, position: any, context: any) {
|
||||
provideCompletionItems: function (
|
||||
model: editor.ITextModel,
|
||||
position: IPosition,
|
||||
context: languages.CompletionContext
|
||||
) {
|
||||
let iterator = new BackwardIterator(model, position.column - 2, position.lineNumber - 1)
|
||||
if (iterator.isNextDQuote()) return { suggestions: [] }
|
||||
let suggestions: { label: string; kind: any; insertText: string }[] = []
|
||||
let suggestions: languages.CompletionItem[] = []
|
||||
const word = model.getWordUntilPosition(position)
|
||||
const range = {
|
||||
startLineNumber: position.lineNumber,
|
||||
endLineNumber: position.lineNumber,
|
||||
startColumn: word.startColumn,
|
||||
endColumn: word.endColumn,
|
||||
}
|
||||
|
||||
let schemasInUse = logConstants.schemas.filter((schema) =>
|
||||
iterator._text.includes(schema.reference)
|
||||
@@ -515,6 +536,7 @@ export const useEditorHints = () => {
|
||||
label: key,
|
||||
kind: monaco.languages.CompletionItemKind.Property,
|
||||
insertText: key,
|
||||
range,
|
||||
}))
|
||||
suggestions = suggestions.concat(trailingToAdd)
|
||||
}
|
||||
@@ -525,6 +547,7 @@ export const useEditorHints = () => {
|
||||
label: schema.reference,
|
||||
kind: monaco.languages.CompletionItemKind.Class,
|
||||
insertText: schema.reference,
|
||||
range,
|
||||
}))
|
||||
|
||||
const fields = schemasInUse.flatMap((schema) => schema.fields)
|
||||
@@ -538,6 +561,7 @@ export const useEditorHints = () => {
|
||||
label: key,
|
||||
kind: monaco.languages.CompletionItemKind.Property,
|
||||
insertText: key,
|
||||
range,
|
||||
}))
|
||||
suggestions = suggestions.concat(leadingToAdd)
|
||||
suggestions = suggestions.concat(referencesToAdd)
|
||||
@@ -546,7 +570,7 @@ export const useEditorHints = () => {
|
||||
suggestions: uniqBy(suggestions, 'label'),
|
||||
}
|
||||
},
|
||||
} as any
|
||||
}
|
||||
|
||||
// register completion item provider for pgsql
|
||||
const completeProvider = monaco.languages.registerCompletionItemProvider(
|
||||
@@ -566,8 +590,11 @@ export const useEditorHints = () => {
|
||||
*
|
||||
* min/max are the datetime strings that extend beyond the given timeseries data.
|
||||
*/
|
||||
const toTimestampInput = (value: unknown): string | number =>
|
||||
typeof value === 'number' ? value : String(value)
|
||||
|
||||
export const fillTimeseries = (
|
||||
timeseriesData: any[],
|
||||
timeseriesData: Record<string, unknown>[],
|
||||
timestampKey: string,
|
||||
valueKey: string | string[],
|
||||
defaultValue: number,
|
||||
@@ -582,7 +609,7 @@ export const fillTimeseries = (
|
||||
// If we have more points than minPointsToFill, just normalize timestamps and return
|
||||
if (timeseriesData.length > minPointsToFill) {
|
||||
return timeseriesData.map((datum) => {
|
||||
const timestamp = datum[timestampKey]
|
||||
const timestamp = toTimestampInput(datum[timestampKey])
|
||||
const iso = isUnixMicro(timestamp)
|
||||
? unixMicroToIsoTimestamp(timestamp)
|
||||
: dayjs.utc(timestamp).toISOString()
|
||||
@@ -592,14 +619,14 @@ export const fillTimeseries = (
|
||||
}
|
||||
|
||||
if (timeseriesData.length === 1 && !(min && max)) {
|
||||
const timestamp = timeseriesData[0][timestampKey]
|
||||
const timestamp = toTimestampInput(timeseriesData[0][timestampKey])
|
||||
timeseriesData[0][timestampKey] = isUnixMicro(timestamp)
|
||||
? unixMicroToIsoTimestamp(timestamp)
|
||||
: dayjs.utc(timestamp).toISOString()
|
||||
return timeseriesData
|
||||
}
|
||||
const dates = timeseriesData.map((datum) => {
|
||||
const timestamp = datum[timestampKey]
|
||||
const timestamp = toTimestampInput(datum[timestampKey])
|
||||
return dayjs.utc(isUnixMicro(timestamp) ? unixMicroToIsoTimestamp(timestamp) : timestamp)
|
||||
})
|
||||
|
||||
@@ -811,8 +838,16 @@ export function getAuthLogSeverity(level?: unknown, status?: unknown): string {
|
||||
return normalizedLevel
|
||||
}
|
||||
|
||||
export function jwtAPIKey(metadata: any) {
|
||||
const apikeyHeader = metadata?.[0]?.request?.[0]?.sb?.[0]?.jwt?.[0]?.apikey?.[0]
|
||||
type JwtApiKeyHeader = {
|
||||
invalid?: boolean
|
||||
payload?: { algorithm?: string; issuer?: string; role?: string; subject?: string }[]
|
||||
}
|
||||
type ApiKeyHeader = { error?: string; prefix?: string }
|
||||
type AuthorizationHeader = { invalid?: boolean; payload?: { role?: string }[] }
|
||||
|
||||
export function jwtAPIKey(metadata?: Metadata) {
|
||||
const apikeyHeader: JwtApiKeyHeader | undefined =
|
||||
metadata?.[0]?.request?.[0]?.sb?.[0]?.jwt?.[0]?.apikey?.[0]
|
||||
if (!apikeyHeader) {
|
||||
return undefined
|
||||
}
|
||||
@@ -829,6 +864,7 @@ export function jwtAPIKey(metadata: any) {
|
||||
if (
|
||||
payload.algorithm === 'HS256' &&
|
||||
payload.issuer === 'supabase' &&
|
||||
payload.role !== undefined &&
|
||||
['anon', 'service_role'].includes(payload.role) &&
|
||||
!payload.subject
|
||||
) {
|
||||
@@ -838,8 +874,9 @@ export function jwtAPIKey(metadata: any) {
|
||||
return '<unrecognized>'
|
||||
}
|
||||
|
||||
export function apiKey(metadata: any) {
|
||||
const apikeyHeader = metadata?.[0]?.request?.[0]?.sb?.[0]?.apikey?.[0]?.apikey?.[0]
|
||||
export function apiKey(metadata?: Metadata) {
|
||||
const apikeyHeader: ApiKeyHeader | undefined =
|
||||
metadata?.[0]?.request?.[0]?.sb?.[0]?.apikey?.[0]?.apikey?.[0]
|
||||
if (!apikeyHeader) {
|
||||
return undefined
|
||||
}
|
||||
@@ -851,8 +888,9 @@ export function apiKey(metadata: any) {
|
||||
return `${apikeyHeader.prefix}...`
|
||||
}
|
||||
|
||||
export function role(metadata: any) {
|
||||
const authorizationHeader = metadata?.[0]?.request?.[0]?.sb?.[0]?.jwt?.[0]?.authorization?.[0]
|
||||
export function role(metadata?: Metadata) {
|
||||
const authorizationHeader: AuthorizationHeader | undefined =
|
||||
metadata?.[0]?.request?.[0]?.sb?.[0]?.jwt?.[0]?.authorization?.[0]
|
||||
if (!authorizationHeader) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
} from './Logs.constants'
|
||||
import { DatePickerValue } from './Logs.DatePickers'
|
||||
import type { Filters, LogSearchCallback, LogTemplate, QueryType } from './Logs.types'
|
||||
import { maybeShowUpgradePromptIfNotEntitled } from './Logs.utils'
|
||||
import { isStartOutsideRetention } from './Logs.utils'
|
||||
import { calculateBarClickTimeRange } from './LogsBarChart.utils'
|
||||
import { LogTable } from './LogTable'
|
||||
import UpgradePrompt from './UpgradePrompt'
|
||||
@@ -173,10 +173,7 @@ export const LogsPreviewer = ({
|
||||
setSelectedLogId(null)
|
||||
setTimeRange(from || '', to || '')
|
||||
} else if (event === 'datepicker-change') {
|
||||
const shouldShowUpgradePrompt = maybeShowUpgradePromptIfNotEntitled(
|
||||
from || '',
|
||||
entitledToAuditLogDays
|
||||
)
|
||||
const shouldShowUpgradePrompt = isStartOutsideRetention(from || '', entitledToAuditLogDays)
|
||||
if (shouldShowUpgradePrompt) {
|
||||
setShowUpgradePrompt(!showUpgradePrompt)
|
||||
} else {
|
||||
@@ -189,7 +186,7 @@ export const LogsPreviewer = ({
|
||||
// Show the prompt on page load based on query params
|
||||
useEffect(() => {
|
||||
if (timestampStart) {
|
||||
const shouldShowUpgradePrompt = maybeShowUpgradePromptIfNotEntitled(
|
||||
const shouldShowUpgradePrompt = isStartOutsideRetention(
|
||||
timestampStart,
|
||||
entitledToAuditLogDays
|
||||
)
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
DatePickerValue,
|
||||
LogsDatePicker,
|
||||
} from '@/components/interfaces/Settings/Logs/Logs.DatePickers'
|
||||
import { maybeShowUpgradePromptIfNotEntitled } from '@/components/interfaces/Settings/Logs/Logs.utils'
|
||||
import { isStartOutsideRetention } from '@/components/interfaces/Settings/Logs/Logs.utils'
|
||||
import UpgradePrompt from '@/components/interfaces/Settings/Logs/UpgradePrompt'
|
||||
import { useCheckEntitlements } from '@/hooks/misc/useCheckEntitlements'
|
||||
|
||||
@@ -44,10 +44,7 @@ export function DataTableFilterTimerange<TData>({
|
||||
|
||||
const handleDatePickerChange = (vals: DatePickerValue) => {
|
||||
// Check if the selected date range exceeds the plan limits
|
||||
const shouldShowUpgradePrompt = maybeShowUpgradePromptIfNotEntitled(
|
||||
vals.from,
|
||||
entitledToAuditLogDays
|
||||
)
|
||||
const shouldShowUpgradePrompt = isStartOutsideRetention(vals.from, entitledToAuditLogDays)
|
||||
|
||||
if (shouldShowUpgradePrompt) {
|
||||
setShowUpgradePrompt(true)
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { QueryClient } from '@tanstack/react-query'
|
||||
import { act } from '@testing-library/react'
|
||||
import dayjs from 'dayjs'
|
||||
import { describe, expect, test } from 'vitest'
|
||||
|
||||
import { organizationKeys } from '@/data/organizations/keys'
|
||||
import { projectKeys } from '@/data/projects/keys'
|
||||
import { useReportDateRange } from '@/hooks/misc/useReportDateRange'
|
||||
import { customRenderHook } from '@/tests/lib/custom-render'
|
||||
|
||||
const freePlanQueryClient = () => {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity } } })
|
||||
queryClient.setQueryData(projectKeys.detail('default'), { organization_id: 1 })
|
||||
queryClient.setQueryData(organizationKeys.list(), [
|
||||
{ id: 1, slug: 'free-org', plan: { id: 'free' } },
|
||||
])
|
||||
queryClient.setQueryData(organizationKeys.entitlements('free-org'), {
|
||||
entitlements: [
|
||||
{
|
||||
feature: { key: 'log.retention_days' },
|
||||
type: 'numeric',
|
||||
config: { enabled: true, unlimited: false, value: 1 },
|
||||
},
|
||||
],
|
||||
})
|
||||
return queryClient
|
||||
}
|
||||
|
||||
describe('organization log retention', () => {
|
||||
test.each([7, 30])(
|
||||
'requires an upgrade for a %s-day range beyond log retention',
|
||||
async (days) => {
|
||||
const { result } = customRenderHook(() => useReportDateRange(), {
|
||||
queryClient: freePlanQueryClient(),
|
||||
})
|
||||
const from = dayjs().subtract(days, 'day').toISOString()
|
||||
|
||||
await act(async () => {
|
||||
expect(result.current.handleDatePickerChange({ from, to: dayjs().toISOString() })).toBe(
|
||||
true
|
||||
)
|
||||
})
|
||||
|
||||
expect(result.current.showUpgradePrompt).toBe(true)
|
||||
expect(result.current.selectedDateRange.period_start.date).not.toBe(from)
|
||||
}
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,86 @@
|
||||
import { QueryClient } from '@tanstack/react-query'
|
||||
import { act, waitFor } from '@testing-library/react'
|
||||
import dayjs from 'dayjs'
|
||||
import { describe, expect, test } from 'vitest'
|
||||
|
||||
import { useReportDateRange } from './useReportDateRange'
|
||||
import { organizationKeys } from '@/data/organizations/keys'
|
||||
import { projectKeys } from '@/data/projects/keys'
|
||||
import { customRenderHook } from '@/tests/lib/custom-render'
|
||||
|
||||
const hoursAgo = (hours: number) => dayjs().subtract(hours, 'hour').toISOString()
|
||||
|
||||
const render = (searchParams?: Record<string, string>) => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false, staleTime: Infinity } },
|
||||
})
|
||||
queryClient.setQueryData(projectKeys.detail('default'), { organization_id: 1 })
|
||||
queryClient.setQueryData(organizationKeys.list(), [
|
||||
{ id: 1, slug: 'free-org', plan: { id: 'free' } },
|
||||
])
|
||||
queryClient.setQueryData(organizationKeys.entitlements('free-org'), {
|
||||
entitlements: [
|
||||
{
|
||||
feature: { key: 'log.retention_days' },
|
||||
type: 'numeric',
|
||||
config: { enabled: true, unlimited: false, value: 1 },
|
||||
},
|
||||
],
|
||||
})
|
||||
return customRenderHook(() => useReportDateRange(), {
|
||||
queryClient,
|
||||
nuqs: { hasMemory: true, searchParams },
|
||||
})
|
||||
}
|
||||
|
||||
describe('useReportDateRange retention entitlement', () => {
|
||||
test('handleDatePickerChange prompts for a start 36 hours ago with a one-day entitlement', async () => {
|
||||
const { result } = render()
|
||||
await waitFor(() => expect(result.current.isOrgPlanLoading).toBe(false))
|
||||
|
||||
let isLocked = false
|
||||
act(() => {
|
||||
isLocked = result.current.handleDatePickerChange({
|
||||
from: hoursAgo(36),
|
||||
to: dayjs().toISOString(),
|
||||
isHelper: false,
|
||||
})
|
||||
})
|
||||
|
||||
expect(isLocked).toBe(true)
|
||||
expect(result.current.showUpgradePrompt).toBe(true)
|
||||
})
|
||||
|
||||
test('handleDatePickerChange accepts a start inside the entitlement', async () => {
|
||||
const { result } = render()
|
||||
await waitFor(() => expect(result.current.isOrgPlanLoading).toBe(false))
|
||||
|
||||
let isLocked = true
|
||||
act(() => {
|
||||
isLocked = result.current.handleDatePickerChange({
|
||||
from: hoursAgo(12),
|
||||
to: dayjs().toISOString(),
|
||||
isHelper: false,
|
||||
})
|
||||
})
|
||||
|
||||
expect(isLocked).toBe(false)
|
||||
expect(result.current.showUpgradePrompt).toBe(false)
|
||||
})
|
||||
|
||||
test('ignores a stored start 36 hours ago and falls back to the default range', async () => {
|
||||
const stored = hoursAgo(36)
|
||||
const { result } = render({ its: stored, ite: dayjs().toISOString() })
|
||||
await waitFor(() => expect(result.current.isOrgPlanLoading).toBe(false))
|
||||
|
||||
expect(result.current.selectedDateRange.period_start.date).not.toBe(stored)
|
||||
})
|
||||
|
||||
test('keeps a stored start inside the entitlement', async () => {
|
||||
const stored = hoursAgo(12)
|
||||
const { result } = render({ its: stored, ite: dayjs().toISOString() })
|
||||
await waitFor(() => expect(result.current.isOrgPlanLoading).toBe(false))
|
||||
|
||||
expect(result.current.selectedDateRange.period_start.date).toBe(stored)
|
||||
})
|
||||
})
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
ReportsDatetimeHelper,
|
||||
} from '@/components/interfaces/Reports/Reports.constants'
|
||||
import { DatePickerValue } from '@/components/interfaces/Settings/Logs/Logs.DatePickers'
|
||||
import { maybeShowUpgradePromptIfNotEntitled } from '@/components/interfaces/Settings/Logs/Logs.utils'
|
||||
import { isStartOutsideRetention } from '@/components/interfaces/Settings/Logs/Logs.utils'
|
||||
import { AnalyticsInterval } from '@/data/analytics/constants'
|
||||
import { useCheckEntitlements } from '@/hooks/misc/useCheckEntitlements'
|
||||
import { useCurrentOrgPlan } from '@/hooks/misc/useCurrentOrgPlan'
|
||||
@@ -168,7 +168,7 @@ export const useReportDateRange = (
|
||||
storedFrom.isValid() &&
|
||||
storedFrom.isAfter(now.subtract(90, 'day')) &&
|
||||
storedFrom.isBefore(now.add(1, 'day')) &&
|
||||
!maybeShowUpgradePromptIfNotEntitled(timestampStartValue, entitledToAuditLogDays)
|
||||
!isStartOutsideRetention(timestampStartValue, entitledToAuditLogDays)
|
||||
) {
|
||||
return timestampStartValue
|
||||
}
|
||||
@@ -255,10 +255,7 @@ export const useReportDateRange = (
|
||||
)
|
||||
|
||||
const handleDatePickerChange = (values: DatePickerValue) => {
|
||||
const shouldShowUpgradePrompt = maybeShowUpgradePromptIfNotEntitled(
|
||||
values.from,
|
||||
entitledToAuditLogDays
|
||||
)
|
||||
const shouldShowUpgradePrompt = isStartOutsideRetention(values.from, entitledToAuditLogDays)
|
||||
if (shouldShowUpgradePrompt) {
|
||||
setShowUpgradePrompt(true)
|
||||
return true
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
|
||||
import { useCheckEntitlements } from './useCheckEntitlements'
|
||||
import { maybeShowUpgradePromptIfNotEntitled } from '@/components/interfaces/Settings/Logs/Logs.utils'
|
||||
import { isStartOutsideRetention } from '@/components/interfaces/Settings/Logs/Logs.utils'
|
||||
|
||||
export const useUpgradePrompt = (from: string) => {
|
||||
const [showUpgradePrompt, setShowUpgradePrompt] = useState(false)
|
||||
const { getEntitlementNumericValue } = useCheckEntitlements('log.retention_days')
|
||||
const entitledToAuditLogDays = getEntitlementNumericValue()
|
||||
|
||||
const shouldShowUpgradePrompt = maybeShowUpgradePromptIfNotEntitled(from, entitledToAuditLogDays)
|
||||
const shouldShowUpgradePrompt = isStartOutsideRetention(from, entitledToAuditLogDays)
|
||||
|
||||
useEffect(() => {
|
||||
if (shouldShowUpgradePrompt) {
|
||||
|
||||
@@ -25,7 +25,7 @@ import {
|
||||
import { UpdateSavedQueryModal } from '@/components/interfaces/Settings/Logs/Logs.UpdateSavedQueryModal'
|
||||
import {
|
||||
checkForLimitClause,
|
||||
maybeShowUpgradePromptIfNotEntitled,
|
||||
isStartOutsideRetention,
|
||||
useEditorHints,
|
||||
} from '@/components/interfaces/Settings/Logs/Logs.utils'
|
||||
import {
|
||||
@@ -398,7 +398,7 @@ function LogsExplorerPage() {
|
||||
const handleDateChange = (value: DatePickerValue) => {
|
||||
setDatePickerValue(value)
|
||||
const resolvedRange = resolveLogDateRange(value)
|
||||
const shouldShowUpgradePrompt = maybeShowUpgradePromptIfNotEntitled(
|
||||
const shouldShowUpgradePrompt = isStartOutsideRetention(
|
||||
resolvedRange.from,
|
||||
entitledToAuditLogDays
|
||||
)
|
||||
@@ -469,7 +469,7 @@ function LogsExplorerPage() {
|
||||
// Show the prompt on page load based on query params
|
||||
useEffect(() => {
|
||||
if (timestampStart) {
|
||||
const shouldShowUpgradePrompt = maybeShowUpgradePromptIfNotEntitled(
|
||||
const shouldShowUpgradePrompt = isStartOutsideRetention(
|
||||
timestampStart,
|
||||
entitledToAuditLogDays
|
||||
)
|
||||
|
||||
@@ -40,7 +40,9 @@ describe('fillTimeseries', () => {
|
||||
const result = fillTimeseries(data, 'timestamp', 'value', 0, min, max, 20, '2m')
|
||||
|
||||
expect(result).toHaveLength(5)
|
||||
const sortedResult = result.sort((a, b) => a.timestamp.localeCompare(b.timestamp))
|
||||
const sortedResult = result.sort((a, b) =>
|
||||
String(a.timestamp).localeCompare(String(b.timestamp))
|
||||
)
|
||||
|
||||
expect(sortedResult[0]).toEqual({ timestamp: '2023-01-01T00:00:00.000Z', value: 0 })
|
||||
expect(sortedResult[1]).toEqual({ timestamp: '2023-01-01T00:01:00.000Z', value: 10 })
|
||||
@@ -57,7 +59,9 @@ describe('fillTimeseries', () => {
|
||||
const result = fillTimeseries(data, 'timestamp', ['count1', 'count2'], 5, min, max, 20, '1m')
|
||||
|
||||
expect(result).toHaveLength(3)
|
||||
const sortedResult = result.sort((a, b) => a.timestamp.localeCompare(b.timestamp))
|
||||
const sortedResult = result.sort((a, b) =>
|
||||
String(a.timestamp).localeCompare(String(b.timestamp))
|
||||
)
|
||||
|
||||
expect(sortedResult[0]).toEqual({ timestamp: '2023-01-01T00:00:00.000Z', count1: 5, count2: 5 })
|
||||
expect(sortedResult[1]).toEqual({
|
||||
@@ -191,7 +195,9 @@ describe('fillTimeseries', () => {
|
||||
const result = fillTimeseries(data, 'timestamp', 'value', 0, min, max, 20, '1m')
|
||||
|
||||
expect(result).toHaveLength(3)
|
||||
const sortedResult = result.sort((a, b) => a.timestamp.localeCompare(b.timestamp))
|
||||
const sortedResult = result.sort((a, b) =>
|
||||
String(a.timestamp).localeCompare(String(b.timestamp))
|
||||
)
|
||||
|
||||
expect(sortedResult[0]).toEqual({ timestamp: '2023-01-01T00:00:00.000Z', value: 0 })
|
||||
expect(sortedResult[1]).toEqual({ timestamp: '2023-01-01T00:01:00.000Z', value: 1 })
|
||||
|
||||
Reference in new issue
Block a user