Files
Alaister YoungandAlaister Young fc5e03f9e3 [FE-4019] fix(studio): direct-only connection strings with SSL params for Multigres (#48433)
Multigres (high-availability) projects only accept TLS connections with
direct SSL negotiation, and they don't support connection pooling at all
— neither Supavisor nor the dedicated PgBouncer pooler exists for them.
Studio previously showed pooler connection strings that would fail with
"server closed the connection unexpectedly". This PR makes every
connection-string surface direct-only for HA projects and appends
`?sslmode=require&sslnegotiation=direct` to the examples. Non-HA
projects are unchanged.

Addresses
[FE-4019](https://linear.app/supabase/issue/FE-4019/append-ssl-params-to-multigres-connection-string-examples-in-ui)

**Changed:**

- `buildConnectionStringPooler` gets an HA branch that collapses every
slot in the bag to the direct connection string with the SSL params
appended (mirroring the existing CLI branch, which also has no pooler) —
dedicated slots come back `undefined` and
`ipv4SupportedForDedicatedPooler` is forced off. Since HA never reaches
the pooler layout anymore, the earlier per-URI SSL-append logic on
pooler strings is removed
- `useConnectState` coerces `connectionMethod` to `direct` and
`useSharedPooler` to `false` for HA projects. The Connect sheet restores
the last-used method from localStorage shared across projects, so a
"Transaction pooler" selection made on a regular project could otherwise
leak pooler-flavored notices, badges, and telemetry into an HA project
- Prisma and Drizzle ORM tabs get an HA branch:
`DATABASE_URL`/`DIRECT_URL` both use the direct connection, no
`?pgbouncer=true` appended, with a comment explaining Multigres doesn't
support pooling. The 5-arm nested ternaries in both files are flattened
into `getEnvCode` helpers that switch on a shared
`resolveOrmConnectionScenario` helper (`OrmConnection.utils.ts`), so the
deployment-mode/HA branching lives in one tested place and each file
keeps only its own formatting
- The PgBouncer and Supavisor config queries are disabled (`enabled:
!isHighAvailability`) in the Connect sheet — those endpoints serve
pooler config that doesn't exist on Multigres
- `parseConnectionParams` keeps the URI's query string in a new `search`
field so formats rebuilt from parsed parts can carry it
- psql switches from the `-h/-p/-d/-U` flag form to the quoted-URI form
when query params are present (flags can't express them; psql still
prompts for the password)
- JDBC appends the params using pgJDBC's casing (`sslNegotiation`,
supported since 42.7.4)
- Prisma's `?pgbouncer=true` appends are query-aware (join with `&` when
the URI already has a query string) via a new
`appendConnectionStringParams` helper
- The project home "Direct connection string" copy item also appends the
params for HA projects

**Added:**

