feat(sources): 数据源配置收敛成 dws 导入 + PP 导入;「去掉来源」= 归档下架(不删数据)
build / build (push) Successful in 58s

主人要求:去掉入口,统一成 dws 导入与 PP 导入;其他来源连数据一起下架,之后用 dws 重新获取。

界面(web):
- 「数据源配置」只剩两块:**dws 导入(钉钉)**(按当前钉钉账号列出可访问的知识库与钉盘空间)
  与 **PP 导入**(PP 资料下载中心)。上一步加的「显示 AList/钉钉知识库来源」折叠开关删除。
- 来源卡片新增管理员可见的「去掉来源」(带确认弹窗,说明是归档下架、数据保留可恢复)。
- 侧栏文案改成"只留两个入口";发现面板标题改为「dws 导入(钉钉)」。

后端(归档语义,可逆):
- 迁移 000047:source_connections 增 archived_at / archived_by + 只覆盖未归档行的部分索引。
- store:ArchiveSourceConnection / RestoreSourceConnection(幂等;归档同时停用并清空
  next_refresh_at,避免被手工改回后立刻带着旧调度跑)。列表、目录、计划刷新(claimDue)、
  手动扫描(triggerBlock/inspect)四类查询一律排除归档行。
- 注册路径(dws 重新获取):RegisterDingtalkSpace 的 ON CONFLICT 清掉归档标记 ——
  重新登记同一个空间**原地复活同一行**,不产生重复,历史快照仍属于同一行。
- HTTP:POST /api/v1/source-connections/{id}/archive|restore(管理员专属,写意图头
  source-archive / source-restore + Idempotency-Key;404 区分"不存在"与"已是目标状态");
  openapi 同步两条契约。

验证:
- 集成测试(真 postgres):归档从列表消失但 source_items 一行不少、重复归档不漂移归档时间与人、
  未知 ID 报 ErrSourceConnectionNotFound、归档来源不能再被扫描、恢复后回到列表但保持停用;
  dws 重新登记同一空间复活同一行。
