Skip to content

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

Chore/small refactors (#47740)

Joshen Lim944c5862f3fa
diff --git a/apps/studio/components/interfaces/APIKeys/SecretAPIKeys.tsx b/apps/studio/components/interfaces/APIKeys/SecretAPIKeys.tsx
index aca9bef5988..e359a35113f 100644
--- a/apps/studio/components/interfaces/APIKeys/SecretAPIKeys.tsx
+++ b/apps/studio/components/interfaces/APIKeys/SecretAPIKeys.tsx
@@ -35,15 +35,15 @@ function useLastSeen({ projectRef, enabled }: { projectRef: string; enabled?: bo
} {
const now = useRef(new Date()).current
- const query = useLogsQuery(
+ const query = useLogsQuery({
+ enabled,
projectRef,
- {
+ initialParams: {
iso_timestamp_start: new Date(now.getTime() - 24 * 60 * 60 * 1000).toISOString(),
iso_timestamp_end: now.toISOString(),
sql: "-- last-used-secret-api-keys\nSELECT unix_millis(max(timestamp)) as timestamp, apikey.`hash` FROM edge_logs cross join unnest(metadata) as m cross join unnest(m.request) as request cross join unnest(request.sb) as sb cross join unnest(sb.apikey) as sbapikey cross join unnest(sbapikey.apikey) as apikey WHERE apikey.error is null and apikey.`hash` is not null and apikey.prefix like 'sb_secret_%' GROUP BY apikey.`hash`",
},
- enabled
- )
+ })
return useMemo(() => {
if (query.isLoading || !query.logData) {
diff --git a/apps/studio/components/interfaces/Functions/EdgeFunctionOverview/EdgeFunctionRecentErrors.tsx b/apps/studio/components/interfaces/Functions/EdgeFunctionOverview/EdgeFunctionRecentErrors.tsx
index c58c800761e..8333ec6445a 100644
--- a/apps/studio/components/interfaces/Functions/EdgeFunctionOverview/EdgeFunctionRecentErrors.tsx
+++ b/apps/studio/components/interfaces/Functions/EdgeFunctionOverview/EdgeFunctionRecentErrors.tsx
@@ -87,16 +87,16 @@ export const EdgeFunctionRecentErrors = ({
logData: recentErrorInvocations,
isLoading: isLoadingRecentErrorInvocations,
error: recentErrorInvocationsError,
- } = useLogsQuery(
- projectRef as string,
- {
+ } = useLogsQuery({
+ projectRef: projectRef!,
+ initialParams: {
sql: recentErrorInvocationsSql,
iso_timestamp_start: isoTimestampStart,
iso_timestamp_end: isoTimestampEnd,
},
- isQueryEnabled,
- { useOtel: true }
- )
+ enabled: isQueryEnabled,
+ options: { useOtel: true },
+ })
const recentErrorGroupsBase = useMemo(
() => getRecentErrorGroupsBase(recentErrorInvocations),
@@ -106,16 +106,16 @@ export const EdgeFunctionRecentErrors = ({
logData: sinceLastDeployInvocationCountRows,
isLoading: isLoadingSinceLastDeployInvocationCount,
error: sinceLastDeployInvocationCountError,
- } = useLogsQuery(
- projectRef as string,
- {
+ } = useLogsQuery({
+ projectRef: projectRef!,
+ initialParams: {
sql: sinceLastDeployInvocationCountSql,
iso_timestamp_start: isoTimestampStart,
iso_timestamp_end: isoTimestampEnd,
},
- Boolean(projectRef && sinceLastDeployInvocationCountSql && isoTimestampStart),
- { useOtel: true }
- )
+ enabled: Boolean(projectRef && sinceLastDeployInvocationCountSql && isoTimestampStart),
+ options: { useOtel: true },
+ })
const relatedExecutionIds = useMemo(
() => getRelatedExecutionIds(recentErrorGroupsBase),
@@ -131,16 +131,16 @@ export const EdgeFunctionRecentErrors = ({
logData: functionRuntimeLogs,
isLoading: isLoadingFunctionRuntimeLogs,
error: functionRuntimeLogsError,
- } = useLogsQuery(
- projectRef as string,
- {
+ } = useLogsQuery({
+ projectRef: projectRef!,
+ initialParams: {
sql: functionRuntimeLogsSql,
iso_timestamp_start: isoTimestampStart,
iso_timestamp_end: isoTimestampEnd,
},
- Boolean(projectRef && functionRuntimeLogsSql && isoTimestampStart),
- { useOtel: true }
- )
+ enabled: Boolean(projectRef && functionRuntimeLogsSql && isoTimestampStart),
+ options: { useOtel: true },
+ })
const queryError =
toAlertError(recentErrorInvocationsError) ?? toAlertError(functionRuntimeLogsError)
diff --git a/apps/studio/components/interfaces/QueryInsights/QueryInsights.tsx b/apps/studio/components/interfaces/QueryInsights/QueryInsights.tsx
index 0d022f375cb..4e0802c8745 100644
--- a/apps/studio/components/interfaces/QueryInsights/QueryInsights.tsx
+++ b/apps/studio/components/interfaces/QueryInsights/QueryInsights.tsx
@@ -53,10 +53,13 @@ export const QueryInsights = ({ dateRange }: QueryInsightsProps) => {
[effectiveDateRange]
)
- const { logData, isLoading } = useLogsQuery(ref as string, {
- sql,
- iso_timestamp_start: effectiveDateRange.iso_timestamp_start,
- iso_timestamp_end: effectiveDateRange.iso_timestamp_end,
+ const { logData, isLoading } = useLogsQuery({
+ projectRef: ref as string,
+ initialParams: {
+ sql,
+ iso_timestamp_start: effectiveDateRange.iso_timestamp_start,
+ iso_timestamp_end: effectiveDateRange.iso_timestamp_end,
+ },
})
const [selectedQuery, setSelectedQuery] = useState<string | null>(null)
diff --git a/apps/studio/components/interfaces/Reports/Reports.utils.tsx b/apps/studio/components/interfaces/Reports/Reports.utils.tsx
index f7f58c41a15..e844f6241db 100644
--- a/apps/studio/components/interfaces/Reports/Reports.utils.tsx
+++ b/apps/studio/components/interfaces/Reports/Reports.utils.tsx
@@ -58,7 +58,7 @@ export const queriesFactory = <T extends string>(
} else {
return {
...acc,
- [k]: () => useLogsQuery(projectRef),
+ [k]: () => useLogsQuery({ projectRef }),
}
}
}, {})
diff --git a/apps/studio/components/ui/ProjectSettings/DisplayApiSettings.utils.ts b/apps/studio/components/ui/ProjectSettings/DisplayApiSettings.utils.ts
index 1afca9a16dd..6281e3c6361 100644
--- a/apps/studio/components/ui/ProjectSettings/DisplayApiSettings.utils.ts
+++ b/apps/studio/components/ui/ProjectSettings/DisplayApiSettings.utils.ts
@@ -11,15 +11,16 @@ export function useLastUsedAPIKeysLogQuery({
enabled?: boolean
}) {
const now = useRef(new Date()).current
- return useLogsQuery(
+
+ return useLogsQuery({
projectRef,
- {
+ enabled,
+ initialParams: {
iso_timestamp_start: new Date(now.getTime() - 24 * 60 * 60 * 1000).toISOString(),
iso_timestamp_end: now.toISOString(),
sql: "-- last-used-anon--service_role-api-keys\nSELECT unix_millis(max(timestamp)) as timestamp, payload.role, payload.signature_prefix FROM edge_logs cross join unnest(metadata) as m cross join unnest(m.request) as request cross join unnest(request.sb) as sb cross join unnest(sb.jwt) as jwt cross join unnest(jwt.apikey) as apikey cross join unnest(apikey.payload) as payload WHERE apikey.invalid is null and payload.issuer = 'supabase' and payload.algorithm = 'HS256' and payload.role in ('anon', 'service_role') GROUP BY payload.role, payload.signature_prefix",
},
- enabled
- )
+ })
}
export function getLastUsedAPIKeys(
diff --git a/apps/studio/data/profile/profile-identities-query.ts b/apps/studio/data/profile/profile-identities-query.ts
index f41bcd98ca8..cb7260499c1 100644
--- a/apps/studio/data/profile/profile-identities-query.ts
+++ b/apps/studio/data/profile/profile-identities-query.ts
@@ -6,16 +6,15 @@ import { auth } from '@/lib/gotrue'
import { UseCustomQueryOptions } from '@/types'
export async function getProfileIdentities() {
- // getSession() uses a cached user object, which is almost never stale as the
- // session refresh logic keeps it fresh. If there are claims of data not being
- // fresh, it's because it was modified on another device / browser and the
- // session hasn't been refreshed yet.
- const { error, data } = await auth.getSession()
+ // getUser() is used instead of getSession() here because the client is configured
+ // with a `userStorage` option, under which getSession() can return a session whose
+ // `user` is a placeholder that throws when any of its properties are read.
+ const { error, data } = await auth.getUser()
if (error) throw error
- if (!data.session) throw new Error('Session not found with getSession()')
+ if (!data.user) throw new Error('User not found with getUser()')
- const { identities = [], new_email, email_change_sent_at } = data.session.user
+ const { identities = [], new_email, email_change_sent_at } = data.user
return { identities, new_email, email_change_sent_at }
}
diff --git a/apps/studio/hooks/analytics/useLogsQuery.tsx b/apps/studio/hooks/analytics/useLogsQuery.tsx
index e9bba8e4a30..0affe0b3c91 100644
--- a/apps/studio/hooks/analytics/useLogsQuery.tsx
+++ b/apps/studio/hooks/analytics/useLogsQuery.tsx
@@ -32,12 +32,17 @@ export interface LogsQueryHook {
enabled?: boolean
}
-export const useLogsQuery = (
- projectRef: string,
- initialParams: Partial<LogsEndpointParams> = {},
+export const useLogsQuery = ({
+ projectRef,
+ initialParams = {},
enabled = true,
- options: { useOtel?: boolean } = {}
-): LogsQueryHook => {
+ options = {},
+}: {
+ projectRef?: string
+ initialParams?: Partial<LogsEndpointParams>
+ enabled?: boolean
+ options?: { useOtel?: boolean }
+}): LogsQueryHook => {
const { useOtel = false } = options
const defaultHelper = getDefaultHelper(EXPLORER_DATEPICKER_HELPERS)
const [params, setParams] = useState<LogsEndpointParams>({
@@ -78,7 +83,7 @@ export const useLogsQuery = (
queryFn: async ({ signal }) => {
const { data, error } = await get(logsAllEndpointUrl(useOtel), {
params: {
- path: { ref: projectRef },
+ path: { ref: projectRef! },
query: params,
},
signal,
diff --git a/apps/studio/pages/project/[ref]/logs/explorer/index.tsx b/apps/studio/pages/project/[ref]/logs/explorer/index.tsx
index 87522878e74..e25431adb4a 100644
--- a/apps/studio/pages/project/[ref]/logs/explorer/index.tsx
+++ b/apps/studio/pages/project/[ref]/logs/explorer/index.tsx
@@ -91,16 +91,16 @@ const MISSING_LIMIT_ERROR: LogQueryError = {
export const LogsExplorerPage: NextPageWithLayout = () => {
useEditorHints()
+ const track = useTrack()
const monaco = useMonaco()
const router = useRouter()
const { profile } = useProfile()
+ const { ref: projectRef, q, queryId } = useParams()
+ const useOtelEndpoint = useFlag('otelLegacyLogs')
+ const { logsShowMetadataIpTemplate } = useIsFeatureEnabled(['logs:show_metadata_ip_template'])
+
const { data: project } = useSelectedProjectQuery()
const { data: organization } = useSelectedOrganizationQuery()
- const { ref, q, queryId } = useParams()
- const track = useTrack()
- const projectRef = ref as string
- const { logsShowMetadataIpTemplate } = useIsFeatureEnabled(['logs:show_metadata_ip_template'])
- const useOtelEndpoint = useFlag('otelLegacyLogs')
const allTemplates = useMemo(() => {
const templates = getLogsTemplates(useOtelEndpoint)
@@ -158,10 +158,7 @@ export const LogsExplorerPage: NextPageWithLayout = () => {
const { getEntitlementNumericValue } = useCheckEntitlements('log.retention_days')
const entitledToAuditLogDays = getEntitlementNumericValue()
- const { data: content } = useContentQuery({
- projectRef: ref,
- type: 'log_sql',
- })
+ const { data: content } = useContentQuery({ projectRef, type: 'log_sql' })
const query = content?.content.find((x) => x.id === queryId)
const resolvedRange = useMemo(() => {
@@ -180,15 +177,15 @@ export const LogsExplorerPage: NextPageWithLayout = () => {
error,
isLoading: logsLoading,
setParams,
- } = useLogsQuery(
+ } = useLogsQuery({
projectRef,
- {
+ initialParams: {
iso_timestamp_start: resolvedRange.from,
iso_timestamp_end: resolvedRange.to,
},
- true,
- { useOtel: useOtelEndpoint }
- )
+ enabled: true,
+ options: { useOtel: useOtelEndpoint },
+ })
const results = logData
const isLoading = logsLoading
@@ -258,11 +255,11 @@ export const LogsExplorerPage: NextPageWithLayout = () => {
const headerData = await constructHeaders()
const source = detectLogSource(currentSql)
const availableKeys = source
- ? await fetchOtelLogKeys({ projectRef, source }).catch(() => undefined)
+ ? await fetchOtelLogKeys({ projectRef: projectRef!, source }).catch(() => undefined)
: undefined
const rewritten = await rewriteLogsSqlWithAI({
sql: currentSql,
- projectRef,
+ projectRef: projectRef!,
connectionString: project?.connectionString,
orgSlug: organization?.slug,
authorizationHeader: headerData.get('Authorization'),
@@ -566,7 +563,7 @@ export const LogsExplorerPage: NextPageWithLayout = () => {
hasEditorValue={Boolean(editorValue)}
data={showMissingLimitError ? [] : results}
error={showMissingLimitError ? MISSING_LIMIT_ERROR : error}
- projectRef={projectRef}
+ projectRef={projectRef!}
onSelectedLogChange={setSelectedLog}
selectedLog={selectedLog || undefined}
sqlQuery={editorValue}
diff --git a/packages/common/auth.tsx b/packages/common/auth.tsx
index 7caf2ab95f4..24a7f9e4bc3 100644
--- a/packages/common/auth.tsx
+++ b/packages/common/auth.tsx
@@ -128,7 +128,16 @@ export const useAuth = () => useContext(AuthContext)
export const useSession = () => useAuth().session
-export const useUser = () => useSession()?.user ?? null
+export const useUser = () => {
+ const user = useSession()?.user ?? null
+
+ // auth-js substitutes a throwing proxy for `user` when it was configured with
+ // `userStorage` and hasn't migrated the user into storage yet. Treat that as
+ // "no user" instead of crashing whenever a property on it is read.
+ if (user && (user as any).__isUserNotAvailableProxy) return null
+
+ return user
+}
export const useIsUserLoading = () => useAuth().isLoading
diff --git a/packages/common/feature-flags.tsx b/packages/common/feature-flags.tsx
index 1c44c639a9d..9761584dc64 100644
--- a/packages/common/feature-flags.tsx
+++ b/packages/common/feature-flags.tsx
@@ -4,7 +4,7 @@ import { components } from 'api-types'
import { FlagValues } from 'flags/react'
import { createContext, PropsWithChildren, useContext, useEffect, useRef, useState } from 'react'
-import { useAuth } from './auth'
+import { useAuth, useUser } from './auth'
import { getFlags as getDefaultConfigCatFlags } from './configcat'
import { hasConsented } from './consent-state'
import { get, post } from './fetchWrappers'
@@ -90,8 +90,9 @@ export const FeatureFlagProvider = ({
userEmail?: string
) => Promise<{ settingKey: string; settingValue: boolean | number | string | null | undefined }[]>
}>) => {
- const { session, isLoading } = useAuth()
- const userEmail = session?.user?.user_metadata.email ?? session?.user?.email
+ const { isLoading } = useAuth()
+ const user = useUser()
+ const userEmail = user?.user_metadata?.email ?? user?.email
const params = useParams()
const resolvedOrganizationSlug = organizationSlug ?? params.slug
const resolvedProjectRef = projectRef ?? params.ref
@@ -110,7 +111,7 @@ export const FeatureFlagProvider = ({
async function ensureGroupContext() {
if (!API_URL) return
- const userId = session?.user?.id
+ const userId = user?.id
if (!userId) return
if (!hasConsented()) return
@@ -245,7 +246,7 @@ export const FeatureFlagProvider = ({
isLoading,
userEmail,
API_URL,
- session?.user?.id,
+ user?.id,
resolvedOrganizationSlug,
resolvedProjectRef,
getConfigCatFlags,