ResourceWarningsTab.tsx 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. 'use client'
  2. import { useQueryClient } from '@tanstack/react-query'
  3. import { useParams } from 'common'
  4. import { useEffect, useRef, useState } from 'react'
  5. import { cn } from 'ui'
  6. import { usageKeys } from '@/data/usage/keys'
  7. import type { ResourceWarning } from '@/data/usage/resource-warnings-query'
  8. import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
  9. type Severity = 'warning' | 'critical' | null
  10. const WARNING_TYPES = [
  11. { key: 'disk_io_exhaustion', label: 'Disk IO', hasCritical: true },
  12. { key: 'cpu_exhaustion', label: 'CPU', hasCritical: true },
  13. { key: 'memory_and_swap_exhaustion', label: 'Memory & Swap', hasCritical: true },
  14. { key: 'disk_space_exhaustion', label: 'Disk Space', hasCritical: true },
  15. { key: 'auth_rate_limit_exhaustion', label: 'Auth Rate Limit', hasCritical: false },
  16. ] as const
  17. type WarningKey = (typeof WARNING_TYPES)[number]['key']
  18. type WarningState = Record<WarningKey, Severity>
  19. const INITIAL_STATE: WarningState = {
  20. disk_io_exhaustion: null,
  21. cpu_exhaustion: null,
  22. memory_and_swap_exhaustion: null,
  23. disk_space_exhaustion: null,
  24. auth_rate_limit_exhaustion: null,
  25. }
  26. export const ResourceWarningsTab = () => {
  27. const { ref } = useParams()
  28. const queryClient = useQueryClient()
  29. const { data: selectedOrg, isLoading: isOrgLoading } = useSelectedOrganizationQuery()
  30. const orgSlug = selectedOrg?.slug
  31. const [isReadOnly, setIsReadOnly] = useState(false)
  32. const [severities, setSeverities] = useState<WarningState>(INITIAL_STATE)
  33. // Track latest ref/orgSlug so the unmount cleanup always invalidates the
  34. // correct cache keys, even when orgSlug was still loading at mount time.
  35. const latestValues = useRef({ ref, orgSlug })
  36. useEffect(() => {
  37. latestValues.current = { ref, orgSlug }
  38. })
  39. // Only invalidate on unmount if overrides were actually applied to avoid
  40. // unnecessary refetches when the user opens the toolbar but never uses
  41. // the Warnings tab.
  42. const hasOverridesRef = useRef(false)
  43. // Invalidate both cache keys on unmount so banners revert to real data
  44. // when the toolbar sheet closes (which unmounts this component).
  45. useEffect(() => {
  46. return () => {
  47. if (!hasOverridesRef.current) return
  48. const { ref: latestRef, orgSlug: latestOrgSlug } = latestValues.current
  49. queryClient.invalidateQueries({ queryKey: usageKeys.resourceWarnings(undefined, latestRef) })
  50. if (latestOrgSlug) {
  51. queryClient.invalidateQueries({
  52. queryKey: usageKeys.resourceWarnings(latestOrgSlug, undefined),
  53. })
  54. }
  55. }
  56. // eslint-disable-next-line react-hooks/exhaustive-deps
  57. }, [])
  58. // When navigating to a different project: reset UI state and invalidate the
  59. // departing project's cache keys (the cleanup closure captures the old ref).
  60. // This component never unmounts during client-side navigation, so without
  61. // this project A's mocked banners would linger on project B.
  62. useEffect(() => {
  63. return () => {
  64. if (!hasOverridesRef.current) return
  65. queryClient.invalidateQueries({ queryKey: usageKeys.resourceWarnings(undefined, ref) })
  66. const { orgSlug: currentOrgSlug } = latestValues.current
  67. if (currentOrgSlug) {
  68. queryClient.invalidateQueries({
  69. queryKey: usageKeys.resourceWarnings(currentOrgSlug, undefined),
  70. })
  71. }
  72. setSeverities(INITIAL_STATE)
  73. setIsReadOnly(false)
  74. hasOverridesRef.current = false
  75. }
  76. // eslint-disable-next-line react-hooks/exhaustive-deps
  77. }, [ref])
  78. const applyOverrides = (nextSeverities: WarningState, nextIsReadOnly: boolean) => {
  79. if (!orgSlug || !ref) return
  80. const mockWarning: ResourceWarning = {
  81. project: ref,
  82. is_readonly_mode_enabled: nextIsReadOnly,
  83. ...nextSeverities,
  84. auth_email_offender: null,
  85. auth_restricted_email_sending: null,
  86. need_pitr: null,
  87. }
  88. // Write to both cache keys: ref-based (ResourceExhaustionWarningBanner) and
  89. // slug-based (ProjectLayout, TopSection, ProjectList) consumers.
  90. queryClient.setQueryData(usageKeys.resourceWarnings(undefined, ref), [mockWarning])
  91. queryClient.setQueryData(usageKeys.resourceWarnings(orgSlug, undefined), [mockWarning])
  92. hasOverridesRef.current = true
  93. }
  94. const handleSeverityChange = (key: WarningKey, value: Severity) => {
  95. const next = { ...severities, [key]: value }
  96. setSeverities(next)
  97. applyOverrides(next, isReadOnly)
  98. }
  99. const handleReadOnlyChange = (value: boolean) => {
  100. setIsReadOnly(value)
  101. applyOverrides(severities, value)
  102. }
  103. const handleReset = () => {
  104. setSeverities(INITIAL_STATE)
  105. setIsReadOnly(false)
  106. hasOverridesRef.current = false
  107. queryClient.invalidateQueries({ queryKey: usageKeys.resourceWarnings(undefined, ref) })
  108. if (orgSlug) {
  109. queryClient.invalidateQueries({ queryKey: usageKeys.resourceWarnings(orgSlug, undefined) })
  110. }
  111. }
  112. // Disabled when org is loading, org slug is unavailable, or we're not on a
  113. // project page (ref is undefined on org-level pages like /org/[slug]/settings).
  114. const isDisabled = isOrgLoading || !orgSlug || !ref
  115. return (
  116. <div className="p-6 space-y-4">
  117. <div className="flex items-center justify-between">
  118. <p className="text-sm text-foreground-light">
  119. Override resource warning banners for the current project.
  120. </p>
  121. <button
  122. onClick={handleReset}
  123. disabled={isDisabled}
  124. className="text-xs text-foreground-lighter hover:text-foreground transition underline disabled:opacity-50 disabled:cursor-not-allowed"
  125. >
  126. Reset to real data
  127. </button>
  128. </div>
  129. {isDisabled && (
  130. <p className="text-xs text-foreground-muted">
  131. {!ref ? 'Navigate to a project page to use this tab.' : 'Loading org context...'}
  132. </p>
  133. )}
  134. <div className={cn('space-y-3', isDisabled && 'opacity-50 pointer-events-none')}>
  135. <div className="flex items-center justify-between py-2 border-b border-overlay">
  136. <span className="text-sm font-medium">Read-only mode</span>
  137. <div className="flex gap-1">
  138. <SeverityButton
  139. active={!isReadOnly}
  140. variant="off"
  141. onClick={() => handleReadOnlyChange(false)}
  142. >
  143. Off
  144. </SeverityButton>
  145. <SeverityButton
  146. active={isReadOnly}
  147. variant="critical"
  148. onClick={() => handleReadOnlyChange(true)}
  149. >
  150. On
  151. </SeverityButton>
  152. </div>
  153. </div>
  154. {WARNING_TYPES.map(({ key, label, hasCritical }) => (
  155. <div key={key} className="flex items-center justify-between">
  156. <span className="text-sm text-foreground-light">{label}</span>
  157. <div className="flex gap-1">
  158. <SeverityButton
  159. active={severities[key] === null}
  160. variant="off"
  161. onClick={() => handleSeverityChange(key, null)}
  162. >
  163. Off
  164. </SeverityButton>
  165. <SeverityButton
  166. active={severities[key] === 'warning'}
  167. variant="warning"
  168. onClick={() => handleSeverityChange(key, 'warning')}
  169. >
  170. Warn
  171. </SeverityButton>
  172. {hasCritical && (
  173. <SeverityButton
  174. active={severities[key] === 'critical'}
  175. variant="critical"
  176. onClick={() => handleSeverityChange(key, 'critical')}
  177. >
  178. Crit
  179. </SeverityButton>
  180. )}
  181. </div>
  182. </div>
  183. ))}
  184. </div>
  185. </div>
  186. )
  187. }
  188. interface SeverityButtonProps {
  189. active: boolean
  190. variant: 'off' | 'warning' | 'critical'
  191. onClick: () => void
  192. children: React.ReactNode
  193. }
  194. const SeverityButton = ({ active, variant, onClick, children }: SeverityButtonProps) => (
  195. <button
  196. onClick={onClick}
  197. className={cn(
  198. 'px-1.5 py-0.5 rounded-sm text-xs font-mono transition border',
  199. active
  200. ? variant === 'off'
  201. ? 'bg-surface-300 text-foreground border-strong'
  202. : variant === 'warning'
  203. ? 'bg-warning/20 text-warning border-warning'
  204. : 'bg-destructive/20 text-destructive border-destructive'
  205. : 'bg-transparent text-foreground-muted border-transparent hover:border-border'
  206. )}
  207. >
  208. {children}
  209. </button>
  210. )