Files
supabase/apps/studio/components/interfaces/Settings/Logs/Logs.utils.test.ts
Danny WhiteandJoshen Lim 8fcd5e7f65 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>
2026-11-19 15:08:18 +11:00

431 lines
16 KiB
TypeScript

import dayjs from 'dayjs'
import { describe, expect, test, vi } from 'vitest'
import { LogsTableName } from './Logs.constants'
import type { Filters, LogData } from './Logs.types'
import {
buildLogsPrompt,
checkForLimitClause,
ensureNoTimestampConflict,
extractEdgeFunctionName,
formatLogsAsCsv,
formatLogsAsJson,
formatLogsAsMarkdown,
genChartQuery,
genCountQuery,
genDefaultQuery,
getAuthLogSeverity,
isStartOutsideRetention,
parseMultigresEventMessage,
} from './Logs.utils'
const createLog = (overrides: Partial<LogData> = {}): LogData => ({
id: 'test-id',
timestamp: 1621323232312,
event_message: 'test message',
...overrides,
})
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' })]
const result = formatLogsAsJson(rows)
expect(result).toContain('"id": "1"')
expect(result).toContain('"event_message": "test message"')
})
test('formats multiple logs as JSON array', () => {
const rows: LogData[] = [
createLog({ id: '1', event_message: 'first' }),
createLog({ id: '2', event_message: 'second' }),
]
const result = formatLogsAsJson(rows)
expect(result).toContain('"id": "1"')
expect(result).toContain('"id": "2"')
})
})
describe('formatLogsAsCsv', () => {
test('returns empty string for empty list', () => {
expect(formatLogsAsCsv([])).toBe('')
})
test('formats single row with header line', () => {
const rows: LogData[] = [createLog({ id: '1', event_message: 'hello' })]
const result = formatLogsAsCsv(rows)
const [header, row] = result.split('\r\n')
expect(header.split(',').sort()).toEqual(['event_message', 'id', 'timestamp'].sort())
expect(row).toContain('1')
expect(row).toContain('hello')
})
test('formats multiple rows', () => {
const rows: LogData[] = [
createLog({ id: '1', event_message: 'first' }),
createLog({ id: '2', event_message: 'second' }),
]
const lines = formatLogsAsCsv(rows).split('\r\n')
expect(lines).toHaveLength(3)
expect(lines[1]).toContain('first')
expect(lines[2]).toContain('second')
})
test('escapes commas, quotes, and newlines per RFC 4180', () => {
const rows: LogData[] = [
createLog({
id: 'a,b',
event_message: 'line1\nline2',
}),
createLog({
id: 'c"d',
event_message: 'has "quotes"',
}),
]
const result = formatLogsAsCsv(rows)
expect(result).toContain('"a,b"')
expect(result).toContain('"line1\nline2"')
expect(result).toContain('"c""d"')
expect(result).toContain('"has ""quotes"""')
})
test('emits columns based on the first row', () => {
const rows: LogData[] = [
{ id: '1', event_message: 'first', timestamp: 1 },
// Extra `status` key on later rows is dropped because headers
// come from the first row.
{ id: '2', event_message: 'second', timestamp: 2, status: '500' } as LogData,
]
const result = formatLogsAsCsv(rows)
expect(result).not.toContain('500')
expect(result.split('\r\n')[0]).toBe('id,event_message,timestamp')
})
test('renders null as the string "null" and undefined as empty', () => {
const rows: LogData[] = [
{ id: '1', event_message: null as unknown as string, timestamp: undefined as any },
]
const result = formatLogsAsCsv(rows)
const dataRow = result.split('\r\n')[1]
// Order matches first-row keys: id, event_message, timestamp
expect(dataRow).toBe('1,null,')
})
})
describe('formatLogsAsMarkdown', () => {
test('formats single log with timestamp', () => {
const rows: LogData[] = [
createLog({
id: '123',
timestamp: 1621323232312,
event_message: 'Test error',
status: '500',
}),
]
const result = formatLogsAsMarkdown(rows)
expect(result).toContain('## Log 1')
expect(result).toContain('**Timestamp:**')
expect(result).toContain('**Message:** Test error')
expect(result).toContain('**Details:**')
})
test('formats multiple logs with separators', () => {
const rows: LogData[] = [
createLog({ id: '1', event_message: 'first error' }),
createLog({ id: '2', event_message: 'second error' }),
]
const result = formatLogsAsMarkdown(rows)
expect(result).toContain('## Log 1')
expect(result).toContain('## Log 2')
expect(result).toContain('---')
})
})
describe('buildLogsPrompt', () => {
test.each([
'2026-10-27T10:15:00.000000',
'2026-10-27 10:15:00.000000',
'2026-10-27T10:15:00Z',
'2026-10-27T11:15:00+01:00',
])(
'preserves the UTC log time in Assistant prompts regardless of the local timezone: %s',
(timestamp) => {
vi.stubEnv('TZ', 'Europe/Madrid')
try {
expect(new Date('2026-10-27T10:15:00').getTimezoneOffset()).toBe(-60)
const prompt = buildLogsPrompt([
{ id: 'log', timestamp, event_message: 'Function failed' },
])
expect(prompt).toContain('**Timestamp:** 2026-10-27T10:15:00.000Z')
} finally {
vi.unstubAllEnvs()
}
}
)
test('builds prompt with single log', () => {
const rows: LogData[] = [createLog({ id: '1', event_message: 'error occurred' })]
const result = buildLogsPrompt(rows)
expect(result).toContain('1 Supabase log entry')
expect(result).toContain('error occurred')
expect(result).toContain('What do these logs indicate')
expect(result).not.toContain('more matching log')
})
test('builds prompt with multiple logs', () => {
const rows: LogData[] = [
createLog({ id: '1', event_message: 'error 1' }),
createLog({ id: '2', event_message: 'error 2' }),
]
const result = buildLogsPrompt(rows)
expect(result).toContain('2 Supabase log entries')
})
test.each([
[1, '+1 more matching log entry not included.'],
[45, '+45 more matching log entries not included.'],
[1234, '+1,234 more matching log entries not included.'],
])('tells the assistant that %i matching preview logs were omitted', (omittedCount, note) => {
const rows: LogData[] = [createLog({ id: '1', event_message: 'latest error' })]
const result = buildLogsPrompt(rows, {
queryType: 'functions',
sqlQuery: 'select event_message from function_logs limit 1',
omittedCount,
})
expect(result).toContain('from the **Edge Functions** service')
expect(result).toContain('latest error')
expect(result.indexOf('latest error')).toBeLessThan(result.indexOf(note))
expect(result).toContain(note)
expect(result).toContain(
'**Query used:**\n```sql\nselect event_message from function_logs limit 1\n```'
)
})
})
describe('extractEdgeFunctionName', () => {
test('extracts function name from full pathname', () => {
expect(extractEdgeFunctionName('/functions/v1/hello-world-1')).toBe('hello-world-1')
})
test.each([null, undefined, 42, {}])(
'returns empty string for non-string value %o',
(value) => {
expect(extractEdgeFunctionName(value)).toBe('')
}
)
test('handles pathname with no slashes', () => {
expect(extractEdgeFunctionName('my-function')).toBe('my-function')
})
test('handles trailing slash', () => {
expect(extractEdgeFunctionName('/functions/v1/hello-world-1/')).toBe('hello-world-1')
})
})
describe('parseMultigresEventMessage', () => {
test('parses a JSON object event_message into a plain object', () => {
const eventMessage = JSON.stringify({
time: '2026-06-02T15:44:52.84043038Z',
level: 'ERROR',
msg: 'Failed to write heartbeat',
error: 'context deadline exceeded',
})
expect(parseMultigresEventMessage(eventMessage)).toEqual({
time: '2026-06-02T15:44:52.84043038Z',
level: 'ERROR',
msg: 'Failed to write heartbeat',
error: 'context deadline exceeded',
})
})
test('returns null when event_message is not valid JSON', () => {
expect(parseMultigresEventMessage('connection closed')).toBeNull()
})
test('returns null when event_message parses to an array', () => {
expect(parseMultigresEventMessage('[1, 2, 3]')).toBeNull()
})
test('returns null when event_message parses to a primitive', () => {
expect(parseMultigresEventMessage('42')).toBeNull()
expect(parseMultigresEventMessage('"a string"')).toBeNull()
})
test('returns null for non-string input', () => {
expect(parseMultigresEventMessage(undefined)).toBeNull()
expect(parseMultigresEventMessage(null)).toBeNull()
expect(parseMultigresEventMessage(42)).toBeNull()
})
})
describe('getAuthLogSeverity', () => {
test('reports server errors (5xx) as error', () => {
expect(getAuthLogSeverity('info', 500)).toBe('error')
expect(getAuthLogSeverity('info', 503)).toBe('error')
})
test('reports client errors (4xx) as warning', () => {
expect(getAuthLogSeverity('info', 400)).toBe('warning')
expect(getAuthLogSeverity('info', 401)).toBe('warning')
expect(getAuthLogSeverity('info', 429)).toBe('warning')
expect(getAuthLogSeverity('info', 499)).toBe('warning')
})
test('handles status passed as a string', () => {
expect(getAuthLogSeverity('info', '500')).toBe('error')
expect(getAuthLogSeverity('info', '404')).toBe('warning')
expect(getAuthLogSeverity('info', '200')).toBe('info')
})
test('preserves the original level for non-error statuses', () => {
expect(getAuthLogSeverity('info', 200)).toBe('info')
expect(getAuthLogSeverity('info', 302)).toBe('info')
expect(getAuthLogSeverity('info', 399)).toBe('info')
})
test('falls back to the level when status is missing or invalid', () => {
expect(getAuthLogSeverity('info')).toBe('info')
expect(getAuthLogSeverity('warning', null)).toBe('warning')
expect(getAuthLogSeverity('info', 'not-a-number')).toBe('info')
})
test('keeps explicit error levels even with a non-error status', () => {
expect(getAuthLogSeverity('error')).toBe('error')
expect(getAuthLogSeverity('fatal')).toBe('fatal')
expect(getAuthLogSeverity('error', 200)).toBe('error')
expect(getAuthLogSeverity('fatal', 404)).toBe('fatal')
})
test('returns an empty string when level is missing', () => {
expect(getAuthLogSeverity()).toBe('')
expect(getAuthLogSeverity(null, 200)).toBe('')
})
test('ignores non-string levels and non-numeric statuses', () => {
expect(getAuthLogSeverity({}, {})).toBe('')
expect(getAuthLogSeverity(42, 500)).toBe('error')
expect(getAuthLogSeverity('info', {})).toBe('info')
expect(getAuthLogSeverity('info', [500])).toBe('info')
})
})
describe('auth_logs severity filter query', () => {
const queryFor = (severity: Filters['severity']) =>
genDefaultQuery(LogsTableName.AUTH, { severity } as Filters, 100)
test('error severity filter matches 5xx status as well as the log level', () => {
const sql = queryFor({ error: true })
expect(sql).toContain("IFNULL(metadata.level, '') IN ('error', 'fatal')")
expect(sql).toContain('IFNULL(SAFE_CAST(metadata.status AS INT64), 0) >= 500')
})
test('warning severity filter matches 4xx status as well as the log level', () => {
const sql = queryFor({ warning: true })
expect(sql).toContain("IFNULL(metadata.level, '') = 'warning'")
expect(sql).toContain('IFNULL(SAFE_CAST(metadata.status AS INT64), 0) BETWEEN 400 AND 499')
})
test('info severity filter excludes error and warning rows', () => {
const sql = queryFor({ info: true })
expect(sql).toContain('NOT (')
})
})
describe('checkForLimitClause', () => {
test('detects a limit clause regardless of casing', () => {
expect(checkForLimitClause('select event_message from edge_logs limit 100')).toBe(true)
expect(checkForLimitClause('SELECT event_message FROM edge_logs LIMIT 5')).toBe(true)
})
test('detects a limit clause across newlines', () => {
expect(checkForLimitClause('select event_message\nfrom edge_logs\nlimit 50')).toBe(true)
})
test('returns false when no limit clause is present', () => {
expect(checkForLimitClause('select event_message from edge_logs')).toBe(false)
})
test('returns false for a bare limit keyword without a row count', () => {
expect(checkForLimitClause('select event_message from edge_logs limit')).toBe(false)
})
test('ignores a column named like limit', () => {
expect(checkForLimitClause('select limit_reached from edge_logs')).toBe(false)
})
test('ignores the word limit inside a string literal', () => {
expect(checkForLimitClause("select event_message from edge_logs where s = 'limit 10'")).toBe(
false
)
})
test('ignores a limit clause that is commented out', () => {
expect(checkForLimitClause('select event_message from edge_logs -- limit 10')).toBe(false)
})
})
describe('genChartQuery', () => {
test.each([150, '00150', '03dg2o5teb2eucxr9ggh3uie6', "opaque' OR '1'='1"])(
'reads only pipeline_id_v2 for pipeline %s in every legacy query',
(pipelineId) => {
const params = {
iso_timestamp_start: '2026-10-30T10:00:00Z',
iso_timestamp_end: '2026-10-30T11:00:00Z',
}
// Legacy links can carry numeric IDs in the JSON filters query parameter.
const filters: Filters = JSON.parse(JSON.stringify({ pipeline_id: pipelineId }))
const expectedId = String(pipelineId).replaceAll("'", "''")
for (const sql of [
genChartQuery(LogsTableName.PIPELINES, params, filters),
genDefaultQuery(LogsTableName.PIPELINES, filters),
genCountQuery(LogsTableName.PIPELINES, filters),
]) {
expect(sql).toContain('etl_replication_logs t')
expect(sql).toContain("json_value(to_json_string(t), '$.pipeline_id_v2')")
expect(sql).not.toContain('cast(t.pipeline_id as string)')
expect(sql).not.toContain('etl_replication_logs.pipeline_id')
expect(sql).not.toContain('to_json_string(etl_replication_logs)')
expect(sql).toContain(`= '${expectedId}'`)
}
}
)
// Regression: an unparseable iso_timestamp_start used to reach
// startOffset.toISOString() as an Invalid Date and throw RangeError.
test('falls back to minute buckets for an unparseable time range without throwing', () => {
const params = { iso_timestamp_start: 'not-a-date', iso_timestamp_end: 'also-bad' }
expect(() => genChartQuery(LogsTableName.AUTH, params as any, {})).not.toThrow()
expect(genChartQuery(LogsTableName.AUTH, params as any, {})).toContain(
'timestamp_trunc(t.timestamp, minute)'
)
})
})
describe('ensureNoTimestampConflict', () => {
test('does not throw for unparseable initial timestamps', () => {
expect(() =>
ensureNoTimestampConflict(['not-a-date', 'also-bad'], ['', '2024-01-01T00:00:00.000Z'])
).not.toThrow()
})
})
})