EdgeFunctionRecentErrors.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. import { BookOpen, Check, ExternalLink, Eye } from 'lucide-react'
  2. import { useRouter } from 'next/router'
  3. import { Fragment, useMemo } from 'react'
  4. import {
  5. Badge,
  6. Button,
  7. Card,
  8. cn,
  9. Table,
  10. TableBody,
  11. TableCell,
  12. TableHead,
  13. TableHeader,
  14. TableRow,
  15. } from 'ui'
  16. import { PageContainer } from 'ui-patterns/PageContainer'
  17. import {
  18. PageSection,
  19. PageSectionAside,
  20. PageSectionContent,
  21. PageSectionMeta,
  22. PageSectionSummary,
  23. PageSectionTitle,
  24. } from 'ui-patterns/PageSection'
  25. import { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader'
  26. import {
  27. buildGroupAssistantPrompt,
  28. buildTroubleshootingDocsUrl,
  29. formatLogTimestamp,
  30. formatSingleLineMessage,
  31. getDisplayErrorMessage,
  32. getFunctionRuntimeLogsSql,
  33. getRecentErrorGroups,
  34. getRecentErrorGroupsBase,
  35. getRecentErrorInvocationsSql,
  36. getRelatedExecutionIds,
  37. getSinceLastDeployInvocationCount,
  38. getSinceLastDeployInvocationCountSql,
  39. getSinceLastDeployInvocationPhrase,
  40. getSinceLastDeployLogRange,
  41. getStatusBadgeVariant,
  42. toAlertError,
  43. type RecentErrorGroup,
  44. } from './EdgeFunctionRecentErrors.utils'
  45. import { SIDEBAR_KEYS } from '@/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'
  46. import { AiAssistantDropdown } from '@/components/ui/AiAssistantDropdown'
  47. import AlertError from '@/components/ui/AlertError'
  48. import useLogsQuery from '@/hooks/analytics/useLogsQuery'
  49. import { useAiAssistantStateSnapshot } from '@/state/ai-assistant-state'
  50. import { useSidebarManagerSnapshot } from '@/state/sidebar-manager-state'
  51. interface EdgeFunctionRecentErrorsProps {
  52. functionId?: string
  53. functionSlug?: string
  54. projectRef?: string
  55. updatedAt?: string | number
  56. }
  57. export const EdgeFunctionRecentErrors = ({
  58. functionId,
  59. functionSlug,
  60. projectRef,
  61. updatedAt,
  62. }: EdgeFunctionRecentErrorsProps) => {
  63. const router = useRouter()
  64. const { openSidebar } = useSidebarManagerSnapshot()
  65. const aiAssistant = useAiAssistantStateSnapshot()
  66. const { isoTimestampStart, isoTimestampEnd } = useMemo(
  67. () => getSinceLastDeployLogRange(updatedAt),
  68. [updatedAt]
  69. )
  70. const emptyStateFallback =
  71. 'Runtime errors since the last deploy will appear here when this function returns a 5xx response.'
  72. const isQueryEnabled = Boolean(projectRef && functionId && isoTimestampStart)
  73. const recentErrorInvocationsSql = useMemo(
  74. () => getRecentErrorInvocationsSql(functionId),
  75. [functionId]
  76. )
  77. const sinceLastDeployInvocationCountSql = useMemo(
  78. () => getSinceLastDeployInvocationCountSql(functionId),
  79. [functionId]
  80. )
  81. const {
  82. logData: recentErrorInvocations,
  83. isLoading: isLoadingRecentErrorInvocations,
  84. error: recentErrorInvocationsError,
  85. } = useLogsQuery(
  86. projectRef as string,
  87. {
  88. sql: recentErrorInvocationsSql,
  89. iso_timestamp_start: isoTimestampStart,
  90. iso_timestamp_end: isoTimestampEnd,
  91. },
  92. isQueryEnabled
  93. )
  94. const recentErrorGroupsBase = useMemo(
  95. () => getRecentErrorGroupsBase(recentErrorInvocations),
  96. [recentErrorInvocations]
  97. )
  98. const {
  99. logData: sinceLastDeployInvocationCountRows,
  100. isLoading: isLoadingSinceLastDeployInvocationCount,
  101. error: sinceLastDeployInvocationCountError,
  102. } = useLogsQuery(
  103. projectRef as string,
  104. {
  105. sql: sinceLastDeployInvocationCountSql,
  106. iso_timestamp_start: isoTimestampStart,
  107. iso_timestamp_end: isoTimestampEnd,
  108. },
  109. Boolean(projectRef && sinceLastDeployInvocationCountSql && isoTimestampStart)
  110. )
  111. const relatedExecutionIds = useMemo(
  112. () => getRelatedExecutionIds(recentErrorGroupsBase),
  113. [recentErrorGroupsBase]
  114. )
  115. const functionRuntimeLogsSql = useMemo(
  116. () => getFunctionRuntimeLogsSql({ functionId, executionIds: relatedExecutionIds }),
  117. [functionId, relatedExecutionIds]
  118. )
  119. const {
  120. logData: functionRuntimeLogs,
  121. isLoading: isLoadingFunctionRuntimeLogs,
  122. error: functionRuntimeLogsError,
  123. } = useLogsQuery(
  124. projectRef as string,
  125. {
  126. sql: functionRuntimeLogsSql,
  127. iso_timestamp_start: isoTimestampStart,
  128. iso_timestamp_end: isoTimestampEnd,
  129. },
  130. Boolean(projectRef && functionRuntimeLogsSql && isoTimestampStart)
  131. )
  132. const queryError =
  133. toAlertError(recentErrorInvocationsError) ?? toAlertError(functionRuntimeLogsError)
  134. const recentErrorGroups = useMemo(
  135. () => getRecentErrorGroups({ recentErrorGroupsBase, functionRuntimeLogs }),
  136. [functionRuntimeLogs, recentErrorGroupsBase]
  137. )
  138. const sinceLastDeployInvocationCount = useMemo(
  139. () => getSinceLastDeployInvocationCount(sinceLastDeployInvocationCountRows),
  140. [sinceLastDeployInvocationCountRows]
  141. )
  142. const emptyStateMessage = useMemo(() => {
  143. if (!isoTimestampStart || sinceLastDeployInvocationCountError) return emptyStateFallback
  144. const verb = sinceLastDeployInvocationCount === 1 ? 'has' : 'have'
  145. const invocationPhrase = getSinceLastDeployInvocationPhrase(sinceLastDeployInvocationCount)
  146. return (
  147. <>
  148. There {verb} been <span className="text-foreground">{invocationPhrase}</span> since last
  149. deploy and no errors.
  150. </>
  151. )
  152. }, [
  153. emptyStateFallback,
  154. isoTimestampStart,
  155. sinceLastDeployInvocationCount,
  156. sinceLastDeployInvocationCountError,
  157. ])
  158. const emptyStateIcon =
  159. isoTimestampStart && !sinceLastDeployInvocationCountError ? (
  160. sinceLastDeployInvocationCount > 0 ? (
  161. <Check
  162. size={16}
  163. strokeWidth={1.5}
  164. className="mt-0.5 shrink-0 text-brand"
  165. aria-hidden="true"
  166. />
  167. ) : (
  168. <Eye
  169. size={16}
  170. strokeWidth={1.5}
  171. className="mt-0.5 shrink-0 text-foreground-muted"
  172. aria-hidden="true"
  173. />
  174. )
  175. ) : null
  176. const handleOpenAssistant = (group: RecentErrorGroup) => {
  177. openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)
  178. aiAssistant.newChat({
  179. name: `Investigate ${functionSlug ?? 'error'}`,
  180. initialMessage: buildGroupAssistantPrompt(group, functionSlug),
  181. })
  182. }
  183. return (
  184. <PageSection>
  185. <PageSectionContent>
  186. <PageContainer size="full">
  187. <div className="flex flex-col gap-6">
  188. <PageSectionMeta>
  189. <PageSectionSummary>
  190. <PageSectionTitle>Errors since last deploy</PageSectionTitle>
  191. </PageSectionSummary>
  192. <PageSectionAside>
  193. <Button
  194. type="default"
  195. size="tiny"
  196. icon={<ExternalLink size={14} />}
  197. onClick={() =>
  198. router.push(`/project/${projectRef}/functions/${functionSlug}/logs`)
  199. }
  200. >
  201. View logs
  202. </Button>
  203. </PageSectionAside>
  204. </PageSectionMeta>
  205. {recentErrorInvocationsError || functionRuntimeLogsError ? (
  206. <AlertError
  207. error={queryError}
  208. subject="Failed to retrieve edge function errors since the last deploy"
  209. />
  210. ) : isLoadingRecentErrorInvocations ||
  211. isLoadingFunctionRuntimeLogs ||
  212. isLoadingSinceLastDeployInvocationCount ? (
  213. <GenericSkeletonLoader />
  214. ) : recentErrorGroups.length === 0 ? (
  215. <div className="rounded-md border border-dashed px-5 py-6 text-sm text-foreground-light">
  216. <div className="flex items-start gap-3">
  217. {emptyStateIcon}
  218. <div>{emptyStateMessage}</div>
  219. </div>
  220. </div>
  221. ) : (
  222. <Card className="p-0 overflow-hidden">
  223. <Table>
  224. <TableHeader>
  225. <TableRow>
  226. <TableHead>Error</TableHead>
  227. <TableHead>Count</TableHead>
  228. <TableHead>Last Seen</TableHead>
  229. <TableHead>Method</TableHead>
  230. <TableHead>Status</TableHead>
  231. <TableHead>Duration</TableHead>
  232. <TableHead className="text-right">Troubleshoot</TableHead>
  233. </TableRow>
  234. </TableHeader>
  235. <TableBody>
  236. {recentErrorGroups.map((group) => {
  237. const displayMessage = getDisplayErrorMessage(group)
  238. const docsUrl = buildTroubleshootingDocsUrl({
  239. statusCode: group.lastStatusCode,
  240. })
  241. return (
  242. <Fragment key={group.message}>
  243. <TableRow key={`${group.message}-summary`}>
  244. <TableCell className="max-w-[420px]">
  245. <span
  246. className="block truncate whitespace-nowrap text-foreground"
  247. title={displayMessage}
  248. >
  249. {displayMessage}
  250. </span>
  251. </TableCell>
  252. <TableCell className="text-foreground-light">{group.count}</TableCell>
  253. <TableCell className="text-foreground-light">
  254. {formatLogTimestamp(group.lastSeen, 'relative')}
  255. </TableCell>
  256. <TableCell className="text-foreground-light">
  257. {group.lastMethod ?? '-'}
  258. </TableCell>
  259. <TableCell>
  260. {group.lastStatusCode ? (
  261. <Badge
  262. variant={getStatusBadgeVariant(group.lastStatusCode)}
  263. className="font-mono"
  264. >
  265. {group.lastStatusCode}
  266. </Badge>
  267. ) : (
  268. <Badge variant="destructive" className="font-mono">
  269. Error
  270. </Badge>
  271. )}
  272. </TableCell>
  273. <TableCell className="text-foreground-light">
  274. {group.executionTime ?? '-'}
  275. </TableCell>
  276. <TableCell className="text-right">
  277. <div className="flex justify-end">
  278. <AiAssistantDropdown
  279. label="Ask Assistant"
  280. size="tiny"
  281. buildPrompt={() => buildGroupAssistantPrompt(group, functionSlug)}
  282. onOpenAssistant={() => handleOpenAssistant(group)}
  283. additionalDropdownItems={[
  284. {
  285. label: 'View troubleshooting guide',
  286. icon: <BookOpen size={14} />,
  287. onClick: () =>
  288. window.open(docsUrl, '_blank', 'noopener,noreferrer'),
  289. },
  290. ]}
  291. />
  292. </div>
  293. </TableCell>
  294. </TableRow>
  295. <TableRow key={`${group.message}-logs`} className="hover:bg-transparent">
  296. <TableCell colSpan={7} className="p-0">
  297. <div className="max-h-64 overflow-auto bg-surface-75 font-mono text-xs">
  298. {group.logs.length === 0 ? (
  299. <div className="px-4 py-3 text-foreground-lighter">
  300. No related runtime logs found for this error group.
  301. </div>
  302. ) : (
  303. group.logs.map((log, index) => {
  304. const isError = log.level === 'error'
  305. return (
  306. <div
  307. key={log.key}
  308. className={cn(
  309. 'flex items-start gap-3 px-4 py-2',
  310. index !== 0 && 'border-t border-default',
  311. isError && 'bg-destructive-200/40'
  312. )}
  313. >
  314. <span className="shrink-0 tabular-nums text-foreground-muted">
  315. {formatLogTimestamp(log.lastSeen, 'time')}
  316. </span>
  317. <Badge
  318. variant={isError ? 'destructive' : 'default'}
  319. className="shrink-0"
  320. >
  321. {log.level}
  322. </Badge>
  323. {log.count > 1 && (
  324. <span className="shrink-0 text-foreground-muted tabular-nums">
  325. ×{log.count}
  326. </span>
  327. )}
  328. <span
  329. className={cn(
  330. 'flex-1 wrap-break-word whitespace-pre-wrap',
  331. isError ? 'text-destructive' : 'text-foreground-light'
  332. )}
  333. >
  334. {formatSingleLineMessage(log.message)}
  335. </span>
  336. </div>
  337. )
  338. })
  339. )}
  340. </div>
  341. </TableCell>
  342. </TableRow>
  343. </Fragment>
  344. )
  345. })}
  346. </TableBody>
  347. </Table>
  348. </Card>
  349. )}
  350. </div>
  351. </PageContainer>
  352. </PageSectionContent>
  353. </PageSection>
  354. )
  355. }