import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import type { Key } from 'react' import { Button, Card, Checkbox, Col, Drawer, Alert, Form, Input, Modal, Progress, Row, Select, Space, Table, Tabs, Tag, Tooltip, Typography, message, } from 'antd' import { CopyOutlined, InfoCircleOutlined, PauseCircleOutlined, PlayCircleOutlined, SyncOutlined, } from '@ant-design/icons' import axios, { type AxiosResponse } from 'axios' import { useNavigate } from 'react-router-dom' import AppLayout from '../../components/AppLayout/AppLayout' import ScrollbarOverlay from '../../components/Scrollbar/ScrollbarOverlay' import { formatDateTimeZhCN } from '../../utils/datetime' import { formatPhaseMetric, getPhaseDisplay, getPhaseSummary } from '../../utils/phaseProgress' const { Text } = Typography const COLLECTION_REFRESH_DELAY_MS = 800 interface BuiltInDataSource { id: number source: string name: string display_name?: string module: string priority: string frequency: string endpoint?: string is_active: boolean collector_class: string last_run: string | null last_run_at?: string | null last_status?: string | null product?: string is_running: boolean task_id: number | null progress: number | null phase?: string | null phase_progress?: number | null phase_message?: string | null phase_current?: number | null phase_total?: number | null phase_unit?: string | null records_processed: number | null total_records: number | null collected_records?: number has_collected_data?: boolean is_free?: boolean requires_credentials?: boolean credential_provider?: string | null credential_status?: string } interface CustomDataSourceOverride { id: number name: string description: string | null source_type: string endpoint: string auth_type: string is_active: boolean created_at: string updated_at: string | null } interface RealtimeSourceHealth { connection_state: string last_seen_at: string | null last_success_at: string | null last_error: string | null message_rate: number | null lag_seconds: number | null updated_at: string | null } interface RealtimeSourceStats { total_observations: number observations_24h: number observations_1h: number unique_mmsi_total: number unique_mmsi_24h: number latest_observed_at: string | null latest_collected_at: string | null } interface RealtimeSourceRuntime { running: boolean done: boolean runtime: string } interface RealtimeSource { source: string name: string display_name: string kind: 'builtin' | 'custom' config_id?: number source_type: string endpoint?: string is_active: boolean credential_configured: boolean message_types: string[] bounding_boxes: unknown[] config: Record runtime: RealtimeSourceRuntime health: RealtimeSourceHealth | null stats: RealtimeSourceStats } interface EditableDataSourceConfig { id: number name: string description: string | null source_type: string endpoint: string auth_type: string auth_config: Record headers: Record config: Record is_active?: boolean } interface UnifiedDataSource { key: string id: number name: string display_name: string source: string module?: string priority?: string frequency?: string endpoint?: string is_active: boolean collector_class?: string source_type?: string auth_type?: string last_run_at?: string | null last_status?: string | null product?: string is_running?: boolean progress?: number | null phase?: string | null phase_progress?: number | null phase_message?: string | null phase_current?: number | null phase_total?: number | null phase_unit?: string | null task_id?: number | null created_at?: string updated_at?: string | null description?: string | null headers?: Record config?: Record is_free?: boolean requires_credentials?: boolean credential_provider?: string | null credential_status?: string collected_records?: number has_collected_data?: boolean } interface ViewDataSource extends UnifiedDataSource { headers: Record config: Record } type TriggerDatasourceConflict = { reason?: string message?: string progress?: number | null phase?: string | null phase_progress?: number | null phase_message?: string | null phase_current?: number | null phase_total?: number | null phase_unit?: string | null records_processed?: number | null total_records?: number | null } type TriggerDatasourceResult = | { ok: true; response: AxiosResponse } | { ok: false; status: number; detail?: string | TriggerDatasourceConflict } type DatasourceTaskStatus = { is_running: boolean task_id?: number | null progress?: number | null phase?: string | null phase_progress?: number | null phase_message?: string | null phase_current?: number | null phase_total?: number | null phase_unit?: string | null records_processed?: number | null total_records?: number | null status?: string | null } type ActiveFilter = 'enabled' | 'disabled' | 'all' type StatusFilter = 'all' | 'success' | 'failed' | 'running' | 'not_run' type CollectedFilter = 'all' | 'collected' | 'uncollected' const PRODUCT_LABELS: Record = { vessels: '船只', cables: '海底光缆', satellites: '卫星', bgp: 'BGP', compute: '算力', ai: 'AI', media: '媒体', other: '其他', } const PRODUCT_TAG_COLORS: Record = { vessels: 'cyan', cables: 'geekblue', satellites: 'purple', bgp: 'volcano', compute: 'blue', ai: 'magenta', media: 'green', other: 'default', } function isRealtimeBuiltinSource(source: BuiltInDataSource | UnifiedDataSource) { return source.source === 'aisstream_vessels' } function normalizeBuiltin(source: BuiltInDataSource): UnifiedDataSource { return { key: `builtin:${source.id}`, id: source.id, name: source.name, display_name: source.display_name || source.name, source: source.source, module: source.module, priority: source.priority, product: source.product, frequency: source.frequency, endpoint: source.endpoint, is_active: source.is_active, collector_class: source.collector_class, last_run_at: source.last_run_at || source.last_run, last_status: source.last_status, is_running: source.is_running, progress: source.progress, phase: source.phase, phase_progress: source.phase_progress, phase_message: source.phase_message, phase_current: source.phase_current, phase_total: source.phase_total, phase_unit: source.phase_unit, task_id: source.task_id, is_free: source.is_free, requires_credentials: source.requires_credentials, credential_provider: source.credential_provider, credential_status: source.credential_status, collected_records: source.collected_records, has_collected_data: source.has_collected_data, headers: {}, config: {}, } } function DataSources() { const [messageApi, contextHolder] = message.useMessage() const navigate = useNavigate() const [modal, modalContextHolder] = Modal.useModal() const [builtInSources, setBuiltInSources] = useState([]) const [customOverrides, setCustomOverrides] = useState([]) const [realtimeSources, setRealtimeSources] = useState([]) const [loading, setLoading] = useState(false) const [realtimeLoading, setRealtimeLoading] = useState(false) const [realtimeActionSource, setRealtimeActionSource] = useState(null) const [activeTab, setActiveTab] = useState('tasks') const [triggerAllLoading, setTriggerAllLoading] = useState(false) const [forceTriggerAll, setForceTriggerAll] = useState(false) const [selectedRowKeys, setSelectedRowKeys] = useState([]) const [productFilter, setProductFilter] = useState('all') const [moduleFilter, setModuleFilter] = useState('all') const [activeFilter, setActiveFilter] = useState('enabled') const [statusFilter, setStatusFilter] = useState('all') const [collectedFilter, setCollectedFilter] = useState('all') const [searchQuery, setSearchQuery] = useState('') const [viewDrawerVisible, setViewDrawerVisible] = useState(false) const [runningTasksVisible, setRunningTasksVisible] = useState(false) const [viewingSource, setViewingSource] = useState(null) const [recordCount, setRecordCount] = useState(null) const [tableHeight, setTableHeight] = useState(360) const tableRegionRef = useRef(null) const taskBuiltInSources = useMemo( () => builtInSources.filter((source) => !isRealtimeBuiltinSource(source)), [builtInSources], ) const allSources = useMemo(() => taskBuiltInSources.map(normalizeBuiltin), [taskBuiltInSources]) const selectedSourceIds = useMemo( () => selectedRowKeys .map((key) => allSources.find((source) => source.key === key)?.id) .filter((id): id is number => typeof id === 'number'), [allSources, selectedRowKeys], ) const activeBuiltInCount = taskBuiltInSources.filter((source) => source.is_active).length const collectedBuiltInCount = taskBuiltInSources.filter((source) => source.has_collected_data).length const runningBuiltInSources = taskBuiltInSources.filter((source) => source.is_running) const runningBuiltInCount = runningBuiltInSources.length const aggregateProgress = runningBuiltInCount > 0 ? Math.round( taskBuiltInSources .filter((source) => source.is_running) .reduce((sum, source) => sum + (source.progress || 0), 0) / runningBuiltInCount, ) : 0 const fetchData = useCallback(async () => { setLoading(true) try { const params = { product: productFilter === 'all' ? undefined : productFilter, module: moduleFilter === 'all' ? undefined : moduleFilter, is_active: activeFilter === 'all' ? undefined : activeFilter === 'enabled', run_status: statusFilter === 'all' ? undefined : statusFilter, collected: collectedFilter === 'all' ? undefined : collectedFilter === 'collected', q: searchQuery.trim() || undefined, } const [builtinRes, customRes] = await Promise.all([ axios.get('/api/v1/datasources', { params }), axios.get('/api/v1/datasources/configs'), ]) setBuiltInSources(builtinRes.data.data || []) setCustomOverrides(customRes.data.data || []) } catch (error) { console.error('Failed to fetch data:', error) messageApi.error('获取数据源列表失败') } finally { setLoading(false) } }, [activeFilter, collectedFilter, messageApi, moduleFilter, productFilter, searchQuery, statusFilter]) const fetchRealtimeSources = useCallback(async () => { setRealtimeLoading(true) try { const response = await axios.get('/api/v1/realtime-sources') setRealtimeSources(response.data.data || []) } catch (error) { console.error('Failed to fetch realtime sources:', error) messageApi.error('获取实时流状态失败') } finally { setRealtimeLoading(false) } }, [messageApi]) useEffect(() => { void fetchData() }, [fetchData]) useEffect(() => { void fetchRealtimeSources() }, [fetchRealtimeSources]) useEffect(() => { const visibleKeys = new Set(allSources.map((source) => source.key)) setSelectedRowKeys((keys) => keys.filter((key) => visibleKeys.has(String(key)))) }, [allSources]) useEffect(() => { const updateHeight = () => { setTableHeight(Math.max(260, (tableRegionRef.current?.offsetHeight || 0) - 56)) } updateHeight() if (typeof ResizeObserver === 'undefined') return undefined const observer = new ResizeObserver(updateHeight) if (tableRegionRef.current) observer.observe(tableRegionRef.current) return () => observer.disconnect() }, [allSources.length]) const runRealtimeAction = async (source: string, action: 'start' | 'stop' | 'restart') => { try { setRealtimeActionSource(`${source}:${action}`) await axios.post(`/api/v1/realtime-sources/${encodeURIComponent(source)}/${action}`) messageApi.success(action === 'start' ? '实时流已启动' : action === 'stop' ? '实时流已停止' : '实时流已重连') await Promise.all([fetchRealtimeSources(), fetchData()]) } catch (error: unknown) { const err = error as { response?: { data?: { detail?: string } } } messageApi.error(err.response?.data?.detail || '实时流操作失败') } finally { setRealtimeActionSource(null) } } const fetchDatasourceTaskStatus = async (id: number) => { const res = await axios.get(`/api/v1/datasources/${id}/task-status`) return res.data } const triggerDatasource = async (id: number, options?: { force?: boolean }) => { const res = await axios.post(`/api/v1/datasources/${id}/trigger`, null, { params: { force: options?.force ?? false }, validateStatus: (status) => status < 500, }) if (res.status >= 400) { return { ok: false, status: res.status, detail: res.data?.detail } satisfies TriggerDatasourceResult } if (res.data.task_id) { void fetchData() } else { window.setTimeout(fetchData, COLLECTION_REFRESH_DELAY_MS) } return { ok: true, response: res } satisfies TriggerDatasourceResult } const confirmForceTrigger = (id: number, taskInfo?: TriggerDatasourceConflict) => { modal.confirm({ title: '当前任务未完成', content: (

{taskInfo?.message || '当前采集任务仍在运行,重新触发会丢失本次未完成进度。'}

当前阶段: {getPhaseDisplay(taskInfo || {})}

当前进度: {typeof taskInfo?.progress === 'number' ? `${Math.round(taskInfo.progress)}%` : '未知'}

确认后会强制取消当前采集,并重新开始采集。

), okText: '强制重新采集', cancelText: '取消', okButtonProps: { danger: true }, onOk: async () => { const result = await triggerDatasource(id, { force: true }) if (result.ok) { messageApi.success('已强制重新触发') return } const detail = result.detail messageApi.error(typeof detail === 'string' ? detail : detail?.message || '强制重新采集失败') }, }) } const triggerDatasourceWithPrecheck = async (id: number) => { const taskStatus = await fetchDatasourceTaskStatus(id) if (taskStatus.is_running) { confirmForceTrigger(id, taskStatus) return } const result = await triggerDatasource(id) if (result.ok) { messageApi.success('任务已触发') return } const detail = result.detail if (result.status === 409 && typeof detail === 'object' && detail?.reason === 'running_task_in_progress') { confirmForceTrigger(id, detail) return } messageApi.error(typeof detail === 'string' ? detail : detail?.message || '触发失败') } const handleTriggerAll = async () => { try { setTriggerAllLoading(true) const res = await axios.post('/api/v1/datasources/trigger-batch', { source_ids: selectedSourceIds, force: forceTriggerAll, product: selectedSourceIds.length ? undefined : productFilter === 'all' ? undefined : productFilter, module: selectedSourceIds.length ? undefined : moduleFilter === 'all' ? undefined : moduleFilter, is_active: selectedSourceIds.length ? undefined : activeFilter === 'all' ? undefined : activeFilter === 'enabled', run_status: selectedSourceIds.length ? undefined : statusFilter === 'all' ? undefined : statusFilter, collected: selectedSourceIds.length ? undefined : collectedFilter === 'all' ? undefined : collectedFilter === 'collected', q: selectedSourceIds.length ? undefined : searchQuery.trim() || undefined, }) const triggered = res.data.triggered || [] const skipped = res.data.skipped || [] const failed = res.data.failed || [] messageApi.success([ `已触发 ${triggered.length} 个`, skipped.length ? `跳过 ${skipped.length} 个` : null, failed.length ? `失败 ${failed.length} 个` : null, ].filter(Boolean).join(',')) setSelectedRowKeys([]) void fetchData() } catch (error: unknown) { const err = error as { response?: { data?: { detail?: string } } } messageApi.error(err.response?.data?.detail || '批量触发失败') } finally { setTriggerAllLoading(false) } } const handleToggle = async (id: number, current: boolean) => { const endpoint = current ? 'disable' : 'enable' try { await axios.post(`/api/v1/datasources/${id}/${endpoint}`) messageApi.success(`${current ? '已禁用' : '已启用'}`) void fetchData() } catch (error: unknown) { const err = error as { response?: { data?: { detail?: string } } } messageApi.error(err.response?.data?.detail || '操作失败') } } const handleViewSource = async (source: UnifiedDataSource) => { try { { const override = customOverrides.find((item) => item.name === source.source) const [detailRes, statsRes, overrideDetail] = await Promise.all([ axios.get(`/api/v1/datasources/${source.id}`), axios.get(`/api/v1/datasources/${source.id}/stats`), override ? axios.get(`/api/v1/datasources/configs/${override.id}`).then((res) => res.data) : Promise.resolve(null), ]) const data = detailRes.data setViewingSource({ ...source, name: data.name, display_name: data.display_name || source.display_name, endpoint: overrideDetail?.endpoint || data.endpoint || source.endpoint || '', auth_type: overrideDetail?.auth_type || 'none', headers: overrideDetail?.headers || {}, config: overrideDetail?.config || {}, collector_class: data.collector_class, module: data.module, priority: data.priority, frequency: data.frequency, is_free: data.is_free, requires_credentials: data.requires_credentials, credential_provider: data.credential_provider, credential_status: data.credential_status, }) setRecordCount(statsRes.data.total_records || 0) } setViewDrawerVisible(true) } catch (error) { console.error(error) messageApi.error('获取数据源信息失败') } } const handleCopyLink = async (value: string, successText: string) => { try { await navigator.clipboard.writeText(value) messageApi.success(successText) } catch { messageApi.error('复制失败,请手动复制') } } const formatCount = (value?: number | null) => Number(value || 0).toLocaleString() const formatLagSeconds = (value?: number | null) => { if (value === null || value === undefined || !Number.isFinite(Number(value))) return '-' const seconds = Number(value) if (seconds < 60) return `${Math.round(seconds)} 秒` if (seconds < 3600) return `${Math.round(seconds / 60)} 分钟` return `${Math.round(seconds / 3600)} 小时` } const getConnectionColor = (state?: string | null) => { if (state === 'connected') return 'success' if (state === 'connecting' || state === 'reconnecting') return 'processing' if (state === 'disconnected') return 'default' return 'warning' } const renderConfigPreview = (value: unknown) => { if (!Array.isArray(value) || value.length === 0) return '-' return JSON.stringify(value) } const realtimeTotals = realtimeSources.reduce( (acc, source) => ({ running: acc.running + (source.runtime?.running ? 1 : 0), total: acc.total + (source.stats?.total_observations || 0), recent24h: acc.recent24h + (source.stats?.observations_24h || 0), }), { running: 0, total: 0, recent24h: 0 }, ) const renderRealtimeSource = (source: RealtimeSource) => { const state = source.health?.connection_state || (source.runtime?.running ? 'running' : 'disconnected') const actionBusyPrefix = `${source.source}:` return ( {source.display_name || source.name} {source.kind === 'builtin' ? '内置' : '自定义'} {source.is_active ? '启用' : '禁用'} {source.credential_configured ? '凭证已配置' : '缺少凭证'} {source.runtime?.running ? '运行中' : '未运行'} )} extra={( )} > 连接状态
{state}
累计入库
{formatCount(source.stats?.total_observations)}
近 24h
{formatCount(source.stats?.observations_24h)}
近 1h
{formatCount(source.stats?.observations_1h)}
唯一 MMSI
{formatCount(source.stats?.unique_mmsi_total)}
近 24h MMSI
{formatCount(source.stats?.unique_mmsi_24h)}
最近收到
{formatDateTimeZhCN(source.health?.last_seen_at)}
数据延迟
{formatLagSeconds(source.health?.lag_seconds)}
Endpoint Message Types Bounding Boxes 最近成功
{formatDateTimeZhCN(source.health?.last_success_at)}
状态更新时间
{formatDateTimeZhCN(source.health?.updated_at)}
最近观测
{formatDateTimeZhCN(source.stats?.latest_observed_at)}
最近入库
{formatDateTimeZhCN(source.stats?.latest_collected_at)}
{source.health?.last_error ? ( ) : null}
) } const columns = [ { title: '名称', dataIndex: 'display_name', key: 'name', width: 260, ellipsis: true, render: (_: string, record: UnifiedDataSource) => ( {record.source} ), }, { title: '类型', key: 'kind', width: 100, render: () => 内置, }, { title: '产品域', key: 'product', width: 110, render: (_: unknown, record: UnifiedDataSource) => { const product = record.product || 'other' return {PRODUCT_LABELS[product] || product} }, }, { title: '层级/类型', key: 'module', width: 120, render: (_: unknown, record: UnifiedDataSource) => {record.module}, }, { title: '频率', dataIndex: 'frequency', key: 'frequency', width: 90, render: (value: string | undefined) => value || '-', }, { title: '最近采集', dataIndex: 'last_run_at', key: 'last_run_at', width: 180, render: (value: string | null | undefined) => formatDateTimeZhCN(value) || '-', }, { title: '已采集', key: 'collected', width: 110, render: (_: unknown, record: UnifiedDataSource) => ( {record.has_collected_data ? `${record.collected_records || 0} 条` : '未采集'} ), }, { title: '状态', key: 'status', width: 180, render: (_: unknown, record: UnifiedDataSource) => { if (record.is_running) { return ( {getPhaseSummary(record)} ) } if (!record.last_status) return 未执行 return {record.last_status} }, }, { title: '操作', key: 'action', fixed: 'right' as const, width: 190, render: (_: unknown, record: UnifiedDataSource) => ( ), }, ] return ( {contextHolder} {modalContextHolder}

数据源

采集实时进度
总体进度 {aggregateProgress}%
0 ? 'active' : 'normal'} showInfo={false} strokeColor="#1677ff" />
当前筛选 {allSources.length}
内置 {taskBuiltInSources.length}
已启用 {activeBuiltInCount}
已有数据 {collectedBuiltInCount}
{selectedSourceIds.length > 0 ? (
已选择 {selectedSourceIds.length}
) : null} {runningBuiltInCount > 0 ? ( ) : null}
setForceTriggerAll(event.target.checked)}> 强制重新采集
标识
模块
优先级
频率
数据量
采集器
{viewingSource.requires_credentials ? ( navigate(`/settings?tab=collector_credentials&collector=${encodeURIComponent(viewingSource.source)}`)} > 去配置 ) : undefined} /> ) : null}