dashboard-logs.ts78 lines · main
1import * as Sentry from '@sentry/nextjs'
2import { SupportCategories } from '@supabase/shared-types/out/constants'
3
4import { createSupportStorageClient } from './support-storage-client'
5import type { ExtendedSupportCategories } from './Support.constants'
6import type {
7 GenerateAttachmentURLsData,
8 GenerateAttachmentURLsVariables,
9} from '@/data/support/generate-attachment-urls-mutation'
10import { getMirroredBreadcrumbs, getOwnershipOfBreadcrumbSnapshot } from '@/lib/breadcrumbs'
11import { uuidv4 } from '@/lib/helpers'
12import { sanitizeArrayOfObjects } from '@/lib/sanitize'
13
14export type DashboardBreadcrumb = Sentry.Breadcrumb
15
16export const DASHBOARD_LOG_BUCKET = 'dashboard-logs'
17
18export const DASHBOARD_LOG_CATEGORIES: ExtendedSupportCategories[] = [
19 SupportCategories.DASHBOARD_BUG,
20]
21
22export const getSanitizedBreadcrumbs = (): unknown[] => {
23 const breadcrumbs = getOwnershipOfBreadcrumbSnapshot() ?? getMirroredBreadcrumbs()
24 return sanitizeArrayOfObjects(breadcrumbs)
25}
26
27export const uploadDashboardLog = async ({
28 userId,
29 sanitizedLogs,
30 uploadDashboardLogFn,
31}: {
32 userId: string | undefined
33 sanitizedLogs: unknown[]
34 uploadDashboardLogFn: (
35 vars: GenerateAttachmentURLsVariables
36 ) => Promise<GenerateAttachmentURLsData>
37}): Promise<string[]> => {
38 if (!userId) {
39 console.error(
40 '[SupportForm > uploadDashboardLog] Cannot upload dashboard log: user ID is undefined'
41 )
42 return []
43 }
44
45 if (sanitizedLogs.length === 0) return []
46
47 try {
48 const supportStorageClient = createSupportStorageClient()
49 const objectKey = `${userId}/${uuidv4()}.json`
50 const body = new Blob([JSON.stringify(sanitizedLogs, null, 2)], {
51 type: 'application/json',
52 })
53
54 const { error: uploadError } = await supportStorageClient.storage
55 .from(DASHBOARD_LOG_BUCKET)
56 .upload(objectKey, body, {
57 cacheControl: '3600',
58 contentType: 'application/json',
59 upsert: false,
60 })
61
62 if (uploadError) {
63 console.error(
64 '[SupportForm > uploadDashboardLog] Failed to upload dashboard log to support storage bucket',
65 uploadError
66 )
67 return []
68 }
69
70 return uploadDashboardLogFn({
71 bucket: DASHBOARD_LOG_BUCKET,
72 filenames: [objectKey],
73 })
74 } catch (error) {
75 console.error('[SupportForm] Unexpected error uploading dashboard log', error)
76 return []
77 }
78}