DatabaseInfrastructureSection.tsx 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. import { useParams } from 'common'
  2. import dayjs from 'dayjs'
  3. import Link from 'next/link'
  4. import { useMemo } from 'react'
  5. import {
  6. MetricCard,
  7. MetricCardContent,
  8. MetricCardHeader,
  9. MetricCardLabel,
  10. MetricCardValue,
  11. } from 'ui-patterns/MetricCard'
  12. import {
  13. parseConnectionsData,
  14. parseInfrastructureMetrics,
  15. } from './DatabaseInfrastructureSection.utils'
  16. import { useInfraMonitoringAttributesQuery } from '@/data/analytics/infra-monitoring-query'
  17. import { useMaxConnectionsQuery } from '@/data/database/max-connections-query'
  18. import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
  19. type DatabaseInfrastructureSectionProps = {
  20. interval: '1hr' | '1day' | '7day'
  21. refreshKey: number
  22. dbErrorRate: number
  23. isLoading: boolean
  24. slowQueriesCount?: number
  25. slowQueriesLoading?: boolean
  26. }
  27. export const DatabaseInfrastructureSection = ({
  28. interval,
  29. refreshKey,
  30. dbErrorRate: _dbErrorRate,
  31. isLoading: _dbLoading,
  32. slowQueriesCount = 0,
  33. slowQueriesLoading = false,
  34. }: DatabaseInfrastructureSectionProps) => {
  35. const { ref: projectRef } = useParams()
  36. const { data: project } = useSelectedProjectQuery()
  37. // refreshKey forces date recalculation when user clicks refresh button
  38. // eslint-disable-next-line react-hooks/exhaustive-deps
  39. const { startDate, endDate, infraInterval } = useMemo(() => {
  40. const now = dayjs()
  41. const end = now.toISOString()
  42. let start: string
  43. let infraInterval: '1h' | '1d'
  44. switch (interval) {
  45. case '1hr':
  46. start = now.subtract(1, 'hour').toISOString()
  47. infraInterval = '1h'
  48. break
  49. case '1day':
  50. start = now.subtract(1, 'day').toISOString()
  51. infraInterval = '1h'
  52. break
  53. case '7day':
  54. start = now.subtract(7, 'day').toISOString()
  55. infraInterval = '1d'
  56. break
  57. default:
  58. start = now.subtract(1, 'hour').toISOString()
  59. infraInterval = '1h'
  60. }
  61. return { startDate: start, endDate: end, infraInterval }
  62. }, [interval, refreshKey])
  63. const {
  64. data: infraData,
  65. isLoading: infraLoading,
  66. error: infraError,
  67. } = useInfraMonitoringAttributesQuery({
  68. projectRef,
  69. attributes: [
  70. 'avg_cpu_usage',
  71. 'ram_usage',
  72. 'disk_fs_used_system',
  73. 'disk_fs_used_wal',
  74. 'pg_database_size',
  75. 'disk_fs_size',
  76. 'disk_io_consumption',
  77. 'pg_stat_database_num_backends',
  78. ],
  79. startDate,
  80. endDate,
  81. interval: infraInterval,
  82. })
  83. const { data: maxConnectionsData } = useMaxConnectionsQuery({
  84. projectRef,
  85. connectionString: project?.connectionString,
  86. })
  87. const metrics = useMemo(() => parseInfrastructureMetrics(infraData), [infraData])
  88. const connections = useMemo(
  89. () => parseConnectionsData(infraData, maxConnectionsData),
  90. [infraData, maxConnectionsData]
  91. )
  92. const errorMessage =
  93. infraError && typeof infraError === 'object' && 'message' in infraError
  94. ? String(infraError.message)
  95. : 'Error loading data'
  96. // Generate database report URL with time range parameters
  97. const getDatabaseReportUrl = () => {
  98. const now = dayjs()
  99. let its: string
  100. let helperText: string
  101. switch (interval) {
  102. case '1hr':
  103. its = now.subtract(1, 'hour').toISOString()
  104. helperText = 'Last 60 minutes'
  105. break
  106. case '1day':
  107. its = now.subtract(24, 'hour').toISOString()
  108. helperText = 'Last 24 hours'
  109. break
  110. case '7day':
  111. its = now.subtract(7, 'day').toISOString()
  112. helperText = 'Last 7 days'
  113. break
  114. default:
  115. its = now.subtract(24, 'hour').toISOString()
  116. helperText = 'Last 24 hours'
  117. }
  118. const ite = now.toISOString()
  119. const params = new URLSearchParams({
  120. its,
  121. ite,
  122. isHelper: 'true',
  123. helperText,
  124. })
  125. return `/project/${projectRef}/observability/database?${params.toString()}`
  126. }
  127. const databaseReportUrl = getDatabaseReportUrl()
  128. return (
  129. <div>
  130. <h2 className="mb-4">Database</h2>
  131. {/* First row: Metrics */}
  132. <div className="grid grid-cols-3 gap-2">
  133. <Link
  134. href={`/project/${projectRef}/observability/query-performance?totalTimeFilter=${encodeURIComponent(JSON.stringify({ operator: '>', value: 1000 }))}`}
  135. className="block group"
  136. >
  137. <MetricCard isLoading={slowQueriesLoading}>
  138. <MetricCardHeader
  139. href={`/project/${projectRef}/observability/query-performance?totalTimeFilter=${encodeURIComponent(JSON.stringify({ operator: '>', value: 1000 }))}`}
  140. linkTooltip="Go to query performance"
  141. >
  142. <MetricCardLabel tooltip="Queries with total execution time (execution time + planning time) greater than 1000ms. High values may indicate query optimization opportunities">
  143. Slow Queries
  144. </MetricCardLabel>
  145. </MetricCardHeader>
  146. <MetricCardContent>
  147. <MetricCardValue>{slowQueriesCount}</MetricCardValue>
  148. </MetricCardContent>
  149. </MetricCard>
  150. </Link>
  151. <Link href={databaseReportUrl} className="block group">
  152. <MetricCard isLoading={infraLoading}>
  153. <MetricCardHeader href={databaseReportUrl} linkTooltip="Go to database report">
  154. <MetricCardLabel tooltip="Active database connections (current/max). Monitor to avoid connection exhaustion">
  155. Connections
  156. </MetricCardLabel>
  157. </MetricCardHeader>
  158. <MetricCardContent>
  159. {infraError ? (
  160. <div className="text-xs text-destructive wrap-break-word">{errorMessage}</div>
  161. ) : connections.max > 0 ? (
  162. <MetricCardValue>
  163. {connections.current}/{connections.max}
  164. </MetricCardValue>
  165. ) : (
  166. <MetricCardValue>--</MetricCardValue>
  167. )}
  168. </MetricCardContent>
  169. </MetricCard>
  170. </Link>
  171. <Link href={databaseReportUrl} className="block group">
  172. <MetricCard isLoading={infraLoading}>
  173. <MetricCardHeader href={databaseReportUrl} linkTooltip="Go to database report">
  174. <MetricCardLabel tooltip="Disk usage percentage of total disk space used">
  175. Disk Usage
  176. </MetricCardLabel>
  177. </MetricCardHeader>
  178. <MetricCardContent>
  179. {infraError ? (
  180. <div className="text-xs text-destructive wrap-break-word">{errorMessage}</div>
  181. ) : metrics ? (
  182. <MetricCardValue>{metrics.disk.current.toFixed(0)}%</MetricCardValue>
  183. ) : (
  184. <MetricCardValue>--</MetricCardValue>
  185. )}
  186. </MetricCardContent>
  187. </MetricCard>
  188. </Link>
  189. <Link href={databaseReportUrl} className="block group">
  190. <MetricCard isLoading={infraLoading}>
  191. <MetricCardHeader href={databaseReportUrl} linkTooltip="Go to database report">
  192. <MetricCardLabel tooltip="Disk I/O consumption percentage. High values may indicate disk bottlenecks">
  193. Disk IO
  194. </MetricCardLabel>
  195. </MetricCardHeader>
  196. <MetricCardContent>
  197. {infraError ? (
  198. <div className="text-xs text-destructive wrap-break-word">{errorMessage}</div>
  199. ) : metrics ? (
  200. <MetricCardValue>{metrics.diskIo.current.toFixed(0)}%</MetricCardValue>
  201. ) : (
  202. <MetricCardValue>--</MetricCardValue>
  203. )}
  204. </MetricCardContent>
  205. </MetricCard>
  206. </Link>
  207. <Link href={databaseReportUrl} className="block group">
  208. <MetricCard isLoading={infraLoading}>
  209. <MetricCardHeader href={databaseReportUrl} linkTooltip="Go to database report">
  210. <MetricCardLabel tooltip="RAM usage percentage. Sustained high usage may indicate memory pressure">
  211. Memory
  212. </MetricCardLabel>
  213. </MetricCardHeader>
  214. <MetricCardContent>
  215. {infraError ? (
  216. <div className="text-xs text-destructive wrap-break-word">{errorMessage}</div>
  217. ) : metrics ? (
  218. <MetricCardValue>{metrics.ram.current.toFixed(0)}%</MetricCardValue>
  219. ) : (
  220. <MetricCardValue>--</MetricCardValue>
  221. )}
  222. </MetricCardContent>
  223. </MetricCard>
  224. </Link>
  225. <Link href={databaseReportUrl} className="block group">
  226. <MetricCard isLoading={infraLoading}>
  227. <MetricCardHeader href={databaseReportUrl} linkTooltip="Go to database report">
  228. <MetricCardLabel tooltip="CPU usage percentage. High values may suggest CPU-intensive queries or workloads">
  229. CPU
  230. </MetricCardLabel>
  231. </MetricCardHeader>
  232. <MetricCardContent>
  233. {infraError ? (
  234. <div className="text-xs text-destructive wrap-break-word">{errorMessage}</div>
  235. ) : metrics ? (
  236. <MetricCardValue>{metrics.cpu.current.toFixed(0)}%</MetricCardValue>
  237. ) : (
  238. <MetricCardValue>--</MetricCardValue>
  239. )}
  240. </MetricCardContent>
  241. </MetricCard>
  242. </Link>
  243. </div>
  244. </div>
  245. )
  246. }