fix: refactor edge functions

This commit is contained in:
TzeYiing committed 2023-04-26 00:54:03 +09:00
1 parent fd82ab26b6
commit 8cb84aa7fe
2 files changed
+83 -141

No files matched your search

@@ -14,7 +14,8 @@ export interface ReportWidgetProps<T = any> {
tooltip?: string
className?: string
renderer: (props: ReportWidgetRendererProps) => React.ReactNode
params: BaseReportParams | LogsEndpointParams
// omitting params will hide the "View in logs explorer" button
params?: BaseReportParams | LogsEndpointParams
isLoading: boolean
}
@@ -64,38 +65,40 @@ const ReportWidget: React.FC<ReportWidgetProps> = (props) => {
</div>
<p className="text-sm text-scale-1100">{props.description}</p>
</div>
<Tooltip.Root delayDuration={0}>
<Tooltip.Trigger>
<Button
type="default"
icon={<IconExternalLink strokeWidth={1.5} />}
className="px-1"
onClick={() => {
router.push({
pathname: `/project/${projectRef}/logs/explorer`,
query: {
q: props.params?.sql,
its: props.params.iso_timestamp_start,
ite: props.params.iso_timestamp_end,
},
})
}}
/>
</Tooltip.Trigger>
<Tooltip.Portal>
<Tooltip.Content side="bottom">
<Tooltip.Arrow className="radix-tooltip-arrow" />
<div
className={[
'rounded bg-scale-100 py-1 px-2 max-w-xs leading-none shadow',
'border border-scale-200',
].join(' ')}
>
<span className="text-xs text-scale-1200">Open in Logs Explorer</span>
</div>
</Tooltip.Content>
</Tooltip.Portal>
</Tooltip.Root>
{props.params && (
<Tooltip.Root delayDuration={0}>
<Tooltip.Trigger>
<Button
type="default"
icon={<IconExternalLink strokeWidth={1.5} />}
className="px-1"
onClick={() => {
router.push({
pathname: `/project/${projectRef}/logs/explorer`,
query: {
q: props.params?.sql,
its: props.params!.iso_timestamp_start,
ite: props.params!.iso_timestamp_end,
},
})
}}
/>
</Tooltip.Trigger>
<Tooltip.Portal>
<Tooltip.Content side="bottom">
<Tooltip.Arrow className="radix-tooltip-arrow" />
<div
className={[
'rounded bg-scale-100 py-1 px-2 max-w-xs leading-none shadow',
'border border-scale-200',
].join(' ')}
>
<span className="text-xs text-scale-1200">Open in Logs Explorer</span>
</div>
</Tooltip.Content>
</Tooltip.Portal>
</Tooltip.Root>
)}
</div>
<LoadingOpacity className="w-full" active={props.isLoading}>
@@ -1,20 +1,23 @@
import dayjs from 'dayjs'
import { useState } from 'react'
import { useMemo, useState } from 'react'
import { useRouter } from 'next/router'
import { Button } from 'ui'
import { observer } from 'mobx-react-lite'
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { checkPermissions } from 'hooks'
import { useParams } from 'common/hooks'
import { ChartIntervals, NextPageWithLayout } from 'types'
import { DATE_FORMAT } from 'lib/constants'
import Panel from 'components/ui/Panel'
import NoPermission from 'components/ui/NoPermission'
import ChartHandler from 'components/to-be-cleaned/Charts/ChartHandler'
import FunctionsLayout from 'components/layouts/FunctionsLayout'
import { useEdgeFunctionQuery } from 'data/edge-functions/edge-function-query'
import { useFunctionsInvStatsQuery } from 'data/analytics/functions-inv-stats-query'
import ReportWidget from 'components/interfaces/Reports/ReportWidget'
import BarChart from 'components/ui/Charts/BarChart'
import AreaChart from 'components/ui/Charts/AreaChart'
import { isUnixMicro, unixMicroToIsoTimestamp } from 'components/interfaces/Settings/Logs'
import meanBy from 'lodash/meanBy'
import sumBy from 'lodash/sumBy'
const CHART_INTERVALS: ChartIntervals[] = [
{
@@ -30,25 +33,6 @@ const CHART_INTERVALS: ChartIntervals[] = [
{ key: '7day', label: '7 days', startValue: 7, startUnit: 'day', format: 'MMM D' },
]
function calculateHighlightedValue(array: any, attribute: string, options?: { sum: boolean }) {
if (!array) return ''
let total = 0
let count = 0
array.forEach(function (item: any, index: number) {
const _item = item[attribute]
total += _item
count++
})
if (options?.sum) {
return total
} else {
return total / count
}
}
const PageLayout: NextPageWithLayout = () => {
const router = useRouter()
const { ref: projectRef, functionSlug } = useParams()
@@ -64,37 +48,24 @@ const PageLayout: NextPageWithLayout = () => {
functionId: id,
interval: selectedInterval.key,
})
const isChartLoading = !data?.result && !error ? true : false
console.log(isChartLoading)
const chartData = useMemo(() => {
return (data?.result || []).map((d: any) => ({
...d,
timestamp: isUnixMicro(d.timestamp) ? unixMicroToIsoTimestamp(d.timestamp) : d.timestamp,
}))
}, [data?.result])
const startDate = dayjs()
.subtract(selectedInterval.startValue, selectedInterval.startUnit)
.format(DATE_FORMAT)
const endDate = dayjs().format(DATE_FORMAT)
const charts: any = {}
charts.data = data?.result
const datetimeFormat = selectedInterval.format || 'MMM D, ha'
const handleBarClick = (v: any, search: string) => {
if (!v || !v.activePayload?.[0]?.payload) return
// returns rechart internal tooltip data type
const payload = v.activePayload[0].payload
const timestamp = payload.timestamp
const timestampDigits = String(timestamp).length
if (timestampDigits < 16) {
// pad unix timestamp with additional 0 and then forward
const paddedTimestamp = String(timestamp) + '0'.repeat(16 - timestampDigits)
router.push(`/project/${projectRef}/functions/${id}/logs?te=${paddedTimestamp}`)
} else {
router.push(`/project/${projectRef}/functions/${id}/logs?te=${timestamp}`)
}
}
const canReadFunction = checkPermissions(PermissionAction.FUNCTIONS_READ, functionSlug as string)
if (!canReadFunction) {
return <NoPermission isFullPage resourceText="access this edge function" />
}
return (
<div className="space-y-6 py-2">
<div className="flex flex-row items-center gap-2">
@@ -131,74 +102,42 @@ const PageLayout: NextPageWithLayout = () => {
{startDate && endDate && (
<>
<div className="grid grid-cols-1 md:grid-cols-2 md:gap-4 lg:grid-cols-2 lg:gap-8">
<Panel key="database-chart">
<Panel.Content className="space-y-4">
{/*
// @ts-ignore */}
<ChartHandler
label="Execution time"
defaultChartStyle="line"
startDate={startDate}
endDate={endDate}
attribute={'avg_execution_time'}
provider="log-stats"
// interval="1d"
hideChartType
customDateFormat={datetimeFormat}
data={charts}
<ReportWidget
title="Execution time"
tooltip="Average execution time of function invocations"
data={chartData}
isLoading={isChartLoading}
renderer={(props) => (
<AreaChart
className="w-full"
xAxisKey="timestamp"
yAxisKey="avg_execution_time"
data={props.data}
format="ms"
isLoading={!charts.data && !error ? true : false}
highlightedValue={calculateHighlightedValue(data?.result, 'avg_execution_time')}
// onBarClick={(v) => handleBarClick(v, '/rest')}
highlightedValue={meanBy(props.data, 'avg_execution_time')}
/>
</Panel.Content>
</Panel>
<Panel key="invocation-chart">
<Panel.Content className="space-y-4">
{/*
{/*
{/*
// @ts-ignore */}
<ChartHandler
label="Invocations"
startDate={startDate}
endDate={endDate}
attribute={'count'}
provider="log-stats"
// interval="1d"
hideChartType
customDateFormat={datetimeFormat}
data={charts}
isLoading={!charts.data && !error ? true : false}
highlightedValue={calculateHighlightedValue(data?.result, 'count', {
sum: true,
})}
onBarClick={(v) => handleBarClick(v, '/auth')}
)}
/>
<ReportWidget
title="Invocations"
data={chartData}
isLoading={isChartLoading}
renderer={(props) => (
<BarChart
className="w-full"
xAxisKey="timestamp"
yAxisKey="count"
data={props.data}
highlightedValue={sumBy(props.data, 'count')}
onBarClick={(v) => {
router.push(
`/project/${projectRef}/functions/${functionSlug}/invocations?ite=${v.timestamp}`
)
}}
/>
</Panel.Content>
</Panel>
)}
/>
</div>
{/* <Panel key="error-chart">
<Panel.Content className="space-y-4">
<ChartHandler
defaultChartStyle="line"
label="Error count"
startDate={startDate}
endDate={endDate}
attribute={'min_execution_time'}
provider="log-stats"
// interval="1d"
hideChartType
customDateFormat={datetimeFormat}
data={charts}
isLoading={!charts.data && !error ? true : false}
highlightedValue={calculateHighlightedValue(data?.result, 'min_execution_time', {
sum: true,
})}
onBarClick={(v) => handleBarClick(v, '/auth')}
/>
</Panel.Content>
</Panel> */}
</>
)}
</div>