Files
supabase/apps/studio/data/replication/pipeline-status-query.ts
T
edec85d1ca fix(pipelines): Make pipeline actions and status updates reliable (#50085)
## Summary

Make pipeline actions and status feedback reliable while requests are
running or fail. Let the backend coordinate table resets and restarts,
keep stopped pipelines stopped after resets or settings changes, and
refresh the UI from confirmed backend state.

## Pipeline actions and recovery

- Reset one table, all errored tables, or all tables through the
rollback endpoint without separate frontend stop/start requests. Explain
which destination data is deleted, which rows are copied again, initial
sync charges, and the skip-initial-sync setting.
- Keep pending feedback until the action and a fresh status read finish,
including across navigation and polling errors. Prevent overlapping
actions and disable start/stop controls when status is unavailable or
transitioning.
- Close the creation form once the pipeline is created. If its initial
start fails, users can retry Start on the existing pipeline without
creating a duplicate.
- Wait for confirmed shutdown before deletion; a shutdown error or
timeout leaves deletion retryable. Keep failed version updates open and
avoid reporting success.
- Clarify recovery guidance and pending labels, suppress duplicate error
toasts, and hide stale table errors during transitions.

## Status updates and shared UI

- Poll pipeline status and table metrics one second after each response,
share in-flight reads, pause dashboard polling in background tabs, and
respect rate-limit backoff. The shutdown waiter continues in the
background.
- Refresh metadata after mutations even when an older read is in flight,
while preserving shared polling requests. Refresh affected data after
failures that may follow a committed reset or settings change.
- Move pending request state into the shared, project-keyed
`DatabaseLayout` so the list, detail page, and diagram stay consistent.
The surrounding database-page changes update named imports in both
Next.js and TanStack routes.
- Simplify action, status, and form rendering; announce status changes
to assistive technology; and sort table statuses without mutating cached
data.

---------

Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
Co-authored-by: Danny White <3104761+dnywh@users.noreply.github.com>
2026-09-18 11:32:48 +08:00

94 lines
3.4 KiB
TypeScript

import { QueryObserver, queryOptions, useQuery, type QueryClient } from '@tanstack/react-query'
import { components } from 'api-types'
import { replicationKeys } from './keys'
import { replicationPollingOptions } from './polling'
import { get, handleError } from '@/data/fetchers'
import type { ResponseError, UseCustomQueryOptions } from '@/types'
type ReplicationPipelinesStatusParams = { projectRef?: string; pipelineId?: number }
const PIPELINE_STOP_TIMEOUT_MS = 30_000
export type ReplicationPipelineStatusResponse =
components['schemas']['PipelineStatusResponse_Output']
export type ReplicationPipelineStatus = ReplicationPipelineStatusResponse['status']['name']
async function fetchReplicationPipelineStatus(
{ projectRef, pipelineId }: ReplicationPipelinesStatusParams,
signal?: AbortSignal
) {
if (!projectRef) throw new Error('projectRef is required')
if (!pipelineId) throw new Error('pipelineId is required')
const { data, error } = await get('/platform/replication/{ref}/pipelines/{pipeline_id}/status', {
params: { path: { ref: projectRef, pipeline_id: pipelineId } },
signal,
})
if (error) {
handleError(error)
}
return data
}
export type ReplicationPipelineStatusData = Awaited<
ReturnType<typeof fetchReplicationPipelineStatus>
>
/**
* Shared definition so callers that need many pipeline statuses at once (`useQueries`) hit the
* same cache entries as the per-pipeline hook below, rather than fetching each status twice.
*/
export const replicationPipelineStatusQueryOptions = <TData = ReplicationPipelineStatusData>({
projectRef,
pipelineId,
}: ReplicationPipelinesStatusParams) =>
queryOptions<ReplicationPipelineStatusData, ResponseError, TData>({
queryKey: replicationKeys.pipelinesStatus(projectRef, pipelineId),
queryFn: ({ signal }) => fetchReplicationPipelineStatus({ projectRef, pipelineId }, signal),
...replicationPollingOptions,
enabled: typeof projectRef !== 'undefined' && typeof pipelineId !== 'undefined',
})
/** Shares the dashboard's status request while waiting for shutdown before deletion. */
export function waitForPipelineStopped(
queryClient: QueryClient,
variables: ReplicationPipelinesStatusParams
): Promise<void> {
return new Promise((resolve, reject) => {
const observer = new QueryObserver(queryClient, {
...replicationPipelineStatusQueryOptions(variables),
staleTime: 0,
refetchIntervalInBackground: true,
})
const timer = setTimeout(() => {
observer.destroy()
reject(
new Error('Pipeline is still stopping. Wait for it to stop, then try deleting it again.')
)
}, PIPELINE_STOP_TIMEOUT_MS)
observer.subscribe((result) => {
if (result.fetchStatus !== 'idle') return
if (result.isError || result.data?.status.name === 'stopped') {
clearTimeout(timer)
observer.destroy()
if (result.isError) reject(result.error)
else resolve()
}
})
})
}
export const useReplicationPipelineStatusQuery = <TData = ReplicationPipelineStatusData>(
variables: ReplicationPipelinesStatusParams,
options: UseCustomQueryOptions<ReplicationPipelineStatusData, ResponseError, TData> = {}
) =>
useQuery<ReplicationPipelineStatusData, ResponseError, TData>({
...replicationPipelineStatusQueryOptions<TData>(variables),
...options,
enabled:
options.enabled !== false &&
typeof variables.projectRef !== 'undefined' &&
typeof variables.pipelineId !== 'undefined',
})