Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 20 additions & 5 deletions dashboard/src/pages/ProductionDeployModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,30 @@ import { FieldLabel, OverlayModal } from '../components/workbench'

export default function ProductionDeployModal({
task,
gate,
gateStatus,
confirmPhrase,
busyAction,
onConfirmPhraseChange,
onClose,
onDeploy,
}: Readonly<{
task: ReleaseTask | null
gate?: ReleaseTask['pr_gate']
gateStatus?: 'idle' | 'loading' | 'ready' | 'error'
confirmPhrase: string
busyAction: string | null
onConfirmPhraseChange: (value: string) => void
onClose: () => void
onDeploy: () => void
}>) {
if (!task) {
return null
}
const busyKey = task ? `release-task-${task.id}-deploy-production` : ''
const effectiveGate = gate || task?.pr_gate
const gateReady = Boolean(effectiveGate?.can_deploy_production)
const gateLoading = gateStatus === 'loading'
return (
<OverlayModal
open={Boolean(task)}
Expand All @@ -25,7 +35,7 @@ export default function ProductionDeployModal({
description="生产发布会触发 GitHub Environment production 与 GCP WIF Cloud Run 工作流。不会自动 rollback。"
onClose={onClose}
>
{task ? (
{(
<div className="space-y-5">
<div className="rounded-2xl border border-[color:var(--ops-state-blocked-border)] bg-[color:var(--ops-state-blocked-bg)] p-4 text-sm text-[color:var(--ops-state-blocked-text)]">
<div className="font-semibold">Production Human Gate</div>
Expand All @@ -37,9 +47,14 @@ export default function ProductionDeployModal({
<div className="grid gap-3 md:grid-cols-2">
<InfoCard label="Project / Service" value={`${task.project_display_name || task.project_key} · ${task.service_key || '-'}`} />
<InfoCard label="GCP Project" value="synapse-network-prod" mono />
<InfoCard label="Main Commit" value={task.pr_gate?.resolved_commit_sha || '-'} mono />
<InfoCard label="Staging Evidence" value={`Deployment #${task.pr_gate?.staging_deployment_record_id || '-'}`} />
<InfoCard label="Main Commit" value={effectiveGate?.resolved_commit_sha || '-'} mono />
<InfoCard label="Staging Evidence" value={`Deployment #${effectiveGate?.staging_deployment_record_id || '-'}`} />
</div>
{!gateReady ? (
<div className="rounded-2xl border border-[color:var(--ops-state-running-border)] bg-[color:var(--ops-state-running-bg)] p-4 text-sm text-[color:var(--ops-state-running-text)]">
{gateLoading ? 'Production gate 检查中…' : effectiveGate?.blocked_reason || '请先检查 production gate。'}
</div>
) : null}
<label className="block space-y-2">
<FieldLabel>输入确认短语</FieldLabel>
<input
Expand All @@ -56,14 +71,14 @@ export default function ProductionDeployModal({
<button
type="button"
className="rounded-xl border border-[color:var(--ops-state-blocked-border)] bg-[color:var(--ops-state-blocked-bg)] px-4 py-2.5 text-sm font-semibold text-[color:var(--ops-state-blocked-text)] disabled:opacity-50"
disabled={confirmPhrase !== 'DEPLOY_PRODUCTION' || Boolean(busyAction)}
disabled={confirmPhrase !== 'DEPLOY_PRODUCTION' || Boolean(busyAction) || !gateReady}
onClick={onDeploy}
>
{busyAction === busyKey ? '发布中…' : '确认发布到 production'}
</button>
</div>
</div>
) : null}
)}
</OverlayModal>
)
}
Expand Down
150 changes: 150 additions & 0 deletions dashboard/src/pages/ReleasesPage.production.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
// @vitest-environment jsdom

import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter } from 'react-router-dom'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import ReleasesPage from './ReleasesPage'

const apiMock = vi.hoisted(() => ({
getReleaseCandidates: vi.fn(),
getReleaseTasksPage: vi.fn(),
getReleaseTaskGateStatus: vi.fn(),
deployReleaseTask: vi.fn(),
getOnlineReleaseRecords: vi.fn(),
getProjectPolicies: vi.fn(),
getSdkPackageReleases: vi.fn(),
getScheduledCloudRunJobsStatus: vi.fn(),
}))

vi.mock('../api', () => ({
api: {
getReleaseCandidates: apiMock.getReleaseCandidates,
getOnlineReleaseRecords: apiMock.getOnlineReleaseRecords,
getProjectPolicies: apiMock.getProjectPolicies,
getSdkPackageReleases: apiMock.getSdkPackageReleases,
getScheduledCloudRunJobsStatus: apiMock.getScheduledCloudRunJobsStatus,
},
}))

vi.mock('../apiReleaseTasks', () => ({
getReleaseTasksPage: apiMock.getReleaseTasksPage,
getReleaseTaskGateStatus: apiMock.getReleaseTaskGateStatus,
deployReleaseTask: apiMock.deployReleaseTask,
}))

function releaseTask(overrides: Record<string, unknown> = {}) {
return {
id: 42,
source_type: 'manual',
requirement_id: null,
deployment_record_id: null,
project_key: 'synapse-network',
project_display_name: 'Synapse-Network',
service_key: 'user-front',
branch_name: 'main',
environment: 'production',
status: 'requested',
actor: 'operator',
operator: null,
note: 'Manual staging release',
deployment_status: null,
deployment_external_run_id: null,
deployment_external_url: null,
deployment_commit_sha: null,
deployment_health_status: null,
deployment_failure_summary: null,
deployment_workflow_file: null,
deployment_metadata: null,
pr_gate: {
branch_exists: true,
pr_exists: false,
pr_url: null,
pr_number: null,
pr_state: 'production',
checks_status: 'unknown',
checks_summary: null,
can_create_pr: false,
can_deploy_staging: false,
can_deploy_production: false,
resolved_commit_sha: null,
staging_deployment_record_id: null,
blocked_reason: 'Production gate pending.',
},
created_at: '2026-05-15T10:00:00Z',
updated_at: '2026-05-15T10:00:00Z',
...overrides,
}
}

describe('ReleasesPage production deploy', () => {
beforeEach(() => {
vi.clearAllMocks()
apiMock.getReleaseCandidates.mockResolvedValue([])
apiMock.getOnlineReleaseRecords.mockResolvedValue([])
apiMock.getProjectPolicies.mockResolvedValue([])
apiMock.getSdkPackageReleases.mockResolvedValue([])
apiMock.getScheduledCloudRunJobsStatus.mockResolvedValue({
items: [],
diagnostics: [],
})
apiMock.getReleaseTasksPage.mockResolvedValue({
items: [releaseTask()],
total: 1,
limit: 10,
offset: 0,
})
})

it('uses live production gate and does not reload the task page after deploy', async () => {
apiMock.getReleaseTaskGateStatus.mockResolvedValue({
branch_exists: true,
pr_exists: false,
pr_url: null,
pr_number: null,
pr_state: 'production',
checks_status: 'success',
checks_summary: 'Staging deployment #71 passed.',
can_create_pr: false,
can_deploy_staging: false,
can_deploy_production: true,
resolved_commit_sha: 'prod-main-sha',
staging_deployment_record_id: 71,
blocked_reason: null,
})
apiMock.deployReleaseTask.mockResolvedValueOnce(
releaseTask({
status: 'deploying',
deployment_record_id: 99,
deployment_status: 'requested',
deployment_health_status: 'checking',
deployment_metadata: { dispatchPending: true, dispatchStatus: 'pending' },
}),
)
const user = userEvent.setup()
render(<ReleasesPage />, { wrapper: MemoryRouter })

await user.click(await screen.findByRole('button', { name: '发布管理' }))
await user.click(await screen.findByRole('button', { name: '发布到 production' }))

expect(await screen.findByText('prod-main-sha')).toBeTruthy()
expect(screen.getByText('Deployment #71')).toBeTruthy()
const initialTaskPageCalls = apiMock.getReleaseTasksPage.mock.calls.length
await user.type(screen.getByLabelText('输入确认短语'), 'DEPLOY_PRODUCTION')
await user.click(screen.getByRole('button', { name: '确认发布到 production' }))

await waitFor(() => {
expect(apiMock.deployReleaseTask).toHaveBeenCalledWith(42, {
actor: 'operator',
note: 'Manual staging release',
confirm_phrase: 'DEPLOY_PRODUCTION',
})
})
expect(apiMock.getReleaseTasksPage).toHaveBeenCalledTimes(initialTaskPageCalls)
await waitFor(() => {
expect(screen.queryByText('确认发布到 production')).toBeNull()
})
expect(screen.getByText('Deploy: 待执行')).toBeTruthy()
expect(screen.getByText('Health: 检查中')).toBeTruthy()
})
})
23 changes: 19 additions & 4 deletions dashboard/src/pages/ReleasesPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -432,12 +432,13 @@ export default function ReleasesPage() {
if (busyAction) return
setBusyAction(busyKey)
try {
await api.deployReleaseTaskToStaging(task.id, {
const updated = await api.deployReleaseTaskToStaging(task.id, {
actor: 'operator',
note: task.note,
})
toast.success('Staging 发布已触发')
await load()
setTasks((current) => current.map((item) => (item.id === updated.id ? updated : item)))
setTaskDetail((current) => (current?.id === updated.id ? updated : current))
} catch (error) {
const message = error instanceof Error ? error.message : '触发 staging 发布失败'
toast.error(message)
Expand Down Expand Up @@ -467,15 +468,22 @@ export default function ReleasesPage() {
const busyKey = `release-task-${productionDeployTask.id}-deploy-production`
setBusyAction(busyKey)
try {
await deployReleaseTask(productionDeployTask.id, {
const updated = await deployReleaseTask(productionDeployTask.id, {
actor: 'operator',
note: productionDeployTask.note,
confirm_phrase: productionConfirmPhrase,
})
toast.success('Production 发布已触发')
setTasks((current) => current.map((item) => (item.id === updated.id ? updated : item)))
setTaskDetail((current) => (current?.id === updated.id ? updated : current))
setGateStatusByTaskId((current) => {
if (!(updated.id in current)) return current
const next = { ...current }
delete next[updated.id]
return next
})
setProductionDeployTask(null)
setProductionConfirmPhrase('')
await load()
} catch (error) {
const message = error instanceof Error ? error.message : '触发 production 发布失败'
toast.error(message)
Expand Down Expand Up @@ -659,6 +667,7 @@ export default function ReleasesPage() {
onDeployProduction={(task) => {
setProductionConfirmPhrase('')
setProductionDeployTask(task)
refreshTaskGateStatus(task).catch(() => {})
}}
onRefreshGate={(task) => refreshTaskGateStatus(task)}
onRefresh={() => load().catch(() => {})}
Expand All @@ -682,6 +691,12 @@ export default function ReleasesPage() {

<ProductionDeployModal
task={productionDeployTask}
gate={
productionDeployTask
? gateStatusByTaskId[productionDeployTask.id]?.gate || productionDeployTask.pr_gate
: undefined
}
gateStatus={productionDeployTask ? gateStatusByTaskId[productionDeployTask.id]?.status : undefined}
confirmPhrase={productionConfirmPhrase}
busyAction={busyAction}
onConfirmPhraseChange={setProductionConfirmPhrase}
Expand Down
42 changes: 42 additions & 0 deletions server/services/releases/db_retry.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
"""Small DB write retry helpers for release synchronization."""

from __future__ import annotations

import time
from collections.abc import Callable
from typing import TypeVar

from sqlalchemy.exc import OperationalError
from sqlalchemy.orm import Session


T = TypeVar("T")


def _is_sqlite_locked_error(exc: OperationalError) -> bool:
return "database is locked" in str(exc).lower()


def commit_with_sqlite_lock_retry(
db: Session,
apply_changes: Callable[[], T],
*,
attempts: int = 5,
) -> T:
"""Apply and commit writes, retrying transient SQLite writer contention."""

last_error: OperationalError | None = None
for attempt in range(max(1, attempts)):
try:
result = apply_changes()
db.commit()
return result
except OperationalError as exc:
if not _is_sqlite_locked_error(exc) or attempt >= attempts - 1:
raise
last_error = exc
db.rollback()
time.sleep(0.15 * (attempt + 1))
if last_error is not None: # pragma: no cover - loop always raises above.
raise last_error
return apply_changes() # pragma: no cover - attempts is normalized to at least one.
Loading
Loading