Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Add type-safe event tracking utility (#39745)

Sean Oliver73e3143b0c56
diff --git a/apps/studio/components/interfaces/ProjectCreation/SchemaGenerator.tsx b/apps/studio/components/interfaces/ProjectCreation/SchemaGenerator.tsx
index deaf56126fd..2e2678050f4 100644
--- a/apps/studio/components/interfaces/ProjectCreation/SchemaGenerator.tsx
+++ b/apps/studio/components/interfaces/ProjectCreation/SchemaGenerator.tsx
@@ -4,8 +4,8 @@ import { useEffect, useState } from 'react'
import { Markdown } from 'components/interfaces/Markdown'
import { onErrorChat } from 'components/ui/AIAssistantPanel/AIAssistant.utils'
-import { useSendEventMutation } from 'data/telemetry/send-event-mutation'
import { BASE_PATH } from 'lib/constants'
+import { useTrack } from 'lib/telemetry/track'
import { AiIconAnimation, Button, Label_Shadcn_, Textarea } from 'ui'
interface SupabaseService {
@@ -34,7 +34,7 @@ export const SchemaGenerator = ({
const [hasSql, setHasSql] = useState(false)
const [promptIntendSent, setPromptIntendSent] = useState(false)
- const { mutate: sendEvent } = useSendEventMutation()
+ const track = useTrack()
const { messages, setMessages, sendMessage, status, addToolResult } = useChat({
id: 'schema-generator',
@@ -193,18 +193,12 @@ export const SchemaGenerator = ({
const isNewPrompt = messages.length == 0
// distinguish between initial step or second step
if (step === 'initial') {
- sendEvent({
- action: 'project_creation_initial_step_prompt_intended',
- properties: {
- isNewPrompt,
- },
+ track('project_creation_initial_step_prompt_intended', {
+ isNewPrompt,
})
} else {
- sendEvent({
- action: 'project_creation_second_step_prompt_intended',
- properties: {
- isNewPrompt,
- },
+ track('project_creation_second_step_prompt_intended', {
+ isNewPrompt,
})
}
setPromptIntendSent(true)
diff --git a/apps/studio/lib/telemetry/track.ts b/apps/studio/lib/telemetry/track.ts
new file mode 100644
index 00000000000..ec1755bc9a3
--- /dev/null
+++ b/apps/studio/lib/telemetry/track.ts
@@ -0,0 +1,61 @@
+import { sendTelemetryEvent } from 'common'
+import { TelemetryEvent, TelemetryGroups } from 'common/telemetry-constants'
+import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
+import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
+import { API_URL } from 'lib/constants'
+import { useRouter } from 'next/router'
+import { useCallback } from 'react'
+
+type EventMap = {
+ [E in TelemetryEvent as E['action']]: E
+}
+
+type PropertiesForAction<A extends keyof EventMap> = EventMap[A] extends { properties: infer P }
+ ? P
+ : never
+
+type HasProperties<A extends keyof EventMap> = EventMap[A] extends { properties: any }
+ ? true
+ : false
+
+/**
+ * Hook for type-safe telemetry event tracking with automatic project/org context injection.
+ *
+ * @example
+ * const track = useTrack()
+ * track('table_created', { method: 'sql_editor', schema_name: 'public' })
+ * track('help_button_clicked')
+ */
+export const useTrack = () => {
+ const { data: project } = useSelectedProjectQuery()
+ const { data: org } = useSelectedOrganizationQuery()
+ const router = useRouter()
+
+ const track = useCallback(
+ <A extends keyof EventMap>(
+ action: A,
+ ...args: HasProperties<A> extends true
+ ? [properties: PropertiesForAction<A>, groupOverrides?: Partial<TelemetryGroups>]
+ : [properties?: undefined, groupOverrides?: Partial<TelemetryGroups>]
+ ) => {
+ const [properties, groupOverrides] = args
+
+ const groups = {
+ ...(project?.ref && { project: project.ref }),
+ ...(org?.slug && { organization: org.slug }),
+ ...groupOverrides,
+ }
+
+ const event = {
+ action,
+ ...(properties && { properties }),
+ ...(groups && { groups }),
+ } as EventMap[A]
+
+ sendTelemetryEvent(API_URL, event, router.pathname)
+ },
+ [project?.ref, org?.slug, router.pathname]
+ )
+
+ return track
+}
diff --git a/apps/studio/pages/new/[slug].tsx b/apps/studio/pages/new/[slug].tsx
index d0448411dbd..5d1782ce87b 100644
--- a/apps/studio/pages/new/[slug].tsx
+++ b/apps/studio/pages/new/[slug].tsx
@@ -43,7 +43,7 @@ import {
ProjectCreateVariables,
useProjectCreateMutation,
} from 'data/projects/project-create-mutation'
-import { useSendEventMutation } from 'data/telemetry/send-event-mutation'
+import { useTrack } from 'lib/telemetry/track'
import { useCustomContent } from 'hooks/custom-content/useCustomContent'
import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions'
import { useIsFeatureEnabled } from 'hooks/misc/useIsFeatureEnabled'
@@ -171,7 +171,7 @@ const Wizard: NextPageWithLayout = () => {
const [isComputeCostsConfirmationModalVisible, setIsComputeCostsConfirmationModalVisible] =
useState(false)
- const { mutate: sendEvent } = useSendEventMutation()
+ const track = useTrack()
FormSchema.superRefine(({ dbPassStrength }, refinementContext) => {
if (dbPassStrength < DEFAULT_MINIMUM_PASSWORD_STRENGTH) {
@@ -247,16 +247,16 @@ const Wizard: NextPageWithLayout = () => {
isSuccess: isSuccessNewProject,
} = useProjectCreateMutation({
onSuccess: (res) => {
- sendEvent({
- action: 'project_creation_simple_version_submitted',
- properties: {
+ track(
+ 'project_creation_simple_version_submitted',
+ {
instanceSize: form.getValues('instanceSize'),
},
- groups: {
+ {
project: res.ref,
organization: res.organization_slug,
- },
- })
+ }
+ )
router.push(isHomeNew ? `/project/${res.ref}` : `/project/${res.ref}/building`)
},
})
@@ -372,14 +372,8 @@ const Wizard: NextPageWithLayout = () => {
!sizesWithNoCostConfirmationRequired.includes(values.instanceSize as DesiredInstanceSize)
if (additionalMonthlySpend > 0 && (hasOAuthApps || launchingLargerInstance)) {
- sendEvent({
- action: 'project_creation_simple_version_confirm_modal_opened',
- properties: {
- instanceSize: values.instanceSize,
- },
- groups: {
- organization: currentOrg?.slug ?? 'Unknown',
- },
+ track('project_creation_simple_version_confirm_modal_opened', {
+ instanceSize: values.instanceSize,
})
setIsComputeCostsConfirmationModalVisible(true)
} else {
diff --git a/packages/common/telemetry-constants.ts b/packages/common/telemetry-constants.ts
index 0d370b71ea4..300f25a189e 100644
--- a/packages/common/telemetry-constants.ts
+++ b/packages/common/telemetry-constants.ts
@@ -9,7 +9,7 @@
* @module telemetry-frontend
*/
-type TelemetryGroups = {
+export type TelemetryGroups = {
project: string
organization: string
}