fix(ui): 修复F12-F16入口与追溯缺陷
build / build (push) Successful in 1m59s

Dockerfile 运行阶段补齐 dws_dingtalk_scan(F12),并新增 runtime-scripts 门禁
做脚本依赖闭包正负例;就绪探测每次解析当前端点/绑定/凭据并区分 404、未配置、
不可达(F13);路由写入来源路径与父目录,历史空值仅按同连接同 item 的意图读时
补齐(F14);目标筛选显示短 ID 与当前绑定/历史并提供快捷筛选(F15);刷新终态
移除后台运行、展示失败时间/旧快照/脱敏原因/作业 ID 与重试(F16)。

验证:make verify 17 项全过(identity 本地按设计 skipped);一次性 schema 的
Monitor 目录/路由集成用例通过;8088 部署与真实 UI 验收仍由父会话执行。
This commit is contained in:
姚章浩
2026-11-05 10:38:26 +08:00
parent dfbf3336b2
commit 1c80b07f2c
29 changed files with 1436 additions and 75 deletions
+5 -2
View File
@@ -36,8 +36,11 @@ type ServiceHealth struct {
ObservedAt time.Time `json:"observed_at"`
LastSuccessAt *time.Time `json:"last_success_at"`
ConsecutiveFailures int `json:"consecutive_failures"`
Configured bool `json:"configured"`
Applicable bool `json:"applicable"`
// ProbeTarget names the object being probed (instance + short binding id),
// never credentials or full UUIDs, so a red light can be attributed.
ProbeTarget string `json:"probe_target"`
Configured bool `json:"configured"`
Applicable bool `json:"applicable"`
}
type KnowledgeBaseProgress struct {
+1
View File
@@ -116,6 +116,7 @@ type CatalogRouteRequest struct {
// fulfillment path needs to materialize and fetch it later.
type CatalogRouteFile struct {
NodeID string
ParentNodeID string
Name string
RelativePath string
SizeBytes *int64
+4
View File
@@ -97,6 +97,10 @@ func listMonitorTasks(w http.ResponseWriter, r *http.Request, config Config) {
writeJSON(w, 500, map[string]string{"error": "无法读取文件处理状态"})
return
}
// 目标同名不罕见(两侧都叫“对内知识库”):把当前生效绑定随页返回,
// 前端才能在同一口径下标注“当前绑定/历史”,而不是拿本页条目反推全局。
internal, external := config.effectiveRoutingTargets(r.Context())
page.Bindings = postgresstore.MonitorBindings{Internal: internal, External: external}
w.Header().Set("Cache-Control", "no-store")
writeJSON(w, 200, map[string]any{"data": page})
}
+37
View File
@@ -2,6 +2,7 @@ package httpapi
import (
"context"
"encoding/json"
postgresstore "knowledge-governance/internal/platform/postgres"
"net/http/httptest"
"testing"
@@ -51,3 +52,39 @@ func TestMonitorTasksRoute(t *testing.T) {
t.Fatalf("viewer removal %d", removal.Code)
}
}
// F15:筛选里的“当前绑定”必须来自持久化绑定(与业务同一真源),不是 env 旧值,
// 也不能让前端拿本页数据猜全局。
func TestMonitorTasksReportsEffectiveTargetBindings(t *testing.T) {
store := &monitorTasksTestStore{}
handler, err := NewHandler(Config{
Store: store,
InternalRoutingKnowledgeBaseID: "env-old-internal",
ExternalRoutingKnowledgeBaseID: "env-old-external",
RoutingBindings: &bindingStoreFake{internal: "current-internal", external: "current-external"},
})
if err != nil {
t.Fatal(err)
}
req := httptest.NewRequest("GET", "/api/v1/monitor/tasks?limit=20", nil)
req = req.WithContext(context.WithValue(req.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleViewer}))
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, req)
if recorder.Code != 200 {
t.Fatalf("status %d: %s", recorder.Code, recorder.Body.String())
}
var payload struct {
Data struct {
Bindings struct {
Internal string `json:"internal"`
External string `json:"external"`
} `json:"bindings"`
} `json:"data"`
}
if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil {
t.Fatal(err)
}
if payload.Data.Bindings.Internal != "current-internal" || payload.Data.Bindings.External != "current-external" {
t.Fatalf("bindings = %#v, want the persisted current bindings", payload.Data.Bindings)
}
}
+5 -2
View File
@@ -177,10 +177,13 @@ func (provider *RealProvider) weKnoraProbe(ctx context.Context, now time.Time) g
return provider.track(classify("weknora", "WeKnora API", false, true, ProbeOutcome{ObservedAt: now}))
}
outcome := provider.httpProbeOutcome(ctx, baseURL, now)
probeTarget := ""
if outcome.Reachability == nil && provider.weknoraReadiness != nil {
outcome.WorkReadiness = provider.weknoraReadiness(ctx)
probeTarget, outcome.WorkReadiness = provider.weknoraReadiness(ctx)
}
return provider.track(classify("weknora", "WeKnora API", true, true, outcome))
health := provider.track(classify("weknora", "WeKnora API", true, true, outcome))
health.ProbeTarget = probeTarget
return health
}
// productionWeKnoraProbe reports the real state of the production WeKnora
+29
View File
@@ -12,6 +12,7 @@ import (
"time"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/readiness"
)
func testNow() time.Time { return time.Date(2026, 9, 12, 9, 0, 0, 0, time.UTC) }
@@ -141,3 +142,31 @@ func TestOverallReadinessTreatsProductionEndpointAsAdvisory(t *testing.T) {
t.Fatalf("real dependency failure must still block: ok=%v blocked=%v", ok, blocked)
}
}
// F13: 旧 env 绑定 404 是「业务就绪被阻断」,不是「服务不可达」;
// 同时必须把脱敏后的探测对象带出来,否则红灯无法归因。
func TestWeKnoraReadinessReportsBindingBlockWithoutLosingLiveness(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
writer.WriteHeader(http.StatusOK)
}))
defer server.Close()
provider := &RealProvider{
httpClient: server.Client(),
weknoraBaseURL: server.URL,
health: newHealthTracker(),
weknoraReadiness: func(context.Context) (string, error) {
target := "实例 weknora.test · 知识库 1b52c140"
return target, fmt.Errorf("%w(%s)", readiness.ErrKnowledgeBaseMissing, target)
},
}
health := provider.weKnoraProbe(context.Background(), testNow())
if health.Liveness != LiveUp || health.Readiness != ReadBlocked {
t.Fatalf("404 binding = %+v, want up/blocked", health)
}
if health.ProbeTarget != "实例 weknora.test · 知识库 1b52c140" {
t.Fatalf("probe target = %q", health.ProbeTarget)
}
if !strings.Contains(health.Reason, "1b52c140") || strings.Contains(health.Reason, "1b52c140-2e18-4676-afc5-4c7d8d190a8c") {
t.Fatalf("reason = %q, want short target only", health.Reason)
}
}
+4 -4
View File
@@ -44,9 +44,9 @@ type RealProviderConfig struct {
// place operators configure it — and the env value above stays the
// bootstrap fallback for containers that were wired before the UI existed.
ProductionWeKnoraResolver func(ctx context.Context) string
// WeKnoraReadiness optionally exercises a real read against a routing
// knowledge base (nil = API key not configured; liveness-only).
WeKnoraReadiness func(ctx context.Context) error
// WeKnoraReadiness optionally exercises a real read against the CURRENT
// routing binding and reports the sanitized probe target alongside the error.
WeKnoraReadiness func(ctx context.Context) (target string, err error)
// WorkerStaleAfter bounds how long a missing worker heartbeat still counts
// as alive (P10).
WorkerStaleAfter time.Duration
@@ -61,7 +61,7 @@ type RealProvider struct {
testWeKnoraResolver func(ctx context.Context) string
productionWeKnoraBaseURL string
productionWeKnoraResolver func(ctx context.Context) string
weknoraReadiness func(ctx context.Context) error
weknoraReadiness func(ctx context.Context) (string, error)
workerStaleAfter time.Duration
health *healthTracker
}
@@ -114,7 +114,7 @@ FOR UPDATE OF node`, request.ConnectionID, nodeIDs)
JOIN source_catalog_nodes child ON child.snapshot_id=parent.snapshot_id AND child.parent_node_id=parent.node_id
WHERE parent.node_type='folder'
)
SELECT DISTINCT node.node_id,node.name,node.relative_path,node.size_bytes,node.modified_at,node.content_sha256,
SELECT DISTINCT node.node_id,node.parent_node_id,node.name,node.relative_path,node.size_bytes,node.modified_at,node.content_sha256,
node.source_locator_hash,(node.node_id=ANY($2::text[])) AS directly_selected
FROM descendants
JOIN source_catalog_nodes node ON node.snapshot_id=descendants.snapshot_id AND node.node_id=descendants.node_id
@@ -130,7 +130,7 @@ ORDER BY node.node_id`, request.ConnectionID, nodeIDs)
files := make([]governance.CatalogRouteFile, 0, len(nodeIDs))
for rows.Next() {
var file governance.CatalogRouteFile
if err := rows.Scan(&file.NodeID, &file.Name, &file.RelativePath, &file.SizeBytes, &file.ModifiedAt,
if err := rows.Scan(&file.NodeID, &file.ParentNodeID, &file.Name, &file.RelativePath, &file.SizeBytes, &file.ModifiedAt,
&file.ContentSHA256, &file.LocatorHash, &file.Direct); err != nil {
rows.Close()
return governance.CatalogRouteResult{}, fmt.Errorf("scan catalog route file: %w", err)
@@ -0,0 +1,217 @@
package postgres
import (
"context"
"os"
"testing"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"knowledge-governance/internal/governance"
)
// F14:来源目录在取件/路由时写入 source_items;对历史行(当时没写)只在读时
// 按「同一连接 + 同一 item」的 catalog intent 补齐,绝不按文件名猜配。
func TestMonitorTaskCatalogDirectoryIdentityIntegration(t *testing.T) {
url := isolatedIntegrationDatabaseURL(t, os.Getenv("TEST_DATABASE_URL"))
if url == "" {
t.Skip("TEST_DATABASE_URL is not set")
}
ctx := context.Background()
pool, err := pgxpool.New(ctx, url)
if err != nil {
t.Fatal(err)
}
defer pool.Close()
if err = ApplyMigrations(ctx, pool); err != nil {
t.Fatal(err)
}
exec := func(query string, args ...any) {
t.Helper()
if _, err := pool.Exec(ctx, query, args...); err != nil {
t.Fatalf("%v: %s", err, query)
}
}
now := time.Date(2026, 11, 5, 2, 0, 0, 0, time.UTC)
exec(`INSERT INTO source_connections (id,source_type,name) VALUES
('conn-atom','dingtalk','ATOM知识库'),('conn-pp','pp','PP资料下载中心')`)
for index, connection := range []struct{ id, snapshot, folder, file string }{
{"conn-atom", "snap-atom", "node-atom-folder", "node-atom-file"},
{"conn-pp", "snap-pp", "node-pp-folder", "node-pp-file"},
} {
exec(`INSERT INTO source_catalog_snapshots (id,source_connection_id,snapshot_sha256,source_label,node_count,folder_count,file_count,observed_at)
VALUES ($1,$2,repeat($3,64),'fixture',2,1,1,$4)`,
connection.snapshot, connection.id, string(rune('a'+index)), now)
exec(`INSERT INTO source_catalog_nodes (snapshot_id,node_id,parent_node_id,node_type,name,relative_path,source_locator_hash)
VALUES ($1,$2,NULL,'folder','售后机器出厂问题整改','售后机器出厂问题整改',repeat($3,64))`,
connection.snapshot, connection.folder, "b")
exec(`INSERT INTO source_catalog_nodes (snapshot_id,node_id,parent_node_id,node_type,name,relative_path,source_locator_hash)
VALUES ($1,$2,$3,'file','末端航插线序问题.adoc.docx',$4,repeat($5,64))`,
connection.snapshot, connection.file, connection.folder,
map[string]string{"conn-atom": "售后机器出厂问题整改/末端航插线序问题.adoc.docx", "conn-pp": "PP公开资料/末端航插线序问题.adoc.docx"}[connection.id],
"c")
exec(`INSERT INTO source_catalog_heads (source_connection_id,snapshot_id,activated_at) VALUES ($1,$2,$3)`,
connection.id, connection.snapshot, now)
}
// 两条来源的标题完全相同、来源不同;路径必须各自来自自己的 intent。
insertItem := func(id, connection, title, storedPath, parent string) {
exec(`INSERT INTO source_items (id,source_connection_id,stable_external_id,canonical_uri_hash,normalized_path,parent_external_id,title,item_type,revision,visibility,visibility_origin,source_change,policy_state,updated_at)
VALUES ($1,$2,$7,repeat('d',64),$3,$4,$5,'file','sha:1','internal','configured_scope','added','internal',$6)`,
id, connection, storedPath, parent, title, now, id)
exec(`INSERT INTO source_item_versions (id,source_item_id,revision,content_state,raw_record_summary,updated_at)
VALUES ('sv-'||$1,$1,'sha:1','verified','{}'::jsonb,$2)`, id, now)
}
insertItem("si-atom", "conn-atom", "末端航插线序问题.adoc.docx", "", "")
insertItem("si-pp", "conn-pp", "末端航插线序问题.adoc.docx", "", "")
insertItem("si-unbound", "conn-pp", "未登记目录文件.adoc.docx", "", "")
insertItem("si-stored", "conn-atom", "已登记目录文件.adoc.docx", "既有登记/已登记目录文件.adoc.docx", "node-atom-folder")
exec(`INSERT INTO catalog_import_intents (source_connection_id,node_id,visibility,source_item_id,decided_by,relative_path,name,locator_hash,updated_at)
VALUES ('conn-atom','node-atom-file','internal','si-atom','fixture','售后机器出厂问题整改/末端航插线序问题.adoc.docx','末端航插线序问题.adoc.docx',repeat('e',64),$1)`, now)
exec(`INSERT INTO catalog_import_intents (source_connection_id,node_id,visibility,source_item_id,decided_by,relative_path,name,locator_hash,updated_at)
VALUES ('conn-pp','node-pp-file','internal','si-pp','fixture','PP公开资料/末端航插线序问题.adoc.docx','末端航插线序问题.adoc.docx',repeat('f',64),$1)`, now)
exec(`INSERT INTO catalog_import_intents (source_connection_id,node_id,visibility,source_item_id,decided_by,relative_path,name,locator_hash,updated_at)
VALUES ('conn-atom','node-atom-folder','internal','si-stored','fixture','售后机器出厂问题整改/已登记目录文件.adoc.docx','已登记目录文件.adoc.docx',repeat('1',64),$1)`, now)
for index, publication := range []struct{ id, item, kb, scope string }{
{"tp-atom", "si-atom", "kb-internal-a", "internal"},
{"tp-pp", "si-pp", "kb-internal-b", "internal"},
{"tp-unbound", "si-unbound", "kb-internal-b", "internal"},
{"tp-stored", "si-stored", "kb-internal-a", "internal"},
} {
exec(`INSERT INTO test_publications (id,source_item_version_id,test_kb_id,ingest_state,processing_state,retrieval_state,target_scope,updated_at)
VALUES ($1,'sv-'||$2,$3,'uploaded','completed','unpublished',$4,$5)`,
publication.id, publication.item, publication.kb, publication.scope, now.Add(time.Duration(index)*time.Minute))
}
store := NewStore(pool)
page, err := store.ListMonitorTasks(ctx, MonitorTaskFilter{Limit: 20})
if err != nil {
t.Fatal(err)
}
byID := map[string]MonitorTask{}
for _, item := range page.Items {
byID[item.ID] = item
}
atom := byID["tp-atom"]
if atom.Path != "售后机器出厂问题整改/末端航插线序问题.adoc.docx" || atom.ParentNodeID != "node-atom-folder" || atom.NodeID != "node-atom-file" {
t.Fatalf("historical item lost its catalog directory: %#v", atom)
}
pp := byID["tp-pp"]
if pp.Path != "PP公开资料/末端航插线序问题.adoc.docx" || pp.ParentNodeID != "node-pp-folder" {
t.Fatalf("same-title item took another source's path: %#v", pp)
}
if byID["tp-unbound"].Path != "" || byID["tp-unbound"].ParentNodeID != "" {
t.Fatalf("missing intent must not invent a directory: %#v", byID["tp-unbound"])
}
if stored := byID["tp-stored"]; stored.Path != "既有登记/已登记目录文件.adoc.docx" {
t.Fatalf("stored path must win over the intent snapshot: %#v", stored)
}
searched, err := store.ListMonitorTasks(ctx, MonitorTaskFilter{Search: "售后机器出厂问题整改", Limit: 20})
if err != nil {
t.Fatal(err)
}
if searched.Total != 1 || len(searched.Items) != 1 || searched.Items[0].SourceID != "conn-atom" {
t.Fatalf("directory search total=%d items=%#v, want exactly the ATOM row", searched.Total, searched.Items)
}
// 同名文件在另一来源下不应被这条目录搜索带出来(同名异源隔离)。
other, err := store.ListMonitorTasks(ctx, MonitorTaskFilter{Search: "PP公开资料", Limit: 20})
if err != nil {
t.Fatal(err)
}
if other.Total != 1 || len(other.Items) != 1 || other.Items[0].SourceID != "conn-pp" {
t.Fatalf("cross-source search leaked: %#v", other.Items)
}
// F15:目标选项带 scope(同名知识库靠短 ID + scope 区分),筛选总数由后端全量算。
if len(page.Targets) != 2 {
t.Fatalf("target options = %#v", page.Targets)
}
for _, option := range page.Targets {
if option.Scope != "internal" || len(option.ID) < 8 {
t.Fatalf("target option missing identity: %#v", option)
}
}
filtered, err := store.ListMonitorTasks(ctx, MonitorTaskFilter{Target: "kb-internal-b", Limit: 20})
if err != nil {
t.Fatal(err)
}
if filtered.Total != 2 || len(filtered.Items) != 2 {
t.Fatalf("target filter total=%d items=%d, want 2", filtered.Total, len(filtered.Items))
}
}
// F14 写入侧:路由/取件时就把来源路径与父目录写进 source_items;
// 对已存在但当时没写的行,只在同一 intent 绑定的 item 上补空值,绝不覆盖既有值。
func TestCatalogRoutePersistsSourceDirectoryIntegration(t *testing.T) {
url := isolatedIntegrationDatabaseURL(t, os.Getenv("TEST_DATABASE_URL"))
if url == "" {
t.Skip("TEST_DATABASE_URL is not set")
}
ctx := context.Background()
pool, err := pgxpool.New(ctx, url)
if err != nil {
t.Fatal(err)
}
defer pool.Close()
if err = ApplyMigrations(ctx, pool); err != nil {
t.Fatal(err)
}
exec := func(query string, args ...any) {
t.Helper()
if _, err := pool.Exec(ctx, query, args...); err != nil {
t.Fatalf("%v: %s", err, query)
}
}
now := time.Date(2026, 11, 5, 3, 0, 0, 0, time.UTC)
exec(`INSERT INTO source_connections (id,source_type,name) VALUES ('conn-route','dingtalk','路由来源')`)
exec(`INSERT INTO source_catalog_snapshots (id,source_connection_id,snapshot_sha256,source_label,node_count,folder_count,file_count,observed_at)
VALUES ('snap-route','conn-route',repeat('9',64),'fixture',2,1,1,$1)`, now)
exec(`INSERT INTO source_catalog_nodes (snapshot_id,node_id,parent_node_id,node_type,name,relative_path,source_locator_hash)
VALUES ('snap-route','node-route-folder',NULL,'folder','售后机器出厂问题整改','售后机器出厂问题整改',repeat('8',64))`)
exec(`INSERT INTO source_catalog_nodes (snapshot_id,node_id,parent_node_id,node_type,name,relative_path,source_locator_hash)
VALUES ('snap-route','node-route-file','node-route-folder','file','末端航插线序问题.adoc.docx','售后机器出厂问题整改/末端航插线序问题.adoc.docx',repeat('7',64))`)
exec(`INSERT INTO source_catalog_heads (source_connection_id,snapshot_id,activated_at) VALUES ('conn-route','snap-route',$1)`, now)
// 历史行:当时没写路径,但 intent 已把它绑定到本 item。
exec(`INSERT INTO source_items (id,source_connection_id,stable_external_id,canonical_uri_hash,title,item_type,revision,visibility,visibility_origin,source_change,policy_state,updated_at)
VALUES ('si-route-old','conn-route','legacy-item',repeat('6',64),'末端航插线序问题.adoc.docx','file','','internal','configured_scope','unchanged','internal',$1)`, now)
exec(`INSERT INTO source_item_versions (id,source_item_id,revision,content_state,raw_record_summary,updated_at)
VALUES ('sv-route-old','si-route-old','','unknown','{}'::jsonb,$1)`, now)
exec(`INSERT INTO catalog_import_intents (source_connection_id,node_id,visibility,source_item_id,decided_by,relative_path,name,locator_hash,updated_at)
VALUES ('conn-route','node-route-file','internal','si-route-old','fixture','售后机器出厂问题整改/末端航插线序问题.adoc.docx','末端航插线序问题.adoc.docx',repeat('5',64),$1)`, now)
store := NewStore(pool)
if _, err := store.RouteCatalogFiles(ctx, governance.CatalogRouteRequest{
ConnectionID: "conn-route",
NodeIDs: []string{"node-route-file"},
Visibility: governance.VisibilityInternal,
TargetKnowledgeBaseID: "kb-route",
OperatorRef: "fixture",
Reason: "fixture",
Now: now,
}); err != nil {
t.Fatal(err)
}
var path, parent string
if err := pool.QueryRow(ctx, `SELECT normalized_path,parent_external_id FROM source_items WHERE id='si-route-old'`).Scan(&path, &parent); err != nil {
t.Fatal(err)
}
if path != "售后机器出厂问题整改/末端航插线序问题.adoc.docx" || parent != "node-route-folder" {
t.Fatalf("route did not persist the source directory: path=%q parent=%q", path, parent)
}
// 已有值不被后续路由覆盖(现有目录精确匹配)。
exec(`UPDATE source_items SET normalized_path='既有登记/保留路径',parent_external_id='node-existing' WHERE id='si-route-old'`)
if _, err := store.RouteCatalogFiles(ctx, governance.CatalogRouteRequest{
ConnectionID: "conn-route",
NodeIDs: []string{"node-route-file"},
Visibility: governance.VisibilityInternal,
TargetKnowledgeBaseID: "kb-route",
OperatorRef: "fixture",
Reason: "fixture",
Now: now.Add(time.Minute),
}); err != nil {
t.Fatal(err)
}
if err := pool.QueryRow(ctx, `SELECT normalized_path,parent_external_id FROM source_items WHERE id='si-route-old'`).Scan(&path, &parent); err != nil {
t.Fatal(err)
}
if path != "既有登记/保留路径" || parent != "node-existing" {
t.Fatalf("existing directory was overwritten: path=%q parent=%q", path, parent)
}
}
+45 -22
View File
@@ -16,23 +16,27 @@ type MonitorTaskEvent struct {
Detail string `json:"detail"`
}
type MonitorTask struct {
History []MonitorTaskEvent `json:"history"`
ID string `json:"id"`
Title string `json:"title"`
Path string `json:"path"`
SourceID string `json:"source_id"`
SourceName string `json:"source_name"`
TargetScope string `json:"target_scope"`
TargetKB string `json:"target_kb"`
Action string `json:"action"`
Stage string `json:"stage"`
Status string `json:"status"`
Detail string `json:"detail"`
UpdatedAt string `json:"updated_at"`
RetryKind string `json:"retry_kind"`
FailureID string `json:"failure_id"`
RetryCount int `json:"retry_count"`
VersionID string `json:"version_id"`
History []MonitorTaskEvent `json:"history"`
ID string `json:"id"`
Title string `json:"title"`
Path string `json:"path"`
// NodeID/ParentNodeID let the UI return to the exact source directory;
// both come from the catalog snapshot bound to THIS source item.
NodeID string `json:"node_id"`
ParentNodeID string `json:"parent_node_id"`
SourceID string `json:"source_id"`
SourceName string `json:"source_name"`
TargetScope string `json:"target_scope"`
TargetKB string `json:"target_kb"`
Action string `json:"action"`
Stage string `json:"stage"`
Status string `json:"status"`
Detail string `json:"detail"`
UpdatedAt string `json:"updated_at"`
RetryKind string `json:"retry_kind"`
FailureID string `json:"failure_id"`
RetryCount int `json:"retry_count"`
VersionID string `json:"version_id"`
}
type MonitorTaskPage struct {
Items []MonitorTask `json:"items"`
@@ -42,10 +46,18 @@ type MonitorTaskPage struct {
Sources []MonitorOption `json:"sources"`
Targets []MonitorOption `json:"targets"`
Retryable int `json:"retryable"`
// Bindings is the effective (persisted, env-fallback aware) target for each
// scope. The UI marks rows/options against it; counts stay this page's totals.
Bindings MonitorBindings `json:"bindings"`
}
type MonitorOption struct {
ID string `json:"id"`
Name string `json:"name"`
ID string `json:"id"`
Name string `json:"name"`
Scope string `json:"scope,omitempty"`
}
type MonitorBindings struct {
Internal string `json:"internal"`
External string `json:"external"`
}
// Reduce publication versions before filtering; totals and pages share one snapshot.
@@ -62,7 +74,11 @@ const monitorTasksCTE = `WITH history_publications AS (
WHERE p.superseded_at IS NULL
ORDER BY v.source_item_id,p.test_kb_id,p.created_at DESC,p.id DESC
), base AS (
SELECT p.id,si.title,si.normalized_path AS path,c.id AS source_id,c.name AS source_name,
SELECT p.id,si.title,
COALESCE(NULLIF(si.normalized_path,''),ci.relative_path,'') AS path,
COALESCE(NULLIF(si.parent_external_id,''),cn.parent_node_id,'') AS parent_node_id,
COALESCE(ci.node_id,'') AS node_id,
c.id AS source_id,c.name AS source_name,
p.target_scope,p.test_kb_id AS target_kb,p.source_item_version_id AS version_id,p.retry_count,
GREATEST(p.updated_at,j.updated_at,f.created_at) AS updated_at,
p.processing_state,p.ingest_state,p.retrieval_state,p.last_error,p.knowledge_id,
@@ -72,6 +88,13 @@ const monitorTasksCTE = `WITH history_publications AS (
COALESCE(j.type,'') AS job_type,COALESCE(j.state,'') AS job_state,COALESCE(j.attempt,0) AS job_attempt,j.available_at,
COALESCE(f.id,'') AS failure_id,COALESCE(f.job_type,'') AS failure_type,COALESCE(NULLIF(f.last_error,''),f.error_code,'') AS failure_error
FROM latest p JOIN source_items si ON si.id=p.source_item_id JOIN source_connections c ON c.id=si.source_connection_id
-- 历史行路径为空时,只用「同一连接 + 同一 item」的取件意图补齐:不按文件名猜配。
LEFT JOIN LATERAL(SELECT intent.relative_path,intent.node_id FROM catalog_import_intents intent
WHERE intent.source_item_id=si.id AND intent.source_connection_id=si.source_connection_id
ORDER BY intent.updated_at DESC,intent.node_id LIMIT 1) ci ON TRUE
LEFT JOIN LATERAL(SELECT node.parent_node_id FROM source_catalog_heads head
JOIN source_catalog_nodes node ON node.snapshot_id=head.snapshot_id
WHERE head.source_connection_id=si.source_connection_id AND node.node_id=ci.node_id LIMIT 1) cn ON TRUE
LEFT JOIN content_objects co ON co.id=p.content_object_id
LEFT JOIN LATERAL(SELECT j.type,j.state,j.attempt,j.available_at,j.updated_at FROM jobs j WHERE
(j.payload->>'publication_id'=p.id OR (j.type='artifact.fetch' AND j.payload->>'version_id'=p.source_item_version_id))
@@ -101,7 +124,7 @@ const monitorTasksCTE = `WITH history_publications AS (
ELSE 'waiting' END AS stage
FROM base
), projected AS (
SELECT id,title,path,source_id,source_name,target_scope,target_kb,version_id,retry_count,updated_at,action,stage,status,failure_id,
SELECT id,title,path,parent_node_id,node_id,source_id,source_name,target_scope,target_kb,version_id,retry_count,updated_at,action,stage,status,failure_id,
CASE WHEN status<>'attention' THEN ''
WHEN action='remove' THEN CASE WHEN job_type='test.remove' AND job_state='failed' AND retrieval_state IN ('failed','disabling') AND policy_state='blocked' THEN 'remove' ELSE '' END
WHEN failure_type='artifact.fetch' THEN 'fetch'
@@ -130,7 +153,7 @@ func (s *Store) ListMonitorTasks(ctx context.Context, f MonitorTaskFilter) (Moni
return MonitorTaskPage{}, errors.New("invalid monitor pagination")
}
var raw []byte
err := s.db.QueryRow(ctx, monitorTasksCTE+`SELECT jsonb_build_object('items',COALESCE((SELECT jsonb_agg(to_jsonb(x)||jsonb_build_object('history',COALESCE((SELECT jsonb_agg(e ORDER BY e.at DESC,e.kind,e.detail) FROM (SELECT * FROM history_events ORDER BY at DESC,kind,detail LIMIT 50)e),'[]'::jsonb)) ORDER BY x.updated_at DESC,x.id) FROM (SELECT * FROM filtered ORDER BY updated_at DESC,id LIMIT $8 OFFSET $9)x),'[]'::jsonb),'total',(SELECT count(*) FROM filtered),'limit',$8::int,'offset',$9::int,'retryable',(SELECT count(*) FROM filtered WHERE retry_kind<>''),'sources',COALESCE((SELECT jsonb_agg(x ORDER BY x.name) FROM (SELECT DISTINCT source_id AS id,source_name AS name FROM projected)x),'[]'::jsonb),'targets',COALESCE((SELECT jsonb_agg(x ORDER BY x.name) FROM (SELECT DISTINCT target_kb AS id,target_kb AS name FROM projected)x),'[]'::jsonb))`, f.Search, f.Source, f.Scope, f.Action, f.Status, f.Stage, f.ID, f.Limit, f.Offset, f.Target, f.Since, f.Until).Scan(&raw)
err := s.db.QueryRow(ctx, monitorTasksCTE+`SELECT jsonb_build_object('items',COALESCE((SELECT jsonb_agg(to_jsonb(x)||jsonb_build_object('history',COALESCE((SELECT jsonb_agg(e ORDER BY e.at DESC,e.kind,e.detail) FROM (SELECT * FROM history_events ORDER BY at DESC,kind,detail LIMIT 50)e),'[]'::jsonb)) ORDER BY x.updated_at DESC,x.id) FROM (SELECT * FROM filtered ORDER BY updated_at DESC,id LIMIT $8 OFFSET $9)x),'[]'::jsonb),'total',(SELECT count(*) FROM filtered),'limit',$8::int,'offset',$9::int,'retryable',(SELECT count(*) FROM filtered WHERE retry_kind<>''),'sources',COALESCE((SELECT jsonb_agg(x ORDER BY x.name) FROM (SELECT DISTINCT source_id AS id,source_name AS name FROM projected)x),'[]'::jsonb),'targets',COALESCE((SELECT jsonb_agg(x ORDER BY x.scope,x.id) FROM (SELECT target_kb AS id,MIN(target_scope) AS scope FROM projected GROUP BY target_kb)x),'[]'::jsonb))`, f.Search, f.Source, f.Scope, f.Action, f.Status, f.Stage, f.ID, f.Limit, f.Offset, f.Target, f.Since, f.Until).Scan(&raw)
if err != nil {
return MonitorTaskPage{}, err
}
+12 -3
View File
@@ -118,11 +118,11 @@ ORDER BY head.activated_at DESC NULLS LAST LIMIT 1 FOR UPDATE OF node`, request.
if _, err := tx.Exec(ctx, `INSERT INTO source_items(
id,source_connection_id,stable_external_id,canonical_uri_hash,title,item_type,revision,
visibility,visibility_origin,source_change,absence_streak,identity_confidence,
policy_state,created_at,updated_at)
VALUES($1,$2,$3,$4,$5,'file','',$7,'configured_scope','unchanged',0,'object_id',$6,NOW(),NOW())`,
policy_state,normalized_path,parent_external_id,created_at,updated_at)
VALUES($1,$2,$3,$4,$5,'file','',$7,'configured_scope','unchanged',0,'object_id',$6,$8,$9,NOW(),NOW())`,
newItemID, request.ConnectionID, "cat:"+file.NodeID,
sha256Hex("policy:"+request.ConnectionID+"\x00"+file.NodeID),
file.Name, policy, itemVisibilityFor(request.Visibility)); err != nil {
file.Name, policy, itemVisibilityFor(request.Visibility), file.RelativePath, file.ParentNodeID); err != nil {
return false, false, 0, false, fmt.Errorf("materialize policy source item: %w", err)
}
if _, err := tx.Exec(ctx, `UPDATE catalog_import_intents SET source_item_id=$3 WHERE source_connection_id=$1 AND node_id=$2`,
@@ -131,6 +131,15 @@ VALUES($1,$2,$3,$4,$5,'file','',$7,'configured_scope','unchanged',0,'object_id',
}
itemID = newItemID
}
// 历史行(当时没写来源路径)只补空值:意图已把 item 绑定到本连接的这个 node,
// 身份可证;已有路径绝不被覆盖,避免把下架连接重绑成当前来源。
if _, err := tx.Exec(ctx, `UPDATE source_items SET
normalized_path=CASE WHEN normalized_path='' THEN $2 ELSE normalized_path END,
parent_external_id=CASE WHEN parent_external_id='' THEN $3 ELSE parent_external_id END,
updated_at=CASE WHEN normalized_path='' OR parent_external_id='' THEN NOW() ELSE updated_at END
WHERE id=$1`, itemID, file.RelativePath, file.ParentNodeID); err != nil {
return false, false, 0, false, fmt.Errorf("persist policy source path: %w", err)
}
// Bind the snapshot nodes too (new or reused item): the browser's
// 已导入/已解析 counters join source_catalog_nodes.source_item_id; without
// this write every catalog-only source keeps showing "尚未导入" even after
+111
View File
@@ -0,0 +1,111 @@
package readiness
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"time"
"knowledge-governance/internal/platform/weknora"
)
// WeKnora 的 readiness 探测必须与业务执行链看同一个目标:网页保存的端点、
// 当前生效的知识库绑定、同一份 API Key。任何一项在启动时被捕获成常量,
// 都会在管理员改绑之后继续探测旧库(F13:旧库 404 被当成整个服务不可用)。
var (
ErrNotConfigured = errors.New("WeKnora 就绪探测未配置")
ErrKnowledgeBaseMissing = errors.New("WeKnora 探测目标知识库不存在")
ErrNoPermission = errors.New("WeKnora 探测目标知识库无读取权限")
)
type Target struct {
BaseURL string
KnowledgeBaseID string
APIKey string
}
type Result struct {
// Target 是脱敏后的探测对象(实例 + 短 ID),用于界面说明“探的是谁”。
Target string
Err error
}
// Prober 每次 Check 都重新解析目标并新建客户端:端点、凭据、绑定都允许
// 在进程运行期间变化,不能缓存成启动快照。
type Prober struct {
Resolve func(context.Context) (Target, error)
Timeout time.Duration
AllowDockerHTTP bool
}
func (prober Prober) Check(ctx context.Context) Result {
if prober.Resolve == nil {
return Result{Err: ErrNotConfigured}
}
target, err := prober.Resolve(ctx)
if err != nil {
return Result{Err: err}
}
described := describe(target)
if strings.TrimSpace(target.BaseURL) == "" || strings.TrimSpace(target.KnowledgeBaseID) == "" || strings.TrimSpace(target.APIKey) == "" {
return Result{Target: described, Err: ErrNotConfigured}
}
timeout := prober.Timeout
if timeout <= 0 || timeout > 10*time.Second {
timeout = 10 * time.Second
}
client, err := weknora.NewClient(weknora.ClientConfig{
BaseURL: target.BaseURL,
APIKey: target.APIKey,
Timeout: timeout,
AllowDockerHTTP: prober.AllowDockerHTTP,
})
if err != nil {
return Result{Target: described, Err: err}
}
if _, _, err := client.ListKnowledge(ctx, target.KnowledgeBaseID, 1, 1); err != nil {
return Result{Target: described, Err: classify(target, described, err)}
}
return Result{Target: described}
}
func classify(target Target, described string, err error) error {
var httpErr *weknora.HTTPError
if errors.As(err, &httpErr) {
switch httpErr.StatusCode {
case http.StatusNotFound:
return fmt.Errorf("%w(%s)", ErrKnowledgeBaseMissing, described)
case http.StatusUnauthorized, http.StatusForbidden:
return fmt.Errorf("%w(%s)", ErrNoPermission, described)
case http.StatusTooManyRequests:
return fmt.Errorf("目标知识库读取被限流(HTTP 429,%s)", described)
}
}
return err
}
// describe 只保留实例主机与知识库短 ID:诊断够用,不输出完整 UUID、路径或凭据。
func describe(target Target) string {
host := ""
if parsed, err := url.Parse(strings.TrimSpace(target.BaseURL)); err == nil && parsed.Host != "" {
host = parsed.Host
}
id := strings.TrimSpace(target.KnowledgeBaseID)
if len(id) > 8 {
id = id[:8]
}
switch {
case host == "" && id == "":
return ""
case host == "":
return "知识库 " + id
case id == "":
return "实例 " + host
default:
return "实例 " + host + " · 知识库 " + id
}
}
+138
View File
@@ -0,0 +1,138 @@
package readiness
import (
"context"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
)
// fakeWeKnora answers /health and /api/v1/knowledge-bases/{kb}/knowledge.
// 404 is how WeKnora says "this knowledge base does not exist" (F13 的旧 env 绑定).
func fakeWeKnora(t *testing.T, known map[string]int, wantKey string) *httptest.Server {
t.Helper()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if got := r.Header.Get("X-API-Key"); wantKey != "" && got != wantKey {
w.WriteHeader(http.StatusUnauthorized)
return
}
switch {
case r.URL.Path == "/health":
_, _ = w.Write([]byte(`ok`))
case strings.HasPrefix(r.URL.Path, "/api/v1/knowledge-bases/"):
parts := strings.Split(strings.TrimPrefix(r.URL.Path, "/api/v1/knowledge-bases/"), "/")
total, ok := known[parts[0]]
if !ok || len(parts) != 2 || parts[1] != "knowledge" {
w.WriteHeader(http.StatusNotFound)
return
}
_, _ = fmt.Fprintf(w, `{"success":true,"total":%d,"data":[]}`, total)
default:
w.WriteHeader(http.StatusNotFound)
}
}))
t.Cleanup(server.Close)
return server
}
func TestProbeFollowsTheCurrentBindingWithinOneProcess(t *testing.T) {
oldKB := "1b52c140-2e18-4676-afc5-4c7d8d190a8c"
currentKB := "0c84a098-d3ed-4b82-a165-e6de9691d6a8"
server := fakeWeKnora(t, map[string]int{currentKB: 4}, "key-1")
var mu sync.Mutex
binding := oldKB
prober := Prober{
Timeout: 2 * time.Second,
Resolve: func(context.Context) (Target, error) {
mu.Lock()
defer mu.Unlock()
return Target{BaseURL: server.URL, KnowledgeBaseID: binding, APIKey: "key-1"}, nil
},
}
first := prober.Check(context.Background())
if !errors.Is(first.Err, ErrKnowledgeBaseMissing) {
t.Fatalf("old binding probe = %v, want ErrKnowledgeBaseMissing", first.Err)
}
if !strings.Contains(first.Target, "1b52c140") || strings.Contains(first.Target, oldKB) {
t.Fatalf("probe target must name the probed KB in short form only: %q", first.Target)
}
mu.Lock()
binding = currentKB
mu.Unlock()
second := prober.Check(context.Background())
if second.Err != nil {
t.Fatalf("current binding probe = %v, want ready", second.Err)
}
if !strings.Contains(second.Target, "0c84a098") {
t.Fatalf("probe target did not follow the new binding: %q", second.Target)
}
}
func TestProbeReResolvesEndpointAndCredentialOnEveryCheck(t *testing.T) {
kb := "0c84a098-d3ed-4b82-a165-e6de9691d6a8"
denied := fakeWeKnora(t, map[string]int{kb: 4}, "new-key")
allowed := fakeWeKnora(t, map[string]int{kb: 4}, "new-key")
var mu sync.Mutex
endpoint, key := denied.URL, "old-key"
prober := Prober{
Timeout: 2 * time.Second,
Resolve: func(context.Context) (Target, error) {
mu.Lock()
defer mu.Unlock()
return Target{BaseURL: endpoint, KnowledgeBaseID: kb, APIKey: key}, nil
},
}
if err := prober.Check(context.Background()).Err; !errors.Is(err, ErrNoPermission) {
t.Fatalf("stale credential probe = %v, want ErrNoPermission", err)
}
mu.Lock()
endpoint, key = allowed.URL, "new-key"
mu.Unlock()
if err := prober.Check(context.Background()).Err; err != nil {
t.Fatalf("rotated endpoint/credential probe = %v, want ready", err)
}
}
func TestProbeDistinguishesMissingConfigurationFromUnreachable(t *testing.T) {
missing := Prober{Resolve: func(context.Context) (Target, error) {
return Target{BaseURL: "http://127.0.0.1:1", KnowledgeBaseID: ""}, nil
}}
if !errors.Is(missing.Check(context.Background()).Err, ErrNotConfigured) {
t.Fatalf("blank binding must be ErrNotConfigured, got %v", missing.Check(context.Background()).Err)
}
unreachable := Prober{Timeout: 200 * time.Millisecond, Resolve: func(context.Context) (Target, error) {
return Target{BaseURL: "http://127.0.0.1:1", KnowledgeBaseID: "kb-1", APIKey: "key"}, nil
}}
err := unreachable.Check(context.Background()).Err
if err == nil || errors.Is(err, ErrNotConfigured) || errors.Is(err, ErrKnowledgeBaseMissing) {
t.Fatalf("connection refused must stay a transport failure, got %v", err)
}
}
func TestProbeSurfaces404AsMissingKnowledgeBaseNotServiceDown(t *testing.T) {
server := fakeWeKnora(t, map[string]int{}, "key")
prober := Prober{Timeout: 2 * time.Second, Resolve: func(context.Context) (Target, error) {
return Target{BaseURL: server.URL, KnowledgeBaseID: "gone-kb", APIKey: "key"}, nil
}}
err := prober.Check(context.Background()).Err
if !errors.Is(err, ErrKnowledgeBaseMissing) {
t.Fatalf("404 = %v, want ErrKnowledgeBaseMissing", err)
}
if strings.Contains(err.Error(), "key") {
t.Fatalf("probe error leaked the credential: %v", err)
}
}
func TestProbeRejectsAnUnusableResolverResult(t *testing.T) {
prober := Prober{Resolve: func(context.Context) (Target, error) {
return Target{}, errors.New("settings unavailable")
}}
if err := prober.Check(context.Background()).Err; err == nil || errors.Is(err, ErrNotConfigured) {
t.Fatalf("resolver failure must be reported, got %v", err)
}
}