The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Edge Function Report (#36763)
Jordi Enric3d88e1a03dba
diff --git a/apps/studio/components/interfaces/Reports/ReportChart.tsx b/apps/studio/components/interfaces/Reports/ReportChart.tsxindex 4883fc624af..378e11abb32 100644--- a/apps/studio/components/interfaces/Reports/ReportChart.tsx+++ b/apps/studio/components/interfaces/Reports/ReportChart.tsx@@ -18,12 +18,14 @@ const ReportChart = ({endDate,interval,updateDateRange,+ functionIds,}: {chart: anystartDate: stringendDate: stringinterval: stringupdateDateRange: UpdateDateRange+ functionIds?: string[]}) => {const {data,@@ -35,6 +37,7 @@ const ReportChart = ({startDate,endDate,interval,+ functionIds,data: undefined,highlightedValue:chart.id === 'client-connections' || chart.id === 'pgbouncer-connections'diff --git a/apps/studio/components/layouts/ReportsLayout/ReportsMenu.tsx b/apps/studio/components/layouts/ReportsLayout/ReportsMenu.tsxindex 1afb9f51a7a..966e75bbcc4 100644--- a/apps/studio/components/layouts/ReportsLayout/ReportsMenu.tsx+++ b/apps/studio/components/layouts/ReportsLayout/ReportsMenu.tsx@@ -27,6 +27,7 @@ const ReportsMenu = () => {const pageKey = (id || router.pathname.split('/')[4]) as stringconst storageEnabled = useIsFeatureEnabled('project_storage:all')const authEnabled = useFlag('authreportv2')+ const edgeFnEnabled = useFlag('edgefunctionreport')const canCreateCustomReport = useCheckPermissions(PermissionAction.CREATE, 'user_content', {resource: { type: 'report', owner_id: profile?.id },@@ -113,6 +114,15 @@ const ReportsMenu = () => {key: 'database',url: `/project/${ref}/reports/database`,},+ ...(edgeFnEnabled+ ? [+ {+ name: 'Edge Functions',+ key: 'edge-functions',+ url: `/project/${ref}/reports/edge-functions`,+ },+ ]+ : []),...(storageEnabled? [{diff --git a/apps/studio/components/ui/Charts/LogChartHandler.tsx b/apps/studio/components/ui/Charts/LogChartHandler.tsxindex 2db174a9d19..101b28c485c 100644--- a/apps/studio/components/ui/Charts/LogChartHandler.tsx+++ b/apps/studio/components/ui/Charts/LogChartHandler.tsx@@ -11,7 +11,6 @@ import { useInfraMonitoringQueries } from 'data/analytics/infra-monitoring-queriimport { ProjectDailyStatsAttribute } from 'data/analytics/project-daily-stats-query'import { useProjectDailyStatsQueries } from 'data/analytics/project-daily-stats-queries'import { useChartHighlight } from './useChartHighlight'-import { getMockDataForAttribute } from 'data/reports/auth-charts'import type { ChartData } from './Charts.types'import type { UpdateDateRange } from 'pages/project/[ref]/reports/database'@@ -230,12 +229,6 @@ export const useAttributeQueries = (...dailyStatsQueries[dailyStatsIdx++],data: { ...dailyStatsQueries[dailyStatsIdx - 1]?.data, provider: 'daily-stats' },}- } else if (attr.provider === 'mock') {- const mockData = getMockDataForAttribute(attr.attribute)- return {- isLoading: false,- data: { ...mockData, provider: 'mock', attribute: attr.attribute },- }} else if (attr.provider === 'reference-line') {let value = attr.value || 0return {diff --git a/apps/studio/data/reports/auth-charts.ts b/apps/studio/data/reports/auth-charts.tsindex 7978511209c..27965738927 100644--- a/apps/studio/data/reports/auth-charts.ts+++ b/apps/studio/data/reports/auth-charts.ts@@ -198,1000 +198,3 @@ export const getAuthReportAttributes = (isFreePlan: boolean) => [],},]--/**- * ================================================- * Mock data below- * TODO: Remove once we have real data- * ================================================- * */--// Time points for all mock data-const DEFAULT_TIME_POINTS = [- '2025-05-05T13:47:23Z',- '2025-05-05T14:47:23Z',- '2025-05-05T15:47:23Z',- '2025-05-05T16:47:23Z',- '2025-05-05T17:47:23Z',- '2025-05-05T18:47:23Z',- '2025-05-05T19:47:23Z',- '2025-05-05T20:47:23Z',- '2025-05-05T21:47:23Z',- '2025-05-05T22:47:23Z',- '2025-05-05T23:47:23Z',- '2025-05-06T00:47:23Z',- '2025-05-06T01:47:23Z',- '2025-05-06T02:47:23Z',- '2025-05-06T03:47:23Z',- '2025-05-06T04:47:23Z',- '2025-05-06T05:47:23Z',- '2025-05-06T06:47:23Z',- '2025-05-06T07:47:23Z',- '2025-05-06T08:47:23Z',- '2025-05-06T09:47:23Z',- '2025-05-06T10:47:23Z',- '2025-05-06T11:47:23Z',- '2025-05-06T12:47:23Z',- '2025-05-06T13:47:23Z',-]--// Helper to generate random values with some "realistic" patterns-const generatePatternedValues = (- length: number,- base: number = 5,- variance: number = 5,- spikeProbability: number = 0.1,- spikeMultiplier: number = 5-): number[] => {- return Array(length)- .fill(0)- .map(() => {- const hasSpike = Math.random() < spikeProbability- const baseValue = base + Math.floor(Math.random() * variance)- return hasSpike ? baseValue * spikeMultiplier : baseValue- })-}--export const getAuthRequestsMockData = (provider: string) => {- let values: number[] = []-- if (provider === 'Email') {- values = [3, 4, 4, 5, 4, 3, 5, 6, 4, 3, 5, 5, 4, 3, 4, 5, 6, 7, 5, 15, 6, 9, 17, 8, 4]- } else if (provider === 'Google') {- values = [2, 1, 3, 0, 5, 2, 0, 0, 1, 2, 0, 0, 1, 2, 1, 0, 0, 0, 1, 1, 2, 4, 0, 4, 12]- } else if (provider === 'GitHub') {- values = [0, 0, 8, 0, 3, 0, 0, 1, 0, 0, 3, 0, 0, 0, 1, 0, 8, 4, 2, 0, 2, 1, 3, 6, 10]- } else {- values = Array(25).fill(0)- }-- const total = values.reduce((sum, val) => sum + val, 0)- const totalAverage = total / values.length-- const data = DEFAULT_TIME_POINTS.map((time, index) => ({- period_start: time,- [provider]: values[index],- }))-- return {- data,- yAxisLimit: 100,- format: '',- totalAverage: parseFloat(totalAverage.toFixed(2)),- total,- }-}--// Add new mock data generator for provider-specific sessions-export const getProviderSessionsMockData = (provider: string) => {- let values: number[] = []-- // Generate higher base values for sessions compared to signups- if (provider === 'EmailSessions') {- values = generatePatternedValues(DEFAULT_TIME_POINTS.length, 15, 8, 0.1, 2)- } else if (provider === 'GoogleSessions') {- values = generatePatternedValues(DEFAULT_TIME_POINTS.length, 12, 6, 0.1, 2.5)- } else if (provider === 'GitHubSessions') {- values = generatePatternedValues(DEFAULT_TIME_POINTS.length, 10, 5, 0.1, 2.2)- } else {- // For other providers, generate lower values- values = generatePatternedValues(DEFAULT_TIME_POINTS.length, 5, 3, 0.1, 2)- }-- const data = DEFAULT_TIME_POINTS.map((time, index) => ({- period_start: time,- [provider]: values[index],- }))-- const total = values.reduce((sum, val) => sum + val, 0)- const totalAverage = total / values.length-- return {- data,- yAxisLimit: Math.max(...values) * 1.2,- format: '',- totalAverage: parseFloat(totalAverage.toFixed(2)),- total,- }-}--// Add new mock data generator for provider-specific churn rates-export const getProviderChurnMockData = (provider: string) => {- let values: number[] = []-- // Generate realistic churn rates (typically between 2-15%)- if (provider === 'EmailChurn') {- // Email typically has higher churn- values = generatePatternedValues(DEFAULT_TIME_POINTS.length, 2, 10, 0.1, 5.2).map((v) =>- Math.min(v, 20)- )- } else if (provider === 'GoogleChurn') {- // Google typically has lower churn due to account persistence- values = generatePatternedValues(DEFAULT_TIME_POINTS.length, 8, 2, 0.1, 1.3).map((v) =>- Math.min(v, 15)- )- } else if (provider === 'GitHubChurn') {- // GitHub has moderate churn- values = generatePatternedValues(DEFAULT_TIME_POINTS.length, 10, 2.5, 0.1, 1.2).map((v) =>- Math.min(v, 18)- )- } else {- // Other providers have varying churn rates- values = generatePatternedValues(DEFAULT_TIME_POINTS.length, 9, 3, 0.1, 1.4).map((v) =>- Math.min(v, 20)- )- }-- const data = DEFAULT_TIME_POINTS.map((time, index) => ({- period_start: time,- [provider]: values[index],- }))-- const total = values.reduce((sum, val) => sum + val, 0)- const totalAverage = total / values.length-- return {- data,- yAxisLimit: 20, // Max 20% churn rate- format: '%',- totalAverage: parseFloat(totalAverage.toFixed(1)),- total,- }-}--// Add new mock data generator for churn rates-export const getChurnRateMockData = (attribute: string) => {- let values: number[] = []-- // Overall churn rate with some variance- values = generatePatternedValues(DEFAULT_TIME_POINTS.length, 0.6, 2, 0.15, 2.6)- .map((v) => Math.max(0, v - 0.25)) // Allow some values to go to 0- .map((v) => Math.min(v, 3.2))-- const data = DEFAULT_TIME_POINTS.map((time, index) => ({- period_start: time,- [attribute]: values[index],- }))-- const total = values.reduce((sum, val) => sum + val, 0)- const totalAverage = total / values.length-- return {- data,- yAxisLimit: 1.5, // Max 1.5% churn rate- format: '%',- totalAverage: parseFloat(totalAverage.toFixed(1)),- total,- }-}--// Mock data generators for new charts-export const getActiveUsersMockData = (metric: string) => {- const length = DEFAULT_TIME_POINTS.length- let values: number[] = []-- // Generate more realistic pattern for Daily Active Users- // Create 30 days of data for a better view- const thirtyDays = 30- const thirtyDayDates = Array(thirtyDays)- .fill(0)- .map((_, i) => {- const date = new Date()- date.setDate(date.getDate() - (thirtyDays - i - 1))- return date.toISOString()- })-- // Base values that reflect a gradual growth trend- const baseValue = 200- const dailyGrowth = 1.5 // Small daily growth factor-- if (metric === 'DAU') {- values = Array(thirtyDays)- .fill(0)- .map((_, i) => {- const dayOfWeek = new Date(thirtyDayDates[i]).getDay()- const isWeekend = dayOfWeek === 0 || dayOfWeek === 6-- // Base value with growth trend- let value = baseValue + i * dailyGrowth-- // Weekday/weekend pattern (weekends have ~20% less activity)- if (isWeekend) {- value = value * 0.8- }-- // Add some randomness- const randomFactor = 0.9 + Math.random() * 0.2 // ±10%- value = value * randomFactor-- return Math.round(value)- })- } else {- // For WAU and MAU (not used in this case)- values = Array(thirtyDays).fill(0)- }-- const data = thirtyDayDates.map((time, index) => ({- period_start: time,- [metric]: values[index],- }))-- const total = values.reduce((sum, val) => sum + val, 0)- const totalAverage = total / values.length-- return {- data,- yAxisLimit: Math.max(...values) * 1.2,- format: '',- totalAverage: parseFloat(totalAverage.toFixed(2)),- total,- }-}--export const getUserTypesMockData = (type: string) => {- const length = DEFAULT_TIME_POINTS.length- let values: number[] = []-- if (type === 'NewUsers') {- values = generatePatternedValues(length, 40, 20, 0.15, 3)- } else if (type === 'ReturningUsers') {- values = generatePatternedValues(length, 200, 50, 0.1, 1.5)- } else {- values = Array(length).fill(0)- }-- const data = DEFAULT_TIME_POINTS.map((time, index) => ({- period_start: time,- [type]: values[index],- }))-- const total = values.reduce((sum, val) => sum + val, 0)- const totalAverage = total / values.length-- return {- data,- yAxisLimit: Math.max(...values) * 1.2,- format: '',- totalAverage: parseFloat(totalAverage.toFixed(2)),- total,- }-}--export const getAuthSessionsMockData = (sessionType: string) => {- const length = DEFAULT_TIME_POINTS.length- let values: number[] = []-- if (sessionType === 'TotalSessions') {- values = generatePatternedValues(length, 1200, 300, 0.1, 1.3)- } else if (sessionType === 'WebSessions') {- values = generatePatternedValues(length, 800, 200, 0.1, 1.4)- } else if (sessionType === 'MobileSessions') {- values = generatePatternedValues(length, 400, 150, 0.12, 1.5)- } else {- values = Array(length).fill(0)- }-- const data = DEFAULT_TIME_POINTS.map((time, index) => ({- period_start: time,- [sessionType]: values[index],- }))-- const total = values.reduce((sum, val) => sum + val, 0)- const totalAverage = total / values.length-- return {- data,- yAxisLimit: Math.max(...values) * 1.2,- format: '',- totalAverage: parseFloat(totalAverage.toFixed(2)),- total,- }-}--export const getSessionDurationMockData = (metric: string) => {- const length = DEFAULT_TIME_POINTS.length- // Session duration in minutes following a relatively stable pattern- const values = generatePatternedValues(length, 15, 5, 0.05, 1.5)-- const data = DEFAULT_TIME_POINTS.map((time, index) => ({- period_start: time,- [metric]: values[index],- }))-- const total = values.reduce((sum, val) => sum + val, 0)- const totalAverage = total / values.length-- return {- data,- yAxisLimit: Math.max(...values) * 1.2,- format: '',- totalAverage: parseFloat(totalAverage.toFixed(1)),- total,- }-}--// Mock data generators for authentication flows-export const getPasswordResetMockData = (metric: string) => {- const length = DEFAULT_TIME_POINTS.length- let values: number[] = []-- if (metric === 'PasswordResetRequests') {- values = generatePatternedValues(length, 25, 15, 0.1, 2)- } else if (metric === 'PasswordResetCompleted') {- values = generatePatternedValues(length, 18, 10, 0.1, 1.5)- } else {- values = Array(length).fill(0)- }-- const data = DEFAULT_TIME_POINTS.map((time, index) => ({- period_start: time,- [metric]: values[index],- }))-- const total = values.reduce((sum, val) => sum + val, 0)- const totalAverage = total / values.length-- return {- data,- yAxisLimit: Math.max(...values) * 1.2,- format: '',- totalAverage: parseFloat(totalAverage.toFixed(2)),- total,- }-}--export const getEmailVerificationMockData = (metric: string) => {- const length = DEFAULT_TIME_POINTS.length- let values: number[] = []-- if (metric === 'VerificationSent') {- values = generatePatternedValues(length, 50, 20, 0.12, 1.8)- } else if (metric === 'VerificationCompleted') {- values = generatePatternedValues(length, 35, 15, 0.1, 1.5)- } else {- values = Array(length).fill(0)- }-- const data = DEFAULT_TIME_POINTS.map((time, index) => ({- period_start: time,- [metric]: values[index],- }))-- const total = values.reduce((sum, val) => sum + val, 0)- const totalAverage = total / values.length-- return {- data,- yAxisLimit: Math.max(...values) * 1.2,- format: '',- totalAverage: parseFloat(totalAverage.toFixed(2)),- total,- }-}--export const getVerificationRatesMockData = (metric: string) => {- const length = DEFAULT_TIME_POINTS.length- let values: number[] = []-- if (metric === 'EmailOpenRate') {- // Email open rates between 50-80%- values = generatePatternedValues(length, 65, 15, 0.05, 1.2).map((v) => Math.min(v, 100))- } else if (metric === 'VerificationRate') {- // Verification completion rates between 60-90%- values = generatePatternedValues(length, 75, 15, 0.05, 1.1).map((v) => Math.min(v, 100))- } else {- values = Array(length).fill(0)- }-- const data = DEFAULT_TIME_POINTS.map((time, index) => ({- period_start: time,- [metric]: values[index],- }))-- const total = values.reduce((sum, val) => sum + val, 0)- const totalAverage = total / values.length-- return {- data,- yAxisLimit: 100, // Percentage chart- format: '%',- totalAverage: parseFloat(totalAverage.toFixed(1)),- total,- }-}--export const getMfaUsageMockData = (method: string) => {- const length = DEFAULT_TIME_POINTS.length- let values: number[] = []-- if (method === 'MfaSMS') {- values = generatePatternedValues(length, 15, 8, 0.1, 1.5)- } else if (method === 'MfaAuthenticator') {- values = generatePatternedValues(length, 25, 10, 0.1, 1.4)- } else if (method === 'MfaEmail') {- values = generatePatternedValues(length, 10, 5, 0.1, 1.6)- } else {- values = Array(length).fill(0)- }-- const data = DEFAULT_TIME_POINTS.map((time, index) => ({- period_start: time,- [method]: values[index],- }))-- const total = values.reduce((sum, val) => sum + val, 0)- const totalAverage = total / values.length-- return {- data,- yAxisLimit: Math.max(...values) * 1.2,- format: '',- totalAverage: parseFloat(totalAverage.toFixed(2)),- total,- }-}--export const getMfaAdoptionMockData = (metric: string) => {- const length = DEFAULT_TIME_POINTS.length- // MFA adoption between 15-35%- const values = generatePatternedValues(length, 25, 10, 0.05, 1.2).map((v) => Math.min(v, 100))-- const data = DEFAULT_TIME_POINTS.map((time, index) => ({- period_start: time,- [metric]: values[index],- }))-- const total = values.reduce((sum, val) => sum + val, 0)- const totalAverage = total / values.length-- return {- data,- yAxisLimit: 100, // Percentage chart- format: '%',- totalAverage: parseFloat(totalAverage.toFixed(1)),- total,- }-}--// Mock data generators for error and security charts-export const getAuthErrorsMockData = (errorType: string) => {- const length = DEFAULT_TIME_POINTS.length- let values: number[] = []-- if (errorType === 'Status403') {- // 403 Forbidden - Relatively uncommon- values = generatePatternedValues(length, 1, 1, 0.05, 3)- } else if (errorType === 'Status422') {- // 422 Unprocessable Entity - More common validation errors- values = generatePatternedValues(length, 8, 5, 0.12, 2)- } else if (errorType === 'Status429') {- // 429 Too Many Requests - Rate limiting, can be spiky- values = generatePatternedValues(length, 3, 2, 0.15, 4)- } else if (errorType === 'Status500') {- // 500 Internal Server Error - Server errors, usually low but impactful- values = generatePatternedValues(length, 1, 1, 0.08, 5)- } else {- values = Array(length).fill(0)- }-- const data = DEFAULT_TIME_POINTS.map((time, index) => ({- period_start: time,- [errorType]: values[index],- }))-- const total = values.reduce((sum, val) => sum + val, 0)- const totalAverage = total / values.length-- return {- data,- yAxisLimit: Math.max(...values) * 1.2,- format: '',- totalAverage: parseFloat(totalAverage.toFixed(2)),- total,- }-}--export const getProviderErrorRateMockData = (provider: string) => {- const length = DEFAULT_TIME_POINTS.length- let values: number[] = []-- // Error rates between 0.5-8%- if (provider === 'EmailErrorRate') {- values = generatePatternedValues(length, 2.5, 2, 0.15, 2).map((v) => Math.min(v, 10))- } else if (provider === 'GoogleErrorRate') {- values = generatePatternedValues(length, 1.2, 1, 0.1, 2.5).map((v) => Math.min(v, 10))- } else if (provider === 'GitHubErrorRate') {- values = generatePatternedValues(length, 1.5, 1.2, 0.12, 2.2).map((v) => Math.min(v, 10))- } else if (provider === 'FacebookErrorRate') {- values = generatePatternedValues(length, 2, 1.5, 0.1, 2).map((v) => Math.min(v, 10))- } else {- values = Array(length).fill(0)- }-- const data = DEFAULT_TIME_POINTS.map((time, index) => ({- period_start: time,- [provider]: values[index],- }))-- const total = values.reduce((sum, val) => sum + val, 0)- const totalAverage = total / values.length-- return {- data,- yAxisLimit: 10, // Percentage chart- format: '%',- totalAverage: parseFloat(totalAverage.toFixed(1)),- total,- }-}--export const getRateLimitingMockData = (eventType: string) => {- const length = DEFAULT_TIME_POINTS.length- let values: number[] = []-- if (eventType === 'IPRateLimited') {- values = generatePatternedValues(length, 4, 3, 0.1, 4)- } else if (eventType === 'UserRateLimited') {- values = generatePatternedValues(length, 2, 2, 0.08, 3)- } else if (eventType === 'BruteForceAttempts') {- values = generatePatternedValues(length, 1, 1, 0.05, 5)- } else {- values = Array(length).fill(0)- }-- const data = DEFAULT_TIME_POINTS.map((time, index) => ({- period_start: time,- [eventType]: values[index],- }))-- const total = values.reduce((sum, val) => sum + val, 0)- const totalAverage = total / values.length-- return {- data,- yAxisLimit: Math.max(...values) * 1.2,- format: '',- totalAverage: parseFloat(totalAverage.toFixed(2)),- total,- }-}--export const getAuthLatencyMockData = (operationType: string) => {- const length = DEFAULT_TIME_POINTS.length- let values: number[] = []-- if (operationType === 'SignInLatency') {- values = generatePatternedValues(length, 180, 50, 0.1, 1.5)- } else if (operationType === 'SignUpLatency') {- values = generatePatternedValues(length, 250, 70, 0.1, 1.4)- } else if (operationType === 'TokenRefreshLatency') {- values = generatePatternedValues(length, 120, 40, 0.1, 1.6)- } else {- values = Array(length).fill(0)- }-- const data = DEFAULT_TIME_POINTS.map((time, index) => ({- period_start: time,- [operationType]: values[index],- }))-- const total = values.reduce((sum, val) => sum + val, 0)- const totalAverage = total / values.length-- return {- data,- yAxisLimit: Math.max(...values) * 1.2,- format: '',- totalAverage: parseFloat(totalAverage.toFixed(0)),- total,- }-}--export const getSecurityEventsMockData = (eventType: string) => {- const length = DEFAULT_TIME_POINTS.length- let values: number[] = []-- if (eventType === 'SuspiciousLogins') {- values = generatePatternedValues(length, 3, 2, 0.1, 3)- } else if (eventType === 'NewDeviceLogins') {- values = generatePatternedValues(length, 15, 8, 0.1, 1.5)- } else if (eventType === 'PasswordBreachDetections') {- values = generatePatternedValues(length, 1, 1, 0.05, 5)- } else {- values = Array(length).fill(0)- }-- const data = DEFAULT_TIME_POINTS.map((time, index) => ({- period_start: time,- [eventType]: values[index],- }))-- const total = values.reduce((sum, val) => sum + val, 0)- const totalAverage = total / values.length-- return {- data,- yAxisLimit: Math.max(...values) * 1.2,- format: '',- totalAverage: parseFloat(totalAverage.toFixed(2)),- total,- }-}--export const getTokenUsageMockData = (metricType: string) => {- const length = DEFAULT_TIME_POINTS.length- let values: number[] = []-- if (metricType === 'TokenIssuance') {- values = generatePatternedValues(length, 100, 40, 0.1, 1.5)- } else if (metricType === 'TokenRefresh') {- values = generatePatternedValues(length, 400, 100, 0.1, 1.3)- } else if (metricType === 'TokenRevocation') {- values = generatePatternedValues(length, 30, 15, 0.1, 2)- } else {- values = Array(length).fill(0)- }-- const data = DEFAULT_TIME_POINTS.map((time, index) => ({- period_start: time,- [metricType]: values[index],- }))-- const total = values.reduce((sum, val) => sum + val, 0)- const totalAverage = total / values.length-- return {- data,- yAxisLimit: Math.max(...values) * 1.2,- format: '',- totalAverage: parseFloat(totalAverage.toFixed(2)),- total,- }-}--// Mock data generators for conversion metrics-export const getAuthFunnelMockData = (stage: string) => {- const length = DEFAULT_TIME_POINTS.length- let values: number[] = []-- if (stage === 'PageVisits') {- values = generatePatternedValues(length, 500, 200, 0.1, 1.5)- } else if (stage === 'SignupStarts') {- values = generatePatternedValues(length, 120, 50, 0.1, 1.4)- } else if (stage === 'SignupCompletes') {- values = generatePatternedValues(length, 80, 30, 0.1, 1.3)- } else if (stage === 'FirstLogins') {- values = generatePatternedValues(length, 75, 25, 0.1, 1.3)- } else {- values = Array(length).fill(0)- }-- const data = DEFAULT_TIME_POINTS.map((time, index) => ({- period_start: time,- [stage]: values[index],- }))-- const total = values.reduce((sum, val) => sum + val, 0)- const totalAverage = total / values.length-- return {- data,- yAxisLimit: Math.max(...values) * 1.2,- format: '',- totalAverage: parseFloat(totalAverage.toFixed(2)),- total,- }-}--export const getConversionRatesMockData = (rateType: string) => {- const length = DEFAULT_TIME_POINTS.length- let values: number[] = []-- if (rateType === 'VisitToSignupRate') {- // Visit to signup: 20-30%- values = generatePatternedValues(length, 25, 5, 0.1, 1.2).map((v) => Math.min(v, 40))- } else if (rateType === 'SignupCompletionRate') {- // Signup completion: 60-80%- values = generatePatternedValues(length, 70, 10, 0.1, 1.1).map((v) => Math.min(v, 90))- } else if (rateType === 'RetentionRate') {- // 7-day retention: 40-60%- values = generatePatternedValues(length, 50, 10, 0.1, 1.1).map((v) => Math.min(v, 75))- } else {- values = Array(length).fill(0)- }-- const data = DEFAULT_TIME_POINTS.map((time, index) => ({- period_start: time,- [rateType]: values[index],- }))-- const total = values.reduce((sum, val) => sum + val, 0)- const totalAverage = total / values.length-- return {- data,- yAxisLimit: 100, // Percentage chart- format: '%',- totalAverage: parseFloat(totalAverage.toFixed(1)),- total,- }-}--export const getOnboardingCompletionMockData = (stage: string) => {- const length = DEFAULT_TIME_POINTS.length- let values: number[] = []-- if (stage === 'OnboardingStarts') {- values = generatePatternedValues(length, 70, 25, 0.1, 1.4)- } else if (stage === 'ProfileCompletions') {- values = generatePatternedValues(length, 50, 20, 0.1, 1.3)- } else if (stage === 'VerificationCompletions') {- values = generatePatternedValues(length, 40, 15, 0.1, 1.3)- } else {- values = Array(length).fill(0)- }-- const data = DEFAULT_TIME_POINTS.map((time, index) => ({- period_start: time,- [stage]: values[index],- }))-- const total = values.reduce((sum, val) => sum + val, 0)- const totalAverage = total / values.length-- return {- data,- yAxisLimit: Math.max(...values) * 1.2,- format: '',- totalAverage: parseFloat(totalAverage.toFixed(2)),- total,- }-}--export const getOnboardingTimeMockData = (metric: string) => {- const length = DEFAULT_TIME_POINTS.length- // Onboarding time in minutes, generally 5-15 minutes- const values = generatePatternedValues(length, 10, 5, 0.1, 1.3)-- const data = DEFAULT_TIME_POINTS.map((time, index) => ({- period_start: time,- [metric]: values[index],- }))-- const total = values.reduce((sum, val) => sum + val, 0)- const totalAverage = total / values.length-- return {- data,- yAxisLimit: Math.max(...values) * 1.2,- format: '',- totalAverage: parseFloat(totalAverage.toFixed(1)),- total,- }-}--// Master mock data resolver - routes to the appropriate data generator based on attribute-export const getMockDataForAttribute = (attribute: string) => {- // Auth Requests (original chart)- if (- [- 'Email',- 'Google',- 'GitHub',- 'Phone',- 'SAML',- 'Apple',- 'Azure',- 'Bitbucket',- 'Discord',- 'Facebook',- 'Figma',- 'GitLab',- 'Kakao',- 'KeyCloak',- 'LinkedIn',- 'Notion',- 'Twitch',- 'Twitter',- 'Slack',- 'Spotify',- 'WorkOS',- 'Zoom',- ].includes(attribute)- ) {- return getAuthRequestsMockData(attribute)- }-- // Provider-specific sessions- if (- [- 'EmailSessions',- 'PhoneSessions',- 'SAMLSessions',- 'AppleSessions',- 'AzureSessions',- 'BitbucketSessions',- 'DiscordSessions',- 'FacebookSessions',- 'FigmaSessions',- 'GitHubSessions',- 'GitLabSessions',- 'GoogleSessions',- 'KakaoSessions',- 'KeyCloakSessions',- 'LinkedInSessions',- 'NotionSessions',- 'TwitchSessions',- 'TwitterSessions',- 'SlackSessions',- 'SpotifySessions',- 'WorkOSSessions',- 'ZoomSessions',- ].includes(attribute)- ) {- return getProviderSessionsMockData(attribute)- }-- // Provider-specific churn- if (- [- 'EmailChurn',- 'PhoneChurn',- 'SAMLChurn',- 'AppleChurn',- 'AzureChurn',- 'BitbucketChurn',- 'DiscordChurn',- 'FacebookChurn',- 'FigmaChurn',- 'GitHubChurn',- 'GitLabChurn',- 'GoogleChurn',- 'KakaoChurn',- 'KeyCloakChurn',- 'LinkedInChurn',- 'NotionChurn',- 'TwitchChurn',- 'TwitterChurn',- 'SlackChurn',- 'SpotifyChurn',- 'WorkOSChurn',- 'ZoomChurn',- ].includes(attribute)- ) {- return getProviderChurnMockData(attribute)- }-- // Overall churn rate- if (attribute === 'ChurnRate') {- return getChurnRateMockData(attribute)- }-- // Active Users charts- if (['DAU', 'WAU', 'MAU'].includes(attribute)) {- return getActiveUsersMockData(attribute)- }-- // User Types charts- if (['NewUsers', 'ReturningUsers'].includes(attribute)) {- return getUserTypesMockData(attribute)- }-- // Auth Sessions charts- if (['TotalSessions', 'WebSessions', 'MobileSessions'].includes(attribute)) {- return getAuthSessionsMockData(attribute)- }-- // Session Duration- if (attribute === 'AvgSessionDuration') {- return getSessionDurationMockData(attribute)- }-- // Password Reset metrics- if (['PasswordResetRequests', 'PasswordResetCompleted'].includes(attribute)) {- return getPasswordResetMockData(attribute)- }-- // Email Verification metrics- if (['VerificationSent', 'VerificationCompleted'].includes(attribute)) {- return getEmailVerificationMockData(attribute)- }-- // Verification Rates- if (['EmailOpenRate', 'VerificationRate'].includes(attribute)) {- return getVerificationRatesMockData(attribute)- }-- // MFA Usage- if (['MfaSMS', 'MfaAuthenticator', 'MfaEmail'].includes(attribute)) {- return getMfaUsageMockData(attribute)- }-- // MFA Adoption Rate- if (attribute === 'MfaAdoptionRate') {- return getMfaAdoptionMockData(attribute)- }-- // Auth Errors- if (['Status403', 'Status422', 'Status429', 'Status500'].includes(attribute)) {- return getAuthErrorsMockData(attribute)- }-- // Provider Error Rates- if (- ['EmailErrorRate', 'GoogleErrorRate', 'GitHubErrorRate', 'FacebookErrorRate'].includes(- attribute- )- ) {- return getProviderErrorRateMockData(attribute)- }-- // Rate Limiting- if (['IPRateLimited', 'UserRateLimited', 'BruteForceAttempts'].includes(attribute)) {- return getRateLimitingMockData(attribute)- }-- // Auth Latency- if (['SignInLatency', 'SignUpLatency', 'TokenRefreshLatency'].includes(attribute)) {- return getAuthLatencyMockData(attribute)- }-- // Security Events- if (['SuspiciousLogins', 'NewDeviceLogins', 'PasswordBreachDetections'].includes(attribute)) {- return getSecurityEventsMockData(attribute)- }-- // Token Usage- if (['TokenIssuance', 'TokenRefresh', 'TokenRevocation'].includes(attribute)) {- return getTokenUsageMockData(attribute)- }-- // Auth Funnel- if (['PageVisits', 'SignupStarts', 'SignupCompletes', 'FirstLogins'].includes(attribute)) {- return getAuthFunnelMockData(attribute)- }-- // Conversion Rates- if (['VisitToSignupRate', 'SignupCompletionRate', 'RetentionRate'].includes(attribute)) {- return getConversionRatesMockData(attribute)- }-- // Onboarding Completion- if (['OnboardingStarts', 'ProfileCompletions', 'VerificationCompletions'].includes(attribute)) {- return getOnboardingCompletionMockData(attribute)- }-- // Onboarding Time- if (attribute === 'TimeToCompleteOnboarding') {- return getOnboardingTimeMockData(attribute)- }-- // Default fallback- return {- data: DEFAULT_TIME_POINTS.map((time) => ({ period_start: time, [attribute]: 0 })),- yAxisLimit: 10,- format: '',- totalAverage: 0,- total: 0,- }-}diff --git a/apps/studio/data/reports/edgefn-charts.ts b/apps/studio/data/reports/edgefn-charts.tsnew file mode 100644index 00000000000..24c5f72be5b--- /dev/null+++ b/apps/studio/data/reports/edgefn-charts.ts@@ -0,0 +1,80 @@+export const getEdgeFunctionReportAttributes = () => [+ {+ id: 'invocations',+ label: 'Edge Function Invocations',+ valuePrecision: 0,+ hide: false,+ showTooltip: true,+ showLegend: true,+ showMaxValue: false,+ hideChartType: false,+ defaultChartStyle: 'bar',+ titleTooltip: 'The total number of edge function invocations.',+ attributes: [+ {+ attribute: 'TotalInvocations',+ provider: 'logs',+ label: 'Invocations',+ enabled: true,+ },+ ],+ },+ {+ id: 'execution-status-codes',+ label: 'Edge Function Execution Status Codes',+ valuePrecision: 0,+ hide: false,+ showTooltip: true,+ showLegend: true,+ showMaxValue: false,+ hideChartType: false,+ defaultChartStyle: 'bar',+ titleTooltip: 'The total number of edge function executions by status code.',+ attributes: [+ {+ attribute: 'ExecutionStatusCodes',+ provider: 'logs',+ label: 'Execution Status Codes',+ },+ ],+ },+ {+ id: 'invocations-by-region',+ label: 'Edge Function Invocations by Region',+ valuePrecision: 0,+ hide: false,+ showTooltip: true,+ showLegend: true,+ showMaxValue: false,+ hideChartType: false,+ defaultChartStyle: 'bar',+ titleTooltip: 'The total number of edge function invocations by region.',+ attributes: [+ {+ attribute: 'InvocationsByRegion',+ provider: 'logs',+ label: 'Invocations by Region',+ },+ ],+ },+ {+ id: 'execution-time',+ label: 'Edge Function Execution Time',+ valuePrecision: 2,+ hide: false,+ showTooltip: true,+ showLegend: true,+ showMaxValue: false,+ hideChartType: false,+ defaultChartStyle: 'line',+ titleTooltip: 'Average execution time for edge functions.',+ attributes: [+ {+ attribute: 'ExecutionTime',+ label: 'Avg. Execution Time (ms)',+ provider: 'logs',+ enabled: true,+ },+ ],+ },+]diff --git a/apps/studio/data/reports/edgefn-query.ts b/apps/studio/data/reports/edgefn-query.tsnew file mode 100644index 00000000000..3e445d92953--- /dev/null+++ b/apps/studio/data/reports/edgefn-query.ts@@ -0,0 +1,399 @@+import { useQuery } from '@tanstack/react-query'+import { get } from 'data/fetchers'+import { AnalyticsInterval } from 'data/analytics/constants'+import type { MultiAttribute } from 'components/ui/Charts/ComposedChart.utils'+import { getHttpStatusCodeInfo } from 'lib/http-status-codes'+import { analyticsIntervalToGranularity, useEdgeFnIdToName } from './report.utils'+import { REPORT_STATUS_CODE_COLORS } from './report.utils'++/**+ * METRICS+ * Each chart in the UI has a corresponding metric key.+ */++const METRIC_KEYS = [+ 'TotalInvocations',+ 'ExecutionStatusCodes',+ 'InvocationsByRegion',+ 'ExecutionTime',+]++type MetricKey = (typeof METRIC_KEYS)[number]++/**+ * SQL+ * Each metric has a corresponding SQL query.+ */++const METRIC_SQL: Record<+ MetricKey,+ (interval: AnalyticsInterval, functionIds?: string[]) => string+> = {+ TotalInvocations: (interval, functionIds) => {+ return `+--edgefn-report-invocations+select+ timestamp_trunc(timestamp, ${analyticsIntervalToGranularity(interval)}) as timestamp,+ function_id,+ count(*) as count+from+ function_edge_logs+ CROSS JOIN UNNEST(metadata) AS m+ CROSS JOIN UNNEST(m.request) AS request+ CROSS JOIN UNNEST(m.response) AS response+ ${+ functionIds && functionIds.length > 0+ ? `WHERE function_id IN (${functionIds.map((id) => `'${id}'`).join(',')})`+ : ''+ }+group by+ timestamp,+ function_id+order by+ timestamp desc;++ `+ },+ ExecutionStatusCodes: (interval, functionIds) => {+ return `+--edgefn-report-execution-status-codes+select+ timestamp_trunc(timestamp, ${analyticsIntervalToGranularity(interval)}) as timestamp,+ response.status_code AS status_code,+ COUNT(*) AS count+FROM+ function_edge_logs+ CROSS JOIN UNNEST(metadata) AS m+ CROSS JOIN UNNEST(m.response) AS response+ CROSS JOIN UNNEST(m.request) AS request+ ${+ functionIds && functionIds.length > 0+ ? `WHERE function_id IN (${functionIds.map((id) => `'${id}'`).join(',')})`+ : ''+ }+group by+ timestamp,+ status_code+order by+ timestamp desc;+ `+ },+ InvocationsByRegion: (interval, functionIds) => {+ const granularity = analyticsIntervalToGranularity(interval)+ return `+--edgefn-report-invocations-by-region+select+ timestamp_trunc(timestamp, ${granularity}) as timestamp,+ h.x_sb_edge_region as region,+ count(*) as count+from+ function_edge_logs+ cross join unnest(metadata) as m+ cross join unnest(m.response) as r+ cross join unnest(r.headers) as h+ where h.x_sb_edge_region is not null+ ${+ functionIds && functionIds.length > 0+ ? `and function_id IN (${functionIds.map((id) => `'${id}'`).join(',')})`+ : ''+ }+group by+ timestamp,+ region+order by+ timestamp desc+ `+ },+ ExecutionTime: (interval, functionIds) => {+ const granularity = analyticsIntervalToGranularity(interval)+ return `+--edgefn-report-execution-time+select+ timestamp_trunc(timestamp, ${granularity}) as timestamp,+ function_id,+ avg(m.execution_time_ms) as avg_execution_time+from+ function_edge_logs+ cross join unnest(metadata) as m+ cross join unnest(m.request) as request+ ${+ functionIds && functionIds.length > 0+ ? `where function_id IN (${functionIds.map((id) => `'${id}'`).join(',')})`+ : ''+ }+group by+ timestamp,+ function_id+order by+ timestamp desc+ `+ },+}++/**+ * FORMATTERS.+ * Metrics need to be formatted before being passed on to the UI charts.+ */++function defaultFormatter(rawData: any, attributes: MultiAttribute[]) {+ const chartAttributes = attributes+ if (!rawData) return { data: undefined, chartAttributes }+ const result = rawData.result || []+ const timestamps = new Set<string>(result.map((p: any) => p.timestamp))+ const data = Array.from(timestamps)+ .sort()+ .map((timestamp) => {+ const point: any = { period_start: timestamp }+ chartAttributes.forEach((attr) => {+ point[attr.attribute] = 0+ })+ const matchingPoints = result.filter((p: any) => p.timestamp === timestamp)+ matchingPoints.forEach((p: any) => {+ point[attributes[0].attribute] = p.count+ })+ return point+ })+ return { data, chartAttributes }+}++const METRIC_FORMATTER: Record<+ MetricKey,+ (+ rawData: any,+ attributes: MultiAttribute[],+ logsMetric: string,+ functionIds?: string[],+ edgeFnIdToName?: (id: string) => string | undefined+ ) => { data: any; chartAttributes: any }+> = {+ TotalInvocations: (rawData, attributes, logsMetric, functionIds, edgeFnIdToName) => {+ // Always use dynamic attributes, so the chart can show per-function stats.+ if (!rawData) return { data: undefined, chartAttributes: attributes }+ const result = rawData.result || []++ const functionIdsInData = Array.from(new Set(result.map((p: any) => p.function_id))) as string[]++ const chartFunctionIds = functionIds && functionIds.length > 0 ? functionIds : functionIdsInData++ if (chartFunctionIds.length === 0) {+ return { data: [], chartAttributes: [] } // No data, empty chart+ }++ const chartAttributes = chartFunctionIds.map((id: string) => ({+ attribute: id,+ label: edgeFnIdToName?.(id) ?? id,+ provider: 'logs',+ enabled: true,+ }))++ const timestamps = new Set<string>(result.map((p: any) => p.timestamp))+ const data = Array.from(timestamps)+ .sort()+ .map((timestamp) => {+ const point: any = { period_start: timestamp }+ chartAttributes.forEach((attr) => {+ point[attr.attribute] = 0+ })+ const matchingPoints = result.filter((p: any) => p.timestamp === timestamp)+ matchingPoints.forEach((p: any) => {+ point[p.function_id as string] = p.count+ })+ return point+ })++ return { data, chartAttributes }+ },+ ExecutionStatusCodes: (rawData, attributes) => {+ if (!rawData) return { data: undefined, chartAttributes: attributes }+ const result = rawData.result || []++ const statusCodes = Array.from(new Set(result.map((p: any) => p.status_code)))++ const chartAttributes = statusCodes.map((statusCode) => {+ const statusCodeInfo = getHttpStatusCodeInfo(Number(statusCode))+ const color =+ REPORT_STATUS_CODE_COLORS[String(statusCode)] || REPORT_STATUS_CODE_COLORS.default++ return {+ attribute: `status_${statusCode}`,+ label: `${statusCode} ${statusCodeInfo.label}`,+ provider: 'logs',+ enabled: true,+ color: color,+ statusCode: String(statusCode),+ }+ })++ const timestamps = new Set<string>(result.map((p: any) => p.timestamp))+ const data = Array.from(timestamps)+ .sort()+ .map((timestamp) => {+ const point: any = { period_start: timestamp }+ chartAttributes.forEach((attr) => {+ point[attr.attribute] = 0+ })+ const matchingPoints = result.filter((p: any) => p.timestamp === timestamp)+ matchingPoints.forEach((p: any) => {+ point[`status_${p.status_code}`] = p.count+ })+ return point+ })++ return { data, chartAttributes }+ },+ InvocationsByRegion: (rawData, attributes) => {+ if (!rawData) return { data: undefined, chartAttributes: attributes }+ const result = rawData.result || []++ const regions = Array.from(new Set(result.map((p: any) => p.region))).filter(Boolean)++ if (regions.length === 0) {+ return { data: [], chartAttributes: [] } // No data, empty chart+ }++ const chartAttributes = regions.map((region) => {+ return {+ attribute: region,+ label: region,+ provider: 'logs',+ enabled: true,+ }+ })++ const timestamps = new Set<string>(result.map((p: any) => p.timestamp))+ const data = Array.from(timestamps)+ .sort()+ .map((timestamp) => {+ const point: any = { period_start: timestamp }+ chartAttributes.forEach((attr) => {+ point[attr.attribute as string] = 0+ })+ const matchingPoints = result.filter((p: any) => p.timestamp === timestamp)+ matchingPoints.forEach((p: any) => {+ point[p.region] = p.count+ })+ return point+ })++ return { data, chartAttributes }+ },+ ExecutionTime: (rawData, attributes, logsMetric, functionIds, edgeFnIdToName) => {+ // Always use dynamic attributes, so the chart can show per-function stats.+ if (!rawData) return { data: undefined, chartAttributes: attributes }+ const result = rawData.result || []++ const functionIdsInData = Array.from(new Set(result.map((p: any) => p.function_id))) as string[]++ const chartFunctionIds = functionIds && functionIds.length > 0 ? functionIds : functionIdsInData++ if (chartFunctionIds.length === 0) {+ return { data: [], chartAttributes: [] } // No data, empty chart+ }++ const chartAttributes = chartFunctionIds.map((id: string) => ({+ attribute: id,+ label: edgeFnIdToName?.(id) ?? id,+ provider: 'logs',+ enabled: true,+ }))++ const timestamps = new Set<string>(result.map((p: any) => p.timestamp))+ const data = Array.from(timestamps)+ .sort()+ .map((timestamp) => {+ const point: any = { period_start: timestamp }+ chartAttributes.forEach((attr) => {+ point[attr.attribute] = 0+ })+ const matchingPoints = result.filter((p: any) => p.timestamp === timestamp)+ matchingPoints.forEach((p: any) => {+ point[p.function_id as string] = p.avg_execution_time+ })+ return point+ })++ return { data, chartAttributes }+ },+}++/**+ * REPORT QUERY.+ * Fetching and state management for the report.+ */++export function useEdgeFunctionReport({+ projectRef,+ attributes,+ startDate,+ endDate,+ interval,+ enabled = true,+ functionIds,+}: {+ projectRef: string+ attributes: MultiAttribute[]+ startDate: string+ endDate: string+ interval: AnalyticsInterval+ enabled?: boolean+ functionIds?: string[]+}) {+ const logsMetric = attributes.length > 0 ? attributes[0].attribute : ''+ const { edgeFnIdToName } = useEdgeFnIdToName({ projectRef })+ const isEdgeFnMetric = METRIC_KEYS.includes(logsMetric)++ const sql = isEdgeFnMetric ? METRIC_SQL[logsMetric as MetricKey](interval, functionIds) : ''++ const {+ data: rawData,+ error,+ isLoading,+ } = useQuery(+ [+ 'edge-function-report',+ projectRef,+ logsMetric,+ startDate,+ endDate,+ interval,+ sql,+ functionIds,+ ],+ async () => {+ const { data, error } = await get(`/platform/projects/{ref}/analytics/endpoints/logs.all`, {+ params: {+ path: { ref: projectRef },+ query: {+ sql,+ iso_timestamp_start: startDate,+ iso_timestamp_end: endDate,+ },+ },+ })+ if (error) throw error+ return data+ },+ {+ enabled: Boolean(projectRef && sql && enabled && isEdgeFnMetric),+ refetchOnWindowFocus: false,+ }+ )++ // Use formatter if available+ const formatter =+ (isEdgeFnMetric ? METRIC_FORMATTER[logsMetric as MetricKey] : undefined) || defaultFormatter+ const { data, chartAttributes } = formatter(+ rawData,+ attributes,+ logsMetric,+ functionIds,+ edgeFnIdToName+ )++ return {+ data,+ attributes: chartAttributes,+ isLoading,+ error,+ }+}diff --git a/apps/studio/data/reports/report.utils.ts b/apps/studio/data/reports/report.utils.tsindex e41bf7e759d..67629df57fc 100644--- a/apps/studio/data/reports/report.utils.ts+++ b/apps/studio/data/reports/report.utils.ts@@ -1,6 +1,7 @@import { AnalyticsInterval } from 'data/analytics/constants'+import { useEdgeFunctionsQuery } from 'data/edge-functions/edge-functions-query'-export type Granularity = 'minute' | 'hour' | 'day' | 'week'+export type Granularity = 'minute' | 'hour' | 'day'export function analyticsIntervalToGranularity(interval: AnalyticsInterval): Granularity {switch (interval) {case '1m':@@ -19,3 +20,34 @@ export function analyticsIntervalToGranularity(interval: AnalyticsInterval): Grareturn 'hour'}}++export const REPORT_STATUS_CODE_COLORS: { [key: string]: { light: string; dark: string } } = {+ '400': { light: '#FFD54F', dark: '#FFF176' },+ '401': { light: '#FF8A65', dark: '#FFAB91' },+ '403': { light: '#FFB74D', dark: '#FFCC80' },+ '404': { light: '#90A4AE', dark: '#B0BEC5' },+ '409': { light: '#BA68C8', dark: '#CE93D8' },+ '410': { light: '#A1887F', dark: '#BCAAA4' },+ '422': { light: '#FF9800', dark: '#FFB74D' },+ '429': { light: '#E65100', dark: '#F57C00' },+ '500': { light: '#B71C1C', dark: '#D32F2F' },+ '502': { light: '#9575CD', dark: '#B39DDB' },+ '503': { light: '#0097A7', dark: '#4DD0E1' },+ '504': { light: '#C0CA33', dark: '#D4E157' },+ default: { light: '#757575', dark: '#9E9E9E' },+}++export const useEdgeFnIdToName = ({ projectRef }: { projectRef: string }) => {+ const { data: edgeFunctions, isLoading } = useEdgeFunctionsQuery({+ projectRef,+ })++ function edgeFnIdToName(id: string) {+ return edgeFunctions?.find((fn) => fn.id === id)?.name+ }++ return {+ edgeFnIdToName,+ isLoading,+ }+}diff --git a/apps/studio/hooks/useChartData.ts b/apps/studio/hooks/useChartData.tsindex 003d4bab529..ce90139b960 100644--- a/apps/studio/hooks/useChartData.ts+++ b/apps/studio/hooks/useChartData.ts@@ -17,6 +17,7 @@ import { useAuthLogsReport } from 'data/reports/auth-report-query'import type { ChartData } from 'components/ui/Charts/Charts.types'import type { MultiAttribute } from 'components/ui/Charts/ComposedChart.utils'import { useAttributeQueries } from 'components/ui/Charts/LogChartHandler'+import { useEdgeFunctionReport } from 'data/reports/edgefn-query'export const useChartData = ({attributes,@@ -25,6 +26,7 @@ export const useChartData = ({interval,data,highlightedValue,+ functionIds,}: {attributes: MultiAttribute[]startDate: string@@ -32,6 +34,7 @@ export const useChartData = ({interval: stringdata?: ChartDatahighlightedValue?: string | number+ functionIds?: string[]}) => {const router = useRouter()const { ref } = router.query@@ -40,19 +43,41 @@ export const useChartData = ({const logsAttributes = attributes.filter((attr) => attr.provider === 'logs')const nonLogsAttributes = attributes.filter((attr) => attr.provider !== 'logs')+ const isEdgeFunctionRoute = router.asPath.includes('/reports/edge-functions')+const {- data: logsData,- attributes: logsChartAttributes,- isLoading: isLogsLoading,+ data: authData,+ attributes: authChartAttributes,+ isLoading: isAuthLoading,} = useAuthLogsReport({projectRef: ref as string,attributes: logsAttributes,startDate,endDate,interval: interval as AnalyticsInterval,- enabled: logsAttributes.length > 0,+ enabled: logsAttributes.length > 0 && !isEdgeFunctionRoute,+ })++ const {+ data: edgeFunctionData,+ attributes: edgeFunctionChartAttributes,+ isLoading: isEdgeFunctionLoading,+ } = useEdgeFunctionReport({+ projectRef: ref as string,+ attributes: logsAttributes,+ startDate,+ endDate,+ interval: interval as AnalyticsInterval,+ enabled: logsAttributes.length > 0 && isEdgeFunctionRoute,+ functionIds,})+ const logsData = isEdgeFunctionRoute ? edgeFunctionData : authData+ const logsChartAttributes = isEdgeFunctionRoute+ ? edgeFunctionChartAttributes+ : authChartAttributes+ const isLogsLoading = isEdgeFunctionRoute ? isEdgeFunctionLoading : isAuthLoading+const chartAttributes = useMemo(() => nonLogsAttributes.concat(logsChartAttributes || []),[nonLogsAttributes, logsChartAttributes]diff --git a/apps/studio/pages/project/[ref]/reports/edge-functions.tsx b/apps/studio/pages/project/[ref]/reports/edge-functions.tsxnew file mode 100644index 00000000000..d0060d55816--- /dev/null+++ b/apps/studio/pages/project/[ref]/reports/edge-functions.tsx@@ -0,0 +1,264 @@+import { useState, useEffect } from 'react'+import { useQueryClient } from '@tanstack/react-query'+import dayjs from 'dayjs'+import { ArrowRight, ChevronDown, RefreshCw } from 'lucide-react'+import { useParams } from 'common'++import ReportHeader from 'components/interfaces/Reports/ReportHeader'+import ReportPadding from 'components/interfaces/Reports/ReportPadding'+import DefaultLayout from 'components/layouts/DefaultLayout'+import ReportsLayout from 'components/layouts/ReportsLayout/ReportsLayout'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'+import ShimmerLine from 'components/ui/ShimmerLine'+import { DateRangePicker } from 'components/ui/DateRangePicker'++import { useCurrentOrgPlan } from 'hooks/misc/useCurrentOrgPlan'+import { TIME_PERIODS_INFRA } from 'lib/constants/metrics'++import type { NextPageWithLayout } from 'types'++import { Button, Checkbox, DropdownMenu, DropdownMenuContent, DropdownMenuTrigger } from 'ui'+import ReportChart from 'components/interfaces/Reports/ReportChart'+import { getEdgeFunctionReportAttributes } from 'data/reports/edgefn-charts'+import { useEdgeFunctionsQuery } from 'data/edge-functions/edge-functions-query'+import { Label } from '@ui/components/shadcn/ui/label'++const EdgeFunctionsReport: NextPageWithLayout = () => {+ return (+ <ReportPadding>+ <EdgeFunctionsUsage />+ </ReportPadding>+ )+}++EdgeFunctionsReport.getLayout = (page) => (+ <DefaultLayout>+ <ReportsLayout title="Edge Functions">{page}</ReportsLayout>+ </DefaultLayout>+)++export type UpdateDateRange = (from: string, to: string) => void+export default EdgeFunctionsReport++const EdgeFunctionsUsage = () => {+ const { ref } = useParams()+ const { data: functions, isLoading: isLoadingFunctions } = useEdgeFunctionsQuery({+ projectRef: ref,+ })+ const [isOpen, setIsOpen] = useState(false)+ const [functionIds, setFunctionIds] = useState<string[]>([])+ const [tempFunctionIds, setTempFunctionIds] = useState<string[]>(functionIds)++ useEffect(() => {+ if (isOpen) {+ setTempFunctionIds(functionIds)+ }+ }, [isOpen, functionIds])++ const defaultStart = dayjs().subtract(1, 'day').toISOString()+ const defaultEnd = dayjs().toISOString()+ const [dateRange, setDateRange] = useState<any>({+ period_start: { date: defaultStart, time_period: '1d' },+ period_end: { date: defaultEnd, time_period: 'today' },+ interval: '1h',+ })++ const queryClient = useQueryClient()+ const [isRefreshing, setIsRefreshing] = useState(false)++ useCurrentOrgPlan()++ const EDGEFN_CHARTS = getEdgeFunctionReportAttributes()++ const onRefreshReport = async () => {+ if (!dateRange) return++ setIsRefreshing(true)+ queryClient.invalidateQueries(['edge-function-report', ref])+ setTimeout(() => setIsRefreshing(false), 1000)+ }++ const handleIntervalGranularity = (from: string, to: string) => {+ const conditions = {+ '1m': dayjs(to).diff(from, 'hour') < 3, // less than 3 hours+ '10m': dayjs(to).diff(from, 'hour') < 6, // less than 6 hours+ '30m': dayjs(to).diff(from, 'hour') < 18, // less than 18 hours+ '1h': dayjs(to).diff(from, 'day') < 10, // less than 10 days+ '1d': dayjs(to).diff(from, 'day') >= 10, // more than 10 days+ }++ switch (true) {+ case conditions['1m']:+ return '1m'+ case conditions['10m']:+ return '10m'+ case conditions['30m']:+ return '30m'+ default:+ return '1h'+ }+ }++ const updateDateRange: UpdateDateRange = (from: string, to: string) => {+ setDateRange({+ period_start: { date: from, time_period: '1d' },+ period_end: { date: to, time_period: 'today' },+ interval: handleIntervalGranularity(from, to),+ })+ }++ if (!ref) {+ // Prevent rendering charts until the ref is available+ return <></>+ }++ return (+ <>+ <ReportHeader title="Edge Functions" />+ <div className="w-full flex flex-col gap-1">+ <div className="h-2 w-full">+ <ShimmerLine active={isRefreshing || isLoadingFunctions} />+ </div>+ </div>+ <section className="relative pt-16 -mt-2">+ <div className="absolute inset-0 z-40 pointer-events-none flex flex-col gap-4">+ <div className="sticky top-0 bg-200 py-4 mb-4 flex items-center space-x-3 pointer-events-auto">+ <ButtonTooltip+ type="default"+ disabled={isRefreshing}+ icon={<RefreshCw className={isRefreshing ? 'animate-spin' : ''} />}+ className="w-7"+ tooltip={{ content: { side: 'bottom', text: 'Refresh report' } }}+ onClick={onRefreshReport}+ />+ <div className="flex items-center gap-3">+ <DateRangePicker+ loading={false}+ value={'1d'}+ options={TIME_PERIODS_INFRA}+ currentBillingPeriodStart={undefined}+ onChange={(values: any) => {+ if (values.interval === '1d') {+ setDateRange({ ...values, interval: '1h' })+ } else {+ setDateRange(values)+ }+ }}+ />+ <DropdownMenu open={isOpen} onOpenChange={setIsOpen}>+ <DropdownMenuTrigger asChild>+ <Button type="default" iconRight={<ChevronDown />}>+ <span>+ {functionIds.length === 0+ ? 'All Functions'+ : `${functionIds.length} function${+ functionIds.length > 1 ? 's' : ''+ } selected`}+ </span>+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent side="bottom" align="start" className="w-72 p-0">+ <div className="space-y-px max-h-60 overflow-y-auto p-1">+ <Label+ key="all-functions"+ htmlFor="all-functions"+ className="flex items-center hover:bg-overlay-hover overflow-hidden p-2 rounded-sm"+ >+ <Checkbox+ id="all-functions"+ checked={tempFunctionIds.length === 0}+ onChange={(event: React.ChangeEvent<HTMLInputElement>) => {+ if (event.target.checked) {+ setTempFunctionIds([])+ }+ }}+ />+ <div className="flex flex-col">+ <span>All Functions</span>+ </div>+ </Label>+ {functions+ ?.filter((fn: { slug: string }) => typeof fn.slug === 'string')+ .map((fn) => (+ <Label+ key={fn.id}+ htmlFor={fn.id}+ className="flex items-center hover:bg-overlay-hover overflow-hidden p-2 rounded-sm"+ >+ <div>+ <Checkbox+ id={fn.id}+ checked={tempFunctionIds.includes(fn.id)}+ onChange={(event: React.ChangeEvent<HTMLInputElement>) => {+ if (event.target.checked) {+ setTempFunctionIds([...tempFunctionIds, fn.id])+ } else {+ setTempFunctionIds(tempFunctionIds.filter((id) => id !== fn.id))+ }+ }}+ />+ </div>+ <div className="flex flex-col">+ <span>{fn.slug}</span>+ </div>+ </Label>+ ))}+ </div>+ <div className="flex items-center justify-end gap-2 border-t border-default p-2">+ <Button+ size="tiny"+ type="default"+ onClick={() => setIsOpen(false)}+ htmlType="button"+ >+ Cancel+ </Button>+ <Button+ size="tiny"+ type="primary"+ htmlType="button"+ onClick={() => {+ setFunctionIds(tempFunctionIds)+ setIsOpen(false)+ }}+ >+ Apply+ </Button>+ </div>+ </DropdownMenuContent>+ </DropdownMenu>+ {dateRange && (+ <div className="flex items-center gap-x-2 text-xs">+ <p className="text-foreground-light">+ {dayjs(dateRange.period_start.date).format('MMM D, h:mma')}+ </p>+ <p className="text-foreground-light">+ <ArrowRight size={12} />+ </p>+ <p className="text-foreground-light">+ {dayjs(dateRange.period_end.date).format('MMM D, h:mma')}+ </p>+ </div>+ )}+ </div>+ </div>+ </div>++ <div className="grid grid-cols-1 gap-4">+ {dateRange &&+ EDGEFN_CHARTS.filter((attr) => !attr.hide).map((attr, i) => (+ <ReportChart+ key={`${attr.id}-${i}`}+ chart={attr}+ interval={dateRange.interval}+ startDate={dateRange?.period_start?.date}+ endDate={dateRange?.period_end?.date}+ updateDateRange={updateDateRange}+ functionIds={functionIds}+ />+ ))}+ </div>+ </section>+ </>+ )+}diff --git a/apps/studio/tests/features/logs/LogsPreviewer.test.tsx b/apps/studio/tests/features/logs/LogsPreviewer.test.tsxindex 08d0c655571..cc7051267e8 100644--- a/apps/studio/tests/features/logs/LogsPreviewer.test.tsx+++ b/apps/studio/tests/features/logs/LogsPreviewer.test.tsx@@ -117,7 +117,8 @@ test('can click load older', async () => {)const loadOlder = await waitFor(- async () => await screen.findByRole('button', { name: /Load older/i })+ async () => await screen.findByRole('button', { name: /Load older/i }),+ { timeout: 10000 })loadOlder.onclick = vi.fn()