Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .coderabbit.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ reviews:
Strictly enforce event naming: [object]_[verb] in snake_case. Only approved
verbs: opened, clicked, submitted, created, removed, updated, retrieved,
intended, evaluated, added, enabled, disabled, copied, exposed, failed,
converted. Properties must be camelCase for new events (match existing
converted, completed. Properties must be camelCase for new events (match existing
convention when adding to existing events). Flag any usage of
useSendEventMutation. Verify @group Events and @source JSDoc tags are
accurate. Check that new interfaces are added to the TelemetryEvent union type.
Expand Down
4 changes: 3 additions & 1 deletion apps/studio/components/interfaces/App/AppBannerWrapper.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { OrganizationResourceBanner } from '../Organization/HeaderBanner'
import { isLogsOrObservabilityPath, isOrganizationLandingPath } from './AppBannerWrapper.utils'
import { ClockSkewBanner } from '@/components/layouts/AppLayout/ClockSkewBanner'
import { NoticeBanner } from '@/components/layouts/AppLayout/NoticeBanner'
import { StatusBanner } from '@/components/layouts/AppLayout/StatusBanner'
import { StatusPageBanner } from '@/components/layouts/AppLayout/StatusPageBanner'
import { BannerLogsAllDeprecation } from '@/components/ui/BannerStack/Banners/BannerLogsAllDeprecation'
import { BannerPrivacyPolicyUpdate } from '@/components/ui/BannerStack/Banners/BannerPrivacyPolicyUpdate'
Expand All @@ -33,6 +34,7 @@ const MAX_TIMEOUT_MS = 2_147_483_647
export const AppBannerWrapper = ({ children }: PropsWithChildren<{}>) => {
const showNoticeBanner = useFlag('showNoticeBanner')
const clockSkewBanner = useFlag('clockSkewBanner')
const useStatusPageWidget = useFlag('incidentIoStatusPage')

const { addBanner, dismissBanner } = useBannerStack()
const pathname = usePathname()
Expand Down Expand Up @@ -158,7 +160,7 @@ export const AppBannerWrapper = ({ children }: PropsWithChildren<{}>) => {
return (
<div className="flex flex-col">
<div className="shrink-0">
<StatusPageBanner />
{useStatusPageWidget ? <StatusBanner /> : <StatusPageBanner />}
{showNoticeBanner && <NoticeBanner />}
<OrganizationResourceBanner />
{clockSkewBanner && <ClockSkewBanner />}
Expand Down
25 changes: 23 additions & 2 deletions apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ import { useUpsertNotebookMutation } from '@/data/content/notebooks/notebook-ups
import { acceptUntrustedLogsSql } from '@/data/logs/safe-analytics-sql'
import { useLocalStorageQuery } from '@/hooks/misc/useLocalStorage'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { useTrack } from '@/lib/telemetry/track'
import {
getNotebooksStateSnapshot,
useCurrentNotebook,
Expand All @@ -109,6 +110,7 @@ export const ExplorerNotebookTab = () => {
const { name, content } = currentNotebook?.notebook ?? {}
const { isNotFound } = useLoadNotebook({ id, projectRef: ref })
const { data: project } = useSelectedProjectQuery()
const track = useTrack()
const cells = content?.cells ?? []
const queryCellIds = cells.filter(isQueryCell).map((cell) => cell._id)

Expand All @@ -121,12 +123,31 @@ export const ExplorerNotebookTab = () => {
} | null>(null)
const [skipMutatingCells, setSkipMutatingCells] = useState(false)
const [isExportingPdf, setIsExportingPdf] = useState(false)

const queryCellRefs = useRef(new Map<string, QueryEditorHandle>())
const savedContentRef = useRef<typeof content>(undefined)
const confirmedCreatedNotebookIdsRef = useRef(new Set<string>())
const scrollContainerRef = useRef<HTMLDivElement>(null)

const { mutate: updateNotebook, isPending: isUpdating } = useUpsertNotebookMutation({
onSuccess: (data) => {
const { mutate: updateNotebook, isPending: isUpdating } = useUpsertNotebookMutation<{
isCreation: boolean
}>({
onMutate: (variables) => ({
isCreation:
(currentNotebook?.status === 'new' ||
snap.serverDivergedWhileDirty.get(variables.id) === 'deleted') &&
!confirmedCreatedNotebookIdsRef.current.has(variables.id),
}),
onSuccess: (data, variables, context) => {
const { isCreation } = context
if (isCreation) confirmedCreatedNotebookIdsRef.current.add(variables.id)

track(
isCreation ? 'explorer_notebook_created' : 'explorer_notebook_updated',
{ notebookId: variables.id },
{ project: variables.projectRef }
)

if (id && content === savedContentRef.current) {
snap.markSaved({ id, updatedAt: data?.updated_at })
toast.success('Successfully saved notebook!')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ export const ExplorerQueryTab = () => {
<QueryEditor
ref={queryEditorRef}
id={id}
location={{ surface: 'query_tab', queryId: id }}
variant="viewport"
title={draft.name}
query={query}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,15 @@ export const QueryCell = forwardRef<QueryEditorHandle, QueryCellProps>(function
<QueryEditor
ref={ref}
id={cell._id}
location={
currentNotebook
? {
surface: 'notebook_cell',
notebookId: currentNotebook.notebook.id,
cellId: cell._id,
}
: undefined
}
variant="embedded"
className="min-h-0"
title={title}
Expand Down
47 changes: 42 additions & 5 deletions apps/studio/components/interfaces/Explorer/QueryEditor/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { useMonaco } from '@monaco-editor/react'
import { acceptUntrustedSql, untrustedSql, type UntrustedSqlFragment } from '@supabase/pg-meta'
import { useFlag } from 'common'
import type { ExplorerQueryLocation } from 'common/telemetry-constants'
import { CodeSquare, Eye, EyeOff } from 'lucide-react'
import type { editor as monacoEditor, Selection } from 'monaco-editor'
import {
Expand Down Expand Up @@ -73,6 +74,7 @@ import { useLatest } from '@/hooks/misc/useLatest'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { detectOS } from '@/lib/helpers'
import { wrapWithRoleImpersonation } from '@/lib/role-impersonation'
import { useTrack } from '@/lib/telemetry/track'
import {
isRoleImpersonationEnabled,
type RoleImpersonationController,
Expand Down Expand Up @@ -122,6 +124,7 @@ export type QueryEditorHandle = {

type QueryEditorProps = {
id: string
location?: ExplorerQueryLocation
isReadOnly?: boolean
variant: 'embedded' | 'viewport'
title: string
Expand Down Expand Up @@ -154,6 +157,7 @@ type QueryEditorProps = {
export const QueryEditor = forwardRef<QueryEditorHandle, QueryEditorProps>(function QueryEditor(
{
id,
location,
isReadOnly = false,
variant,
title,
Expand All @@ -179,6 +183,7 @@ export const QueryEditor = forwardRef<QueryEditorHandle, QueryEditorProps>(funct
ref
) {
const os = detectOS()
const track = useTrack()
const sql = query.uncheckedSql
const sqlRef = useLatest<string>(sql)
const onSqlCommitRef = useLatest(onSqlCommit)
Expand Down Expand Up @@ -260,13 +265,33 @@ export const QueryEditor = forwardRef<QueryEditorHandle, QueryEditorProps>(funct
}

onRun?.()

const querySnapshot = { sql: rawSql, source: query._tag }
const runProperties = location
? { ...location, runId: crypto.randomUUID(), source: query._tag }
: undefined
const groups = { project: project.ref }

if (runProperties) track('explorer_query_submitted', runProperties, groups)

const trackRunResult = (
failureReason?: 'logs_unavailable' | 'connection_unavailable' | 'execution_error'
) => {
if (!runProperties) return
if (failureReason) {
track('explorer_query_failed', { ...runProperties, failureReason }, groups)
} else {
track('explorer_query_completed', runProperties, groups)
}
}

// [Joshen] This is deliberate to commit the sql, rather than the passed rawSql
// As we want to save the cell's content into the store, rather than what's getting run
onSqlCommit?.(sql)

if (query._tag === 'logs') {
if (!isOtelLogsEnabled) {
trackRunResult('logs_unavailable')
onResultChange({
error: { message: "Querying logs isn't available for this project yet." },
...querySnapshot,
Expand All @@ -280,12 +305,17 @@ export const QueryEditor = forwardRef<QueryEditorHandle, QueryEditorProps>(funct
range: resolveLogTimeRange(query.time_range),
endpoint: QUERY_SOURCE_REGISTRY.logs.endpoint,
}).then(
(data) =>
(data) => {
trackRunResult()
onResultChange({
rows: data.rows as readonly Record<string, unknown>[],
...querySnapshot,
}),
(error) => onResultChange({ error, ...querySnapshot })
})
},
(error) => {
trackRunResult('execution_error')
onResultChange({ error, ...querySnapshot })
}
)
return
}
Expand All @@ -294,6 +324,7 @@ export const QueryEditor = forwardRef<QueryEditorHandle, QueryEditorProps>(funct
const limitedSql = applyAutoLimit(safeSql, rowLimit)

if (!isValidConnString(connectionString)) {
trackRunResult('connection_unavailable')
onResultChange({
error: { message: 'Unable to run query: Connection string is missing' },
...querySnapshot,
Expand All @@ -310,8 +341,14 @@ export const QueryEditor = forwardRef<QueryEditorHandle, QueryEditorProps>(funct
isStatementTimeoutDisabled: true,
isRoleImpersonationEnabled: isRoleImpersonationEnabled(roleImpersonationState?.role),
}).then(
(data) => onResultChange({ rows: data.result, ...querySnapshot }),
(error) => onResultChange({ error, ...querySnapshot })
(data) => {
trackRunResult()
onResultChange({ rows: data.result, ...querySnapshot })
},
(error) => {
trackRunResult('execution_error')
onResultChange({ error, ...querySnapshot })
}
)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,12 @@ import { setupSqlEditorMocks } from '@/tests/lib/sql-editor-test-utils'
import type { Notebooks } from '@/types'

const testContext = vi.hoisted(() => ({
track: vi.fn(),
flags: { otelLegacyLogs: true } as Record<string, boolean>,
}))

vi.mock('@/lib/telemetry/track', () => ({ useTrack: () => testContext.track }))

vi.mock('common', async (importOriginal) => {
const actual = await importOriginal<typeof import('common')>()
return {
Expand Down Expand Up @@ -119,6 +122,7 @@ const mockDatabaseQueryRequests = () => {
}

beforeEach(() => {
testContext.track.mockClear()
setupSqlEditorMocks()
testContext.flags.otelLegacyLogs = true
for (const id of Object.keys(notebooksState.notebooks)) {
Expand Down Expand Up @@ -191,6 +195,26 @@ describe('ExplorerNotebookTab', () => {
await waitFor(() => expect(dbRequests).toHaveLength(1))
await waitFor(() => expect(logRequests).toHaveLength(1))
await waitFor(() => expect(runNotebookButton).toBeEnabled())
const queryEvents = testContext.track.mock.calls.filter(([action]) =>
action.startsWith('explorer_query_')
)
expect(queryEvents.filter(([action]) => action === 'explorer_query_submitted')).toHaveLength(2)
expect(queryEvents.filter(([action]) => action === 'explorer_query_completed')).toHaveLength(2)
for (const [, properties] of queryEvents) {
expect(properties).toMatchObject({ surface: 'notebook_cell', notebookId: NOTEBOOK_ID })
expect(properties.cellId).toBeDefined()
expect(properties).not.toHaveProperty('sql')
}
const submittedRuns = queryEvents.filter(([action]) => action === 'explorer_query_submitted')
const completedRuns = queryEvents.filter(([action]) => action === 'explorer_query_completed')
expect(new Set(submittedRuns.map(([, properties]) => properties.runId)).size).toBe(2)
for (const [, properties] of submittedRuns) {
expect(completedRuns).toContainEqual([
'explorer_query_completed',
properties,
expect.objectContaining({ project: 'default' }),
])
}
})

describe('mutation confirmation on "Run notebook"', () => {
Expand Down Expand Up @@ -406,6 +430,56 @@ describe('ExplorerNotebookTab', () => {
await waitFor(() => expect(tabsState.tabsMap[tabId]?.isPreview).toBe(false))
})

it('tracks confirmed creation once and later saves as updates', async () => {
seedNotebook([databaseCell], 'new')
addAPIMock({
method: 'put',
path: '/platform/projects/:ref/content',
response: () => HttpResponse.json({ id: NOTEBOOK_ID }),
})

renderNotebookTab()
const saveButton = await screen.findByRole('button', { name: 'Save changes' })
await userEvent.click(saveButton)
await waitFor(() =>
expect(testContext.track).toHaveBeenCalledWith(
'explorer_notebook_created',
{ notebookId: NOTEBOOK_ID },
{ project: 'default' }
)
)

notebooksState.insertCellAfter({ id: NOTEBOOK_ID, cell: createMarkdownCellSkeleton() })
await userEvent.click(saveButton)
await waitFor(() =>
expect(testContext.track).toHaveBeenCalledWith(
'explorer_notebook_updated',
{ notebookId: NOTEBOOK_ID },
{ project: 'default' }
)
)
expect(
testContext.track.mock.calls.filter(([action]) => action === 'explorer_notebook_created')
).toHaveLength(1)
})

it('does not track an unsaved draft or a failed first save', async () => {
seedNotebook([databaseCell], 'new')
addAPIMock({
method: 'put',
path: '/platform/projects/:ref/content',
response: () => HttpResponse.json({ message: 'Save failed' }, { status: 500 }),
})

renderNotebookTab()
expect(testContext.track).not.toHaveBeenCalled()
await userEvent.click(await screen.findByRole('button', { name: 'Save changes' }))
await waitFor(() => expect(screen.getByRole('button', { name: 'Save changes' })).toBeEnabled())
expect(
testContext.track.mock.calls.filter(([action]) => action.startsWith('explorer_notebook_'))
).toEqual([])
})

it('does not mark a newer edit as saved when an earlier save resolves after it', async () => {
let resolveSave: (() => void) | undefined
const savePromise = new Promise<void>((resolve) => {
Expand Down
Loading
Loading