Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

feat: Improved log event chart, timestamp conflict fixes, use iso timestamp only

TzeYiingb4c5c0f0998b
diff --git a/studio/components/interfaces/Settings/Logs/LogEventChart.tsx b/studio/components/interfaces/Settings/Logs/LogEventChart.tsx
index 79a680f3040..ac4e51cca10 100644
--- a/studio/components/interfaces/Settings/Logs/LogEventChart.tsx
+++ b/studio/components/interfaces/Settings/Logs/LogEventChart.tsx
@@ -1,99 +1,116 @@
import { BarChart } from 'components/to-be-cleaned/Charts/ChartRenderer'
import dayjs from 'dayjs'
-import { LogData } from '.'
+import { EventChartData, isUnixMicro, LogData, unixMicroToIsoTimestamp } from '.'
import { useMemo } from 'react'
interface Props {
- data?: LogData[]
- onBarClick: (timestamp: number) => void
+ data?: EventChartData[]
+ onBarClick: (isoTimestamp: string) => void
}
-type TimestampMap = { [timestamp: number]: number }
const LogEventChart: React.FC<Props> = ({ data, onBarClick }) => {
if (!data) return null
- const aggregated = useAggregated(data)
+ // TODO: remove once endpoint returns iso timestamp directly
+ const transformedData = useMemo(() => {
+ return data.map((d) => {
+ const iso = isUnixMicro(d.timestamp)
+ ? unixMicroToIsoTimestamp(d.timestamp)
+ : dayjs(d.timestamp).toISOString()
+
+ return {
+ ...d,
+ timestamp: iso,
+ // needed for bar chart
+ // TODO: remove once bar chart is refactored
+ period_start: iso,
+ }
+ })
+ }, [JSON.stringify(data)])
return (
<BarChart
minimalHeader
chartSize="tiny"
- data={aggregated}
+ data={transformedData}
attribute="count"
label="Events"
onBarClick={(v?: { activePayload?: { payload: any }[] }) => {
if (!v || !v?.activePayload?.[0]?.payload) return
- const timestamp = v.activePayload[0].payload.timestamp
+ const unixOrIsoTimestamp = v.activePayload[0].payload.timestamp
+ const isoTimestamp = isUnixMicro(unixOrIsoTimestamp)
+ ? unixMicroToIsoTimestamp(unixOrIsoTimestamp)
+ : unixOrIsoTimestamp
// 60s before
- onBarClick((Number(timestamp) + 60) * 1000 * 1000)
+ onBarClick(isoTimestamp)
}}
- customDateFormat="MMM D, HH:mm"
+ customDateFormat="MMM D, HH:mm:s"
noDataMessage={''}
/>
)
}
-const useAggregated = (data: LogData[]) => {
- const truncateToMinute = (micro: number) => Math.floor(micro / 1000 / 1000 / 60) * 60
- const truncateToHour = (micro: number) => Math.floor(micro / 1000 / 1000 / 60 / 60) * 60 * 60
- const getDiffMinute = (currentTimestamp: number, olderTimestamp: number) =>
- Math.round((currentTimestamp - olderTimestamp) / 1000 / 60)
- const getDiffHour = (currentTimestamp: number, olderTimestamp: number) =>
- Math.round((currentTimestamp - olderTimestamp) / 1000 / 60 / 60)
- const diffMultiplierMinute = (v: number) => v * 60
- const diffMultiplierHour = (v: number) => v * 60 * 60
- return useMemo(() => {
- const oldest = data[data.length - 1]
- if (!oldest) return
- const latest = data[0]
- const oldestDayjs = dayjs(oldest.timestamp / 1000)
- const latestDayjs = dayjs(latest.timestamp / 1000)
- let truncFunc = truncateToMinute
- let getDiff = getDiffMinute
- let diffMultiplier = diffMultiplierMinute
- if (Math.abs(oldestDayjs.diff(latestDayjs, 'day', true)) > 0.25) {
- truncFunc = truncateToHour
- getDiff = getDiffHour
- diffMultiplier = diffMultiplierHour
- }
+// const useAggregated = (data: LogData[]) => {
+// const truncateToMinute = (micro: number) => Math.floor(micro / 1000 / 1000 / 60) * 60
+// const truncateToHour = (micro: number) => Math.floor(micro / 1000 / 1000 / 60 / 60) * 60 * 60
+// const getDiffMinute = (currentTimestamp: number, olderTimestamp: number) =>
+// Math.round((currentTimestamp - olderTimestamp) / 1000 / 60)
+// const getDiffHour = (currentTimestamp: number, olderTimestamp: number) =>
+// Math.round((currentTimestamp - olderTimestamp) / 1000 / 60 / 60)
+// const diffMultiplierMinute = (v: number) => v * 60
+// const diffMultiplierHour = (v: number) => v * 60 * 60
+// return useMemo(() => {
+// const oldest = data[data.length - 1]
+// if (!oldest) return
+// const latest = data[0]
+// const oldestDayjs = dayjs(oldest.timestamp / 1000)
+// const latestDayjs = dayjs(latest.timestamp / 1000)
+// let truncFunc = truncateToMinute
+// let getDiff = getDiffMinute
+// let diffMultiplier = diffMultiplierMinute
+// if (Math.abs(oldestDayjs.diff(latestDayjs, 'day', true)) > 0.25) {
+// truncFunc = truncateToHour
+// getDiff = getDiffHour
+// diffMultiplier = diffMultiplierHour
+// }
- const countMap = data
- .map((d) => {
- // truncate to per-minute
- return { ...d, timestamp: truncateToMinute(d.timestamp) }
- })
- .reduce((acc, d) => {
- if (acc[d.timestamp]) {
- acc[d.timestamp] = acc[d.timestamp] + 1
- } else {
- acc[d.timestamp] = 1
- }
- return acc
- }, {} as TimestampMap)
+// const countMap = data
+// .map((d) => {
+// // truncate to per-minute
+// return { ...d, timestamp: truncateToMinute(d.timestamp) }
+// })
+// .reduce((acc, d) => {
+// if (acc[d.timestamp]) {
+// acc[d.timestamp] = acc[d.timestamp] + 1
+// } else {
+// acc[d.timestamp] = 1
+// }
+// return acc
+// }, {} as TimestampMap)
- // Add in additional data points for empty minutes
- const oldestEvent = data[data.length - 1]
- if (!oldestEvent) return []
- const currentTimestamp = new Date().getTime()
- const oldestTimestampMicro = oldestEvent.timestamp
- const latestTimestamp = truncFunc(data[0]['timestamp'])
- const diff = getDiff(currentTimestamp, oldestTimestampMicro / 1000)
- for (const toAdd of Array.from(Array(diff).keys())) {
- const tsToCheck = truncFunc(oldestTimestampMicro) + diffMultiplier(toAdd)
- if (!(tsToCheck in countMap) && tsToCheck <= latestTimestamp) {
- countMap[tsToCheck] = 0
- }
- }
+// // Add in additional data points for empty minutes
+// const oldestEvent = data[data.length - 1]
+// if (!oldestEvent) return []
+// const currentTimestamp = new Date().getTime()
+// const oldestTimestampMicro = oldestEvent.timestamp
+// const latestTimestamp = truncFunc(data[0]['timestamp'])
+// const diff = getDiff(currentTimestamp, oldestTimestampMicro / 1000)
+// for (const toAdd of Array.from(Array(diff).keys())) {
+// const tsToCheck = truncFunc(oldestTimestampMicro) + diffMultiplier(toAdd)
+// if (!(tsToCheck in countMap) && tsToCheck <= latestTimestamp) {
+// countMap[tsToCheck] = 0
+// }
+// }
- let aggregated = []
- for (const [key, value] of Object.entries(countMap)) {
- const v: number = Number(key)
- aggregated.push({
- timestamp: key,
- timestampMicro: v * 1000 * 1000,
- count: value,
- })
- }
- return aggregated.sort((a, b) => a.timestampMicro - b.timestampMicro)
- }, [JSON.stringify(data)])
-}
+// let aggregated = []
+// for (const [key, value] of Object.entries(countMap)) {
+// const v: number = Number(key)
+// aggregated.push({
+// timestamp: key,
+// timestampMicro: v * 1000 * 1000,
+// count: value,
+// })
+// }
+// return aggregated.sort((a, b) => a.timestampMicro - b.timestampMicro)
+// }, [JSON.stringify(data)])
+// }
export default LogEventChart
diff --git a/studio/components/interfaces/Settings/Logs/Logs.constants.ts b/studio/components/interfaces/Settings/Logs/Logs.constants.ts
index aa915d032d2..9f1f791f8fa 100644
--- a/studio/components/interfaces/Settings/Logs/Logs.constants.ts
+++ b/studio/components/interfaces/Settings/Logs/Logs.constants.ts
@@ -254,7 +254,7 @@ export const LOGS_TABLES = {
functions: LogsTableName.FUNCTIONS,
fn_edge: LogsTableName.FN_EDGE,
auth: LogsTableName.AUTH,
- realtime: LogsTableName.REALTIME
+ realtime: LogsTableName.REALTIME,
}
export const LOGS_SOURCE_DESCRIPTION = {
@@ -266,8 +266,6 @@ export const LOGS_SOURCE_DESCRIPTION = {
[LogsTableName.REALTIME]: 'Realtime server for Postgres logical replication broadcasting',
}
-export const genCountQuery = (table: string): string => `SELECT count(*) as count FROM ${table}`
-
export const genQueryParams = (params: { [k: string]: string }) => {
// remove keys which are empty strings, null, or undefined
for (const k in params) {
diff --git a/studio/components/interfaces/Settings/Logs/Logs.types.ts b/studio/components/interfaces/Settings/Logs/Logs.types.ts
index 7e5280a45a8..d99a3d214b1 100644
--- a/studio/components/interfaces/Settings/Logs/Logs.types.ts
+++ b/studio/components/interfaces/Settings/Logs/Logs.types.ts
@@ -7,9 +7,13 @@ interface Metadata {
export type DatePickerToFrom = { to: string | null; from: string | null }
export type LogSearchCallback = (
+ event:
+ | 'search-input-change'
+ | 'event-chart-bar-click'
+ | 'datepicker-change',
filters: {
- query: string
- } & DatePickerToFrom
+ query?: string
+ } & Partial<DatePickerToFrom>
) => void
export interface LogsWarning {
@@ -48,6 +52,11 @@ export interface CountData {
count: number
}
+export interface EventChartData {
+ count: number
+ timestamp: string | number
+}
+
type LFResponse<T> = {
result: T[]
error?: {
@@ -63,9 +72,10 @@ type LFResponse<T> = {
}
type ApiError = string
-export type LogQueryError = Omit<LFResponse<unknown>, "result"> | ApiError
+export type LogQueryError = Omit<LFResponse<unknown>, 'result'> | ApiError
export type Count = LFResponse<CountData>
+export type EventChart = LFResponse<EventChartData>
export type Logs = LFResponse<LogData>
diff --git a/studio/components/interfaces/Settings/Logs/Logs.utils.ts b/studio/components/interfaces/Settings/Logs/Logs.utils.ts
index 95a373b8f8a..2c2f2f58200 100644
--- a/studio/components/interfaces/Settings/Logs/Logs.utils.ts
+++ b/studio/components/interfaces/Settings/Logs/Logs.utils.ts
@@ -1,5 +1,5 @@
-import { Filters, LogData, LogsTableName, SQL_FILTER_TEMPLATES } from '.'
-import dayjs from 'dayjs'
+import { Filters, LogData, LogsEndpointParams, LogsTableName, SQL_FILTER_TEMPLATES } from '.'
+import dayjs, { Dayjs } from 'dayjs'
import { get } from 'lodash'
/**
@@ -164,4 +164,74 @@ export const genDefaultQuery = (table: LogsTableName, filters: Filters) => {
/**
* SQL query to retrieve only one log
*/
-export const genSingleLogQuery = (table: LogsTableName, id: string) => `select id, timestamp, event_message, metadata from ${table} where id = '${id}' limit 1`
\ No newline at end of file
+export const genSingleLogQuery = (table: LogsTableName, id: string) =>
+ `select id, timestamp, event_message, metadata from ${table} where id = '${id}' limit 1`
+
+export const genCountQuery = (table: string): string => `SELECT count(*) as count FROM ${table}`
+
+/** calculates how much the chart start datetime should be offset given the current datetime filter params */
+export const calcChartStart = (params: Partial<LogsEndpointParams>): [Dayjs, string] => {
+ const ite = params.iso_timestamp_end ? dayjs(params.iso_timestamp_end) : dayjs()
+ const its = params.iso_timestamp_start ? dayjs(params.iso_timestamp_start) : dayjs()
+ let trunc = 'minute'
+ let extendValue = 60 * 6
+ const minuteDiff = ite.diff(its, 'minute')
+ const hourDiff = ite.diff(its, 'hour')
+ if (minuteDiff > (60 * 12)) {
+ trunc = 'hour'
+ extendValue = 24 * 3
+ } else if (hourDiff > 24 * 5) {
+ trunc = 'day'
+ extendValue = 7
+ }
+ return [its.add(-extendValue, trunc), trunc]
+}
+
+/**
+ *
+ * generates log event chart query
+ */
+export const genChartQuery = (
+ table: LogsTableName,
+ params: LogsEndpointParams,
+ filters: Filters
+) => {
+ const [startOffset, trunc] = calcChartStart(params)
+ const where = _genWhereStatement(table, filters)
+ return `
+SELECT
+ timestamp_trunc(t.timestamp, ${trunc}) as timestamp,
+ count(timestamp) as count
+FROM
+ ${table} t
+${where ? where + ` and t.timestamp > '${startOffset.toISOString()}'` : ""}
+GROUP BY
+timestamp
+ORDER BY
+ timestamp ASC
+ `
+}
+
+
+type TsPair = [string | '', string | '']
+export const ensureNoTimestampConflict = ([initialStart, initialEnd]: TsPair, [nextStart, nextEnd]: TsPair): TsPair => {
+ if (initialStart && initialEnd && nextEnd && !nextStart) {
+ const resolvedDiff = dayjs(nextEnd).diff(dayjs(initialStart))
+ let start = dayjs(initialStart)
+
+ if (resolvedDiff <= 0) {
+ // start ts is definitely before end ts
+ const currDiff = Math.abs(
+ dayjs(initialEnd).diff(start, 'minute')
+ )
+ // shift start ts backwards by the current ts difference
+ start = dayjs(nextEnd).subtract(currDiff, 'minute')
+ }
+ return [start.toISOString(), nextEnd]
+ } else if (!nextEnd && nextStart) {
+ return [nextStart, initialEnd]
+ } else {
+ return [nextStart, nextEnd]
+ }
+
+}
\ No newline at end of file
diff --git a/studio/components/interfaces/Settings/Logs/LogsPreviewer.tsx b/studio/components/interfaces/Settings/Logs/LogsPreviewer.tsx
index a972f28d9c1..14b8880ff19 100644
--- a/studio/components/interfaces/Settings/Logs/LogsPreviewer.tsx
+++ b/studio/components/interfaces/Settings/Logs/LogsPreviewer.tsx
@@ -11,7 +11,7 @@ import {
QueryType,
LogEventChart,
Filters,
- unixMicroToIsoTimestamp,
+ ensureNoTimestampConflict,
} from 'components/interfaces/Settings/Logs'
import useLogsPreview from 'hooks/analytics/useLogsPreview'
import PreviewFilterPanel from 'components/interfaces/Settings/Logs/PreviewFilterPanel'
@@ -52,7 +52,7 @@ export const LogsPreviewer: React.FC<Props> = ({
const table = !tableName ? LOGS_TABLES[queryType] : tableName
const [
- { error, logData, params, newCount, filters, isLoading },
+ { error, logData, params, newCount, filters, isLoading, eventChartData },
{ loadOlder, setFilters, refresh, setParams },
] = useLogsPreview(projectRef as string, table, filterOverride)
@@ -83,24 +83,48 @@ export const LogsPreviewer: React.FC<Props> = ({
},
})
}
-
- const handleSearch: LogSearchCallback = async ({ query = '', to, from }) => {
- setParams((prev) => ({
- ...prev,
- iso_timestamp_start: from || prev.iso_timestamp_start || '',
- iso_timestamp_end: to || prev.iso_timestamp_end || '',
- }))
- setFilters((prev) => ({ ...prev, search_query: query }))
- router.push({
- pathname: router.pathname,
- query: {
- ...router.query,
- s: query || '',
- its: from || its || '',
- ite: to || ite || '',
- },
- })
+ const handleSearch: LogSearchCallback = async (event, { query, to, from }) => {
+ if (event === 'search-input-change') {
+ setFilters((prev) => ({ ...prev, search_query: query }))
+ router.push({
+ pathname: router.pathname,
+ query: { ...router.query, s: query },
+ })
+ } else if (event === 'event-chart-bar-click') {
+ const [nextStart, nextEnd] = ensureNoTimestampConflict(
+ [params.iso_timestamp_start || '', params.iso_timestamp_end || ''],
+ [from || '', to || '']
+ )
+ setParams((prev) => ({
+ ...prev,
+ iso_timestamp_start: nextStart,
+ iso_timestamp_end: nextEnd,
+ }))
+ router.push({
+ pathname: router.pathname,
+ query: {
+ ...router.query,
+ its: nextStart,
+ ite: nextEnd,
+ },
+ })
+ } else if (event === 'datepicker-change') {
+ setParams((prev) => ({
+ ...prev,
+ iso_timestamp_start: from || '',
+ iso_timestamp_end: to || '',
+ }))
+ router.push({
+ pathname: router.pathname,
+ query: {
+ ...router.query,
+ its: from || '',
+ ite: to || '',
+ },
+ })
+ }
}
+
return (
<div className="h-full flex flex-col flex-grow">
<PreviewFilterPanel
@@ -143,10 +167,13 @@ export const LogsPreviewer: React.FC<Props> = ({
<div className={condensedLayout ? 'px-4' : ''}>
{showChart && (
<LogEventChart
- data={!isLoading ? logData : undefined}
- onBarClick={(timestampMicro) => {
- const to = unixMicroToIsoTimestamp(timestampMicro)
- handleSearch({ query: filters.search_query as string, to, from: null })
+ data={!isLoading && eventChartData ? eventChartData : undefined}
+ onBarClick={(isoTimestamp) => {
+ handleSearch('event-chart-bar-click', {
+ query: filters.search_query as string,
+ to: isoTimestamp as string,
+ from: null,
+ })
}}
/>
)}
diff --git a/studio/components/interfaces/Settings/Logs/PreviewFilterPanel.tsx b/studio/components/interfaces/Settings/Logs/PreviewFilterPanel.tsx
index 68867800ec9..52e670b762d 100644
--- a/studio/components/interfaces/Settings/Logs/PreviewFilterPanel.tsx
+++ b/studio/components/interfaces/Settings/Logs/PreviewFilterPanel.tsx
@@ -97,8 +97,10 @@ const PreviewFilterPanel: FC<Props> = ({
Refresh
</Button>
)
- const handleSearch = (partial: Partial<Parameters<LogSearchCallback>[0]>) =>
- onSearch({ query: search, to: partial?.to || null, from: partial?.from || null })
+ const handleDatepickerChange = ({ to, from }: Partial<Parameters<LogSearchCallback>[1]>) => {
+ onSearch('datepicker-change', { to, from })
+ }
+ const handleInputSearch = (query: string) => onSearch('search-input-change', { query })
return (
<div
@@ -110,7 +112,7 @@ const PreviewFilterPanel: FC<Props> = ({
onSubmit={(e) => {
// prevent redirection
e.preventDefault()
- handleSearch({})
+ handleInputSearch(search)
}}
>
<Input
@@ -120,7 +122,7 @@ const PreviewFilterPanel: FC<Props> = ({
onChange={(e) => setSearch(e.target.value)}
onBlur={(e: React.FocusEvent<HTMLInputElement>) => {
setSearch(e.target.value)
- handleSearch({ query: e.target.value })
+ handleInputSearch(e.target.value)
}}
icon={
<div className="text-scale-900">
@@ -131,7 +133,7 @@ const PreviewFilterPanel: FC<Props> = ({
actions={
hasEdits && (
<button
- onClick={() => handleSearch({})}
+ onClick={() => handleInputSearch(search)}
className="text-scale-1100 hover:text-scale-1200 mx-2"
>
{'↲'}
@@ -142,7 +144,7 @@ const PreviewFilterPanel: FC<Props> = ({
</form>
<DatePickers
- onChange={handleSearch}
+ onChange={handleDatepickerChange}
to={defaultToValue}
from={defaultFromValue}
helpers={PREVIEWER_DATEPICKER_HELPERS}
diff --git a/studio/hooks/analytics/useLogsPreview.tsx b/studio/hooks/analytics/useLogsPreview.tsx
index d22fa934c6c..b31575e956b 100644
--- a/studio/hooks/analytics/useLogsPreview.tsx
+++ b/studio/hooks/analytics/useLogsPreview.tsx
@@ -1,6 +1,9 @@
import {
Count,
+ EventChart,
+ EventChartData,
Filters,
+ genChartQuery,
genCountQuery,
genDefaultQuery,
genQueryParams,
@@ -27,6 +30,7 @@ interface Data {
filters: Filters
params: LogsEndpointParams
oldestTimestamp?: string
+ eventChartData: EventChartData[] | null
}
interface Handlers {
loadOlder: () => void
@@ -116,11 +120,40 @@ function useLogsPreview(
})
const newCount = countData?.result?.[0]?.count ?? 0
+ // chart data
+
+ const chartQuery = genChartQuery(table, params, filters)
+ const chartUrl = () => {
+ // cancel request if no sql provided
+ if (!params.sql) {
+ // return null to restrict unnecessary requests to api
+ // https://swr.vercel.app/docs/conditional-fetching#conditional
+ return null
+ }
+
+ return `${API_URL}/projects/${projectRef}/analytics/endpoints/logs.all?${genQueryParams({
+ iso_timestamp_end: params.iso_timestamp_end,
+ project: params.project,
+ sql: chartQuery,
+ } as any)}`
+ }
+
+ const { data: eventChartResponse, mutate: refreshEventChart } = useSWR<EventChart>(
+ chartUrl,
+ get,
+ {
+ revalidateOnFocus: false,
+ dedupingInterval: 10000,
+ refreshInterval: 0,
+ }
+ )
+
const refresh = async () => {
const generatedSql = genDefaultQuery(table, filters)
setParams((prev) => ({ ...prev, sql: generatedSql }))
setLatestRefresh(new Date().toISOString())
setSize(1)
+ refreshEventChart()
}
let error: null | string | object = swrError ? swrError.message : null
@@ -155,6 +188,7 @@ function useLogsPreview(
filters,
params,
oldestTimestamp: oldestTimestamp ? String(oldestTimestamp) : undefined,
+ eventChartData: eventChartResponse?.result || null,
},
{
setFilters: handleSetFilters,
diff --git a/studio/tests/pages/projects/Logs.utils.test.js b/studio/tests/pages/projects/Logs.utils.test.js
index eb3d0a56fe1..1b4f66eee48 100644
--- a/studio/tests/pages/projects/Logs.utils.test.js
+++ b/studio/tests/pages/projects/Logs.utils.test.js
@@ -1,8 +1,11 @@
import {
+ ensureNoTimestampConflict,
+ genChartQuery,
genDefaultQuery,
LogsTableName,
SQL_FILTER_TEMPLATES,
} from 'components/interfaces/Settings/Logs'
+import dayjs from 'dayjs'
describe.each(Object.values(LogsTableName))('%s', (table) => {
const templates = SQL_FILTER_TEMPLATES[table]
@@ -60,5 +63,38 @@ describe.each(Object.values(LogsTableName))('%s', (table) => {
contains.forEach((str) => expect(generated).toContain(str))
excludes.forEach((str) => expect(generated).not.toContain(str))
})
+ test('generated chart query should include filters', () => {
+ const generated = genChartQuery(table, {}, { 'override.nested': 'something' })
+ expect(generated).toContain('override.nested')
+ expect(generated).toContain('something')
+ expect(generated).toContain('timestamp_trunc')
+ })
})
})
+
+const base = dayjs().subtract(2, 'day')
+const baseIso = base.toISOString()
+test.each([
+ {
+ case: 'next start is after initial start',
+ initial: [base.subtract(1, 'day').toISOString(), baseIso],
+ next: [base.subtract(2, 'day').toISOString(), null],
+ expected: [base.subtract(2, 'day').toISOString(), baseIso],
+ },
+ {
+ case: 'next end is before initial start',
+ initial: [base.subtract(1, 'day').toISOString(), baseIso],
+ next: [null, base.subtract(2, 'day').toISOString()],
+ expected: [base.subtract(3, 'day').toISOString(), base.subtract(2, 'day').toISOString()],
+ },
+ {
+ case: 'next end is not before initial start',
+ initial: [base.subtract(2, 'day').toISOString(), baseIso],
+ next: [null, base.subtract(1, 'day').toISOString()],
+ expected: [base.subtract(2, 'day').toISOString(), base.subtract(1, 'day').toISOString()],
+ },
+])('ensure no timestamp conflict: $case', ({ initial, next, expected }) => {
+ const result = ensureNoTimestampConflict(initial, next)
+ expect(result[0]).toEqual(expected[0])
+ expect(result[1]).toEqual(expected[1])
+})
diff --git a/studio/tests/pages/projects/LogsPreviewer.test.js b/studio/tests/pages/projects/LogsPreviewer.test.js
index 0eac35647b3..58f187e7403 100644
--- a/studio/tests/pages/projects/LogsPreviewer.test.js
+++ b/studio/tests/pages/projects/LogsPreviewer.test.js
@@ -193,6 +193,21 @@ test('poll count for new messages', async () => {
await waitFor(() => screen.queryByText(/125/) === null)
await screen.findByText(/some-uuid123/)
})
+test('log event chart', async () => {
+ get.mockImplementation((url) => {
+ // truncate
+ if (url.includes('trunc')) {
+ return { result: [{ timestamp: new Date().toISOString(), count: 125 }] }
+ }
+ return {
+ result: [logDataFixture({ id: 'some-uuid123' })],
+ }
+ })
+ render(<LogsPreviewer projectRef="123" tableName={LogsTableName.EDGE} />)
+
+ await waitFor(() => screen.queryByText(/some-uuid123/) === null)
+ expect(get).toBeCalledWith(expect.stringContaining('trunc'))
+})
test('s= query param will populate the search bar', async () => {
const router = defaultRouterMock()
@@ -289,6 +304,9 @@ test('bug: load older btn does not error out when previous page is empty', async
})
test('log event chart hide', async () => {
+ get.mockImplementation((url) => {
+ return { result: [] }
+ })
render(<LogsPreviewer projectRef="123" tableName={LogsTableName.EDGE} />)
await screen.findByText('Events')
const toggle = await screen.findByText(/Chart/)