EdgeFunctionRecentErrors.utils.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. import { afterEach, describe, expect, it, vi } from 'vitest'
  2. import {
  3. buildGroupAssistantPrompt,
  4. buildTroubleshootingDocsUrl,
  5. formatLogTimestamp,
  6. formatSingleLineMessage,
  7. getDisplayErrorMessage,
  8. getFunctionRuntimeLogsSql,
  9. getNoErrorsSinceLastDeployMessage,
  10. getRecentErrorGroups,
  11. getRecentErrorGroupsBase,
  12. getRelatedExecutionIds,
  13. getSinceLastDeployInvocationCount,
  14. getSinceLastDeployInvocationCountSql,
  15. getSinceLastDeployInvocationPhrase,
  16. getSinceLastDeployLogRange,
  17. getStatusBadgeVariant,
  18. summarizeErrorMessage,
  19. toAlertError,
  20. toIsoTimestamp,
  21. } from './EdgeFunctionRecentErrors.utils'
  22. describe('EdgeFunctionRecentErrors.utils', () => {
  23. afterEach(() => {
  24. vi.useRealTimers()
  25. })
  26. it('normalizes alert errors and single-line messages', () => {
  27. expect(toAlertError('boom')).toEqual({ message: 'boom' })
  28. expect(toAlertError({ message: 'broken' })).toEqual({ message: 'broken' })
  29. expect(toAlertError({ message: 123 })).toBeUndefined()
  30. expect(toAlertError(null)).toBeUndefined()
  31. expect(formatSingleLineMessage(' first line\n second\t\tline ')).toBe(
  32. 'first line second line'
  33. )
  34. })
  35. it('builds runtime log SQL and escapes interpolated values', () => {
  36. expect(getFunctionRuntimeLogsSql({ functionId: undefined, executionIds: ['abc'] })).toBe('')
  37. expect(getFunctionRuntimeLogsSql({ functionId: 'fn_123', executionIds: [] })).toBe('')
  38. expect(
  39. getFunctionRuntimeLogsSql({
  40. functionId: "fn_'123",
  41. executionIds: ['exec_1', "exec_'2"],
  42. limit: 25,
  43. })
  44. )
  45. .toBe(`select id, function_logs.timestamp, event_message, metadata.event_type, metadata.function_id, metadata.execution_id, metadata.level from function_logs
  46. cross join unnest(metadata) as metadata
  47. where metadata.function_id = 'fn_''123' and metadata.execution_id in ('exec_1', 'exec_''2')
  48. order by timestamp desc
  49. limit 25`)
  50. })
  51. it('normalizes deploy timestamps and derives the logs query range', () => {
  52. vi.useFakeTimers()
  53. vi.setSystemTime(new Date('2026-03-20T12:00:00.000Z'))
  54. const deployedAt = '2026-03-20T10:15:00.000Z'
  55. const deployedAtMilliseconds = Date.parse(deployedAt)
  56. expect(toIsoTimestamp(deployedAt)).toBe(deployedAt)
  57. expect(toIsoTimestamp(String(deployedAtMilliseconds))).toBe(deployedAt)
  58. expect(toIsoTimestamp(String(deployedAtMilliseconds * 1000))).toBe(deployedAt)
  59. expect(toIsoTimestamp('')).toBeUndefined()
  60. expect(toIsoTimestamp('not-a-date')).toBeUndefined()
  61. expect(getSinceLastDeployLogRange(deployedAt)).toEqual({
  62. isoTimestampStart: deployedAt,
  63. isoTimestampEnd: '2026-03-20T12:00:00.000Z',
  64. })
  65. expect(getSinceLastDeployLogRange('2026-03-20T13:00:00.000Z')).toEqual({
  66. isoTimestampStart: '2026-03-20T13:00:00.000Z',
  67. isoTimestampEnd: '2026-03-20T13:00:00.000Z',
  68. })
  69. expect(getSinceLastDeployLogRange()).toEqual({})
  70. })
  71. it('builds the since-deploy invocation count query and empty-state message', () => {
  72. expect(getSinceLastDeployInvocationCountSql()).toContain(
  73. 'SELECT count(*) as count FROM function_edge_logs'
  74. )
  75. expect(getSinceLastDeployInvocationCountSql()).toContain("(function_id = '__pending__')")
  76. expect(
  77. getSinceLastDeployInvocationCount([
  78. {
  79. count: '12',
  80. },
  81. ] as unknown as Parameters<typeof getSinceLastDeployInvocationCount>[0])
  82. ).toBe(12)
  83. expect(getSinceLastDeployInvocationCount([])).toBe(0)
  84. expect(getSinceLastDeployInvocationPhrase(1)).toBe('1 invocation')
  85. expect(getSinceLastDeployInvocationPhrase(1200)).toBe('1,200 invocations')
  86. expect(getNoErrorsSinceLastDeployMessage(0)).toBe(
  87. 'There have been 0 invocations since last deploy and no errors.'
  88. )
  89. expect(getNoErrorsSinceLastDeployMessage(1)).toBe(
  90. 'There has been 1 invocation since last deploy and no errors.'
  91. )
  92. expect(getNoErrorsSinceLastDeployMessage(1200)).toBe(
  93. 'There have been 1,200 invocations since last deploy and no errors.'
  94. )
  95. })
  96. it('groups recent failed invocations by parsed error message', () => {
  97. const groups = getRecentErrorGroupsBase([
  98. {
  99. id: 'invocation-1',
  100. event_message: 'POST | 500 | database exploded',
  101. method: 'POST',
  102. status_code: 500,
  103. execution_id: 'exec-1',
  104. execution_time_ms: 123.7,
  105. timestamp: 100,
  106. },
  107. {
  108. id: 'invocation-2',
  109. event_message: 'POST | 500 | database exploded',
  110. method: 'POST',
  111. status_code: 500,
  112. execution_id: 'exec-2',
  113. execution_time_ms: 85.1,
  114. timestamp: 120,
  115. },
  116. {
  117. id: 'invocation-3',
  118. event_message: '',
  119. method: 'GET',
  120. status_code: 503,
  121. execution_id: '',
  122. timestamp: 110,
  123. },
  124. ])
  125. expect(groups).toEqual([
  126. {
  127. message: 'database exploded',
  128. count: 2,
  129. lastSeen: 120,
  130. lastExecutionId: 'exec-2',
  131. lastStatusCode: '500',
  132. lastMethod: 'POST',
  133. executionTime: '85ms',
  134. executionIds: ['exec-1', 'exec-2'],
  135. },
  136. {
  137. message: 'Unknown error',
  138. count: 1,
  139. lastSeen: 110,
  140. lastExecutionId: undefined,
  141. lastStatusCode: '503',
  142. lastMethod: 'GET',
  143. executionTime: undefined,
  144. executionIds: [],
  145. },
  146. ])
  147. })
  148. it('deduplicates execution ids and attaches grouped runtime logs', () => {
  149. const recentErrorGroupsBase = [
  150. {
  151. message: 'database exploded',
  152. count: 2,
  153. lastSeen: 120,
  154. lastExecutionId: 'exec-2',
  155. lastStatusCode: '500',
  156. lastMethod: 'POST',
  157. executionTime: '85ms',
  158. executionIds: ['exec-1', 'exec-2', 'exec-1'],
  159. },
  160. ]
  161. expect(getRelatedExecutionIds(recentErrorGroupsBase)).toEqual(['exec-1', 'exec-2'])
  162. expect(
  163. getRecentErrorGroups({
  164. recentErrorGroupsBase,
  165. functionRuntimeLogs: [
  166. {
  167. id: 'runtime-log-1',
  168. execution_id: 'exec-1',
  169. level: 'error',
  170. event_message: 'stack trace',
  171. timestamp: 101,
  172. },
  173. {
  174. id: 'runtime-log-2',
  175. execution_id: 'exec-2',
  176. level: 'error',
  177. event_message: 'stack trace',
  178. timestamp: 121,
  179. },
  180. {
  181. id: 'runtime-log-3',
  182. execution_id: 'exec-2',
  183. event_type: 'warn',
  184. event_message: 'retrying upstream',
  185. timestamp: 119,
  186. },
  187. {
  188. id: 'runtime-log-4',
  189. execution_id: '',
  190. level: 'info',
  191. event_message: 'ignored',
  192. timestamp: 999,
  193. },
  194. ],
  195. })
  196. ).toEqual([
  197. {
  198. ...recentErrorGroupsBase[0],
  199. logs: [
  200. {
  201. key: 'error:stack trace',
  202. message: 'stack trace',
  203. level: 'error',
  204. count: 2,
  205. lastSeen: 121,
  206. },
  207. {
  208. key: 'warn:retrying upstream',
  209. message: 'retrying upstream',
  210. level: 'warn',
  211. count: 1,
  212. lastSeen: 119,
  213. },
  214. ],
  215. },
  216. ])
  217. })
  218. it('formats timestamps, prompts, and status variants', () => {
  219. expect(formatLogTimestamp(undefined, 'time')).toBe('-')
  220. expect(formatLogTimestamp('2026-03-20T10:15:00.000Z', 'time')).toBe('10:15:00')
  221. expect(
  222. buildGroupAssistantPrompt(
  223. {
  224. message: 'database exploded',
  225. count: 2,
  226. lastSeen: 1742465700000000,
  227. lastExecutionId: 'exec-2',
  228. lastStatusCode: '500',
  229. lastMethod: 'POST',
  230. executionTime: '85ms',
  231. executionIds: ['exec-1', 'exec-2'],
  232. logs: [
  233. {
  234. key: 'error:stack trace',
  235. message: 'stack trace',
  236. level: 'error',
  237. count: 2,
  238. lastSeen: 1742465700000000,
  239. },
  240. ],
  241. },
  242. 'my-function'
  243. )
  244. ).toContain('Analyze this edge function error since the last deploy for `my-function`.')
  245. expect(getStatusBadgeVariant()).toBe('destructive')
  246. expect(getStatusBadgeVariant('500')).toBe('destructive')
  247. expect(getStatusBadgeVariant('404')).toBe('default')
  248. })
  249. it('summarizes verbose error messages by trimming the stack trace', () => {
  250. expect(summarizeErrorMessage('')).toBe('')
  251. expect(summarizeErrorMessage('boom')).toBe('boom')
  252. expect(
  253. summarizeErrorMessage(
  254. "SyntaxError: Expected ',' or '}' after property value in JSON at position 22 at parse (<anonymous>) at packageData (ext:deno_fetch/22_body.js:408:14)"
  255. )
  256. ).toBe("SyntaxError: Expected ',' or '}' after property value in JSON at position 22")
  257. expect(summarizeErrorMessage(' multi\n line\t error ')).toBe('multi line error')
  258. })
  259. it('prefers the first runtime error log message and falls back to invocation message', () => {
  260. expect(
  261. getDisplayErrorMessage({
  262. message: 'https://example.briven.red/functions/v1/hello-world',
  263. count: 1,
  264. lastSeen: 0,
  265. executionIds: [],
  266. logs: [
  267. {
  268. key: 'log:booted (time: 22ms)',
  269. message: 'booted (time: 22ms)',
  270. level: 'log',
  271. count: 1,
  272. lastSeen: 1,
  273. },
  274. {
  275. key: 'error:SyntaxError: bad json at parse (<anonymous>)',
  276. message: 'SyntaxError: bad json at parse (<anonymous>)',
  277. level: 'error',
  278. count: 1,
  279. lastSeen: 2,
  280. },
  281. ],
  282. })
  283. ).toBe('SyntaxError: bad json')
  284. expect(
  285. getDisplayErrorMessage({
  286. message: 'https://example.briven.red/functions/v1/hello-world',
  287. count: 1,
  288. lastSeen: 0,
  289. executionIds: [],
  290. logs: [],
  291. })
  292. ).toBe('https://example.briven.red/functions/v1/hello-world')
  293. })
  294. it('builds a troubleshooting docs URL keyed off the response status code', () => {
  295. expect(buildTroubleshootingDocsUrl({ statusCode: '500' })).toBe(
  296. 'https://supabase.com/docs/guides/troubleshooting/edge-function-500-response'
  297. )
  298. expect(buildTroubleshootingDocsUrl({ statusCode: '503' })).toBe(
  299. 'https://supabase.com/docs/guides/troubleshooting/edge-function-503-response'
  300. )
  301. expect(buildTroubleshootingDocsUrl({})).toBe(
  302. 'https://supabase.com/docs/guides/troubleshooting?search=edge%20function'
  303. )
  304. expect(buildTroubleshootingDocsUrl({ statusCode: 'not-a-number' })).toBe(
  305. 'https://supabase.com/docs/guides/troubleshooting?search=edge%20function'
  306. )
  307. })
  308. })