- httpapi:写意图/幂等键门禁、200/403/404/500、错误体不回显内部细节、classifyRole 管理员专属。
- 迁移护栏:000047 结构 + 四类 SQL 必须含 archived_at is null(漏一条就是入口没去掉)。
- make verify 15/15。
This commit is contained in:
姚章浩
2026-10-14 12:36:32 +08:00
parent 64b32c2da6
commit 2c7265efc4
20 changed files with 1426 additions and 281 deletions
+5 -3
View File
@@ -5,8 +5,10 @@ import { DingtalkSourceDiscovery } from './DingtalkSourceDiscovery'
describe('DingtalkSourceDiscovery', () => {
it('renders the discovery shell without any file-format filter', () => {
const html = renderToStaticMarkup(<DingtalkSourceDiscovery registeredNames={['ATOM知识库']} onRegistered={vi.fn()} />)
for (const text of ['可加入的来源', '刷新列表', '加入为来源(选中 0)', '已是来源']) {
const html = renderToStaticMarkup(
<DingtalkSourceDiscovery registeredNames={['ATOM知识库']} onRegistered={vi.fn()} />
)
for (const text of ['dws 导入(钉钉)', '刷新列表', '加入为来源(选中 0)', '已是来源']) {
expect(html).toContain(text)
}
// 需求(2026-10-10):数据源配置这里不再做文件格式筛选——格式归目录级标注决定。
@@ -14,4 +16,4 @@ describe('DingtalkSourceDiscovery', () => {
expect(html).not.toContain(removed)
}
})
})
})
+103 -47
View File
@@ -2,7 +2,12 @@ import { useCallback, useEffect, useState } from 'react'
import { DingtalkRequestError, registerDingtalkSpace } from './dingtalkSession'
import { DingtalkSessionControl } from './DingtalkSessionControl'
import { discoveryCandidates, fetchAvailableDingtalkSources, type AvailableDingtalkSources, type DiscoveryCandidate } from './dingtalkSources'
import {
discoveryCandidates,
fetchAvailableDingtalkSources,
type AvailableDingtalkSources,
type DiscoveryCandidate,
} from './dingtalkSources'
// 「系统设置 → 数据源配置」里的数据源发现面板(管理员):
// ① 列出当前钉钉账号(dws)能看到的钉钉知识库;
@@ -11,7 +16,13 @@ import { discoveryCandidates, fetchAvailableDingtalkSources, type AvailableDingt
// ④ 登记需要有效的钉钉扫码会话:会话失效时直接弹二维码,扫完自动重试本次登记。
// 这里不显示文件格式筛选:格式由目录级标注决定,不在这张卡上做。
export function DingtalkSourceDiscovery({ registeredNames, onRegistered }: { registeredNames: string[]; onRegistered: () => void }) {
export function DingtalkSourceDiscovery({
registeredNames,
onRegistered,
}: {
registeredNames: string[]
onRegistered: () => void
}) {
const [list, setList] = useState<AvailableDingtalkSources | null>(null)
const [loading, setLoading] = useState(false)
const [loadError, setLoadError] = useState<string | null>(null)
@@ -22,7 +33,8 @@ export function DingtalkSourceDiscovery({ registeredNames, onRegistered }: { reg
const [loginRequired, setLoginRequired] = useState(false)
const load = useCallback(async (signal?: AbortSignal) => {
setLoading(true); setLoadError(null)
setLoading(true)
setLoadError(null)
try {
const next = await fetchAvailableDingtalkSources(signal)
setList(next)
@@ -47,10 +59,13 @@ export function DingtalkSourceDiscovery({ registeredNames, onRegistered }: { reg
const knowledgeBases = candidates.filter((item) => item.kind === 'knowledge_base')
const driveSpaces = candidates.filter((item) => item.kind === 'drive_space')
const selected = candidates.filter((item) => checked.includes(item.key))
const toggle = (key: string) => setChecked((current) => current.includes(key) ? current.filter((item) => item !== key) : [...current, key])
const toggle = (key: string) =>
setChecked((current) => (current.includes(key) ? current.filter((item) => item !== key) : [...current, key]))
const submit = async (retryAfterLogin = false) => {
setBusy(true); setFailure(null); setMessage(null)
setBusy(true)
setFailure(null)
setMessage(null)
const added: string[] = []
const failed: string[] = []
let needLogin = false
@@ -89,49 +104,90 @@ export function DingtalkSourceDiscovery({ registeredNames, onRegistered }: { reg
const renderRow = (candidate: DiscoveryCandidate) => {
const already = candidate.alreadyRegistered
return <li key={candidate.key} className={already ? 'discovery-row registered' : 'discovery-row'}>
<label>
<input type="checkbox" aria-label={`选择${candidate.name}`} checked={checked.includes(candidate.key)} disabled={already || busy} onChange={() => toggle(candidate.key)} />
<span><strong>{candidate.name}</strong><small>{candidate.detail}</small></span>
</label>
{already ? <span className="safe-badge">已是来源</span> : null}
</li>
return (
<li key={candidate.key} className={already ? 'discovery-row registered' : 'discovery-row'}>
<label>
<input
type="checkbox"
aria-label={`选择${candidate.name}`}
checked={checked.includes(candidate.key)}
disabled={already || busy}
onChange={() => toggle(candidate.key)}
/>
<span>
<strong>{candidate.name}</strong>
<small>{candidate.detail}</small>
</span>
</label>
{already ? <span className="safe-badge">已是来源</span> : null}
</li>
)
}
return <section className="dingtalk-discovery" aria-label="可加入的数据源">
<div className="dingtalk-discovery-heading">
<div>
<strong>可加入的来源</strong>
<small>按当前钉钉账号列出能访问的知识库与钉盘空间;勾选后加入为来源,首次目录扫描自动排队。</small>
return (
<section className="dingtalk-discovery" aria-label="可加入的数据源">
<div className="dingtalk-discovery-heading">
<div>
<strong>dws 导入(钉钉)</strong>
<small>按当前钉钉账号列出能访问的知识库与钉盘空间;勾选后加入为来源,首次目录扫描自动排队。</small>
</div>
<button type="button" className="secondary" onClick={() => void load()} disabled={loading}>
{loading ? '正在列举…' : '刷新列表'}
</button>
</div>
<button type="button" className="secondary" onClick={() => void load()} disabled={loading}>{loading ? '正在列举…' : '刷新列表'}</button>
</div>
{loadError ? <p className="error-message" role="alert">{loadError}</p> : null}
{list ? <div className="dingtalk-discovery-groups">
<div className="discovery-group">
<h4>知识库({knowledgeBases.length})</h4>
{list.knowledge_notice ? <small className="empty-inline">知识库列表可能不全:{list.knowledge_notice}</small> : null}
{knowledgeBases.length ? <ul>{knowledgeBases.map(renderRow)}</ul> : <small className="empty-inline">当前账号下没有可访问的知识库。</small>}
{loadError ? (
<p className="error-message" role="alert">
{loadError}
</p>
) : null}
{list ? (
<div className="dingtalk-discovery-groups">
<div className="discovery-group">
<h4>知识库({knowledgeBases.length})</h4>
{list.knowledge_notice ? (
<small className="empty-inline">知识库列表可能不全:{list.knowledge_notice}</small>
) : null}
{knowledgeBases.length ? (
<ul>{knowledgeBases.map(renderRow)}</ul>
) : (
<small className="empty-inline">当前账号下没有可访问的知识库。</small>
)}
</div>
<div className="discovery-group">
<h4>钉盘({driveSpaces.length})</h4>
{list.drive_notice ? <small className="empty-inline">钉盘这次列不出来:{list.drive_notice}</small> : null}
{!list.drive_notice && !driveSpaces.length ? (
<small className="empty-inline">当前账号下没有可见的钉盘空间。</small>
) : null}
{driveSpaces.length ? <ul>{driveSpaces.map(renderRow)}</ul> : null}
</div>
</div>
) : null}
<div className="dingtalk-discovery-actions">
<button type="button" disabled={!selected.length || busy} onClick={() => void submit()}>
{busy ? '正在加入…' : `加入为来源(选中 ${selected.length})`}
</button>
<small>勾选的知识库会登记为来源连接;已登记的条目标为「已是来源」,不会重复登记。</small>
</div>
<div className="discovery-group">
<h4>钉盘({driveSpaces.length})</h4>
{list.drive_notice ? <small className="empty-inline">钉盘这次列不出来:{list.drive_notice}</small> : null}
{!list.drive_notice && !driveSpaces.length ? <small className="empty-inline">当前账号下没有可见的钉盘空间。</small> : null}
{driveSpaces.length ? <ul>{driveSpaces.map(renderRow)}</ul> : null}
</div>
</div> : null}
<div className="dingtalk-discovery-actions">
<button type="button" disabled={!selected.length || busy} onClick={() => void submit()}>{busy ? '正在加入…' : `加入为来源(选中 ${selected.length})`}</button>
<small>勾选的知识库会登记为来源连接;已登记的条目标为「已是来源」,不会重复登记。</small>
</div>
{message ? <p className="success-message" role="status">{message}</p> : null}
{failure ? <p className="error-message" role="alert">{failure}</p> : null}
{loginRequired ? <DingtalkSessionControl
autoStart
hideTrigger
space={selected[0]?.url}
onSuccess={resumeAfterLogin}
onClose={() => setLoginRequired(false)}
/> : null}
</section>
}
{message ? (
<p className="success-message" role="status">
{message}
</p>
) : null}
{failure ? (
<p className="error-message" role="alert">
{failure}
</p>
) : null}
{loginRequired ? (
<DingtalkSessionControl
autoStart
hideTrigger
space={selected[0]?.url}
onSuccess={resumeAfterLogin}
onClose={() => setLoginRequired(false)}
/>
) : null}
</section>
)
}
+60 -47
View File
@@ -1,6 +1,6 @@
import { renderToStaticMarkup } from 'react-dom/server'
import { describe, expect, it, vi } from 'vitest'
import { SystemSettingsView, splitSourceConnections, visibleSaveMessage } from './SystemSettings'
import { SystemSettingsView, ppSourceConnections, visibleSaveMessage } from './SystemSettings'
import { AuthContext } from './auth'
import type { MonitorOverview } from './monitor'
import type { CatalogSource } from './sourceCatalog'
@@ -193,18 +193,16 @@ describe('SystemSettingsView', () => {
'刷新策略',
'设置服务已启用',
'当前活动版本',
'端点与凭据',
'文档工程师可调整',
'管理员设置已锁定',
])
expect(html).toContain(text)
// 需求(2026-10-14):数据源配置默认只列 PP 资料 + 「可加入的来源」;AList 与钉钉知识库来源
// 不删除,收进折叠开关,展开后才渲染(原来它们默认就在列表里)。
// 折叠开关自己的文案里就含“钉钉知识库”,所以只核对来源卡片才有的标记。
for (const folded of ['公司级技术支持知识库', '专用浏览器扫码会话', '直连 API Token'])
expect(html).not.toContain(folded)
expect(html).toContain('显示 AList/钉钉知识库来源(1)')
expect(html).toContain('这 1 个已接入来源未删除,数据不变')
// 需求(2026-10-14 收敛):数据源配置只剩两个入口 —— dws 导入(按当前钉钉账号发现)
// 与 PP 导入;AList/静态钉钉知识库等来源类型不再出现在这里(也没有折叠开关兜着)。
for (const hidden of ['公司级技术支持知识库', '专用浏览器扫码会话', '显示 AList/钉钉知识库来源'])
expect(html).not.toContain(hidden)
expect(html).toContain('dws 导入')
expect(html).toContain('PP 导入')
// 需求(2026-10-10):数据源配置不再做文件格式筛选(格式由目录级标注决定)。
for (const removed of ['文件格式筛选', '未勾选的一律不取件', '保存保留格式', '恢复继承上级规则'])
expect(html).not.toContain(removed)
@@ -293,13 +291,11 @@ describe('SystemSettingsView', () => {
expect(servicesHtml).toContain('端点探测:暂无真实探测结果')
// V1: left-nav section controls, per-source schedule editing, danger modal & history affordances.
expect(html).toContain('settings-nav')
expect(html).toContain('查看修订历史')
expect(html).toContain('保存并启用')
expect(html).toContain('停用中(不入队)')
// 卡片级调度/停用按钮仍在,只是默认只对可见来源渲染(钉钉/AList 卡片已折起)。
for (const foldedControl of ['下次自动刷新', '保存并启用调度', '停用来源'])
expect(html).not.toContain(foldedControl)
expect(html).toContain('本地手工导入来源不支持定时刷新')
// 非 PP 来源在这里根本不渲染卡片:连它们卡片上的调度、停用、修订入口一起消失。
for (const gone of ['查看修订历史', '保存并启用调度', '停用来源', '下次自动刷新']) expect(html).not.toContain(gone)
expect(html).toContain('本页只列 PP 来源')
// 手工来源(本地手工验收)也不再列在这里,它的专属提示自然不出现。
expect(html).not.toContain('本地手工导入来源不支持定时刷新')
// dead buttons removed
expect(html).not.toContain('添加内容源')
expect(html).not.toContain('管理员编辑')
@@ -537,38 +533,48 @@ describe('SystemSettingsView 数据源配置的默认清单', () => {
next_refresh_at: null,
},
]
const view = () =>
const view = (role: 'admin' | 'engineer' = 'admin') =>
renderToStaticMarkup(
<SystemSettingsView
sources={[]}
connections={withPP}
monitor={monitor}
settings={settings}
productionEnabled={false}
routingCapabilities={{ internal_enabled: true, external_enabled: true }}
loading={false}
saving={false}
error={null}
saveMessage={null}
onSave={vi.fn()}
onSourcesChanged={vi.fn()}
onRefresh={vi.fn()}
/>
<AuthContext.Provider value={authValue(role)}>
<SystemSettingsView
sources={[]}
connections={withPP}
monitor={monitor}
settings={settings}
productionEnabled={false}
routingCapabilities={{ internal_enabled: true, external_enabled: true }}
loading={false}
saving={false}
error={null}
saveMessage={null}
onSave={vi.fn()}
onSourcesChanged={vi.fn()}
onRefresh={vi.fn()}
/>
</AuthContext.Provider>
)
it('默认只列 PP 资料:AList 与钉钉知识库来源折起来但没删', () => {
it('只有两个入口:PP 来源列在 PP 导入下,AList/钉钉知识库/手工都不出现', () => {
const html = view()
expect(html).toContain('PP资料下载中心')
expect(html).toContain('PP 资料下载中心')
expect(html).not.toContain('国内工业')
expect(html).not.toContain('ATOM知识库')
expect(html).toContain('显示 AList/钉钉知识库来源(2)')
// 登记路径说清楚:新来源一律走「可加入的来源」;格式筛选与旧的新增入口继续不存在。
expect(html).toContain('可加入的来源')
expect(html).toContain('钉盘文件已替代 AList')
// 三个非 PP 来源一个都不该渲染,也没有任何折叠开关。
for (const hidden of ['国内工业', 'ATOM知识库', '本地手工验收', '显示 AList', '折叠'])
expect(html).not.toContain(hidden)
expect(html).toContain('dws 导入(钉钉)')
expect(html).toContain('PP 导入')
expect(html).toContain('去掉来源</button>')
expect(html).toContain('端点与凭据')
// PP 来源的卡片操作照旧:改刷新周期、启停、看修订历史。
for (const kept of ['查看修订历史', '保存并启用调度', '停用来源', '自动刷新周期']) expect(html).toContain(kept)
for (const removed of ['+ 新增钉钉知识库', '文件格式筛选']) expect(html).not.toContain(removed)
// 文档工程师看不到 dws 导入面板与「去掉来源」:两者都是管理员动作。
const engineer = view('engineer')
expect(engineer).not.toContain('dws 导入(钉钉)')
expect(engineer).not.toContain('去掉来源</button>')
expect(engineer).toContain('PP 导入')
})
})
describe('splitSourceConnections(数据源配置的默认清单规则)', () => {
describe('ppSourceConnections(数据源配置的清单规则)', () => {
const rows: SourceConnectionListItem[] = [
{
id: 'a',
@@ -614,13 +620,20 @@ describe('splitSourceConnections(数据源配置的默认清单规则)', ()
updated_at: '2026-09-09T09:30:32Z',
next_refresh_at: null,
},
{
id: 'e',
source_type: 'pp',
name: 'PP legacy',
enabled: false,
schedule_configured: false,
health_status: 'unknown',
item_count: 5,
updated_at: '2026-09-09T09:30:32Z',
next_refresh_at: null,
},
]
it('默认折起 AList 与钉钉知识库,展开后原样返回(顺序不变、一个不少)', () => {
const folded = splitSourceConnections(rows, false)
expect(folded.visible.map((item) => item.id)).toEqual(['a', 'd'])
expect(folded.legacy.map((item) => item.id)).toEqual(['b', 'c'])
const expanded = splitSourceConnections(rows, true)
expect(expanded.visible.map((item) => item.id)).toEqual(['a', 'b', 'c', 'd'])
expect(expanded.legacy.length).toBe(2)
it('只放行 PP 来源,顺序不变,其余类型一条都不放行', () => {
expect(ppSourceConnections(rows).map((item) => item.id)).toEqual(['a', 'e'])
expect(ppSourceConnections([])).toEqual([])
})
})
+87 -53
View File
@@ -14,6 +14,7 @@ import { fetchCatalogRoutingCapabilities, fetchCatalogSources } from './sourceCa
import type { CatalogRoutingCapabilities, CatalogSource } from './sourceCatalog'
import {
activateSourceSettingsRevision,
archiveSourceConnection,
createSourceSettingsRevision,
fetchSourceConnectionList,
fetchSourceSettingsRevisions,
@@ -67,13 +68,13 @@ const sourceTypeLabels: Record<string, string> = {
manual: '本地手工导入',
}
// 已由钉盘文件替代 / 改为按当前钉钉账号发现的来源类型:数据不删,只是在「数据源配置」默认折起来。
export const legacySourceTypes = ['alist', 'dingtalk'] as const
export const splitSourceConnections = (connections: SourceConnectionListItem[], showLegacy: boolean) => {
const legacy = connections.filter((item) => (legacySourceTypes as readonly string[]).includes(item.source_type))
const legacyIDs = new Set(legacy.map((item) => item.id))
return { legacy, visible: showLegacy ? connections : connections.filter((item) => !legacyIDs.has(item.id)) }
}
// 「数据源配置」只保留两个入口:**dws 导入**(按当前钉钉账号发现知识库与钉盘空间)
// 与 **PP 导入**。AList 已由钉盘文件替代、钉钉知识库一律走当前账号发现、本地手工与
// PP legacy 也下架了:本页只列 PP 来源。下架用归档(archived_at)实现,不删数据 ——
// 需要时用 dws 重新登记同名来源即原地复活(见 postgres.RegisterDingtalkSpace)。
export const ppSourceConnections = (connections: SourceConnectionListItem[]) =>
connections.filter((item) => item.source_type === 'pp')
const sourceAuthLabels: Record<string, string> = {
dingtalk: '专用浏览器扫码会话',
pp: '公开只读访问',
@@ -163,8 +164,27 @@ function SourceSettingsCard({
const [showHistory, setShowHistory] = useState(false)
const [history, setHistory] = useState<SourceSettingsRevision[] | null>(null)
const [pendingDisable, setPendingDisable] = useState(false)
// 「去掉来源」= 归档下架:先弹确认,再调后端(后端会再校验一次管理员权限)。
const [pendingArchive, setPendingArchive] = useState(false)
const scheduled = connection.source_type !== 'manual'
// 归档下架:来源从列表、目录、调度与扫描里消失,但数据不删;重新登记同一来源即复活。
const archive = async () => {
setBusy(true)
setFailure(null)
setMessage(null)
try {
await archiveSourceConnection(connection.id)
setMessage(`「${connection.name}」已归档下架:列表、来源与目录、计划刷新里都不再出现,数据保留可恢复。`)
setPendingArchive(false)
onSourcesChanged()
} catch (cause) {
setFailure(cause instanceof Error ? cause.message : '去掉来源失败')
} finally {
setBusy(false)
}
}
const submit = async (nextEnabled: boolean) => {
setBusy(true)
setMessage(null)
@@ -263,9 +283,16 @@ function SourceSettingsCard({
</div>
)}
{connection.source_type === 'dingtalk' && isAdmin ? <DingtalkSessionControl /> : null}
<button className="link" onClick={() => void loadHistory()}>
{showHistory ? '收起修订历史' : '查看修订历史'}
</button>
<div className="source-schedule-links">
<button className="link" onClick={() => void loadHistory()}>
{showHistory ? '收起修订历史' : '查看修订历史'}
</button>
{isAdmin ? (
<button className="link danger" disabled={busy} onClick={() => setPendingArchive(true)}>
去掉来源
</button>
) : null}
</div>
</div>
{message ? (
<p className="success-message" role="status">
@@ -318,6 +345,26 @@ function SourceSettingsCard({
</div>
</div>
) : null}
{pendingArchive ? (
<div className="modal-backdrop" role="dialog" aria-modal="true">
<div className="modal-card">
<h3>去掉「{connection.name}」?</h3>
<p>
去掉 =
归档下架:该来源会从数据源配置、来源与目录、计划刷新与手动扫描里摘掉。目录快照、发布记录与审计数据全部保留,
随时可恢复(用 dws 重新登记同一来源即原地复活)。此操作会先由后端再次校验管理员权限。
</p>
<div className="modal-actions">
<button className="danger" disabled={busy} onClick={() => void archive()}>
{busy ? '正在归档…' : '确认去掉'}
</button>
<button className="secondary" disabled={busy} onClick={() => setPendingArchive(false)}>
取消
</button>
</div>
</div>
</div>
) : null}
</article>
)
}
@@ -355,13 +402,8 @@ export function SystemSettingsView({
)
const [dirty, setDirty] = useState(false)
// 「数据源配置」默认只列 PP 资料:AList 已被钉盘文件替代、钉钉知识库一律走当前账号发现
//(见下方「可加入的来源」)。这 9 个已接入来源**不删除**,收进折叠开关里,随时可展开管理。
const [showLegacySources, setShowLegacySources] = useState(false)
const { legacy: legacyConnections, visible: visibleConnections } = splitSourceConnections(
connections,
showLegacySources
)
// 本页只列 PP 来源;dws 导入由下面的发现面板负责(其余类型已归档下架,未删除)。
const ppConnections = ppSourceConnections(connections)
useEffect(() => {
if (!settings) return
@@ -458,8 +500,8 @@ export function SystemSettingsView({
<div>
<h2>数据源配置</h2>
<p>
新来源只从下方「可加入的来源」勾选登记(按当前钉钉账号列出可访问的知识库与钉盘空间,钉盘文件已替代
AList);本页保留 PP 资料。逐来源设置自动刷新周期或保持仅手动,保存会先生成修订、验证后原子启用。
只留两个入口:<strong>dws 导入</strong>(按当前钉钉账号列出可访问的知识库与钉盘空间)与
<strong>PP 导入</strong>。逐来源设置自动刷新周期或保持仅手动,保存会先生成修订、验证后原子启用。
</p>
</div>
</div>
@@ -469,41 +511,33 @@ export function SystemSettingsView({
onRegistered={onSourcesChanged}
/>
) : null}
{legacyConnections.length ? (
<div className="settings-legacy-toggle">
<button type="button" className="secondary" onClick={() => setShowLegacySources((value) => !value)}>
{showLegacySources
? `收起 AList/钉钉知识库来源(${legacyConnections.length})`
: `显示 AList/钉钉知识库来源(${legacyConnections.length})`}
</button>
<small>
{showLegacySources
? '这些来源已在两处保留:本列表可改刷新周期与启停,「来源与目录」里照旧浏览它们的内容。'
: `AList 来源已由钉盘文件替代,钉钉知识库来源改为按当前账号发现;这 ${legacyConnections.length} 个已接入来源未删除,数据不变。`}
</small>
<div className="settings-source-group" id="settings-sources-pp">
<div className="settings-section-heading sub">
<div>
<h3>PP 导入</h3>
<p>
公开只读的 PP 资料下载中心。这里的「去掉来源」是归档下架:从列表、来源与目录、计划刷新里摘掉,
但目录快照与发布记录不删,随时可恢复。
</p>
</div>
</div>
) : null}
{visibleConnections.length ? (
<div className="settings-source-list">
{visibleConnections.map((connection) => (
<SourceSettingsCard
key={connection.id}
connection={connection}
onSourcesChanged={onSourcesChanged}
/>
))}
{sources.length ? null : (
<small className="empty-inline">尚无快照数据;快照将在来源首次刷新完成后出现。</small>
)}
</div>
) : legacyConnections.length ? (
<div className="empty-state">
本页只列 PP 资料;AList/钉钉知识库来源已收在上方开关里(共 {legacyConnections.length}{' '}
个,未删除)。
</div>
) : (
<div className="empty-state">尚无可显示的来源连接。</div>
)}
{ppConnections.length ? (
<div className="settings-source-list">
{ppConnections.map((connection) => (
<SourceSettingsCard
key={connection.id}
connection={connection}
onSourcesChanged={onSourcesChanged}
/>
))}
{sources.length ? null : (
<small className="empty-inline">尚无快照数据;快照将在来源首次刷新完成后出现。</small>
)}
</div>
) : (
<div className="empty-state">本页只列 PP 来源;现在还没有已接入的 PP 来源。</div>
)}
</div>
</section>
) : null}
{section === 'services' ? (
+287 -67
View File
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
import {
activateSourceSettingsRevision,
archiveSourceConnection,
createSourceSettingsRevision,
fetchSourceConnectionList,
fetchSourceConnections,
@@ -11,6 +12,7 @@ import {
parseSourceConnectionsResponse,
parseSourceScanDetailResponse,
parseSourceScansResponse,
restoreSourceConnection,
triggerSourceScan,
} from './sourceConnections'
@@ -19,31 +21,65 @@ afterEach(() => vi.unstubAllGlobals())
describe('parseSourceConnectionsResponse', () => {
it('normalizes only the safe source connection projection', () => {
const result = parseSourceConnectionsResponse({
data: [{
id: 'conn-safe', source_type: 'alist', name: 'AList只读源', enabled: true,
schedule_configured: true, health_status: 'healthy', item_count: 42,
updated_at: '2026-09-06T01:00:00Z', base_url: 'https://secret-origin.example', secret_ref: 'secret-name',
last_scan: {
id: 'scan-1', state: 'completed', observed_items: 42, unchanged_items: 40,
added_items: 1, updated_items: 1, over_limit_items: 0, missing_items: 0,
planned_uploads: 1, error_code: '', created_at: '2026-09-06T00:59:00Z',
completed_at: '2026-09-06T01:00:00Z', snapshot_sha256: 'must-strip', previous_revision: 'must-strip',
data: [
{
id: 'conn-safe',
source_type: 'alist',
name: 'AList只读源',
enabled: true,
schedule_configured: true,
health_status: 'healthy',
item_count: 42,
updated_at: '2026-09-06T01:00:00Z',
base_url: 'https://secret-origin.example',
secret_ref: 'secret-name',
last_scan: {
id: 'scan-1',
state: 'completed',
observed_items: 42,
unchanged_items: 40,
added_items: 1,
updated_items: 1,
over_limit_items: 0,
missing_items: 0,
planned_uploads: 1,
error_code: '',
created_at: '2026-09-06T00:59:00Z',
completed_at: '2026-09-06T01:00:00Z',
snapshot_sha256: 'must-strip',
previous_revision: 'must-strip',
},
},
}],
],
summary: { total: 1, enabled: 1, disabled: 0, healthy: 1, degraded: 0, unhealthy: 0, unknown: 0 },
})
expect(result.items).toEqual([{
id: 'conn-safe', source_type: 'alist', name: 'AList只读源', enabled: true,
schedule_configured: true, health_status: 'healthy', item_count: 42,
updated_at: '2026-09-06T01:00:00Z',
last_scan: {
id: 'scan-1', state: 'completed', observed_items: 42, unchanged_items: 40,
added_items: 1, updated_items: 1, over_limit_items: 0, missing_items: 0,
planned_uploads: 1, error_code: '', created_at: '2026-09-06T00:59:00Z',
completed_at: '2026-09-06T01:00:00Z',
expect(result.items).toEqual([
{
id: 'conn-safe',
source_type: 'alist',
name: 'AList只读源',
enabled: true,
schedule_configured: true,
health_status: 'healthy',
item_count: 42,
updated_at: '2026-09-06T01:00:00Z',
last_scan: {
id: 'scan-1',
state: 'completed',
observed_items: 42,
unchanged_items: 40,
added_items: 1,
updated_items: 1,
over_limit_items: 0,
missing_items: 0,
planned_uploads: 1,
error_code: '',
created_at: '2026-09-06T00:59:00Z',
completed_at: '2026-09-06T01:00:00Z',
},
},
}])
])
expect(result.summary.total).toBe(1)
expect(result.items[0]).not.toHaveProperty('base_url')
expect(result.items[0]).not.toHaveProperty('secret_ref')
@@ -66,7 +102,7 @@ describe('fetchSourceConnections', () => {
expect(fetchMock).toHaveBeenCalledWith(
'/api/v1/source-connections',
expect.objectContaining({ headers: { Accept: 'application/json' } }),
expect.objectContaining({ headers: { Accept: 'application/json' } })
)
})
})
@@ -76,54 +112,120 @@ describe('triggerSourceScan', () => {
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({
id: 'scan-safe', source_connection_id: 'conn/a', source_type: 'pp', state: 'pending',
created_at: '2026-09-06T01:00:00Z', snapshot_sha256: 'must-strip',
id: 'scan-safe',
source_connection_id: 'conn/a',
source_type: 'pp',
state: 'pending',
created_at: '2026-09-06T01:00:00Z',
snapshot_sha256: 'must-strip',
}),
})
vi.stubGlobal('fetch', fetchMock)
const scan = await triggerSourceScan('conn/a')
expect(fetchMock).toHaveBeenCalledWith('/api/v1/source-connections/conn%2Fa/scan', expect.objectContaining({ method: 'POST' }))
expect(fetchMock).toHaveBeenCalledWith(
'/api/v1/source-connections/conn%2Fa/scan',
expect.objectContaining({ method: 'POST' })
)
expect(scan).toEqual({
id: 'scan-safe', source_connection_id: 'conn/a', source_type: 'pp', state: 'pending', created_at: '2026-09-06T01:00:00Z',
id: 'scan-safe',
source_connection_id: 'conn/a',
source_type: 'pp',
state: 'pending',
created_at: '2026-09-06T01:00:00Z',
})
})
})
describe('source scan history and details', () => {
const scan = {
id: 'scan-safe', state: 'completed', observed_items: 2, unchanged_items: 0,
added_items: 1, updated_items: 0, over_limit_items: 0, missing_items: 1,
planned_uploads: 1, error_code: '', created_at: '2026-09-06T06:00:00Z', completed_at: '2026-09-06T06:01:00Z',
snapshot_sha256: 'must-be-dropped', stable_external_id: 'must-be-dropped',
id: 'scan-safe',
state: 'completed',
observed_items: 2,
unchanged_items: 0,
added_items: 1,
updated_items: 0,
over_limit_items: 0,
missing_items: 1,
planned_uploads: 1,
error_code: '',
created_at: '2026-09-06T06:00:00Z',
completed_at: '2026-09-06T06:01:00Z',
snapshot_sha256: 'must-be-dropped',
stable_external_id: 'must-be-dropped',
}
it('strictly parses safe history and detail projections', () => {
expect(parseSourceScansResponse({ data: [scan], total: 1, limit: 20, offset: 0 })).toEqual({
items: [{
id: 'scan-safe', state: 'completed', observed_items: 2, unchanged_items: 0,
added_items: 1, updated_items: 0, over_limit_items: 0, missing_items: 1,
planned_uploads: 1, error_code: '', created_at: '2026-09-06T06:00:00Z', completed_at: '2026-09-06T06:01:00Z',
}], total: 1, limit: 20, offset: 0,
items: [
{
id: 'scan-safe',
state: 'completed',
observed_items: 2,
unchanged_items: 0,
added_items: 1,
updated_items: 0,
over_limit_items: 0,
missing_items: 1,
planned_uploads: 1,
error_code: '',
created_at: '2026-09-06T06:00:00Z',
completed_at: '2026-09-06T06:01:00Z',
},
],
total: 1,
limit: 20,
offset: 0,
})
expect(parseSourceScanDetailResponse({ data: {
...scan,
changes: [{
id: 'chg-safe', source_item_id: 'si-safe', change_type: 'updated', observed_size_bytes: 42,
created_at: '2026-09-06T06:01:00Z', previous_revision: 'must-be-dropped', observed_revision: 'must-be-dropped',
}],
}})).toEqual({
id: 'scan-safe', state: 'completed', observed_items: 2, unchanged_items: 0,
added_items: 1, updated_items: 0, over_limit_items: 0, missing_items: 1,
planned_uploads: 1, error_code: '', created_at: '2026-09-06T06:00:00Z', completed_at: '2026-09-06T06:01:00Z',
changes: [{ id: 'chg-safe', source_item_id: 'si-safe', change_type: 'updated', observed_size_bytes: 42, created_at: '2026-09-06T06:01:00Z' }],
expect(
parseSourceScanDetailResponse({
data: {
...scan,
changes: [
{
id: 'chg-safe',
source_item_id: 'si-safe',
change_type: 'updated',
observed_size_bytes: 42,
created_at: '2026-09-06T06:01:00Z',
previous_revision: 'must-be-dropped',
observed_revision: 'must-be-dropped',
},
],
},
})
).toEqual({
id: 'scan-safe',
state: 'completed',
observed_items: 2,
unchanged_items: 0,
added_items: 1,
updated_items: 0,
over_limit_items: 0,
missing_items: 1,
planned_uploads: 1,
error_code: '',
created_at: '2026-09-06T06:00:00Z',
completed_at: '2026-09-06T06:01:00Z',
changes: [
{
id: 'chg-safe',
source_item_id: 'si-safe',
change_type: 'updated',
observed_size_bytes: 42,
created_at: '2026-09-06T06:01:00Z',
},
],
})
})
it('requests connection-scoped history and details', async () => {
const fetchMock = vi.fn()
.mockResolvedValueOnce(new Response(JSON.stringify({ data: [scan], total: 1, limit: 20, offset: 0 }), { status: 200 }))
const fetchMock = vi
.fn()
.mockResolvedValueOnce(
new Response(JSON.stringify({ data: [scan], total: 1, limit: 20, offset: 0 }), { status: 200 })
)
.mockResolvedValueOnce(new Response(JSON.stringify({ data: { ...scan, changes: [] } }), { status: 200 }))
vi.stubGlobal('fetch', fetchMock)
await fetchSourceScans('conn / pp')
@@ -135,47 +237,165 @@ describe('source scan history and details', () => {
describe('V1 source settings client', () => {
it('projects the connection list without sensitive fields', async () => {
const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({
data: [{ id: 'conn-1', source_type: 'alist', name: 'A', enabled: true, schedule_configured: true,
health_status: 'healthy', item_count: 3, updated_at: '2026-09-12T01:00:00Z', next_refresh_at: '2026-09-12T09:00:00Z',
base_url: 'https://strip.me', secret_ref: 'strip-too' }],
}), { status: 200 }))
const fetchMock = vi.fn().mockResolvedValue(
new Response(
JSON.stringify({
data: [
{
id: 'conn-1',
source_type: 'alist',
name: 'A',
enabled: true,
schedule_configured: true,
health_status: 'healthy',
item_count: 3,
updated_at: '2026-09-12T01:00:00Z',
next_refresh_at: '2026-09-12T09:00:00Z',
base_url: 'https://strip.me',
secret_ref: 'strip-too',
},
],
}),
{ status: 200 }
)
)
vi.stubGlobal('fetch', fetchMock)
const items = await fetchSourceConnectionList()
expect(items).toEqual([{ id: 'conn-1', source_type: 'alist', name: 'A', enabled: true, schedule_configured: true,
health_status: 'healthy', item_count: 3, updated_at: '2026-09-12T01:00:00Z', next_refresh_at: '2026-09-12T09:00:00Z' }])
expect(items).toEqual([
{
id: 'conn-1',
source_type: 'alist',
name: 'A',
enabled: true,
schedule_configured: true,
health_status: 'healthy',
item_count: 3,
updated_at: '2026-09-12T01:00:00Z',
next_refresh_at: '2026-09-12T09:00:00Z',
},
])
expect(JSON.stringify(items)).not.toContain('strip')
})
it('rejects malformed connection items', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({
data: [{ id: 'x' }],
}), { status: 200 })))
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue(
new Response(
JSON.stringify({
data: [{ id: 'x' }],
}),
{ status: 200 }
)
)
)
await expect(fetchSourceConnectionList()).rejects.toThrow('invalid source connection item')
})
it('creates and activates revisions with intent + idempotency headers and surfaces operation', async () => {
const fetchMock = vi.fn()
.mockResolvedValueOnce(new Response(JSON.stringify({ data: { id: 'scr-2' }, operation: 'created' }), { status: 201 }))
.mockResolvedValueOnce(new Response(JSON.stringify({ data: { connection_id: 'c', revision_id: 'scr-2' }, operation: 'replayed' }), { status: 200 }))
const fetchMock = vi
.fn()
.mockResolvedValueOnce(
new Response(JSON.stringify({ data: { id: 'scr-2' }, operation: 'created' }), { status: 201 })
)
.mockResolvedValueOnce(
new Response(JSON.stringify({ data: { connection_id: 'c', revision_id: 'scr-2' }, operation: 'replayed' }), {
status: 200,
})
)
vi.stubGlobal('fetch', fetchMock)
expect(await createSourceSettingsRevision('conn/1', { source_type: 'alist', name: 'A', endpoint: '', credential_ref: '', enabled: true, schedule: { refresh_interval_seconds: 3600 } })).toEqual({ operation: 'created', id: 'scr-2' })
expect(
await createSourceSettingsRevision('conn/1', {
source_type: 'alist',
name: 'A',
endpoint: '',
credential_ref: '',
enabled: true,
schedule: { refresh_interval_seconds: 3600 },
})
).toEqual({ operation: 'created', id: 'scr-2' })
expect(await activateSourceSettingsRevision('conn/1', 'scr/2')).toEqual({ operation: 'replayed', id: null })
const [createCall, activateCall] = fetchMock.mock.calls
expect(createCall[0]).toBe('/api/v1/source-connections/conn%2F1/settings/revisions')
expect((createCall[1] as RequestInit).headers).toMatchObject({ 'X-Governance-Action': 'source-settings' })
expect(((createCall[1] as RequestInit).headers as Record<string, string>)['Idempotency-Key']).toMatch(/[0-9a-f-]{36}/)
expect(((createCall[1] as RequestInit).headers as Record<string, string>)['Idempotency-Key']).toMatch(
/[0-9a-f-]{36}/
)
expect(activateCall[0]).toBe('/api/v1/source-connections/conn%2F1/settings/revisions/scr%2F2/activate')
expect(createCall[1]).not.toBe(activateCall[1])
})
it('surfaces server error details on failure', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ error: 'manual sources cannot be scheduled' }), { status: 400 })))
await expect(createSourceSettingsRevision('c', { source_type: 'manual', name: 'A', endpoint: '', credential_ref: '', enabled: true, schedule: { refresh_interval_seconds: 3600 } })).rejects.toThrow('保存来源设置草稿失败:manual sources cannot be scheduled')
vi.stubGlobal(
'fetch',
vi
.fn()
.mockResolvedValue(
new Response(JSON.stringify({ error: 'manual sources cannot be scheduled' }), { status: 400 })
)
)
await expect(
createSourceSettingsRevision('c', {
source_type: 'manual',
name: 'A',
endpoint: '',
credential_ref: '',
enabled: true,
schedule: { refresh_interval_seconds: 3600 },
})
).rejects.toThrow('保存来源设置草稿失败:manual sources cannot be scheduled')
})
it('parses revision history strictly', async () => {
const revision = { id: 'scr-1', revision_number: 1, state: 'active', name: 'A', endpoint: 'http://x', credential_ref: 'ref', enabled: true, refresh_interval_seconds: '3600', created_by: 'z', created_at: '2026-09-12T01:00:00Z', validated_at: null, activated_at: '2026-09-12T01:00:00Z', retired_at: null }
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: [revision] }), { status: 200 })))
const revision = {
id: 'scr-1',
revision_number: 1,
state: 'active',
name: 'A',
endpoint: 'http://x',
credential_ref: 'ref',
enabled: true,
refresh_interval_seconds: '3600',
created_by: 'z',
created_at: '2026-09-12T01:00:00Z',
validated_at: null,
activated_at: '2026-09-12T01:00:00Z',
retired_at: null,
}
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: [revision] }), { status: 200 }))
)
const history = await fetchSourceSettingsRevisions('c')
expect(history[0].state).toBe('active')
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: [{ ...revision, state: 'weird' }] }), { status: 200 })))
vi.stubGlobal(
'fetch',
vi
.fn()
.mockResolvedValue(new Response(JSON.stringify({ data: [{ ...revision, state: 'weird' }] }), { status: 200 }))
)
await expect(fetchSourceSettingsRevisions('c')).rejects.toThrow('invalid source settings revision')
})
})
describe('去掉来源(归档)客户端', () => {
it('归档/恢复都带写意图头与幂等键,并正确编码来源 ID', async () => {
const fetchMock = vi.fn().mockResolvedValue(new Response('{}', { status: 200 }))
vi.stubGlobal('fetch', fetchMock)
await archiveSourceConnection('conn/1')
const [archiveURL, archiveInit] = fetchMock.mock.calls[0]
expect(archiveURL).toBe('/api/v1/source-connections/conn%2F1/archive')
expect(archiveInit.method).toBe('POST')
expect(archiveInit.headers['X-Governance-Action']).toBe('source-archive')
expect(typeof archiveInit.headers['Idempotency-Key']).toBe('string')
expect(archiveInit.headers['Idempotency-Key'].length).toBeGreaterThan(0)
await restoreSourceConnection('conn/1')
const [restoreURL, restoreInit] = fetchMock.mock.calls[1]
expect(restoreURL).toBe('/api/v1/source-connections/conn%2F1/restore')
expect(restoreInit.headers['X-Governance-Action']).toBe('source-restore')
})
it('后端拒绝时把原因带出来(不吞错误)', async () => {
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue(new Response(JSON.stringify({ error: 'source connection not found' }), { status: 404 }))
)
await expect(archiveSourceConnection('conn-x')).rejects.toThrow('去掉来源失败:source connection not found')
})
})
+218 -58
View File
@@ -79,7 +79,13 @@ const healthStatuses = new Set<SourceHealthStatus>(['unknown', 'healthy', 'degra
const scanStates = new Set<SourceScanState>(['pending', 'running', 'completed', 'failed'])
const scanChangeTypes = new Set<SourceScanChangeType>(['added', 'updated', 'unavailable'])
const summaryKeys: ReadonlyArray<keyof SourceConnectionSummary> = [
'total', 'enabled', 'disabled', 'healthy', 'degraded', 'unhealthy', 'unknown',
'total',
'enabled',
'disabled',
'healthy',
'degraded',
'unhealthy',
'unknown',
]
export function parseSourceConnectionsResponse(value: unknown): SourceConnectionPage {
@@ -87,11 +93,19 @@ export function parseSourceConnectionsResponse(value: unknown): SourceConnection
throw new Error('invalid source connections response')
}
const items = value.data.map((raw): SourceConnectionView => {
if (!isRecord(raw) || typeof raw.id !== 'string' || typeof raw.source_type !== 'string' ||
!sourceTypes.has(raw.source_type as SourceConnectionType) || typeof raw.name !== 'string' ||
typeof raw.enabled !== 'boolean' || typeof raw.schedule_configured !== 'boolean' ||
typeof raw.health_status !== 'string' || !healthStatuses.has(raw.health_status as SourceHealthStatus) ||
!isCount(raw.item_count) || typeof raw.updated_at !== 'string') {
if (
!isRecord(raw) ||
typeof raw.id !== 'string' ||
typeof raw.source_type !== 'string' ||
!sourceTypes.has(raw.source_type as SourceConnectionType) ||
typeof raw.name !== 'string' ||
typeof raw.enabled !== 'boolean' ||
typeof raw.schedule_configured !== 'boolean' ||
typeof raw.health_status !== 'string' ||
!healthStatuses.has(raw.health_status as SourceHealthStatus) ||
!isCount(raw.item_count) ||
typeof raw.updated_at !== 'string'
) {
throw new Error('invalid source connection item')
}
const lastScan = parseSourceScanSummary(raw.last_scan)
@@ -131,18 +145,28 @@ export interface SourceConnectionListItem {
function parseConnectionList(raw: unknown): SourceConnectionListItem[] {
if (!Array.isArray(raw)) throw new Error('invalid source connections list')
return raw.map((item): SourceConnectionListItem => {
if (!isRecord(item) || typeof item.id !== 'string' || typeof item.source_type !== 'string' ||
typeof item.name !== 'string' || typeof item.enabled !== 'boolean' ||
typeof item.schedule_configured !== 'boolean' || typeof item.item_count !== 'number' ||
typeof item.updated_at !== 'string' ||
(item.next_refresh_at !== null && typeof item.next_refresh_at !== 'string')) {
if (
!isRecord(item) ||
typeof item.id !== 'string' ||
typeof item.source_type !== 'string' ||
typeof item.name !== 'string' ||
typeof item.enabled !== 'boolean' ||
typeof item.schedule_configured !== 'boolean' ||
typeof item.item_count !== 'number' ||
typeof item.updated_at !== 'string' ||
(item.next_refresh_at !== null && typeof item.next_refresh_at !== 'string')
) {
throw new Error('invalid source connection item')
}
return {
id: item.id, source_type: item.source_type as SourceConnectionType, name: item.name,
enabled: item.enabled, schedule_configured: item.schedule_configured,
id: item.id,
source_type: item.source_type as SourceConnectionType,
name: item.name,
enabled: item.enabled,
schedule_configured: item.schedule_configured,
health_status: typeof item.health_status === 'string' ? item.health_status : '',
item_count: item.item_count, updated_at: item.updated_at,
item_count: item.item_count,
updated_at: item.updated_at,
next_refresh_at: (item.next_refresh_at as string | null) ?? null,
}
})
@@ -151,7 +175,7 @@ function parseConnectionList(raw: unknown): SourceConnectionListItem[] {
export async function fetchSourceConnectionList(signal?: AbortSignal): Promise<SourceConnectionListItem[]> {
const response = await fetch('/api/v1/source-connections', { headers: { Accept: 'application/json' }, signal })
if (!response.ok) throw new Error(`加载来源连接失败(HTTP ${response.status})`)
const value = await response.json() as unknown
const value = (await response.json()) as unknown
if (!isRecord(value) || !Array.isArray(value.data)) throw new Error('invalid source connections response')
return parseConnectionList(value.data)
}
@@ -175,10 +199,17 @@ export async function triggerSourceScan(connectionID: string): Promise<Triggered
if (!response.ok) {
throw new Error(response.status === 409 ? '该来源已有扫描正在运行' : `触发来源扫描失败(HTTP ${response.status})`)
}
const raw = await response.json() as unknown
if (!isRecord(raw) || typeof raw.id !== 'string' || typeof raw.source_connection_id !== 'string' ||
typeof raw.source_type !== 'string' || !sourceTypes.has(raw.source_type as SourceConnectionType) ||
typeof raw.state !== 'string' || !scanStates.has(raw.state as SourceScanState) || typeof raw.created_at !== 'string') {
const raw = (await response.json()) as unknown
if (
!isRecord(raw) ||
typeof raw.id !== 'string' ||
typeof raw.source_connection_id !== 'string' ||
typeof raw.source_type !== 'string' ||
!sourceTypes.has(raw.source_type as SourceConnectionType) ||
typeof raw.state !== 'string' ||
!scanStates.has(raw.state as SourceScanState) ||
typeof raw.created_at !== 'string'
) {
throw new Error('invalid triggered source scan response')
}
return {
@@ -191,8 +222,14 @@ export async function triggerSourceScan(connectionID: string): Promise<Triggered
}
export function parseSourceScansResponse(value: unknown): SourceScanPage {
if (!isRecord(value) || !Array.isArray(value.data) || !isCount(value.total) ||
!isCount(value.limit) || value.limit < 1 || !isCount(value.offset)) {
if (
!isRecord(value) ||
!Array.isArray(value.data) ||
!isCount(value.total) ||
!isCount(value.limit) ||
value.limit < 1 ||
!isCount(value.offset)
) {
throw new Error('invalid source scans response')
}
return {
@@ -214,10 +251,15 @@ export function parseSourceScanDetailResponse(value: unknown): SourceScanDetail
const summary = parseSourceScanSummary(value.data)
if (!summary) throw new Error('invalid source scan detail response')
const changes = value.data.changes.map((raw): SourceScanChangeView => {
if (!isRecord(raw) || typeof raw.id !== 'string' ||
(raw.source_item_id !== null && typeof raw.source_item_id !== 'string') ||
typeof raw.change_type !== 'string' || !scanChangeTypes.has(raw.change_type as SourceScanChangeType) ||
(raw.observed_size_bytes !== null && !isCount(raw.observed_size_bytes)) || typeof raw.created_at !== 'string') {
if (
!isRecord(raw) ||
typeof raw.id !== 'string' ||
(raw.source_item_id !== null && typeof raw.source_item_id !== 'string') ||
typeof raw.change_type !== 'string' ||
!scanChangeTypes.has(raw.change_type as SourceScanChangeType) ||
(raw.observed_size_bytes !== null && !isCount(raw.observed_size_bytes)) ||
typeof raw.created_at !== 'string'
) {
throw new Error('invalid source scan change')
}
return {
@@ -231,31 +273,59 @@ export function parseSourceScanDetailResponse(value: unknown): SourceScanDetail
return { ...summary, changes }
}
export async function fetchSourceScans(connectionID: string, limit = 20, offset = 0, signal?: AbortSignal): Promise<SourceScanPage> {
export async function fetchSourceScans(
connectionID: string,
limit = 20,
offset = 0,
signal?: AbortSignal
): Promise<SourceScanPage> {
const params = new URLSearchParams({ limit: String(limit), offset: String(offset) })
const response = await fetch(`/api/v1/source-connections/${encodeURIComponent(connectionID)}/scans?${params}`, {
headers: { Accept: 'application/json' }, signal,
headers: { Accept: 'application/json' },
signal,
})
if (!response.ok) throw new Error(`加载扫描历史失败(HTTP ${response.status})`)
return parseSourceScansResponse(await response.json())
}
export async function fetchSourceScanDetail(connectionID: string, scanID: string, signal?: AbortSignal): Promise<SourceScanDetail> {
const response = await fetch(`/api/v1/source-connections/${encodeURIComponent(connectionID)}/scans/${encodeURIComponent(scanID)}`, {
headers: { Accept: 'application/json' }, signal,
})
export async function fetchSourceScanDetail(
connectionID: string,
scanID: string,
signal?: AbortSignal
): Promise<SourceScanDetail> {
const response = await fetch(
`/api/v1/source-connections/${encodeURIComponent(connectionID)}/scans/${encodeURIComponent(scanID)}`,
{
headers: { Accept: 'application/json' },
signal,
}
)
if (!response.ok) throw new Error(`加载扫描详情失败(HTTP ${response.status})`)
return parseSourceScanDetailResponse(await response.json())
}
function parseSourceScanSummary(raw: unknown): SourceScanSummary | null {
if (raw === null || raw === undefined) return null
if (!isRecord(raw) || typeof raw.id !== 'string' || typeof raw.state !== 'string' ||
!scanStates.has(raw.state as SourceScanState) || typeof raw.error_code !== 'string' ||
typeof raw.created_at !== 'string' || (raw.completed_at !== null && typeof raw.completed_at !== 'string')) {
if (
!isRecord(raw) ||
typeof raw.id !== 'string' ||
typeof raw.state !== 'string' ||
!scanStates.has(raw.state as SourceScanState) ||
typeof raw.error_code !== 'string' ||
typeof raw.created_at !== 'string' ||
(raw.completed_at !== null && typeof raw.completed_at !== 'string')
) {
throw new Error('invalid source scan summary')
}
const countKeys = ['observed_items', 'unchanged_items', 'added_items', 'updated_items', 'over_limit_items', 'missing_items', 'planned_uploads'] as const
const countKeys = [
'observed_items',
'unchanged_items',
'added_items',
'updated_items',
'over_limit_items',
'missing_items',
'planned_uploads',
] as const
for (const key of countKeys) {
if (!isCount(raw[key])) throw new Error('invalid source scan summary')
}
@@ -315,63 +385,153 @@ export interface SourceSettingsDraftRequest {
const revisionStates = new Set<SourceSettingsRevisionState>(['validated', 'active', 'retired', 'failed'])
function parseSettingsRevision(raw: unknown): SourceSettingsRevision {
if (!isRecord(raw) || typeof raw.id !== 'string' || typeof raw.revision_number !== 'number' ||
typeof raw.state !== 'string' || !revisionStates.has(raw.state as SourceSettingsRevisionState) ||
typeof raw.name !== 'string' || typeof raw.endpoint !== 'string' || typeof raw.credential_ref !== 'string' ||
typeof raw.enabled !== 'boolean' || typeof raw.refresh_interval_seconds !== 'string' ||
typeof raw.created_by !== 'string' || typeof raw.created_at !== 'string' ||
(raw.validated_at !== null && typeof raw.validated_at !== 'string') ||
(raw.activated_at !== null && typeof raw.activated_at !== 'string') ||
(raw.retired_at !== null && typeof raw.retired_at !== 'string')) {
if (
!isRecord(raw) ||
typeof raw.id !== 'string' ||
typeof raw.revision_number !== 'number' ||
typeof raw.state !== 'string' ||
!revisionStates.has(raw.state as SourceSettingsRevisionState) ||
typeof raw.name !== 'string' ||
typeof raw.endpoint !== 'string' ||
typeof raw.credential_ref !== 'string' ||
typeof raw.enabled !== 'boolean' ||
typeof raw.refresh_interval_seconds !== 'string' ||
typeof raw.created_by !== 'string' ||
typeof raw.created_at !== 'string' ||
(raw.validated_at !== null && typeof raw.validated_at !== 'string') ||
(raw.activated_at !== null && typeof raw.activated_at !== 'string') ||
(raw.retired_at !== null && typeof raw.retired_at !== 'string')
) {
throw new Error('invalid source settings revision')
}
return {
id: raw.id, revision_number: raw.revision_number, state: raw.state as SourceSettingsRevisionState,
name: raw.name, endpoint: raw.endpoint, credential_ref: raw.credential_ref, enabled: raw.enabled,
refresh_interval_seconds: raw.refresh_interval_seconds, created_by: raw.created_by, created_at: raw.created_at,
id: raw.id,
revision_number: raw.revision_number,
state: raw.state as SourceSettingsRevisionState,
name: raw.name,
endpoint: raw.endpoint,
credential_ref: raw.credential_ref,
enabled: raw.enabled,
refresh_interval_seconds: raw.refresh_interval_seconds,
created_by: raw.created_by,
created_at: raw.created_at,
validated_at: (raw.validated_at as string | null) ?? null,
activated_at: (raw.activated_at as string | null) ?? null,
retired_at: (raw.retired_at as string | null) ?? null,
}
}
export async function fetchSourceSettingsRevisions(connectionID: string, signal?: AbortSignal): Promise<SourceSettingsRevision[]> {
export async function fetchSourceSettingsRevisions(
connectionID: string,
signal?: AbortSignal
): Promise<SourceSettingsRevision[]> {
const response = await fetch(`/api/v1/source-connections/${encodeURIComponent(connectionID)}/settings/revisions`, {
headers: { Accept: 'application/json' },
signal,
})
if (!response.ok) throw new Error(`加载来源设置历史失败(HTTP ${response.status})`)
const value = await response.json() as unknown
const value = (await response.json()) as unknown
if (!isRecord(value) || !Array.isArray(value.data)) throw new Error('invalid source settings revisions response')
return value.data.map(parseSettingsRevision)
}
async function postSourceSettings(path: string, body: string, errorMessage: string): Promise<{ operation: string; id: string | null }> {
async function postSourceSettings(
path: string,
body: string,
errorMessage: string
): Promise<{ operation: string; id: string | null }> {
const response = await fetch(path, {
method: 'POST',
headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'X-Governance-Action': 'source-settings', 'Idempotency-Key': newOperationID() },
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'X-Governance-Action': 'source-settings',
'Idempotency-Key': newOperationID(),
},
body,
})
if (!response.ok) {
let detail = ''
try {
const parsed = await response.json() as unknown
const parsed = (await response.json()) as unknown
if (isRecord(parsed) && typeof parsed.error === 'string') detail = parsed.error
} catch { /* keep status-only message */ }
} catch {
/* keep status-only message */
}
throw new Error(detail ? `${errorMessage}:${detail}` : `${errorMessage}(HTTP ${response.status})`)
}
const value = await response.json() as unknown
if (!isRecord(value) || (value.operation !== 'created' && value.operation !== 'replayed') || !isRecord(value.data)) throw new Error('invalid source settings response')
const value = (await response.json()) as unknown
if (!isRecord(value) || (value.operation !== 'created' && value.operation !== 'replayed') || !isRecord(value.data))
throw new Error('invalid source settings response')
const id = typeof value.data.id === 'string' ? value.data.id : null
return { operation: value.operation, id }
}
export async function createSourceSettingsRevision(connectionID: string, draft: SourceSettingsDraftRequest): Promise<{ operation: string; id: string }> {
const result = await postSourceSettings(`/api/v1/source-connections/${encodeURIComponent(connectionID)}/settings/revisions`, JSON.stringify(draft), '保存来源设置草稿失败')
export async function createSourceSettingsRevision(
connectionID: string,
draft: SourceSettingsDraftRequest
): Promise<{ operation: string; id: string }> {
const result = await postSourceSettings(
`/api/v1/source-connections/${encodeURIComponent(connectionID)}/settings/revisions`,
JSON.stringify(draft),
'保存来源设置草稿失败'
)
if (!result.id) throw new Error('创建来源设置草稿未返回修订号')
return result as { operation: string; id: string }
}
export async function activateSourceSettingsRevision(connectionID: string, revisionID: string): Promise<{ operation: string }> {
return postSourceSettings(`/api/v1/source-connections/${encodeURIComponent(connectionID)}/settings/revisions/${encodeURIComponent(revisionID)}/activate`, '{}', '启用来源设置修订失败')
export async function activateSourceSettingsRevision(
connectionID: string,
revisionID: string
): Promise<{ operation: string }> {
return postSourceSettings(
`/api/v1/source-connections/${encodeURIComponent(connectionID)}/settings/revisions/${encodeURIComponent(revisionID)}/activate`,
'{}',
'启用来源设置修订失败'
)
}
/**
* 「去掉来源」:归档下架(**不是物理删除**)。
* 来源会从数据源配置、来源与目录、计划刷新与手动扫描里消失;目录快照、发布记录与
* 审计数据原样保留 —— 再用 dws 重新登记同一个来源就会原地复活。幂等,仅管理员可用。
*/
export async function archiveSourceConnection(connectionID: string): Promise<void> {
await postSourceArchive(
`/api/v1/source-connections/${encodeURIComponent(connectionID)}/archive`,
'source-archive',
'去掉来源失败'
)
}
/** 撤销归档:来源重新出现,但保持停用(调度不会自动恢复)。 */
export async function restoreSourceConnection(connectionID: string): Promise<void> {
await postSourceArchive(
`/api/v1/source-connections/${encodeURIComponent(connectionID)}/restore`,
'source-restore',
'恢复来源失败'
)
}
async function postSourceArchive(path: string, intent: string, errorMessage: string): Promise<void> {
const response = await fetch(path, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'X-Governance-Action': intent,
'Idempotency-Key': newOperationID(),
},
body: '{}',
})
if (!response.ok) {
let detail = ''
try {
const parsed = (await response.json()) as unknown
if (isRecord(parsed) && typeof parsed.error === 'string') detail = parsed.error
} catch {
/* keep status-only message */
}
throw new Error(detail ? `${errorMessage}:${detail}` : `${errorMessage}(HTTP ${response.status})`)
}
}