mirror of
https://github.com/supabase/supabase.git
synced 2026-09-08 19:08:44 +08:00
Second of a stack. **Stacked on #49069** — review that one first; this PR's diff only makes sense on top of it. Base will retarget to `master` automatically when #49069 merges. Net `-72` lines. No behavior change beyond the one noted at the bottom. ## The problem The query-source registry carried its own `LogTimeRange` type and `logTimeRangeSchema`, which had drifted from the notebook wire schema's copy in four ways: | | wire schema | registry | |---|---|---| | discriminant | `_tag: 'relative_time_range'` | `type: 'relative'` | | absolute bounds | `start` / `end` | `from` / `to` | | relative units | minute…year | minute, hour, day | | validation | none | positive int, end-after-start | Two definitions of one concept, neither convertible to the other without a lossy mapping — and the notebook query cell was papering over it by discarding a log cell's persisted range and substituting a default. ## What changed #49069 moved the validations onto the wire schema's `timeRangeSchema` and exported it. This PR deletes the registry's copy and points every consumer at `TimeRange`. The registry keeps what is genuinely runtime: endpoints, labels, availability, defaults. The field renames ripple mechanically through the logs date-picker helpers, the time-range submenu, `useLogsCustomRange`, the SQL editor's session state, and their tests. Coverage for the absolute-range and unit rules moved to `notebook-schema.test.ts` in #49069, alongside the schema that now owns them. `ExplorerQuerySourceMenu` also drops its hand-rolled custom-range construction in favor of `customDateRangeToLogTimeRange`, which already existed and does the same clamping. ## One behavior change `logTimeRangeToDatePickerValue` now renders a range whose unit has no picker preset (week, month, year — allowed by the wire schema, not offered in the UI) as a resolved absolute range, instead of trying and failing to build a helper for it. Previously unreachable, since the registry's narrower unit set made those ranges unrepresentable. ## Verification Typecheck, Prettier, and the lint ratchet clean. 401 tests pass across the notebook schema, query sources, the logs source components, the SQL editor, and the Explorer surfaces. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Improved log time-range handling across Explorer and SQL Editor. * Custom date ranges now display and resolve correctly, including clamping invalid ranges. * Unsupported relative time units are converted to compatible absolute date-picker values. * **Refactor** * Standardized log queries on a shared time-range format for more consistent validation and behavior. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
138 lines
4.7 KiB
TypeScript
138 lines
4.7 KiB
TypeScript
import { act, waitFor } from '@testing-library/react'
|
|
import { HttpResponse } from 'msw'
|
|
import { beforeEach, describe, expect, it } from 'vitest'
|
|
|
|
import { useLogsSqlExecution } from './useLogsSqlExecution'
|
|
import {
|
|
acceptUntrustedLogsSql,
|
|
untrustedLogSql,
|
|
type SafeLogSqlFragment,
|
|
} from '@/data/logs/safe-analytics-sql'
|
|
import { sqlEditorSessionState } from '@/state/sql-editor/sql-editor-session-state'
|
|
import { addAPIMock } from '@/tests/lib/msw'
|
|
import {
|
|
renderSqlEditorHook,
|
|
resetSqlEditorStores,
|
|
seedSnippet,
|
|
setupSqlEditorMocks,
|
|
} from '@/tests/lib/sql-editor-test-utils'
|
|
|
|
const SNIPPET_ID = 'logs-execution-snippet'
|
|
|
|
/** Promote raw text to the `SafeLogSqlFragment` the run pipeline expects, exactly
|
|
* as the toolbar/editor-panel promote it right at the user action. */
|
|
const logsSql = (text: string): SafeLogSqlFragment => acceptUntrustedLogsSql(untrustedLogSql(text))
|
|
|
|
type CapturedBody = { sql: string; iso_timestamp_start: string; iso_timestamp_end: string }
|
|
|
|
function mockLogsAllOtel(rows: unknown[] = []) {
|
|
const captured: CapturedBody[] = []
|
|
addAPIMock({
|
|
method: 'post',
|
|
path: '/platform/projects/:ref/analytics/endpoints/logs.all.otel',
|
|
response: async ({ request }) => {
|
|
const body = (await request.json()) as CapturedBody
|
|
captured.push(body)
|
|
return HttpResponse.json<any>({ result: rows })
|
|
},
|
|
})
|
|
return captured
|
|
}
|
|
|
|
/** Renders the hook with ClickHouse logs enabled by default; pass
|
|
* `{ otelLegacyLogs: false }` to exercise the not-available-yet guard. */
|
|
function renderLogsExecution(flags: Record<string, boolean> = { otelLegacyLogs: true }) {
|
|
return renderSqlEditorHook(() => useLogsSqlExecution({ id: SNIPPET_ID }), { flags })
|
|
}
|
|
|
|
beforeEach(() => {
|
|
resetSqlEditorStores()
|
|
setupSqlEditorMocks()
|
|
seedSnippet({ id: SNIPPET_ID, source: 'logs' })
|
|
})
|
|
|
|
describe('useLogsSqlExecution', () => {
|
|
it('runs a logs query and writes the result to the session store', async () => {
|
|
const rows = [{ event_message: 'hello' }]
|
|
const captured = mockLogsAllOtel(rows)
|
|
|
|
const { result } = renderLogsExecution()
|
|
|
|
act(() => {
|
|
result.current.executeLogsQuery(logsSql('select event_message from edge_logs'))
|
|
})
|
|
|
|
await waitFor(() => expect(sqlEditorSessionState.results[SNIPPET_ID]).toBeDefined())
|
|
expect(sqlEditorSessionState.results[SNIPPET_ID][0].rows).toEqual(rows)
|
|
|
|
expect(captured).toHaveLength(1)
|
|
expect(captured[0].sql).toContain('select event_message from edge_logs')
|
|
expect(captured[0].iso_timestamp_start.length).toBeGreaterThan(0)
|
|
expect(captured[0].iso_timestamp_end.length).toBeGreaterThan(0)
|
|
})
|
|
|
|
it('records a structured 200-body error on the result instead of throwing', async () => {
|
|
addAPIMock({
|
|
method: 'post',
|
|
path: '/platform/projects/:ref/analytics/endpoints/logs.all.otel',
|
|
response: async () =>
|
|
HttpResponse.json<any>({
|
|
error: {
|
|
code: 400,
|
|
errors: [{ domain: 'global', message: 'Missing column', reason: 'invalid' }],
|
|
message: 'Missing column',
|
|
status: 'INVALID_ARGUMENT',
|
|
},
|
|
}),
|
|
})
|
|
|
|
const { result } = renderLogsExecution()
|
|
|
|
act(() => {
|
|
result.current.executeLogsQuery(logsSql('select does_not_exist from edge_logs'))
|
|
})
|
|
|
|
await waitFor(() => expect(sqlEditorSessionState.results[SNIPPET_ID]?.[0]?.error).toBeDefined())
|
|
expect(sqlEditorSessionState.results[SNIPPET_ID][0].error.message).toBe('Missing column')
|
|
})
|
|
|
|
it('resolves a relative session range to a from/to window around now', async () => {
|
|
const captured = mockLogsAllOtel([])
|
|
sqlEditorSessionState.setLogRange(SNIPPET_ID, {
|
|
_tag: 'relative_time_range',
|
|
amount: 2,
|
|
unit: 'hour',
|
|
})
|
|
|
|
const { result } = renderLogsExecution()
|
|
|
|
act(() => {
|
|
result.current.executeLogsQuery(logsSql('select 1'))
|
|
})
|
|
|
|
await waitFor(() => expect(captured).toHaveLength(1))
|
|
const from = Date.parse(captured[0].iso_timestamp_start)
|
|
const to = Date.parse(captured[0].iso_timestamp_end)
|
|
expect(Number.isNaN(from)).toBe(false)
|
|
expect(Number.isNaN(to)).toBe(false)
|
|
expect(from).toBeLessThan(to)
|
|
})
|
|
|
|
it('records an unavailable message and fires no request when ClickHouse logs are off', async () => {
|
|
const captured = mockLogsAllOtel([])
|
|
|
|
const { result } = renderLogsExecution({ otelLegacyLogs: false })
|
|
|
|
act(() => {
|
|
result.current.executeLogsQuery(logsSql('select 1'))
|
|
})
|
|
|
|
await waitFor(() => expect(sqlEditorSessionState.results[SNIPPET_ID]?.[0]?.error).toBeDefined())
|
|
expect(sqlEditorSessionState.results[SNIPPET_ID][0].error.message).toBe(
|
|
"Querying logs from the SQL editor isn't available for this project yet."
|
|
)
|
|
// The doomed request never left the client.
|
|
expect(captured).toHaveLength(0)
|
|
})
|
|
})
|