Skip to content

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

feat: log explorer linking, ReportWidget, widget description

TzeYiing3cd619e0623f
diff --git a/studio/components/interfaces/Reports/PresetReport.tsx b/studio/components/interfaces/Reports/PresetReport.tsx
index 35bdd0bb09b..6dc17b72781 100644
--- a/studio/components/interfaces/Reports/PresetReport.tsx
+++ b/studio/components/interfaces/Reports/PresetReport.tsx
@@ -15,8 +15,10 @@ import { useState } from 'react'
import { DatePickerToFrom } from '../Settings/Logs'
import DatePickers from '../Settings/Logs/Logs.DatePickers'
import { jsonSyntaxHighlight } from '../Settings/Logs/LogsFormatters'
+import { renderRequestsPathsTable, renderStatusCodesChart } from './renderers/OverviewRenderers'
import { DATETIME_FORMAT, PRESET_CONFIG, REPORTS_DATEPICKER_HELPERS } from './Reports.constants'
import { Presets } from './Reports.types'
+import ReportWidget from './ReportWidget'
interface Props {
preset: Presets
@@ -31,12 +33,12 @@ const DEFAULT_PARAMS = {
const PresetReport: React.FC<Props> = ({ projectRef, preset }) => {
const config = PRESET_CONFIG[preset]
const [statusCodes, statusCodesHandlers] = useLogsQuery(projectRef, {
- sql: config.sql.statusCodes(),
+ sql: config.sql.statusCodes,
...DEFAULT_PARAMS,
})
const [requestPaths, requestPathsHandlers] = useLogsQuery(projectRef, {
- sql: config.sql.requestPaths(12),
+ sql: config.sql.requestPaths,
...DEFAULT_PARAMS,
})
@@ -50,9 +52,6 @@ const PresetReport: React.FC<Props> = ({ projectRef, preset }) => {
requestPathsHandlers.setParams((prev) => ({ ...prev, ...newParams }))
}
const isLoading = statusCodes.isLoading || requestPaths.isLoading
- const requestPathsSums = requestPaths.logData.map((v) => v.sum) as number[]
- const requestPathsSumMax = Math.max(...requestPathsSums)
- const requestPathsSumMin = Math.min(...requestPathsSums)
return (
<div className="mx-auto flex flex-col gap-4 px-5 lg:px-16 xl:px-24 1xl:px-28 2xl:px-32 py-6">
@@ -80,119 +79,29 @@ const PresetReport: React.FC<Props> = ({ projectRef, preset }) => {
</Button>
</div>
- <div className="grid md:gap-4 lg:grid-cols-4 lg:gap-8">
- <Panel key="api-status-codes" className="col-span-4 col-start-1" wrapWithLoading={false}>
- <Panel.Content className="space-y-4">
- <h3>API Status Codes</h3>
- <StackedAreaChart
- dateFormat={DATETIME_FORMAT}
- data={statusCodes.logData}
- stackKey="status_code"
- xAxisKey="timestamp"
- yAxisKey="count"
- isLoading={statusCodes.isLoading}
- xAxisFormatAsDate
- size="large"
- styleMap={{
- 200: { stroke: USAGE_COLORS['200'], fill: USAGE_COLORS['200'] },
- 201: { stroke: USAGE_COLORS['201'], fill: USAGE_COLORS['201'] },
- 400: { stroke: USAGE_COLORS['400'], fill: USAGE_COLORS['400'] },
- 401: { stroke: USAGE_COLORS['401'], fill: USAGE_COLORS['401'] },
- 404: { stroke: USAGE_COLORS['404'], fill: USAGE_COLORS['404'] },
- 500: { stroke: USAGE_COLORS['500'], fill: USAGE_COLORS['500'] },
- }}
- />
- </Panel.Content>
- </Panel>
- <Panel
- key="top-routes"
- className="col-span-4 col-start-1 pb-0"
- bodyClassName="h-full"
- wrapWithLoading={false}
- >
- <Panel.Content className="space-y-4">
- <h3>Slow API Requests</h3>
- <Table
- className="border border-scale-600 rounded"
- head={
- <>
- <Table.th>Path</Table.th>
- <Table.th>Count</Table.th>
- <Table.th>Avg. Time (ms)</Table.th>
- <Table.th>Total Query Time</Table.th>
- </>
- }
- body={
- <>
- {requestPaths.logData.map((row: any, index) => {
- const totalQueryTimePercentage =
- ((row.sum - requestPathsSumMin) / requestPathsSumMax) * 100
- return (
- <Table.tr key={index}>
- <Table.td className="max-w-sm lg:max-w-lg" style={{ padding: '0.3rem' }}>
- <Collapsible className="w-full flex flex-col gap-2">
- <Collapsible.Trigger asChild>
- <button
- className="w-full text-scale-1200 flex justify-start space-x-1"
- type="button"
- >
- <IconChevronRight
- size="tiny"
- className="transition data-open-parent:rotate-90 data-closed-parent:rotate-0"
- />
- <div className="flex space-x-2 items-center overflow-x-none">
- <p className="text-scale-1200 font-mono text-xs">{row.method}</p>
- <p className="font-mono text-scale-1200 text-xs truncate max-w-xs ">
- {row.path}
- <span className="text-scale-1000">{row.query_params}</span>
- </p>
- </div>
- </button>
- </Collapsible.Trigger>
- <Collapsible.Content className="bg-scale-300 p-2 rounded">
- <pre className="text-xs syntax-highlight overflow-x-auto">
- <div
- className="text-wrap"
- dangerouslySetInnerHTML={{
- __html: jsonSyntaxHighlight(
- queryParamsToObject(row.query_params)
- ),
- }}
- />
- </pre>
- </Collapsible.Content>
- </Collapsible>
- </Table.td>
- <Table.td style={{ padding: '0.5rem' }} className="text-xs align-top">
- {row.count}
- </Table.td>
- <Table.td style={{ padding: '0.5rem' }} className="text-xs align-top">
- {Number(row.avg_origin_time).toFixed(2)}
- </Table.td>
- <Table.td className="align-top py-1">
- <div
- className={`mt-1 h-2 rounded w-full bg-green-1100`}
- style={{
- width: `${totalQueryTimePercentage}%`,
- }}
- />
- </Table.td>
- </Table.tr>
- )
- })}
- </>
- }
- />
- </Panel.Content>
- </Panel>
+ <div className="grid lg:grid-cols-4">
+ <ReportWidget
+ isLoading={isLoading}
+ params={statusCodes.params}
+ className="col-span-4 col-start-1"
+ title="API Status Codes"
+ description="Distrubution of API reponses by status codes."
+ data={statusCodes.logData}
+ renderer={renderStatusCodesChart}
+ />
+ <ReportWidget
+ isLoading={isLoading}
+ params={requestPaths.params}
+ className="col-span-4 col-start-1"
+ title="Slow API Requests"
+ description="Most frequently used requests, sorted by total querying time"
+ data={requestPaths.logData}
+ renderer={renderRequestsPathsTable}
+ />
</div>
</div>
)
}
-
-const queryParamsToObject = (params: string) => {
- return Object.fromEntries(new URLSearchParams(params))
-}
// const usePresetReport = (projectRef: string, preset: Presets) => {
// const params: LogsEndpointParams = { ...paramsToMerge, project: projectRef, sql }
// const endpointUrl = `${API_URL}/projects/${projectRef}/analytics/endpoints/logs.all?${genQueryParams(
diff --git a/studio/components/interfaces/Reports/ReportWidget.tsx b/studio/components/interfaces/Reports/ReportWidget.tsx
new file mode 100644
index 00000000000..500fe1108e1
--- /dev/null
+++ b/studio/components/interfaces/Reports/ReportWidget.tsx
@@ -0,0 +1,66 @@
+import { render } from '@headlessui/react/dist/utils/render'
+import { Button, Dropdown, IconMoreVertical } from '@supabase/ui'
+import { Misc } from '@supabase/ui/dist/cjs/components/Menu/Menu'
+import Loading from 'components/ui/Loading'
+import LoadingOpacity from 'components/ui/LoadingOpacity'
+import Panel from 'components/ui/Panel'
+import { useRouter } from 'next/router'
+import { LogsEndpointParams } from '../Settings/Logs'
+
+export interface ReportWidgetProps {
+ data: any[]
+ title: string
+ description: string
+ className?: string
+ renderer: (props: ReportWidgetProps) => React.ReactNode
+ params: LogsEndpointParams
+ isLoading: boolean
+}
+
+const ReportWidget: React.FC<ReportWidgetProps> = (props) => {
+ const router = useRouter()
+ const { ref } = router.query
+ return (
+ <Panel className={'pb-0 ' + props.className} bodyClassName="h-full" wrapWithLoading={false}>
+ <Panel.Content className="space-y-4">
+ <div className="flex flex-row justify-between items-start">
+ <div className="gap-2">
+ <h3>{props.title}</h3>
+ <p className="text-sm text-scale-1100">{props.description}</p>
+ </div>
+ <Dropdown
+ align="end"
+ overlay={[
+ <Dropdown.Item
+ onClick={() => {
+ router.push({
+ pathname: `/project/${ref}/logs-explorer`,
+ query: {
+ q: props.params.sql,
+ its: props.params.iso_timestamp_start,
+ ite: props.params.iso_timestamp_end,
+ },
+ })
+ }}
+ >
+ Open in Logs Explorer
+ </Dropdown.Item>,
+ ]}
+ side="bottom"
+ >
+ <Button
+ title="Actions..."
+ as="span"
+ type="text"
+ icon={<IconMoreVertical className="text-scale-1100" size="small" />}
+ ></Button>
+ </Dropdown>
+ </div>
+
+ <LoadingOpacity active={props.isLoading}>{props.renderer(props)}</LoadingOpacity>
+ </Panel.Content>
+ </Panel>
+ )
+}
+
+export default ReportWidget
diff --git a/studio/components/interfaces/Reports/Reports.constants.ts b/studio/components/interfaces/Reports/Reports.constants.ts
index ac3dc225a3a..62853d902a3 100644
--- a/studio/components/interfaces/Reports/Reports.constants.ts
+++ b/studio/components/interfaces/Reports/Reports.constants.ts
@@ -35,7 +35,7 @@ export const PRESET_CONFIG = {
[Presets.OVERVIEW]: {
title: 'Overview',
sql: {
- statusCodes: () => `
+ statusCodes: `
select
timestamp_trunc(timestamp, hour) as timestamp,
r.status_code as status_code,
@@ -49,7 +49,7 @@ export const PRESET_CONFIG = {
status_code
ORDER BY
timestamp ASC`,
- requestPaths: (limit: number) => `
+ requestPaths: `
select
f2.path as path,
f2.search as query_params,
@@ -74,7 +74,7 @@ export const PRESET_CONFIG = {
sum DESC,
count desc,
avg_origin_time DESC
- LIMIT ${limit}
+ LIMIT 50
`
},
},
diff --git a/studio/components/interfaces/Reports/Reports.utils.ts b/studio/components/interfaces/Reports/Reports.utils.ts
new file mode 100644
index 00000000000..12a7d634797
--- /dev/null
+++ b/studio/components/interfaces/Reports/Reports.utils.ts
@@ -0,0 +1,7 @@
+
+/**
+ * Converts a query params string to an object
+ */
+export const queryParamsToObject = (params: string) => {
+ return Object.fromEntries(new URLSearchParams(params))
+}
\ No newline at end of file
diff --git a/studio/components/interfaces/Reports/renderers/OverviewRenderers.tsx b/studio/components/interfaces/Reports/renderers/OverviewRenderers.tsx
new file mode 100644
index 00000000000..a372812711f
--- /dev/null
+++ b/studio/components/interfaces/Reports/renderers/OverviewRenderers.tsx
@@ -0,0 +1,107 @@
+import { Collapsible, IconChevronRight } from '@supabase/ui'
+import { jsonSyntaxHighlight } from 'components/interfaces/Settings/Logs/LogsFormatters'
+import Table from 'components/to-be-cleaned/Table'
+import { USAGE_COLORS } from 'components/ui/Charts/Charts.constants'
+import StackedAreaChart from 'components/ui/Charts/StackedAreaChart'
+import { DATETIME_FORMAT } from '../Reports.constants'
+import { queryParamsToObject } from '../Reports.utils'
+import { ReportWidgetProps } from '../ReportWidget'
+
+export const renderStatusCodesChart = (props: ReportWidgetProps) => (
+ <StackedAreaChart
+ dateFormat={DATETIME_FORMAT}
+ data={props.data}
+ stackKey="status_code"
+ xAxisKey="timestamp"
+ yAxisKey="count"
+ isLoading={false}
+ xAxisFormatAsDate
+ size="large"
+ styleMap={{
+ 200: { stroke: USAGE_COLORS['200'], fill: USAGE_COLORS['200'] },
+ 201: { stroke: USAGE_COLORS['201'], fill: USAGE_COLORS['201'] },
+ 400: { stroke: USAGE_COLORS['400'], fill: USAGE_COLORS['400'] },
+ 401: { stroke: USAGE_COLORS['401'], fill: USAGE_COLORS['401'] },
+ 404: { stroke: USAGE_COLORS['404'], fill: USAGE_COLORS['404'] },
+ 500: { stroke: USAGE_COLORS['500'], fill: USAGE_COLORS['500'] },
+ }}
+ />
+)
+
+export const renderRequestsPathsTable = (props: ReportWidgetProps) => {
+ const requestPathsSums = props.data.map((v) => v.sum) as number[]
+ const requestPathsSumMax = Math.max(...requestPathsSums)
+ const requestPathsSumMin = Math.min(...requestPathsSums)
+ return (
+ <Table
+ containerClassName="max-h-72 w-full overflow-y-auto"
+ className="border border-scale-600 relative rounded"
+ head={
+ <>
+ <Table.th className="sticky top-0 z-10">Path</Table.th>
+ <Table.th className="sticky top-0 z-10">Count</Table.th>
+ <Table.th className="sticky top-0 z-10">Avg. Time (ms)</Table.th>
+ <Table.th className="sticky top-0 z-10">Total Query Time</Table.th>
+ </>
+ }
+ body={
+ <>
+ {props.data.map((row: any, index) => {
+ const totalQueryTimePercentage =
+ ((row.sum - requestPathsSumMin) / requestPathsSumMax) * 100
+ return (
+ <Table.tr key={index}>
+ <Table.td className="max-w-sm lg:max-w-lg" style={{ padding: '0.3rem' }}>
+ <Collapsible className="w-full flex flex-col gap-2">
+ <Collapsible.Trigger asChild>
+ <button
+ className="w-full text-scale-1200 flex justify-start space-x-1"
+ type="button"
+ >
+ <IconChevronRight
+ size="tiny"
+ className="transition data-open-parent:rotate-90 data-closed-parent:rotate-0"
+ />
+ <div className="flex space-x-2 items-center overflow-x-none">
+ <p className="text-scale-1200 font-mono text-xs">{row.method}</p>
+ <p className="font-mono text-scale-1200 text-xs truncate max-w-xs ">
+ {row.path}
+ <span className="text-scale-1000">{row.query_params}</span>
+ </p>
+ </div>
+ </button>
+ </Collapsible.Trigger>
+ <Collapsible.Content className="bg-scale-300 p-2 rounded">
+ <pre className="text-xs syntax-highlight overflow-x-auto">
+ <div
+ className="text-wrap"
+ dangerouslySetInnerHTML={{
+ __html: jsonSyntaxHighlight(queryParamsToObject(row.query_params)),
+ }}
+ />
+ </pre>
+ </Collapsible.Content>
+ </Collapsible>
+ </Table.td>
+ <Table.td style={{ padding: '0.5rem' }} className="text-xs align-top">
+ {row.count}
+ </Table.td>
+ <Table.td style={{ padding: '0.5rem' }} className="text-xs align-top">
+ {Number(row.avg_origin_time).toFixed(2)}
+ </Table.td>
+ <Table.td className="align-top py-1">
+ <div
+ className={`mt-1 h-2 rounded w-full bg-green-1100`}
+ style={{
+ width: `${totalQueryTimePercentage}%`,
+ }}
+ />
+ </Table.td>
+ </Table.tr>
+ )
+ })}
+ </>
+ }
+ />
+ )
+}
diff --git a/studio/components/to-be-cleaned/Table.tsx b/studio/components/to-be-cleaned/Table.tsx
index 6e1c4c4d81a..23ec56b1fa1 100644
--- a/studio/components/to-be-cleaned/Table.tsx
+++ b/studio/components/to-be-cleaned/Table.tsx
@@ -8,6 +8,8 @@ type TableProps = {
containerClassName?: string
borderless?: boolean
headTrClasses?: string
+ bodyClassName?: string
+ style?: React.StyleHTMLAttributes<HTMLTableElement>
}
function Table({
@@ -17,6 +19,8 @@ function Table({
containerClassName,
borderless,
headTrClasses,
+ bodyClassName,
+ style,
}: TableProps) {
let containerClasses = ['table-container']
if (containerClassName) containerClasses.push(containerClassName)
@@ -27,11 +31,11 @@ function Table({
return (
<div className={containerClasses.join(' ')}>
- <table className={classes.join(' ')}>
+ <table className={classes.join(' ')} style={style}>
<thead>
<tr className={headTrClasses}>{head}</tr>
</thead>
- <tbody>{body}</tbody>
+ <tbody className={bodyClassName}>{body}</tbody>
</table>
</div>
)
diff --git a/studio/tests/components/Reports/ReportWidget.test.js b/studio/tests/components/Reports/ReportWidget.test.js
new file mode 100644
index 00000000000..7c7ae5a8eee
--- /dev/null
+++ b/studio/tests/components/Reports/ReportWidget.test.js
@@ -0,0 +1,52 @@
+// mock the fetch function
+jest.mock('lib/common/fetch')
+import { get } from 'lib/common/fetch'
+
+// mock mobx
+jest.mock('mobx-react-lite')
+import { observer } from 'mobx-react-lite'
+observer.mockImplementation((v) => v)
+
+// mock the router
+jest.mock('next/router')
+import { useRouter } from 'next/router'
+const defaultRouterMock = () => {
+ const router = jest.fn()
+ router.query = {}
+ router.push = jest.fn()
+ router.pathname = 'logs/path'
+ return router
+}
+useRouter.mockReturnValue(defaultRouterMock())
+
+// mock usage flags
+jest.mock('components/ui/Flag/Flag')
+import Flag from 'components/ui/Flag/Flag'
+Flag.mockImplementation(({ children }) => <>{children}</>)
+jest.mock('hooks')
+import { useFlag } from 'hooks'
+useFlag.mockReturnValue(true)
+
+import { render, fireEvent, waitFor, screen, act } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { wait } from '@testing-library/user-event/dist/utils'
+import { logDataFixture } from '../../fixtures'
+import { LogsTableName } from 'components/interfaces/Settings/Logs'
+import { Presets } from 'components/interfaces/Reports/Reports.types'
+import ReportWidget from 'components/interfaces/Reports/ReportWidget'
+import { clickDropdown } from 'tests/helpers'
+beforeEach(() => {
+ // reset mocks between tests
+ get.mockReset()
+ useRouter.mockReset()
+ useRouter.mockReturnValue(defaultRouterMock())
+})
+
+test('static elements', async () => {
+ render(<ReportWidget data={[]} title="Some chart" sql="select" renderer={() => 'something'} />)
+ await screen.findByText(/Some chart/)
+ await screen.findByText(/something/)
+ const moreBtn = await screen.findByTitle(/Actions\.\.\./)
+ clickDropdown(moreBtn)
+ await screen.findByText(/Open in Logs Explorer/)
+})
diff --git a/studio/tests/helpers.ts b/studio/tests/helpers.tsx
similarity index 68%
rename from studio/tests/helpers.ts
rename to studio/tests/helpers.tsx
index 85b01d6c5a3..822318b5db6 100644
--- a/studio/tests/helpers.ts
+++ b/studio/tests/helpers.tsx
@@ -1,4 +1,6 @@
import { screen, getByText, fireEvent } from '@testing-library/react'
+import React from 'react'
+import { SWRConfig } from 'swr'
interface SelectorOptions {
container?: HTMLElement
}
@@ -35,3 +37,18 @@ export const clickDropdown = (elem: HTMLElement) => {
})
)
}
+
+/**
+ * Wraps a component with a test SWR config, to reset the cache between tests.
+ */
+export const wrapWithSwrTestConfig = (Component: React.FC<unknown>) => (props: any) =>
+ (
+ <SWRConfig
+ value={{
+ provider: () => new Map(),
+ shouldRetryOnError: false,
+ }}
+ >
+ <Component {...props} />
+ </SWRConfig>
+ )