Skip to content

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

Adds infinite-scroll log pagination, with feature flag

TzeYiing937bb292afcf
diff --git a/studio/pages/project/[ref]/settings/logs/[type].tsx b/studio/pages/project/[ref]/settings/logs/[type].tsx
index ea65f2bcb66..c8f137679d1 100644
--- a/studio/pages/project/[ref]/settings/logs/[type].tsx
+++ b/studio/pages/project/[ref]/settings/logs/[type].tsx
@@ -1,10 +1,10 @@
-import useSWR from 'swr'
+import useSWR, { KeyLoader } from 'swr'
import debounce from 'lodash/debounce'
import { useEffect, useRef, useState } from 'react'
import { NextPage } from 'next'
import { useRouter } from 'next/router'
import { observer } from 'mobx-react-lite'
-import { Typography, IconLoader, IconAlertCircle } from '@supabase/ui'
+import { Typography, IconLoader, IconAlertCircle, IconRewind, Button } from '@supabase/ui'
import { withAuth } from 'hooks'
import { get } from 'lib/common/fetch'
@@ -18,11 +18,17 @@ import {
Logs,
LogTemplate,
TEMPLATES,
+ LogData,
} from 'components/interfaces/Settings/Logs'
import { uuidv4 } from 'lib/helpers'
+import useSWRInfinite from 'swr/infinite'
+import { isUndefined } from 'lodash'
+import Flag from 'components/ui/Flag/Flag'
/**
* Acts as a container component for the entire log display
+ *
+ *
*/
export const LogPage: NextPage = () => {
const router = useRouter()
@@ -34,27 +40,76 @@ export const LogPage: NextPage = () => {
const [where, setWhere] = useState<string>('')
const [mode, setMode] = useState<'simple' | 'custom'>('simple')
const [latestRefresh, setLatestRefresh] = useState<string>(new Date().toISOString())
-
+ const [params, setParams] = useState({
+ type: '',
+ search_query: '',
+ where: '',
+ timestamp_start: '',
+ timestamp_end: '',
+ })
const title = `Logs - ${LOG_TYPE_LABEL_MAPPING[type as string]}`
const debouncedQueryParams = useRef(debounce(setQueryParams, 600)).current
useEffect(() => {
- const params = {
- type: type as string,
- search_query: search || '',
- where: mode === 'custom' ? where || '' : '',
- }
- const qs = new URLSearchParams(params).toString()
+ const qs = genQueryParams(params)
debouncedQueryParams(qs)
return () => debouncedQueryParams.cancel()
}, [mode, search, where, type])
+ const genQueryParams = (params: { [k: string]: string }) => {
+ // remove keys which are empty strings, null, or undefined
+ for (const k in params) {
+ const v = params[k]
+ if (v === null || v === '' || isUndefined(v)) {
+ delete params[k]
+ }
+ }
+ const qs = new URLSearchParams(params).toString()
+ return qs
+ }
// handle log fetching
- const logUrl = `${API_URL}/projects/${ref}/logs?${queryParams}`
- const { data, isValidating, mutate } = useSWR<Logs>(logUrl, get, { revalidateOnFocus: false })
- const { data: logData, error } = data || {}
+ const getKeyLogs: KeyLoader<Logs> = (_pageIndex: number, prevPageData) => {
+ let queryParams
+ // if prev page data is 100 items, could possibly have more records that are not yet fetched within this interval
+ if (prevPageData === null) {
+ // reduce interval window limit by using the timestamp of the last log
+ queryParams = genQueryParams(params)
+ } else {
+ const len = prevPageData.data.length
+ const { timestamp: tsLimit }: LogData = prevPageData.data[len - 1]
+ // create new key from params
+ queryParams = genQueryParams({ ...params, timestamp_end: String(tsLimit) })
+ }
- const countUrl = `${API_URL}/projects/${ref}/logs?${queryParams}&count=true&period_start=${latestRefresh}`
+ const logUrl = `${API_URL}/projects/${ref}/logs?${queryParams}`
+ return logUrl
+ }
+ const {
+ data = [],
+ isValidating,
+ mutate,
+ size,
+ setSize,
+ } = useSWRInfinite<Logs>(getKeyLogs, get, { revalidateOnFocus: false })
+
+ // const { data, isValidating, mutate } = useSWR<Logs>(logUrl, get, { revalidateOnFocus: false })
+ let logData: LogData[] = []
+ let error: null | string = null
+
+ data.forEach((response: Logs) => {
+ if (response && response.data) {
+ logData = [...logData, ...response.data]
+ }
+ if (!error && response && response.error) {
+ error = response.error
+ }
+ })
+
+ const countUrl = `${API_URL}/projects/${ref}/logs?${genQueryParams({
+ ...params,
+ count: String(true),
+ period_start: String(latestRefresh),
+ })}`
const { data: countData } = useSWR<Count>(countUrl, get, { refreshInterval: 5000 })
const newCount = countData?.data?.[0]?.count ?? 0
@@ -135,6 +190,19 @@ export const LogPage: NextPage = () => {
</div>
)}
<LogTable data={logData} isCustomQuery={mode === 'custom'} />
+ {/* Footer section of log ui, appears below table */}
+ <div className="p-2">
+ <Flag name="logsLoadOlder">
+ <Button
+ // trigger page increase
+ onClick={() => setSize(size + 1)}
+ icon={<IconRewind />}
+ type="secondary"
+ >
+ Load older
+ </Button>
+ </Flag>
+ </div>
</div>
</div>
</SettingsLayout>
diff --git a/studio/tests/pages/projects/logs.test.js b/studio/tests/pages/projects/logs.test.js
index 7976d40f8e3..4310b329698 100644
--- a/studio/tests/pages/projects/logs.test.js
+++ b/studio/tests/pages/projects/logs.test.js
@@ -4,33 +4,33 @@ import { get } from 'lib/common/fetch'
// mock the settings layout
jest.mock('components/layouts', () => ({
- SettingsLayout: jest.fn()
- .mockImplementation(({ children }) => <div>{children}</div>)
+ SettingsLayout: jest.fn().mockImplementation(({ children }) => <div>{children}</div>),
}))
// mock mobx
jest.mock('mobx-react-lite')
import { observer } from 'mobx-react-lite'
-observer.mockImplementation(v => v)
+observer.mockImplementation((v) => v)
// mock the router
jest.mock('next/router')
import { useRouter } from 'next/router'
-useRouter.mockReturnValue({ query: { ref: "123", type: "auth" } })
+useRouter.mockReturnValue({ query: { ref: '123', type: 'auth' } })
// mock monaco editor
-jest.mock("@monaco-editor/react")
-import Editor, { useMonaco } from "@monaco-editor/react"
+jest.mock('@monaco-editor/react')
+import Editor, { useMonaco } from '@monaco-editor/react'
Editor = jest.fn()
Editor.mockImplementation((props) => {
return (
- <textarea
- className="monaco-editor"
- onChange={e => props.onChange(e.target.value)}
- ></textarea>
+ <textarea className="monaco-editor" onChange={(e) => props.onChange(e.target.value)}></textarea>
)
})
-useMonaco.mockImplementation(v => v)
+useMonaco.mockImplementation((v) => v)
+
+jest.mock('components/ui/Flag/Flag')
+import Flag from 'components/ui/Flag/Flag'
+Flag.mockImplementation(({ children }) => <>{children}</>)
import { LogPage } from 'pages/project/[ref]/settings/logs/[type]'
import { render, fireEvent, waitFor, screen } from '@testing-library/react'
@@ -40,14 +40,16 @@ beforeEach(() => {
get.mockReset()
})
test('can display log data and metadata', async () => {
- const data = [{
- id: "seome-uuid",
- timestamp: 1621323232312,
- event_message: "some event happened",
- metadata: {
- my_key: "something_value"
- }
- }]
+ const data = [
+ {
+ id: 'seome-uuid',
+ timestamp: 1621323232312,
+ event_message: 'some event happened',
+ metadata: {
+ my_key: 'something_value',
+ },
+ },
+ ]
get.mockResolvedValue({ data })
render(<LogPage />)
@@ -59,15 +61,16 @@ test('can display log data and metadata', async () => {
})
test('Refresh', async () => {
-
- const data = [{
- id: "some-uuid",
- timestamp: 1621323232312,
- event_message: "some event happened",
- metadata: {
- my_key: "something_value"
- }
- }]
+ const data = [
+ {
+ id: 'some-uuid',
+ timestamp: 1621323232312,
+ event_message: 'some event happened',
+ metadata: {
+ my_key: 'something_value',
+ },
+ },
+ ]
get.mockResolvedValueOnce({ data }).mockResolvedValueOnce({ data: [] })
render(<LogPage />)
@@ -82,50 +85,53 @@ test('Refresh', async () => {
await waitFor(() => screen.queryByText(/happened/) === null, { timeout: 1000 })
})
-
-test("Search will trigger a log refresh", async () => {
+test('Search will trigger a log refresh', async () => {
get.mockImplementation((url) => {
-
- if (url.includes("search_query") && url.includes("something")) {
+ if (url.includes('search_query') && url.includes('something')) {
return {
- data: [{
- id: "some-uuid",
- timestamp: 1621323232312,
- event_message: "some event happened",
- metadata: {}
- }]
+ data: [
+ {
+ id: 'some-uuid',
+ timestamp: 1621323232312,
+ event_message: 'some event happened',
+ metadata: {},
+ },
+ ],
}
}
return { data: [] }
})
render(<LogPage />)
- userEvent.type(screen.getByPlaceholderText(/Filter/), "something")
- await waitFor(() => {
- expect(get).toHaveBeenCalledWith(expect.stringContaining("search_query"))
- expect(get).toHaveBeenCalledWith(expect.stringContaining("something"))
- }, { timeout: 1500 })
+ userEvent.type(screen.getByPlaceholderText(/Filter/), 'something')
+ await waitFor(
+ () => {
+ expect(get).toHaveBeenCalledWith(expect.stringContaining('search_query'))
+ expect(get).toHaveBeenCalledWith(expect.stringContaining('something'))
+ },
+ { timeout: 1500 }
+ )
await waitFor(() => screen.getByText(/happened/), { timeout: 1000 })
})
-test("poll count for new messages", async () => {
+test('poll count for new messages', async () => {
get.mockImplementation((url) => {
- if (url.includes("count")) {
+ if (url.includes('count')) {
return { data: [{ count: 3 }] }
}
return {
- data: [{
- id: "some-uuid",
- timestamp: 1621323232312,
- event_message: "some event happened",
- metadata: {}
- }]
+ data: [
+ {
+ id: 'some-uuid',
+ timestamp: 1621323232312,
+ event_message: 'some event happened',
+ metadata: {},
+ },
+ ],
}
})
- render(
- <LogPage />
- )
+ render(<LogPage />)
await waitFor(() => screen.queryByText(/happened/) === null)
await waitFor(() => screen.getByText(/Load new logs/))
@@ -134,39 +140,45 @@ test("poll count for new messages", async () => {
await waitFor(() => screen.getByText(/happened/))
})
-
-test("where clause will trigger a log refresh", async () => {
+test('where clause will trigger a log refresh', async () => {
get.mockImplementation((url) => {
-
- if (url.includes("where") && url.includes("something")) {
+ if (url.includes('where') && url.includes('something')) {
return {
- data: [{
- id: "some-uuid",
- timestamp: 1621323232312,
- event_message: "some event happened",
- metadata: {}
- }]
+ data: [
+ {
+ id: 'some-uuid',
+ timestamp: 1621323232312,
+ event_message: 'some event happened',
+ metadata: {},
+ },
+ ],
}
}
return { data: [] }
})
const { container } = render(<LogPage />)
- let editor = container.querySelector('.monaco-editor');
+ let editor = container.querySelector('.monaco-editor')
expect(editor).toBeFalsy()
- userEvent.click(screen.getByText("Custom query"))
- editor = container.querySelector('.monaco-editor');
- userEvent.type(editor, "metadata.field = something")
- await waitFor(() => {
- expect(get).toHaveBeenCalledWith(expect.stringContaining("where"))
- expect(get).toHaveBeenCalledWith(expect.stringContaining("metadata.field"))
- }, { timeout: 1000 })
+ userEvent.click(screen.getByText('Custom query'))
+ editor = container.querySelector('.monaco-editor')
+ userEvent.type(editor, 'metadata.field = something')
+ await waitFor(
+ () => {
+ expect(get).toHaveBeenCalledWith(expect.stringContaining('where'))
+ expect(get).toHaveBeenCalledWith(expect.stringContaining('metadata.field'))
+ },
+ { timeout: 1000 }
+ )
await waitFor(() => screen.getByText(/happened/))
})
test('load older btn will fetch older logs', async () => {
- get
- .mockResolvedValueOnce({
+ get.mockImplementation((url) => {
+ if (url.includes('count')) {
+ return {}
+ }
+ return {
data: [
{
id: 'some-uuid',
@@ -175,26 +187,28 @@ test('load older btn will fetch older logs', async () => {
metadata: {},
},
],
- })
- .mockResolvedValueOnce({
- data: [
- {
- id: 'some-uuid2',
- timestamp: 1621323232310,
- event_message: 'second event',
- metadata: {},
- },
- ],
- })
+ }
+ })
render(<LogPage />)
// should display first log but not second
await waitFor(() => screen.getByText('first event'))
expect(() => screen.getByText('second event')).toThrow()
- userEvent.click(screen.getByText('Load older'))
+ get.mockResolvedValueOnce({
+ data: [
+ {
+ id: 'some-uuid2',
+ timestamp: 1621323232310,
+ event_message: 'second event',
+ metadata: {},
+ },
+ ],
+ })
// should display first and second log
+ userEvent.click(screen.getByText('Load older'))
await waitFor(() => screen.getByText('first event'))
+ await waitFor(() => {
+ expect(get).toHaveBeenCalledWith(expect.stringContaining('timestamp_end=1'))
+ })
await waitFor(() => screen.getByText('second event'))
- expect(get).toBeCalledTimes(2)
})
-