choose a region in the pipeline creation sheet

This commit is contained in:
Danny White committed 2026-11-26 13:05:08 +11:00
1 parent 74e31a3aa9
commit fa5317968e
8 files changed
+269 -29

No files matched your search

@@ -12,18 +12,20 @@ export const PipelineConnectionSection = ({
type,
form,
children,
regionField,
revealInvalidSettings = false,
}: {
type: DestinationType
form: UseFormReturn<DestinationPanelSchemaType>
children: ReactNode
regionField?: ReactNode
revealInvalidSettings?: boolean
}) => (
<section aria-label="Destination connection">
<div className="flex flex-col gap-y-4 p-5">
<h3 className="text-sm font-medium text-foreground">Destination connection</h3>
<DestinationNameInput form={form} destinationType={type} />
<PipelineRegionField destinationType={type} />
{regionField ?? <PipelineRegionField destinationType={type} />}
</div>
<DialogSectionSeparator />
{children}
@@ -24,7 +24,7 @@ test('shows the API default region as read-only information', async () => {
}),
})
customRender(<PipelineRegionField />)
customRender(<PipelineRegionField onRegionChange={() => {}} />)
const region = screen.getByText(PIPELINE_REGION.displayName).closest('[aria-live="polite"]')
expect(region).toHaveAttribute('aria-atomic', 'true')
@@ -12,13 +12,13 @@ import { customRender } from '@/tests/lib/custom-render'
describe('getPipelineRegionDescription', () => {
test('includes the fixed-region note and destination-specific hint', () => {
expect(getPipelineRegionDescription('BigQuery')).toBe(
'All pipelines run from this region. Choose a nearby BigQuery dataset where possible.'
'Choose a nearby BigQuery dataset where possible.'
)
})
test('falls back to a generic destination hint', () => {
expect(getPipelineRegionDescription()).toBe(
'All pipelines run from this region. Choose a nearby destination region where possible.'
'Choose a nearby destination region where possible.'
)
})
})
@@ -30,7 +30,7 @@ describe('PipelineRegionField', () => {
expect(screen.getByText('Pipeline region')).toBeInTheDocument()
expect(screen.getByText(PIPELINE_REGION.displayName)).toBeInTheDocument()
expect(screen.getByText(PIPELINE_REGION.code)).toBeInTheDocument()
expect(screen.getByText(/All pipelines run from this region/)).toBeInTheDocument()
expect(screen.getByText(/Choose a nearby BigQuery dataset where possible/)).toBeInTheDocument()
expect(screen.getByText(/nearby BigQuery dataset/)).toBeInTheDocument()
expect(screen.queryByRole('combobox')).not.toBeInTheDocument()
})
@@ -1,15 +1,18 @@
import { useQuery } from '@tanstack/react-query'
import { AWS_REGIONS } from 'shared-data'
import { cn } from 'ui'
import { cn, Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from 'ui'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
import type { DestinationType } from '../DestinationPanel.types'
import { toRequestClusterId } from '@/components/interfaces/Database/Replication/PipelineClusterScope.utils'
import { RegionFlag } from '@/components/ui/RegionFlag'
import { replicationClustersQueryOptions } from '@/data/replication/clusters-query'
import {
replicationClustersQueryOptions,
type ReplicationRegion,
} from '@/data/replication/clusters-query'
import { IS_STAGING_OR_LOCAL } from '@/lib/constants'
import { useReplicationClusterId } from '@/state/replication-cluster'
// Keep the existing environment region as a fallback when discovery has no region code.
export const PIPELINE_REGION = IS_STAGING_OR_LOCAL
? AWS_REGIONS.SOUTHEAST_ASIA
: AWS_REGIONS.CENTRAL_EU
@@ -21,21 +24,37 @@ const DESTINATION_REGION_HINT: Record<DestinationType, string> = {
ClickHouse: 'Choose a nearby ClickHouse cluster where possible.',
}
export const getPipelineRegionDescription = (destinationType?: DestinationType) => {
const destinationHint = destinationType
export const getPipelineRegionDescription = (destinationType?: DestinationType) =>
destinationType
? DESTINATION_REGION_HINT[destinationType]
: 'Choose a nearby destination region where possible.'
return `All pipelines run from this region. ${destinationHint}`
}
export const PipelineRegionField = ({
destinationType,
className,
onRegionChange,
preferredClusterId,
disabled,
}: {
destinationType?: DestinationType
className?: string
/** Makes the region selectable when there is more than one region. */
onRegionChange?: (clusterId: string | undefined) => void
preferredClusterId?: string
disabled?: boolean
}) => {
const { data } = useQuery(replicationClustersQueryOptions())
const hasMultipleRegions = (data?.regions.length ?? 0) > 1
const clusterId = useReplicationClusterId()
const canSelectRegion = hasMultipleRegions && onRegionChange !== undefined && data !== undefined
const regions = data?.regions ?? []
const firstRegion = regions.find(
(region) => region.cluster_id === (preferredClusterId ?? data?.default_cluster_id)
)
const orderedRegions = firstRegion
? [firstRegion, ...regions.filter((region) => region.cluster_id !== firstRegion.cluster_id)]
: regions
return (
<FormItemLayout
isReactForm={false}
@@ -43,18 +62,71 @@ export const PipelineRegionField = ({
label="Pipeline region"
description={getPipelineRegionDescription(destinationType)}
>
<PipelineRegionReadonly className={className} />
{canSelectRegion ? (
<PipelineRegionSelect
regions={orderedRegions}
className={className}
disabled={disabled}
value={clusterId ?? data.default_cluster_id}
onValueChange={(value) =>
onRegionChange(toRequestClusterId(value, data.default_cluster_id))
}
/>
) : (
<PipelineRegionReadonly className={className} />
)}
</FormItemLayout>
)
}
const PipelineRegionSelect = ({
regions,
value,
onValueChange,
className,
disabled,
}: {
regions: ReplicationRegion[]
value: string
onValueChange: (clusterId: string) => void
className?: string
disabled?: boolean
}) => (
<Select value={value} onValueChange={onValueChange} disabled={disabled}>
<SelectTrigger aria-label="Pipeline region" className={className}>
<SelectValue />
</SelectTrigger>
<SelectContent>
{regions.map((region) => {
const label = region.region_code
? `${region.region_name} (${region.region_code})`
: region.region_name
return (
<SelectItem key={region.cluster_id} value={region.cluster_id} textValue={label}>
<span className="flex items-center gap-x-2">
{region.region_code && (
<RegionFlag className="w-5 shrink-0" region={region.region_code} />
)}
<span>
{region.region_name}
{region.region_code && (
<span className="text-foreground-lighter"> ({region.region_code})</span>
)}
</span>
</span>
</SelectItem>
)
})}
</SelectContent>
</Select>
)
export const PipelineRegionReadonly = ({ className }: { className?: string }) => {
const selectedClusterId = useReplicationClusterId()
const { data } = useQuery(replicationClustersQueryOptions())
const clusterId = selectedClusterId ?? data?.default_cluster_id
const cluster = data?.regions.find((region) => region.cluster_id === clusterId)
const region = cluster?.region_code ? cluster : undefined
const regionCode = region?.region_code ?? PIPELINE_REGION.code
const cluster = data?.regions.find((item) => item.cluster_id === clusterId)
const regionCode = cluster ? cluster.region_code : PIPELINE_REGION.code
return (
<div
@@ -65,11 +137,13 @@ export const PipelineRegionReadonly = ({ className }: { className?: string }) =>
className
)}
>
<RegionFlag className="w-5 shrink-0" region={regionCode} />
{regionCode && <RegionFlag className="w-5 shrink-0" region={regionCode} />}
<span className="min-w-0 truncate text-foreground">
{region?.region_name ?? PIPELINE_REGION.displayName}
{cluster?.region_name ?? PIPELINE_REGION.displayName}
</span>
<span className="shrink-0 font-mono text-xs text-foreground-lighter">{regionCode}</span>
{regionCode && (
<span className="shrink-0 font-mono text-xs text-foreground-lighter">{regionCode}</span>
)}
</div>
)
}
@@ -56,6 +56,7 @@ import { useDestinationForm } from './useDestinationForm'
import { ValidationFailuresSection } from './ValidationFailuresSection'
import { ValidationWarningsDialog } from './ValidationWarningsDialog'
import { usePipelineCreationPreview } from '@/components/interfaces/App/FeaturePreview/FeaturePreviewContext'
import { useReplicationClusters } from '@/components/interfaces/Database/Replication/useReplicationClusters'
import { AlertError } from '@/components/ui/AlertError'
import { useReplicationDestinationByIdQuery } from '@/data/replication/destination-by-id-query'
import { useReplicationPipelineByIdQuery } from '@/data/replication/pipeline-by-id-query'
@@ -75,7 +76,9 @@ interface DestinationFormProps {
checkIsDirtyRef?: RefObject<() => boolean>
onClose: () => void
onCancel?: () => void
onRegionChange?: (clusterId: string | undefined) => void
isPreparingRegion?: boolean
preferredClusterId?: string
}
export const DestinationForm = ({
@@ -86,7 +89,9 @@ export const DestinationForm = ({
checkIsDirtyRef,
onClose,
onCancel = onClose,
onRegionChange,
isPreparingRegion = false,
preferredClusterId,
}: DestinationFormProps) => {
const { ref: projectRef } = useParams()
const clusterId = useReplicationClusterId()
@@ -116,6 +121,9 @@ export const DestinationForm = ({
const validationSectionRef = useRef<HTMLDivElement>(null)
const editMode = !!existingDestination
const { hasMultipleRegions } = useReplicationClusters()
// Publications are listed through the region's source, so the region is chosen first.
const canSelectRegion = !editMode && hasMultipleRegions && onRegionChange !== undefined
const { isEnabled: isCreationPreviewEnabled } = usePipelineCreationPreview()
const shouldShowConnectionSection = isCreationPreviewEnabled && !editMode
@@ -253,8 +261,8 @@ export const DestinationForm = ({
const isSubmitDisabled =
isSaving ||
isPreparingRegion ||
(isManagedDuckLake && isDuckLakeProjectBlocked) ||
isPreparingRegion ||
!isExistingConfigReady ||
!isSuccessPublicationNames ||
(!!publicationName && !isSuccessPublication) ||
@@ -479,6 +487,22 @@ export const DestinationForm = ({
</>
)
const regionField = (
<PipelineRegionField
destinationType={selectedType}
preferredClusterId={preferredClusterId}
onRegionChange={
canSelectRegion
? (clusterId) => {
resetValidation()
onRegionChange(clusterId)
}
: undefined
}
disabled={isPreparingRegion || isSaving}
/>
)
return (
<>
<SheetSection className="grow overflow-auto px-0 py-0">
@@ -488,7 +512,11 @@ export const DestinationForm = ({
<fieldset disabled={!isExistingConfigReady || isPreparingRegion} className="contents">
{shouldShowConnectionSection && (
<>
<PipelineConnectionSection type={selectedType} form={form}>
<PipelineConnectionSection
type={selectedType}
form={form}
regionField={regionField}
>
{destinationFields}
</PipelineConnectionSection>
<DialogSectionSeparator />
@@ -515,12 +543,13 @@ export const DestinationForm = ({
<div className="flex flex-col gap-y-4">
<DestinationNameInput form={form} destinationType={selectedType} />
{canSelectRegion && regionField}
<PublicationSelection
form={form}
onSelectNewPublication={() => setPublicationPanelVisible(true)}
/>
<TableCopySelection form={form} editMode={editMode} />
<PipelineRegionField destinationType={selectedType} />
{!canSelectRegion && regionField}
</div>
</div>
@@ -1,5 +1,5 @@
import { QueryClient } from '@tanstack/react-query'
import { screen } from '@testing-library/react'
import { fireEvent, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { components } from 'api-types'
import { FeatureFlagContext } from 'common'
@@ -10,6 +10,7 @@ import { expect, test } from 'vitest'
import { DestinationPanel } from './DestinationPanel'
import { organizationKeys } from '@/data/organizations/keys'
import type { OrganizationsData } from '@/data/organizations/organizations-query'
import type { ReplicationCostEstimateData } from '@/data/replication/cost-estimate-query'
import { ReplicationClusterProvider } from '@/state/replication-cluster'
import { PipelineRequestStatusProvider } from '@/state/replication-pipeline-request-status'
import { createMockProject } from '@/tests/helpers'
@@ -130,6 +131,13 @@ const renderPanel = (clusterId?: string) => {
)
}
const findRegionSelector = () => screen.findByRole('combobox', { name: 'Pipeline region' })
const choosePublication = async (name: string) => {
await userEvent.click(await screen.findByText('Select publication'))
await userEvent.click(await screen.findByText(name))
}
test('retries source discovery and opens creation when only another region is enabled', async () => {
mockRegions()
mockProject(FRANKFURT.region_code)
@@ -153,16 +161,135 @@ test('opens the panel with a source only in a non-default region', async () => {
mockPanelResources(new Set([FRANKFURT.cluster_id]))
renderPanel()
expect(await screen.findByText('Frankfurt')).toBeVisible()
expect(await findRegionSelector()).toHaveTextContent('Frankfurt (eu-central-1)')
})
test('uses the default region when the project region lookup fails', async () => {
test('prepares the environment default from a non-default region context', async () => {
mockRegions()
mockProject(FRANKFURT.region_code)
const enabledClusters = new Set<string | null>([FRANKFURT.cluster_id])
mockPanelResources(enabledClusters)
const writes: (string | null)[] = []
addAPIMock({
method: 'post',
path: '/platform/replication/:ref/tenants-sources',
response: ({ request }) => {
const cluster = clusterFrom(request)
writes.push(cluster)
enabledClusters.add(cluster)
return HttpResponse.json<components['schemas']['CreateTenantSourceResponse_Output']>({
tenant_id: 'default',
source_id: 1,
})
},
})
renderPanel(FRANKFURT.cluster_id)
const selector = await findRegionSelector()
expect(selector).toHaveTextContent('Frankfurt (eu-central-1)')
await waitFor(() => expect(selector).toBeEnabled())
await userEvent.click(selector)
const options = within(await screen.findByRole('listbox')).getAllByRole('option')
expect(options.map((option) => option.textContent)).toEqual([
'Frankfurt (eu-central-1)',
'Singapore (ap-southeast-1)',
])
await userEvent.click(options[1])
await waitFor(() => expect(selector).toBeEnabled())
await userEvent.click(await screen.findByText('Select publication'))
expect(await screen.findByText('singapore')).toBeVisible()
expect(selector).toHaveTextContent('Singapore (ap-southeast-1)')
expect(writes).toEqual([null])
})
test('keeps region selection available when the project region lookup fails', async () => {
mockRegions()
mockProject()
mockPanelResources(new Set([null]))
renderPanel()
expect(await screen.findByText('Singapore')).toBeVisible()
const selector = await findRegionSelector()
expect(selector).toHaveTextContent('Singapore (ap-southeast-1)')
await waitFor(() => expect(selector).toBeEnabled())
})
test('locks the region selector while saving the pipeline', async () => {
mockRegions()
mockProject(SINGAPORE.region_code)
mockPanelResources(new Set([null]))
addAPIMock({
method: 'get',
path: '/platform/replication/v2/:ref/sources/:source_id/publications/:publication_name',
response: {
name: 'singapore',
config: {
type: 'tables',
tables: [],
operations: ['insert'],
publish_via_partition_root: false,
},
tables: [],
},
})
addAPIMock({
method: 'get',
path: '/platform/replication/:ref/sources/:source_id/publications/:publication_name/cost-estimate',
response: () =>
HttpResponse.json<ReplicationCostEstimateData>({
currency: 'usd',
pipeline: { hourly_cost: 0.05, monthly_cost: 36.5 },
streaming: { rate_per_gb: 3 },
table_copy: { rate_per_gb: 0.6, total_bytes: 0, total_cost: 0, tables: [] },
}),
})
addAPIMock({
method: 'post',
path: '/platform/replication/:ref/destinations/validate',
response: { validation_failures: [] },
})
addAPIMock({
method: 'post',
path: '/platform/replication/:ref/pipelines/validate',
response: { validation_failures: [] },
})
const pendingSave = Promise.withResolvers<void>()
const saveRequested = Promise.withResolvers<void>()
addAPIMock({
method: 'post',
path: '/platform/replication/:ref/destinations-pipelines',
response: async () => {
saveRequested.resolve()
await pendingSave.promise
return HttpResponse.json<APIErrorBody>({ message: 'Create failed' }, { status: 500 })
},
})
renderPanel()
try {
const selector = await findRegionSelector()
await choosePublication('singapore')
const fields = {
'Pipeline name': 'Warehouse',
'Project ID': 'my-project',
'Dataset ID': 'dataset',
'Service account key': '{}',
}
for (const [name, value] of Object.entries(fields)) {
fireEvent.change(screen.getByLabelText(name), { target: { value } })
}
const submit = screen.getByRole('button', { name: 'Start pipeline' })
await waitFor(() => expect(submit).toBeEnabled())
fireEvent.click(submit)
const confirm = await screen.findByRole('button', { name: 'Create and start pipeline' })
await waitFor(() => expect(confirm).toBeEnabled())
await userEvent.click(confirm)
await saveRequested.promise
await waitFor(() => expect(selector).toBeDisabled())
pendingSave.resolve()
await waitFor(() => expect(selector).toBeEnabled())
} finally {
pendingSave.resolve()
}
})
test('prepares the source in the preferred region before loading its publications', async () => {
@@ -186,9 +313,8 @@ test('prepares the source in the preferred region before loading its publication
})
renderPanel()
expect(await screen.findByText('Frankfurt')).toBeVisible()
expect(await findRegionSelector()).toHaveTextContent('Frankfurt (eu-central-1)')
await userEvent.click(await screen.findByText('Select publication'))
expect(await screen.findByText('frankfurt')).toBeVisible()
expect(writes).toEqual([FRANKFURT.cluster_id])
expect(screen.queryByRole('combobox', { name: 'Pipeline region' })).not.toBeInTheDocument()
})
@@ -133,6 +133,11 @@ export const DestinationPanel = () => {
error: regionSourceError,
reset: resetRegionSource,
} = useEnsurePipelineRegionSource(projectRef)
const handleRegionChange = (clusterId: string | undefined) => {
setChosenClusterId(clusterId)
resetRegionSource()
void ensureRegionSource(clusterId)
}
// A preselected region may need the project's source, just like an explicit pick.
const attemptedPreferredClusterRef = useRef<string | undefined | null>(null)
@@ -294,6 +299,8 @@ export const DestinationPanel = () => {
checkIsDirtyRef={checkIsDirtyRef}
onClose={onClose}
onCancel={confirmOnClose}
preferredClusterId={preferredCluster.clusterId}
onRegionChange={handleRegionChange}
isPreparingRegion={isCreatingSource}
/>
</ReplicationClusterProvider>
@@ -17,6 +17,8 @@ export type ReplicationClustersData = Awaited<ReturnType<typeof getReplicationCl
export type ReplicationClustersError = StudioError
export type ReplicationRegion = ReplicationClustersData['regions'][number]
export const replicationClustersQueryOptions = () =>
queryOptions<ReplicationClustersData, ReplicationClustersError>({
queryKey: replicationKeys.clusters(),