feat(qaops): 接通网页通讯录持久化同步与后台接管

This commit is contained in:
姚章浩
2026-10-17 17:36:07 +08:00
parent 6adfdcdd4f
commit cc4906b6a9
25 changed files with 1203 additions and 24 deletions
+24
View File
@@ -51,6 +51,30 @@ const props = {
onRemoveMissing: vi.fn(),
}
describe('region mapping workbench', () => {
it('shows real synchronization stages without inventing progress and protects dirty drafts', () => {
const syncStatus = {
configured: true,
worker_ready: true,
job: {
id: 'j',
state: 'running' as const,
attempt: 1,
max_attempts: 3,
updated_at: '2026-10-17T08:00:00Z',
error_code: '',
result: null,
},
}
const html = renderToStaticMarkup(<RegionMappingView {...props} syncStatus={syncStatus} />)
expect(html).toContain('正在读取并校验通讯录')
expect(html).not.toMatch(/\d+%/)
expect(html).toMatch(/disabled=""[^>]*>同步通讯录/)
const dirty = renderToStaticMarkup(
<RegionMappingView {...props} dirty syncStatus={{ configured: true, worker_ready: true, job: null }} />
)
expect(dirty).toContain('未保存的区域修改')
expect(dirty).toMatch(/disabled=""[^>]*>同步通讯录/)
})
it('lets long directory paths wrap instead of inheriting the global nowrap table rule', () => {
const css = readFileSync(new URL('./qaRegions.css', import.meta.url), 'utf8')
const bodyRule = css.match(/\.qa-region-table td\s*\{([^}]+)\}/)?.[1] ?? ''
+128 -2
View File
@@ -2,7 +2,14 @@ import { useEffect, useRef, useState } from 'react'
import { changeRegionRule, fetchOrganization, previewOrganization, regionNames, saveOrganization } from './qaOrg'
import type { Organization, RegionRule } from './qaOrg'
import './qaRegions.css'
import { completedSyncAction, directorySyncActive, fetchDirectorySync, startDirectorySync } from './qaOrgSync'
import type { DirectorySyncStatus } from './qaOrgSync'
import { newOperationID } from './operationKey'
interface Props {
syncStatus?: DirectorySyncStatus | null
syncError?: string
syncSubmitting?: boolean
onSync?: () => void
state: Organization | null
preview: Organization | null
rules: RegionRule[]
@@ -32,7 +39,45 @@ export function RegionMappingView(p: Props) {
<button type="button" disabled={p.busy} onClick={p.onReload}>
{p.dirty ? '放弃修改并重读' : '重新读取'}
</button>
<button
type="button"
disabled={
p.busy ||
p.dirty ||
p.syncSubmitting ||
!p.syncStatus?.configured ||
!p.syncStatus.worker_ready ||
directorySyncActive(p.syncStatus ?? null)
}
onClick={p.onSync}
>
同步通讯录
</button>
</div>
<div className="qa-ops-muted" aria-label="通讯录后台同步状态" role="status">
{!p.syncStatus
? '正在读取后台同步状态…'
: !p.syncStatus.configured
? '后台同步未接线'
: p.syncStatus.job
? {
pending: '等待后台执行器',
running: '正在读取并校验通讯录',
retry: '上次同步失败,等待后台重试;保留原快照',
completed: '同步已完成,完整快照已落库',
failed: '同步失败,保留原快照;可重新同步',
cancelled: '同步已取消,保留原快照',
}[p.syncStatus.job.state]
: p.syncStatus.worker_ready
? '后台执行器在线,尚未发起同步'
: '后台执行器未在线,不会创建无人处理的任务'}
{p.dirty ? ';存在未保存的区域修改,请先保存或放弃后同步' : ''}
</div>
{p.syncError ? (
<p role="alert" className="error-banner">
{p.syncError}
</p>
) : null}
{p.state?.directory_synced_at ? (
<p className="qa-ops-muted">
{p.state.directory_source === 'weekly_report_snapshot' ? '历史快照' : '全量同步快照'} · 通讯录同步时间:
@@ -152,6 +197,14 @@ function signature(rules: RegionRule[]) {
return JSON.stringify([...rules].sort((a, b) => a.department_id.localeCompare(b.department_id)))
}
export function QARegions() {
const [syncStatus, setSyncStatus] = useState<DirectorySyncStatus | null>(null),
[syncError, setSyncError] = useState(''),
[syncSubmitting, setSyncSubmitting] = useState(false)
const syncOperation = useRef(''),
syncFlight = useRef(false),
syncAction = useRef<AbortController | null>(null),
lastCompleted = useRef(''),
dirtyRef = useRef(false)
const [state, setState] = useState<Organization | null>(null),
[preview, setPreview] = useState<Organization | null>(null),
[rules, setRules] = useState<RegionRule[]>([])
@@ -176,7 +229,10 @@ export function QARegions() {
setPreview(null)
try {
const value = await fetchOrganization(controller.signal)
if (!controller.signal.aborted) accept(value)
if (!controller.signal.aborted) {
accept(value)
return true
}
} catch (e) {
if (!controller.signal.aborted) setError(e instanceof Error ? e.message : '读取失败')
} finally {
@@ -187,6 +243,72 @@ export function QARegions() {
void load()
return () => request.current?.abort()
}, [])
const dirty = Boolean(state && signature(rules) !== signature(state.rules))
dirtyRef.current = dirty
const loadRef = useRef(load)
loadRef.current = load
useEffect(() => {
const controller = new AbortController()
let timer: ReturnType<typeof setTimeout>
const poll = async () => {
let delay = 10000
try {
const value = await fetchDirectorySync(controller.signal)
if (controller.signal.aborted) return
setSyncStatus(value)
setSyncError('')
delay = directorySyncActive(value) ? 1500 : 10000
const job = value.job
if (job?.state === 'completed' && job.id !== lastCompleted.current) {
const action = completedSyncAction(value, lastCompleted.current, dirtyRef.current)
lastCompleted.current = job.id
if (action === 'preserve') setNotice('通讯录已同步,当前未保存草稿仍保留;请核对后重新读取')
else if (action === 'reload' && (await loadRef.current())) setNotice('通讯录同步完成并已重新读取')
} else if (job && lastCompleted.current === '') lastCompleted.current = 'pending:' + job.id
} catch (e) {
if (!controller.signal.aborted)
setSyncError(e instanceof Error ? e.message : '同步状态读取失败,未将现有快照清空')
} finally {
if (!controller.signal.aborted) timer = setTimeout(() => void poll(), delay)
}
}
void poll()
return () => {
controller.abort()
clearTimeout(timer)
syncAction.current?.abort()
}
}, [])
const synchronize = async () => {
if (
busy ||
dirty ||
syncFlight.current ||
!syncStatus?.configured ||
!syncStatus.worker_ready ||
directorySyncActive(syncStatus)
)
return
syncFlight.current = true
setSyncSubmitting(true)
setSyncError('')
const controller = new AbortController()
syncAction.current = controller
try {
if (!syncOperation.current) syncOperation.current = newOperationID()
const receipt = await startDirectorySync(syncOperation.current, controller.signal)
syncOperation.current = ''
if (controller.signal.aborted) return
lastCompleted.current = 'submitted:' + receipt.job_id
setSyncStatus(await fetchDirectorySync(controller.signal))
} catch (e) {
if (!controller.signal.aborted)
setSyncError(e instanceof Error ? e.message : '同步提交结果未知;重试会复用原操作标识')
} finally {
syncFlight.current = false
if (!controller.signal.aborted) setSyncSubmitting(false)
}
}
const edit = (next: RegionRule[]) => {
setRules(next)
setPreview(null)
@@ -225,6 +347,10 @@ export function QARegions() {
}
return (
<RegionMappingView
syncStatus={syncStatus}
syncError={syncError}
syncSubmitting={syncSubmitting}
onSync={() => void synchronize()}
state={state}
preview={preview}
rules={rules}
@@ -233,7 +359,7 @@ export function QARegions() {
busy={busy}
error={error}
notice={notice}
dirty={Boolean(state && signature(rules) !== signature(state.rules))}
dirty={dirty}
onRegion={setRegion}
onSearch={setSearch}
onToggle={(id, checked) => edit(changeRegionRule(rules, id, region, checked))}
+5 -5
View File
@@ -30,20 +30,20 @@ export interface Organization {
missing_departments: string[]
}
}
function invalid(): never {
export function invalid(): never {
throw new Error('通讯录或区域配置响应格式无效')
}
function obj(value: unknown): Record<string, unknown> {
export function obj(value: unknown): Record<string, unknown> {
if (!value || typeof value !== 'object' || Array.isArray(value)) return invalid()
return value as Record<string, unknown>
}
function str(value: unknown): string {
export function str(value: unknown): string {
return typeof value === 'string' ? value : invalid()
}
function count(value: unknown): number {
export function count(value: unknown): number {
return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : invalid()
}
function instant(value: unknown): string | null {
export function instant(value: unknown): string | null {
return value === null ? null : typeof value === 'string' && Number.isFinite(Date.parse(value)) ? value : invalid()
}
export function parseOrganization(value: unknown): Organization {
+72
View File
@@ -0,0 +1,72 @@
import { describe, expect, it, vi, afterEach } from 'vitest'
import { parseDirectorySync, startDirectorySync, fetchDirectorySync, completedSyncAction } from './qaOrgSync'
afterEach(() => vi.unstubAllGlobals())
const idle = { configured: true, worker_ready: true, job: null }
describe('directory synchronization contract', () => {
it('reloads a completed job even on first observation, without replacing an unsaved draft', () => {
const status = parseDirectorySync({
...idle,
job: {
id: 'new-job',
state: 'completed',
attempt: 1,
max_attempts: 3,
updated_at: '2026-10-17T08:00:00Z',
error_code: '',
result: { directory_id: 'd', departments: 1, people: 1, synced_at: '2026-10-17T08:00:00Z' },
},
})
expect(completedSyncAction(status, '', false)).toBe('reload')
expect(completedSyncAction(status, '', true)).toBe('preserve')
expect(completedSyncAction(status, 'new-job', false)).toBe('none')
expect(completedSyncAction({ ...status, job: { ...status.job!, state: 'running' } }, '', false)).toBe('none')
})
it('keeps unknown/failed state distinct from empty data', () => {
expect(parseDirectorySync(idle).job).toBeNull()
expect(() => parseDirectorySync({ ...idle, worker_ready: 'yes' })).toThrow()
expect(() => parseDirectorySync({ ...idle, job: { id: 'x', state: 'mystery' } })).toThrow()
const result = { directory_id: 'd', departments: 327, people: 1534, synced_at: '2026-10-17T07:00:00Z' }
const job = {
id: 'j',
state: 'completed',
attempt: 1,
max_attempts: 3,
updated_at: '2026-10-17T07:01:00Z',
error_code: '',
result,
}
expect(parseDirectorySync({ ...idle, job }).job?.result?.people).toBe(1534)
expect(() => parseDirectorySync({ ...idle, job: { ...job, result: { ...result, people: -1 } } })).toThrow()
})
it('sends a stable idempotency header and no tenant, credential or executable path', async () => {
const fetcher = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ data: { job_id: 'j', deduplicated: false }, operation: 'replayed' }),
})
vi.stubGlobal('fetch', fetcher)
expect((await startDirectorySync('same-action')).operation).toBe('replayed')
expect(fetcher).toHaveBeenCalledWith(
'/api/v1/qa-ops/organization/sync',
expect.objectContaining({
method: 'POST',
credentials: 'same-origin',
body: '{}',
headers: expect.objectContaining({
'Idempotency-Key': 'same-action',
'X-Governance-Action': 'qa-organization',
}),
})
)
})
it('reads live job state and surfaces server failure instead of a successful empty result', async () => {
vi.stubGlobal(
'fetch',
vi
.fn()
.mockResolvedValueOnce({ ok: true, json: async () => ({ data: idle }) })
.mockResolvedValueOnce({ ok: false, status: 503, json: async () => ({ error: '执行器未在线' }) })
)
expect((await fetchDirectorySync()).worker_ready).toBe(true)
await expect(startDirectorySync('same-action')).rejects.toThrow('执行器未在线')
})
})
+104
View File
@@ -0,0 +1,104 @@
export interface DirectorySyncResult {
directory_id: string
departments: number
people: number
synced_at: string
}
export interface DirectorySyncJob {
id: string
state: 'pending' | 'running' | 'retry' | 'completed' | 'failed' | 'cancelled'
attempt: number
max_attempts: number
updated_at: string
error_code: string
result: DirectorySyncResult | null
}
export interface DirectorySyncStatus {
configured: boolean
worker_ready: boolean
job: DirectorySyncJob | null
}
export function completedSyncAction(
s: DirectorySyncStatus,
last: string,
dirty: boolean
): 'none' | 'preserve' | 'reload' {
if (s.job?.state !== 'completed' || s.job.id === last) return 'none'
return dirty ? 'preserve' : 'reload'
}
export const directorySyncActive = (s: DirectorySyncStatus | null) =>
Boolean(s?.job && ['pending', 'running', 'retry'].includes(s.job.state))
import { invalid as bad, obj as object, str as text, count, instant as nullableInstant } from './qaOrg'
function instant(v: unknown): string {
return nullableInstant(v) ?? bad()
}
export function parseDirectorySync(raw: unknown): DirectorySyncStatus {
const s = object(raw)
if (typeof s.configured !== 'boolean' || typeof s.worker_ready !== 'boolean') return bad()
let job: DirectorySyncJob | null = null
if (s.job !== null) {
const j = object(s.job)
if (!['pending', 'running', 'retry', 'completed', 'failed', 'cancelled'].includes(text(j.state))) return bad()
let result: DirectorySyncResult | null = null
if (j.result !== null) {
const r = object(j.result)
result = {
directory_id: text(r.directory_id),
departments: count(r.departments),
people: count(r.people),
synced_at: instant(r.synced_at),
}
if (!result.directory_id || !result.departments || !result.people) return bad()
}
job = {
id: text(j.id),
state: j.state as DirectorySyncJob['state'],
attempt: count(j.attempt),
max_attempts: count(j.max_attempts),
updated_at: instant(j.updated_at),
error_code: text(j.error_code),
result,
}
if (!job.id || !job.max_attempts || job.attempt > job.max_attempts || (job.state === 'completed' && !result))
return bad()
}
return { configured: s.configured, worker_ready: s.worker_ready, job }
}
async function request(method: string, operationID?: string, signal?: AbortSignal) {
const response = await fetch('/api/v1/qa-ops/organization/sync', {
method,
credentials: 'same-origin',
cache: 'no-store',
signal,
headers:
method === 'POST'
? {
'Content-Type': 'application/json',
'X-Governance-Action': 'qa-organization',
'Idempotency-Key': operationID ?? '',
}
: undefined,
body: method === 'POST' ? '{}' : undefined,
})
const raw: unknown = await response.json().catch(() => null)
if (!response.ok) {
const error = raw && typeof raw === 'object' ? (raw as Record<string, unknown>).error : undefined
throw new Error(typeof error === 'string' ? error : `通讯录同步请求失败(HTTP ${response.status})`)
}
return object(raw)
}
export async function fetchDirectorySync(signal?: AbortSignal) {
return parseDirectorySync((await request('GET', undefined, signal)).data)
}
export async function startDirectorySync(operationID: string, signal?: AbortSignal) {
if (!operationID || operationID.trim() !== operationID || operationID.length > 128) return bad()
const envelope = await request('POST', operationID, signal),
data = object(envelope.data)
if (
(envelope.operation !== 'created' && envelope.operation !== 'replayed') ||
typeof data.deduplicated !== 'boolean' ||
!text(data.job_id)
)
return bad()
return { job_id: text(data.job_id), deduplicated: data.deduplicated, operation: envelope.operation }
}