Skip to content

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

refactor(studio): extract user project regions + emergency override hooks (#51033)

Charisd22702e907f8
diff --git a/apps/studio/components/layouts/AppLayout/StatusPageBanner.utils.ts b/apps/studio/components/layouts/AppLayout/StatusPageBanner.utils.ts
index 11daf030b1c..79bb1f9a86c 100644
--- a/apps/studio/components/layouts/AppLayout/StatusPageBanner.utils.ts
+++ b/apps/studio/components/layouts/AppLayout/StatusPageBanner.utils.ts
@@ -1,4 +1,5 @@
import type { IncidentCache } from '@/lib/api/incident-status'
+import { normalizeRegion } from '@/lib/status-page/status-page.utils'
type BannerIncident = { id: string; cache?: IncidentCache | null }
@@ -10,9 +11,11 @@ type BannerIncident = { id: string; cache?: IncidentCache | null }
*
* @param incidents - Active incidents from the incident-status endpoint
* @param hasProjects - Whether the user has any projects at all
- * @param userRegions - Deduplicated set of regions of all databases (primary and read replicas) owned by the user
- * @param hasUnknownRegions - True when region data is incomplete (org has >100 projects).
- * When true, the region check is skipped and a match is assumed.
+ * @param userRegions - Deduplicated set of regions of all databases (primary and read replicas)
+ * owned by the user, normalized via normalizeRegion
+ * @param hasUnknownRegions - True when region data is incomplete (an org has more than 100
+ * projects, or an org's projects failed to load). When true, the region check is skipped and
+ * a match is assumed.
*/
export function shouldShowBanner({
incidents,
@@ -22,7 +25,7 @@ export function shouldShowBanner({
}: {
incidents: Array<BannerIncident>
hasProjects: boolean
- userRegions: Set<string>
+ userRegions: ReadonlySet<string>
hasUnknownRegions?: boolean
}): boolean {
return incidents.some((incident) => {
@@ -43,7 +46,7 @@ export function shouldShowBanner({
if (hasUnknownRegions) return true
// Region restriction: only show if the user has a database in an affected region
- return affectedRegions.some((region) => userRegions.has(region.toLowerCase()))
+ return affectedRegions.some((region) => userRegions.has(normalizeRegion(region)))
})
}
@@ -61,7 +64,7 @@ export function getRelevantIncidentIds({
}: {
incidents: Array<BannerIncident>
hasProjects: boolean
- userRegions: Set<string>
+ userRegions: ReadonlySet<string>
hasUnknownRegions?: boolean
}): Array<string> {
return incidents
diff --git a/apps/studio/components/layouts/AppLayout/useStatusPageBannerVisibility.ts b/apps/studio/components/layouts/AppLayout/useStatusPageBannerVisibility.ts
index 0a5d0593455..61c59eb584e 100644
--- a/apps/studio/components/layouts/AppLayout/useStatusPageBannerVisibility.ts
+++ b/apps/studio/components/layouts/AppLayout/useStatusPageBannerVisibility.ts
@@ -1,22 +1,19 @@
-import { useQueries, useQuery } from '@tanstack/react-query'
-import { LOCAL_STORAGE_KEYS, useFlag } from 'common'
-import { useCallback, useMemo } from 'react'
+import { useQuery } from '@tanstack/react-query'
+import { LOCAL_STORAGE_KEYS } from 'common'
+import { useCallback } from 'react'
import { getRelevantIncidentIds, shouldShowBanner } from './StatusPageBanner.utils'
-import { useOrganizationsQuery } from '@/data/organizations/organizations-query'
import { incidentBannerQueryOptions } from '@/data/platform/incident-banner-query'
-import { projectKeys } from '@/data/projects/keys'
-import {
- getOrganizationProjects,
- type OrgProject,
-} from '@/data/projects/org-projects-infinite-query'
+import { useEmergencyIncidentOverride } from '@/hooks/misc/useEmergencyIncidentOverride'
import { useLocalStorageQuery } from '@/hooks/misc/useLocalStorage'
+import { useUserProjectRegions } from '@/hooks/misc/useUserProjectRegions'
export type StatusPageBannerData = { title: string; dismiss?: () => void }
+const EMPTY_REGIONS: ReadonlySet<string> = new Set()
+
export function useStatusPageBannerVisibility(): StatusPageBannerData | null {
- const showIncidentBannerOverride =
- useFlag('ongoingIncident') || process.env.NEXT_PUBLIC_ONGOING_INCIDENT === 'true'
+ const showIncidentBannerOverride = useEmergencyIncidentOverride()
const { data: incidentBannerData } = useQuery(incidentBannerQueryOptions())
@@ -24,35 +21,15 @@ export function useStatusPageBannerVisibility(): StatusPageBannerData | null {
const incidents = bannerItems.map((i) => ({ id: i.id, cache: i.metadata }))
const hasActiveIncidents = incidents.length > 0
- const { data: organizations } = useOrganizationsQuery({
+ const userProjectRegions = useUserProjectRegions({
enabled: !showIncidentBannerOverride && hasActiveIncidents,
})
- const orgProjectsQueries = useQueries({
- queries: (organizations ?? []).map((org) => ({
- queryKey: projectKeys.bannerProjectsByOrg(org.slug),
- queryFn: () => getOrganizationProjects({ slug: org.slug, limit: 100 }),
- staleTime: 5 * 60 * 1000,
- enabled: !showIncidentBannerOverride && hasActiveIncidents,
- })),
- })
-
- const isProjectsFetched =
- organizations !== undefined &&
- (organizations.length === 0 || orgProjectsQueries.every((q) => q.isFetched))
-
- const allProjects = orgProjectsQueries.flatMap((q) => q.data?.projects ?? [])
- const hasProjects = allProjects.length > 0
- const userRegions = useMemo(
- () =>
- new Set(
- allProjects.flatMap((project: OrgProject) => project.databases.map((db) => db.region))
- ),
- [allProjects]
- )
- const hasUnknownRegions = orgProjectsQueries.some(
- (q) => q.isError || (q.data !== undefined && q.data.pagination.count > q.data.projects.length)
- )
+ const userContext =
+ userProjectRegions.status === 'resolved' ? userProjectRegions.context : undefined
+ const hasProjects = userContext?.hasProjects ?? false
+ const userRegions = userContext?.regions ?? EMPTY_REGIONS
+ const hasUnknownRegions = userContext !== undefined && !userContext.isComplete
const [dismissedIds, setDismissedIds, { isSuccess: isDismissedLoaded }] = useLocalStorageQuery<
Array<string>
@@ -73,7 +50,7 @@ export function useStatusPageBannerVisibility(): StatusPageBannerData | null {
if (showIncidentBannerOverride) return { title: 'We are investigating a technical issue' }
- if (!hasActiveIncidents || !isProjectsFetched) return null
+ if (!hasActiveIncidents || userProjectRegions.status === 'loading') return null
const dismissedIdSet = new Set(dismissedIds)
const undismissedIncidents = incidents.filter((i) => !dismissedIdSet.has(i.id))
diff --git a/apps/studio/data/projects/keys.ts b/apps/studio/data/projects/keys.ts
index 765133e6368..10da61d84b1 100644
--- a/apps/studio/data/projects/keys.ts
+++ b/apps/studio/data/projects/keys.ts
@@ -39,6 +39,5 @@ export const projectKeys = {
listCloneStatus: (projectRef: string | undefined) =>
['projects', projectRef, 'clone-status'] as const,
- // Banner-specific: first-page snapshot used by the status page banner hook
bannerProjectsByOrg: (slug: string) => ['banner', 'org-projects', slug] as const,
}
diff --git a/apps/studio/hooks/misc/__tests__/useUserProjectRegions.test.ts b/apps/studio/hooks/misc/__tests__/useUserProjectRegions.test.ts
new file mode 100644
index 00000000000..589ef910568
--- /dev/null
+++ b/apps/studio/hooks/misc/__tests__/useUserProjectRegions.test.ts
@@ -0,0 +1,149 @@
+import { waitFor } from '@testing-library/react'
+import { platformComponents as components } from 'api-types'
+import { HttpResponse } from 'msw'
+import { describe, expect, it } from 'vitest'
+
+import { useUserProjectRegions } from '../useUserProjectRegions'
+import { createMockOrganizationResponse } from '@/tests/helpers'
+import { customRenderHook } from '@/tests/lib/custom-render'
+import { addAPIMock, type APIErrorBody } from '@/tests/lib/msw'
+import { createMockProfileContext } from '@/tests/lib/profile-helpers'
+
+type OrganizationResponse = components['schemas']['OrganizationResponse_Output']
+type OrganizationProjectsResponse = components['schemas']['OrganizationProjectsResponse_Output']
+type OrgProject = OrganizationProjectsResponse['projects'][number]
+type OrgDatabase = OrgProject['databases'][number]
+
+function mockProject(
+ ref: string,
+ databases: Array<{ region: string; type: 'PRIMARY' | 'READ_REPLICA' }>
+): OrgProject {
+ return {
+ cloud_provider: 'AWS',
+ databases: databases.map(
+ ({ region, type }): OrgDatabase => ({
+ cloud_provider: 'AWS',
+ identifier: ref,
+ region,
+ status: 'ACTIVE_HEALTHY',
+ type,
+ })
+ ),
+ inserted_at: new Date().toISOString(),
+ integration_source: null,
+ is_branch: false,
+ name: ref,
+ ref,
+ region: databases[0]?.region ?? 'us-east-1',
+ status: 'ACTIVE_HEALTHY',
+ }
+}
+
+describe('useUserProjectRegions', () => {
+ it('resolves normalized regions across orgs, primaries, and read replicas', async () => {
+ addAPIMock({
+ method: 'get',
+ path: '/platform/organizations',
+ response: () =>
+ HttpResponse.json<OrganizationResponse[]>([
+ createMockOrganizationResponse({ slug: 'org-a' }),
+ createMockOrganizationResponse({ slug: 'org-b' }),
+ ]),
+ })
+ addAPIMock({
+ method: 'get',
+ path: '/platform/organizations/:slug/projects',
+ response: ({ params }) => {
+ if (params.slug === 'org-a') {
+ return HttpResponse.json<OrganizationProjectsResponse>({
+ pagination: { count: 1, limit: 100, offset: 0 },
+ projects: [
+ mockProject('project-a', [
+ { region: 'US-East-1', type: 'PRIMARY' },
+ { region: 'eu-west-1', type: 'READ_REPLICA' },
+ ]),
+ ],
+ })
+ }
+ return HttpResponse.json<OrganizationProjectsResponse>({
+ pagination: { count: 1, limit: 100, offset: 0 },
+ projects: [mockProject('project-b', [{ region: 'ap-southeast-1', type: 'PRIMARY' }])],
+ })
+ },
+ })
+
+ const { result } = customRenderHook(() => useUserProjectRegions({ enabled: true }), {
+ profileContext: createMockProfileContext(),
+ })
+
+ await waitFor(() =>
+ expect(result.current).toEqual({
+ status: 'resolved',
+ context: {
+ hasProjects: true,
+ regions: new Set(['us-east-1', 'eu-west-1', 'ap-southeast-1']),
+ isComplete: true,
+ },
+ })
+ )
+ })
+
+ it('marks the context incomplete when an org has more projects than the page returned', async () => {
+ addAPIMock({
+ method: 'get',
+ path: '/platform/organizations',
+ response: () =>
+ HttpResponse.json<OrganizationResponse[]>([
+ createMockOrganizationResponse({ slug: 'org-a' }),
+ ]),
+ })
+ addAPIMock({
+ method: 'get',
+ path: '/platform/organizations/:slug/projects',
+ response: () =>
+ HttpResponse.json<OrganizationProjectsResponse>({
+ pagination: { count: 150, limit: 100, offset: 0 },
+ projects: [mockProject('project-a', [{ region: 'us-east-1', type: 'PRIMARY' }])],
+ }),
+ })
+
+ const { result } = customRenderHook(() => useUserProjectRegions({ enabled: true }), {
+ profileContext: createMockProfileContext(),
+ })
+
+ await waitFor(() =>
+ expect(result.current).toEqual({
+ status: 'resolved',
+ context: {
+ hasProjects: true,
+ regions: new Set(['us-east-1']),
+ isComplete: false,
+ },
+ })
+ )
+ })
+
+ it('fails open when the organizations query errors', async () => {
+ addAPIMock({
+ method: 'get',
+ path: '/platform/organizations',
+ response: () =>
+ HttpResponse.json<APIErrorBody>({ message: 'Boom from the backend' }, { status: 500 }),
+ })
+
+ const { result } = customRenderHook(() => useUserProjectRegions({ enabled: true }), {
+ profileContext: createMockProfileContext(),
+ })
+
+ await waitFor(() =>
+ expect(result.current).toEqual({
+ status: 'resolved',
+ context: {
+ hasProjects: true,
+ regions: new Set(),
+ isComplete: false,
+ },
+ })
+ )
+ })
+})
diff --git a/apps/studio/hooks/misc/useEmergencyIncidentOverride.ts b/apps/studio/hooks/misc/useEmergencyIncidentOverride.ts
new file mode 100644
index 00000000000..06d834d420f
--- /dev/null
+++ b/apps/studio/hooks/misc/useEmergencyIncidentOverride.ts
@@ -0,0 +1,6 @@
+import { useFlag } from 'common'
+
+export function useEmergencyIncidentOverride(): boolean {
+ const isFlagEnabled = useFlag('ongoingIncident')
+ return isFlagEnabled || process.env.NEXT_PUBLIC_ONGOING_INCIDENT === 'true'
+}
diff --git a/apps/studio/hooks/misc/useUserProjectRegions.ts b/apps/studio/hooks/misc/useUserProjectRegions.ts
new file mode 100644
index 00000000000..680f7e0660e
--- /dev/null
+++ b/apps/studio/hooks/misc/useUserProjectRegions.ts
@@ -0,0 +1,67 @@
+import { useQueries, type UseQueryResult } from '@tanstack/react-query'
+
+import { useOrganizationsQuery } from '@/data/organizations/organizations-query'
+import { projectKeys } from '@/data/projects/keys'
+import {
+ getOrganizationProjects,
+ type OrgProjectsInfiniteData,
+} from '@/data/projects/org-projects-infinite-query'
+import { normalizeRegion, type UserRegionContext } from '@/lib/status-page/status-page.utils'
+
+const PROJECTS_PAGE_LIMIT = 100
+const PROJECTS_STALE_TIME_MS = 5 * 60 * 1000
+
+const LOADING: UserProjectRegionsState = { status: 'loading' }
+
+const FAIL_OPEN: UserProjectRegionsState = {
+ status: 'resolved',
+ context: { hasProjects: true, regions: new Set<string>(), isComplete: false },
+}
+
+export type UserProjectRegionsState =
+ | { status: 'loading' }
+ | { status: 'resolved'; context: UserRegionContext }
+
+function combineOrgProjects(
+ results: Array<UseQueryResult<OrgProjectsInfiniteData>>
+): UserProjectRegionsState {
+ if (results.some((r) => r.isPending)) return LOADING
+
+ const anyErrored = results.some((r) => r.isError)
+ const anyTruncated = results.some(
+ (r) => r.data !== undefined && r.data.pagination.count > r.data.projects.length
+ )
+
+ const projects = results.flatMap((r) => r.data?.projects ?? [])
+ const regions = new Set(
+ projects.flatMap((p) => p.databases.map((db) => normalizeRegion(db.region)))
+ )
+
+ return {
+ status: 'resolved',
+ context: {
+ hasProjects: projects.length > 0 || anyErrored,
+ regions,
+ isComplete: !anyErrored && !anyTruncated,
+ },
+ }
+}
+
+export function useUserProjectRegions({ enabled }: { enabled: boolean }): UserProjectRegionsState {
+ const { data: organizations, isError: isOrganizationsError } = useOrganizationsQuery({ enabled })
+
+ const projectsState = useQueries({
+ queries: (organizations ?? []).map((org) => ({
+ queryKey: projectKeys.bannerProjectsByOrg(org.slug),
+ queryFn: ({ signal }: { signal: AbortSignal }) =>
+ getOrganizationProjects({ slug: org.slug, limit: PROJECTS_PAGE_LIMIT }, signal),
+ staleTime: PROJECTS_STALE_TIME_MS,
+ enabled,
+ })),
+ combine: combineOrgProjects,
+ })
+
+ if (!enabled) return LOADING
+ if (organizations === undefined) return isOrganizationsError ? FAIL_OPEN : LOADING
+ return projectsState
+}