- Unit tests for the HA collapse behavior (all slots direct, dedicated
config and IPv4 add-on ignored, no SSL params on non-HA output), the
`useConnectState` coercion, the psql/JDBC builders (moved from
`content.tsx` into `ConnectionString.utils.ts` so they're testable), and
`resolveOrmConnectionScenario` (every deployment-mode/HA/pooler branch)

**Known gaps (left out deliberately):**

- The grid ExportDialog psql/pg_dump commands, the .NET
`appsettings.json` (Npgsql only supports direct negotiation from v9 via
`SSL Negotiation=Direct`), and the SQLAlchemy keyword-style `.env` are
flag/keyword forms that can't carry the URI params — these would still
fail against Multigres and need a follow-up
- Settings > Database's Connection Pooling section and the pooler logs
page have no HA gating yet — they'd still render pooler config UI for a
Multigres project and should be hidden in a follow-up

## To test

On a **Multigres (HA) project** (staging only supports `us-east-1` for
Multigres):

- Open the Connect sheet → Direct tab: there's no connection-method
picker, and the connection string is the direct one ending with
`?sslmode=require&sslnegotiation=direct` for the URI, PHP, and psql
(quoted-URI form) types; JDBC includes
`&sslmode=require&sslNegotiation=direct`
- ORM tab → Prisma: both `DATABASE_URL` and `DIRECT_URL` are the direct
connection string with the SSL params, no `pgbouncer=true`, with a
"Multigres does not support connection pooling" comment. Drizzle
likewise shows the direct string only
- Framework tabs (e.g. Next.js): every `DATABASE_URL` carries the direct
string with the params exactly once
- Open the network tab: no requests to `/config/pgbouncer` or
`/config/supavisor` while using the Connect sheet
- To check the localStorage coercion: on a **regular** project pick
"Transaction pooler" in the Connect sheet, then open the sheet on the
Multigres project — no pooler badge/notices, string is still direct
- Copy the URI, substitute your password, and `psql "<string>"` — it
should connect
- Project home → Copy dropdown → "Direct connection string" includes the
params

On a **regular (non-Multigres) project** — confirm nothing changed:

- Connect sheet: direct/session/transaction strings for all connection
types (URI, psql flag form, JDBC, PHP) look the same as before, no SSL
params appended
- Prisma/Drizzle tabs render identically (`?pgbouncer=true` still
appended with `?`, dedicated-pooler alternatives still shown per IPv4
add-on state)
- Project home copy dropdown is unchanged


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* Enhanced connection-string generation for high-availability projects,
including required SSL settings for direct connections.
* Preserved URI query parameters in PostgreSQL, `psql`, JDBC, and
generated environment configurations.
* Improved ORM environment templates with clearer handling for pooler
and high-availability connection scenarios.

* **Bug Fixes**
* High-availability projects now consistently use direct connections
instead of pooler options.
* Connection strings and generated templates update correctly when
availability settings change.

* **Tests**
* Expanded coverage for query parameters, high-availability behavior,
and connection scenarios.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-07-31 14:34:31 +08:00

412 lines
13 KiB
TypeScript

import { useParams } from 'common'
import { useCallback, useMemo, useState } from 'react'
import { MCP_CLIENTS } from 'ui-patterns/McpUrlBuilder'
import {
connectionStringMethodOptions,
DATABASE_CONNECTION_TYPES,
FRAMEWORKS,
MOBILES,
ORMS,
} from './Connect.constants'
import {
getActiveFields,
getDefaultState,
resetDependentFields,
resolveSteps,
} from './connect.resolver'
import {
connectSchema,
getDefaultMcpFeatures,
getSupportedMcpFeatureGroups,
normalizeMcpFeatures,
} from './connect.schema'
import type {
ConnectMode,
ConnectSchema,
ConnectState,
DeploymentMode,
FieldOption,
ResolvedField,
ResolvedStep,
} from './Connect.types'
import { resolveFrameworkLibraryKey } from './Connect.utils'
import { Database, useReadReplicasQuery } from '@/data/read-replicas/replicas-query'
import { formatDatabaseID, formatDatabaseRegion } from '@/data/read-replicas/replicas.utils'
import { useCheckEntitlements } from '@/hooks/misc/useCheckEntitlements'
import { useDeploymentMode } from '@/hooks/misc/useDeploymentMode'
import { useIsHighAvailability } from '@/hooks/misc/useSelectedProject'
// ============================================================================
// Data Source Helpers
// ============================================================================
/**
* Get field options from a data source reference.
* This maps source names to actual data.
*/
function getFieldOptionsFromSource({
source,
state,
databases,
deploymentMode,
}: {
source: string
state: ConnectState
databases: Database[]
deploymentMode: DeploymentMode
}): FieldOption[] {
switch (source) {
case 'frameworks':
return [...FRAMEWORKS, ...MOBILES].map((f) => ({
value: f.key,
label: f.label,
icon: f.icon,
}))
case 'frameworkVariants': {
// Get variants for the selected framework
const allFrameworks = [...FRAMEWORKS, ...MOBILES]
const selected = allFrameworks.find((f) => f.key === state.framework)
if (!selected?.children?.length) return []
// Only return if there are multiple children (variants)
if (selected.children.length <= 1) return []
return selected.children.map((c) => ({
value: c.key,
label: c.label,
icon: c.icon,
}))
}
case 'libraries': {
// Get libraries for the selected framework and variant
const allFrameworks = [...FRAMEWORKS, ...MOBILES]
const selectedFramework = allFrameworks.find((f) => f.key === state.framework)
if (!selectedFramework) return []
// If framework has variants, look in the variant
if (selectedFramework.children?.length > 1 && state.frameworkVariant) {
const variant = selectedFramework.children.find((c) => c.key === state.frameworkVariant)
if (variant?.children?.length) {
return variant.children.map((c) => ({
value: c.key,
label: c.label,
icon: c.icon,
}))
}
}
// Otherwise look directly in framework children
if (selectedFramework.children?.length === 1) {
const child = selectedFramework.children[0]
if (child.children?.length) {
return child.children.map((c) => ({
value: c.key,
label: c.label,
icon: c.icon,
}))
}
// The child itself is the library
return [{ value: child.key, label: child.label, icon: child.icon }]
}
return []
}
case 'connectionMethods': {
const all = Object.values(connectionStringMethodOptions)
const allowed: string[] = deploymentMode.isCli
? ['direct']
: deploymentMode.isSelfHosted
? ['session', 'transaction', 'direct']
: ['direct', 'transaction', 'session']
const filtered = allowed
.map((value) => all.find((m) => m.value === value))
.filter((m): m is (typeof all)[number] => !!m)
return filtered.map((m) => ({
value: m.value,
label: m.label,
description:
deploymentMode.isSelfHosted && m.value === 'direct'
? 'Manually configurable for self-hosted Supabase.'
: deploymentMode.isSelfHosted && m.value === 'session'
? 'Supavisor (default pooler for self-hosted Supabase).'
: m.description,
}))
}
case 'connectionSources':
return databases.map((db) => {
const region = formatDatabaseRegion(db?.region ?? '')
const id = formatDatabaseID(db.identifier ?? '')
const label = db.identifier.includes('-rr-')
? `Read Replica (${region} - ${id})`
: 'Primary Database'
return { value: db.identifier, label }
})
case 'connectionTypes':
return DATABASE_CONNECTION_TYPES.map((t) => ({
value: t.id,
label: t.label,
}))
case 'orms':
return ORMS.map((o) => ({
value: o.key,
label: o.label,
icon: o.icon,
}))
case 'mcpClients':
return MCP_CLIENTS.map((c) => ({
value: c.key,
label: c.label,
icon: c.icon,
}))
case 'mcpFeatures':
return getSupportedMcpFeatureGroups(deploymentMode.isPlatform).map((f) => ({
value: f.id,
label: f.name,
description: f.description,
}))
default:
return []
}
}
/**
* Resolve field options, handling both static options and data source references.
*/
function resolveFieldOptionsWithSource({
field,
state,
databases,
deploymentMode,
}: {
field: ResolvedField
state: ConnectState
databases: Database[]
deploymentMode: DeploymentMode
}): FieldOption[] {
// If already resolved (from conditional resolution)
if (field.resolvedOptions.length > 0) {
return field.resolvedOptions
}
// Check if it's a source reference
const options = connectSchema.fields[field.id]?.options
if (options && typeof options === 'object' && 'source' in options) {
return getFieldOptionsFromSource({
source: options.source as string,
state,
databases,
deploymentMode,
})
}
return []
}
// ============================================================================
// Hook
// ============================================================================
export interface UseConnectStateReturn {
state: ConnectState
updateField: (fieldId: string, value: string | boolean | string[]) => void
setMode: (mode: ConnectMode) => void
activeFields: ResolvedField[]
resolvedSteps: ResolvedStep[]
getFieldOptions: (fieldId: string) => FieldOption[]
schema: ConnectSchema
}
export function useConnectState(initialState?: Partial<ConnectState>): UseConnectStateReturn {
const { ref: projectRef } = useParams()
const { data: databases = [] } = useReadReplicasQuery({ projectRef })
const { hasAccess: hasDedicatedPooler } = useCheckEntitlements('dedicated_pooler')
const isHighAvailability = useIsHighAvailability()
const deploymentMode = useDeploymentMode()
const [state, setState] = useState<ConnectState>(() => {
const defaults = getDefaultState({ schema: connectSchema })
// Set initial framework if mode is framework
if (defaults.mode === 'framework' && !defaults.framework) {
const firstFramework = FRAMEWORKS[0]
defaults.framework = firstFramework?.key ?? ''
// Set initial variant if framework has variants
if (firstFramework?.children?.length > 1) {
defaults.frameworkVariant = firstFramework.children[0]?.key ?? ''
}
// Set initial library
const libraryKey = resolveFrameworkLibraryKey({
framework: defaults.framework,
frameworkVariant: defaults.frameworkVariant,
library: defaults.library,
})
if (libraryKey) defaults.library = libraryKey
}
// Set initial ORM if mode is orm
if (defaults.mode === 'orm' && !defaults.orm) {
defaults.orm = ORMS[0]?.key ?? ''
}
// Set initial MCP client if mode is mcp
if (defaults.mode === 'mcp' && !defaults.mcpClient) {
defaults.mcpClient = MCP_CLIENTS[0]?.key ?? ''
}
return { ...defaults, ...initialState } as ConnectState
})
const updateField = useCallback((fieldId: string, value: string | boolean | string[]) => {
setState((prev) => {
const next = { ...prev, [fieldId]: value }
// Handle cascading updates for framework selection
if (fieldId === 'framework') {
const allFrameworks = [...FRAMEWORKS, ...MOBILES]
const selected = allFrameworks.find((f) => f.key === value)
// Reset variant if framework changed
if (selected?.children && selected.children.length > 1) {
next.frameworkVariant = selected.children[0]?.key ?? ''
} else {
delete next.frameworkVariant
}
// Reset library
const libraryKey = resolveFrameworkLibraryKey({
framework: next.framework,
frameworkVariant: next.frameworkVariant,
})
if (libraryKey) {
next.library = libraryKey
} else {
delete next.library
}
}
// Handle cascading updates for variant selection
if (fieldId === 'frameworkVariant') {
const libraryKey = resolveFrameworkLibraryKey({
framework: prev.framework,
frameworkVariant: String(value),
})
if (libraryKey) next.library = libraryKey
}
// Reset useSharedPooler when connectionMethod changes to 'direct'
if (fieldId === 'connectionMethod' && value === 'direct') {
next.useSharedPooler = false
}
return resetDependentFields(next, fieldId, connectSchema)
})
}, [])
const setMode = useCallback(
(mode: ConnectMode) => {
setState((prev) => {
const next: ConnectState = { ...prev, mode }
// Initialize mode-specific defaults
if (mode === 'framework' && !next.framework) {
const firstFramework = FRAMEWORKS[0]
next.framework = firstFramework?.key ?? ''
if (firstFramework?.children?.length > 1) {
next.frameworkVariant = firstFramework.children[0]?.key ?? ''
}
const libraryKey = resolveFrameworkLibraryKey({
framework: next.framework,
frameworkVariant: next.frameworkVariant,
})
if (libraryKey) next.library = libraryKey
}
if (mode === 'direct') {
const defaultMethod = deploymentMode.isSelfHosted ? 'session' : 'direct'
next.connectionMethod = next.connectionMethod ?? defaultMethod
next.connectionType = next.connectionType ?? 'uri'
next.connectionSource = projectRef ?? '_'
}
if (mode === 'orm' && !next.orm) {
next.orm = ORMS[0]?.key ?? ''
}
if (mode === 'mcp') {
if (!next.mcpClient) {
next.mcpClient = MCP_CLIENTS[0]?.key ?? ''
}
if (next.mcpFeatures === undefined) {
next.mcpFeatures = getDefaultMcpFeatures(deploymentMode.isPlatform)
} else if (Array.isArray(next.mcpFeatures)) {
next.mcpFeatures = normalizeMcpFeatures(next.mcpFeatures, deploymentMode.isPlatform)
}
}
return next
})
},
[projectRef, deploymentMode.isSelfHosted, deploymentMode.isPlatform]
)
// Multigres has no pooler, so pooler-flavored selections restored from the
// URL or localStorage (shared across projects) must never leak into an HA
// project — every consumer sees the direct connection method.
const resolvedState = useMemo(
() =>
isHighAvailability ? { ...state, connectionMethod: 'direct', useSharedPooler: false } : state,
[state, isHighAvailability]
)
const activeFields = useMemo(() => {
let fields = getActiveFields(connectSchema, resolvedState)
if (!hasDedicatedPooler || !deploymentMode.isPlatform) {
// useSharedPooler is a platform-only toggle (CLI has no pooler; self-hosted
// already uses Supavisor shared)
fields = fields.filter((f) => f.id !== 'useSharedPooler')
}
if (isHighAvailability) {
fields = fields
.filter((f) => f.id !== 'connectionMethod' && f.id !== 'useSharedPooler')
.map((f) => (f.id === 'connectionType' ? { ...f, label: 'Connection Type' } : f))
}
return fields
}, [resolvedState, hasDedicatedPooler, isHighAvailability, deploymentMode.isPlatform])
const resolvedSteps = useMemo(() => resolveSteps(connectSchema, resolvedState), [resolvedState])
const getFieldOptions = useCallback(
(fieldId: string): FieldOption[] => {
const field = activeFields.find((f) => f.id === fieldId)
if (!field) return []
return resolveFieldOptionsWithSource({
field,
state: resolvedState,
databases,
deploymentMode,
})
},
[activeFields, resolvedState, databases, deploymentMode]
)
return {
state: resolvedState,
updateField,
setMode,
activeFields,
resolvedSteps,
getFieldOptions,
schema: connectSchema,
}
}