ProjectUsage.tsx238 lines · main
1import { useParams } from 'common'
2import dayjs from 'dayjs'
3import { Auth, Database, Realtime, Storage } from 'icons'
4import sumBy from 'lodash/sumBy'
5import Link from 'next/link'
6import { useRouter } from 'next/router'
7import { useEffect, useState } from 'react'
8import { Loading } from 'ui'
9
10import BarChart from '@/components/ui/Charts/BarChart'
11import { ChartIntervalDropdown } from '@/components/ui/Logs/ChartIntervalDropdown'
12import { CHART_INTERVALS } from '@/components/ui/Logs/logs.utils'
13import Panel from '@/components/ui/Panel'
14import {
15 ProjectLogStatsVariables,
16 UsageApiCounts,
17 useProjectLogStatsQuery,
18} from '@/data/analytics/project-log-stats-query'
19import { useFillTimeseriesSorted } from '@/hooks/analytics/useFillTimeseriesSorted'
20import { useCheckEntitlements } from '@/hooks/misc/useCheckEntitlements'
21import { useIsFeatureEnabled } from '@/hooks/misc/useIsFeatureEnabled'
22import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
23
24type ChartIntervalKey = ProjectLogStatsVariables['interval']
25
26const ProjectUsage = () => {
27 const router = useRouter()
28 const { ref: projectRef } = useParams()
29 const { data: organization } = useSelectedOrganizationQuery()
30
31 const { projectAuthAll: authEnabled, projectStorageAll: storageEnabled } = useIsFeatureEnabled([
32 'project_auth:all',
33 'project_storage:all',
34 ])
35
36 const { getEntitlementMax } = useCheckEntitlements('log.retention_days')
37 const retentionDays = getEntitlementMax()
38
39 const DEFAULT_INTERVAL: ChartIntervalKey =
40 retentionDays !== undefined && retentionDays < 7 ? '1hr' : '1day'
41
42 const [interval, setInterval] = useState<ChartIntervalKey>(DEFAULT_INTERVAL)
43
44 useEffect(() => {
45 setInterval(retentionDays !== undefined && retentionDays < 7 ? '1hr' : '1day')
46 }, [retentionDays])
47
48 const { data, isPending: isLoading } = useProjectLogStatsQuery({ projectRef, interval })
49
50 const selectedInterval = CHART_INTERVALS.find((i) => i.key === interval) || CHART_INTERVALS[1]
51 const startDateLocal = dayjs().subtract(
52 selectedInterval.startValue,
53 selectedInterval.startUnit as dayjs.ManipulateType
54 )
55 const endDateLocal = dayjs()
56 const { data: charts } = useFillTimeseriesSorted({
57 data: data?.result ?? [],
58 timestampKey: 'timestamp',
59 valueKey: [
60 'total_auth_requests',
61 'total_rest_requests',
62 'total_storage_requests',
63 'total_realtime_requests',
64 ],
65 defaultValue: 0,
66 startDate: startDateLocal.toISOString(),
67 endDate: endDateLocal.toISOString(),
68 minPointsToFill: 5,
69 })
70 const datetimeFormat = selectedInterval.format || 'MMM D, ha'
71
72 const handleBarClick = (
73 value: UsageApiCounts,
74 _type: 'rest' | 'realtime' | 'storage' | 'auth'
75 ) => {
76 const unit = selectedInterval.startUnit
77 const selectedStart = dayjs(value?.timestamp)
78 const selectedEnd = selectedStart.add(1, unit)
79
80 if (_type === 'rest') {
81 router.push(
82 `/project/${projectRef}/logs/edge-logs?its=${selectedStart.toISOString()}&ite=${selectedEnd.toISOString()}`
83 )
84 return
85 }
86
87 router.push(
88 `/project/${projectRef}/logs/edge-logs?its=${selectedStart.toISOString()}&ite=${selectedEnd.toISOString()}&f=${JSON.stringify(
89 {
90 product: {
91 [_type]: true,
92 },
93 }
94 )}`
95 )
96 }
97
98 return (
99 <div className="space-y-6">
100 <div className="flex flex-row items-center gap-x-2">
101 <ChartIntervalDropdown
102 value={interval || '1day'}
103 onChange={(interval) => setInterval(interval as ProjectLogStatsVariables['interval'])}
104 organizationSlug={organization?.slug}
105 dropdownAlign="start"
106 tooltipSide="right"
107 />
108 <span className="text-xs text-foreground-light">
109 Statistics for {selectedInterval.label.toLowerCase()}
110 </span>
111 </div>
112 <div className="grid grid-cols-1 @md:grid-cols-2 gap-4 @2xl:grid-cols-4">
113 <Panel className="mb-0">
114 <Panel.Content className="space-y-4">
115 <PanelHeader
116 icon={
117 <div className="rounded-sm bg-surface-300 p-1.5 text-foreground-light shadow-xs">
118 <Database strokeWidth={1.5} size={16} />
119 </div>
120 }
121 title="Database"
122 href={`/project/${projectRef}/editor`}
123 />
124
125 <Loading active={isLoading}>
126 <BarChart
127 title="REST Requests"
128 data={charts}
129 xAxisKey="timestamp"
130 yAxisKey="total_rest_requests"
131 onBarClick={(v: unknown) => handleBarClick(v as UsageApiCounts, 'rest')}
132 customDateFormat={datetimeFormat}
133 highlightedValue={sumBy(charts, 'total_rest_requests')}
134 />
135 </Loading>
136 </Panel.Content>
137 </Panel>
138 {authEnabled && (
139 <Panel className="mb-0 md:mb-0">
140 <Panel.Content className="space-y-4">
141 <PanelHeader
142 icon={
143 <div className="rounded-sm bg-surface-300 p-1.5 text-foreground-light shadow-xs">
144 <Auth strokeWidth={1.5} size={16} />
145 </div>
146 }
147 title="Auth"
148 href={`/project/${projectRef}/auth/users`}
149 />
150 <Loading active={isLoading}>
151 <BarChart
152 title="Auth Requests"
153 data={charts}
154 xAxisKey="timestamp"
155 yAxisKey="total_auth_requests"
156 onBarClick={(v: unknown) => handleBarClick(v as UsageApiCounts, 'auth')}
157 customDateFormat={datetimeFormat}
158 highlightedValue={sumBy(charts || [], 'total_auth_requests')}
159 />
160 </Loading>
161 </Panel.Content>
162 </Panel>
163 )}
164 {storageEnabled && (
165 <Panel className="mb-0 md:mb-0">
166 <Panel.Content className="space-y-4">
167 <PanelHeader
168 icon={
169 <div className="rounded-sm bg-surface-300 p-1.5 text-foreground-light shadow-xs">
170 <Storage strokeWidth={1.5} size={16} />
171 </div>
172 }
173 title="Storage"
174 href={`/project/${projectRef}/storage/buckets`}
175 />
176
177 <Loading active={isLoading}>
178 <BarChart
179 title="Storage Requests"
180 data={charts}
181 xAxisKey="timestamp"
182 yAxisKey="total_storage_requests"
183 onBarClick={(v: unknown) => handleBarClick(v as UsageApiCounts, 'storage')}
184 customDateFormat={datetimeFormat}
185 highlightedValue={sumBy(charts, 'total_storage_requests')}
186 />
187 </Loading>
188 </Panel.Content>
189 </Panel>
190 )}
191 <Panel className="mb-0 md:mb-0">
192 <Panel.Content className="space-y-4">
193 <PanelHeader
194 icon={
195 <div className="rounded-sm bg-surface-300 p-1.5 text-foreground-light shadow-xs">
196 <Realtime strokeWidth={1.5} size={16} />
197 </div>
198 }
199 title="Realtime"
200 />
201
202 <Loading active={isLoading}>
203 <BarChart
204 title="Realtime Requests"
205 data={charts}
206 xAxisKey="timestamp"
207 yAxisKey="total_realtime_requests"
208 onBarClick={(v: unknown) => handleBarClick(v as UsageApiCounts, 'realtime')}
209 customDateFormat={datetimeFormat}
210 highlightedValue={sumBy(charts, 'total_realtime_requests')}
211 />
212 </Loading>
213 </Panel.Content>
214 </Panel>
215 </div>
216 </div>
217 )
218}
219export default ProjectUsage
220
221const PanelHeader = (props: any) => {
222 const Tag = props?.href ? Link : 'div'
223 return (
224 <Tag href={props.href}>
225 <div
226 className={
227 'flex items-center space-x-3 opacity-80 transition ' +
228 (props.href ? 'cursor-pointer hover:text-gray-1200 hover:opacity-100' : '')
229 }
230 >
231 <div>{props.icon}</div>
232 <span className="flex items-center space-x-1">
233 <h4 className="mb-0 text-lg">{props.title}</h4>
234 </span>
235 </div>
236 </Tag>
237 )
238}