feat(settings): 服务配置四项化并保存时真校验

- 生产/测试 WeKnora 地址、租户 ID、知识库 ID 由静态 env 收敛为版本化 UI 设置,保留修订号与操作人审计
- 新增 serviceverify:保存前真调目标端点探测,端点无效才拒绝;网络抖动或无凭据仅告警
- 迁移 000042(生产 WeKnora 端点)/000043(服务目标);补齐设置候选与校验契约用例
This commit is contained in:
姚章浩
2026-09-30 10:53:25 +08:00
parent e53b98f37d
commit 1db21fb899
28 changed files with 1887 additions and 65 deletions
+20 -3
View File
@@ -172,16 +172,28 @@ func (provider *RealProvider) httpProbe(ctx context.Context, key, name, baseURL
// weKnoraProbe checks the WeKnora API: liveness via /health, readiness via an
// optional real read against a routing knowledge base.
func (provider *RealProvider) weKnoraProbe(ctx context.Context, now time.Time) governance.ServiceHealth {
if provider.weknoraBaseURL == "" {
baseURL := provider.resolveTestWeKnoraBaseURL(ctx)
if baseURL == "" {
return provider.track(classify("weknora", "WeKnora API", false, true, ProbeOutcome{ObservedAt: now}))
}
outcome := provider.httpProbeOutcome(ctx, provider.weknoraBaseURL, now)
outcome := provider.httpProbeOutcome(ctx, baseURL, now)
if outcome.Reachability == nil && provider.weknoraReadiness != nil {
outcome.WorkReadiness = provider.weknoraReadiness(ctx)
}
return provider.track(classify("weknora", "WeKnora API", true, true, outcome))
}
// productionWeKnoraProbe reports the real state of the production WeKnora
// endpoint (liveness via /health). It is advisory: publishing stays gated by the
// production switch and keeps its target in the release runtime config.
func (provider *RealProvider) productionWeKnoraProbe(ctx context.Context, now time.Time) governance.ServiceHealth {
baseURL := provider.resolveProductionWeKnoraBaseURL(ctx)
if baseURL == "" {
return provider.track(classify("weknora-production", "生产 WeKnora", false, true, ProbeOutcome{ObservedAt: now}))
}
return provider.track(classify("weknora-production", "生产 WeKnora", true, true, provider.httpProbeOutcome(ctx, baseURL, now)))
}
func (provider *RealProvider) httpProbeOutcome(ctx context.Context, baseURL string, now time.Time) ProbeOutcome {
parsed, err := url.Parse(baseURL)
outcome := ProbeOutcome{ObservedAt: now}
@@ -284,6 +296,7 @@ func (provider *RealProvider) Services(ctx context.Context) []governance.Service
health = append(health, provider.track(classify("queue", "任务队列", true, true, queueOutcome)))
health = append(health, provider.workerProbe(ctx, now)...)
health = append(health, provider.weKnoraProbe(ctx, now))
health = append(health, provider.productionWeKnoraProbe(ctx, now))
health = append(health, provider.httpProbe(ctx, "mineru", "MinerU", provider.minerUBaseURL, now))
// Not-applicable dependencies stay explicit (embedding/llm managed by
// WeKnora, redis/mq/oss not deployed).
@@ -299,10 +312,14 @@ func (provider *RealProvider) Services(ctx context.Context) []governance.Service
// Readiness blocks only on services that ARE deployed and configured and
// currently fail readiness; not_configured is surfaced as a warning elsewhere.
// advisoryHealthKeys are reported to operators but never block the platform's
// own readiness: a production endpoint outage must not stop the test pipeline.
var advisoryHealthKeys = map[string]bool{"weknora-production": true}
func overallReadiness(health []governance.ServiceHealth) (bool, []string) {
blocked := []string{}
for _, item := range health {
if !item.Applicable || !item.Configured {
if !item.Applicable || !item.Configured || advisoryHealthKeys[item.Key] {
continue
}
if item.Readiness != ReadReady {
+59
View File
@@ -5,9 +5,13 @@ import (
"errors"
"fmt"
"net"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"knowledge-governance/internal/governance"
)
func testNow() time.Time { return time.Date(2026, 9, 12, 9, 0, 0, 0, time.UTC) }
@@ -82,3 +86,58 @@ func TestSanitizeProbeErrorTruncatesLongMessages(t *testing.T) {
t.Fatalf("len=%d", len(got))
}
}
// TestProductionWeKnoraProbeReportsRealEndpointState freezes the production
// WeKnora contract: the console shows the endpoint's real state, an unset
// address is an explicit not-configured state, and no reason ever leaks the URL.
func TestProductionWeKnoraProbeReportsRealEndpointState(t *testing.T) {
// Unset address: explicit not_configured, never a fake "reachable".
provider := &RealProvider{httpClient: &http.Client{Timeout: time.Second}, health: newHealthTracker()}
health := provider.productionWeKnoraProbe(context.Background(), testNow())
if health.Key != "weknora-production" || health.Name != "生产 WeKnora" || health.Configured {
t.Fatalf("production rows must be identified: %+v", health)
}
if health.Liveness != LiveUnknown || health.Readiness != ReadNotConfigured {
t.Fatalf("unconfigured production endpoint = %+v", health)
}
// Reachable: /health is actually called on the configured address.
probed := ""
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
probed = request.URL.Path
writer.WriteHeader(http.StatusOK)
}))
defer server.Close()
provider = &RealProvider{httpClient: server.Client(), productionWeKnoraBaseURL: server.URL, health: newHealthTracker()}
health = provider.productionWeKnoraProbe(context.Background(), testNow())
if probed != "/health" || health.Liveness != LiveUp || health.Readiness != ReadReady || !health.Configured {
t.Fatalf("reachable production endpoint = %+v (probed %q)", health, probed)
}
// Reachable but refusing new work: up/blocked with a sanitized reason.
full := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
writer.WriteHeader(http.StatusTooManyRequests)
}))
defer full.Close()
provider = &RealProvider{httpClient: full.Client(), productionWeKnoraBaseURL: full.URL, health: newHealthTracker()}
health = provider.productionWeKnoraProbe(context.Background(), testNow())
if health.Liveness != LiveUp || health.Readiness != ReadBlocked || health.Reason == "" || strings.Contains(health.Reason, full.URL) {
t.Fatalf("capacity-blocked production endpoint = %+v", health)
}
}
// TestOverallReadinessTreatsProductionEndpointAsAdvisory keeps the platform's
// own readiness independent from the production endpoint's availability.
func TestOverallReadinessTreatsProductionEndpointAsAdvisory(t *testing.T) {
health := []governance.ServiceHealth{
{Key: "postgres", Name: "PostgreSQL", Configured: true, Applicable: true, Liveness: LiveUp, Readiness: ReadReady},
{Key: "weknora-production", Name: "生产 WeKnora", Configured: true, Applicable: true, Liveness: LiveDown, Readiness: ReadBlocked, Reason: "网络不可达"},
}
if ok, blocked := overallReadiness(health); !ok || len(blocked) != 0 {
t.Fatalf("production endpoint must not block readiness: ok=%v blocked=%v", ok, blocked)
}
health[0].Readiness = ReadBlocked
if ok, blocked := overallReadiness(health); ok || len(blocked) != 1 || blocked[0] != "postgres" {
t.Fatalf("real dependency failure must still block: ok=%v blocked=%v", ok, blocked)
}
}
@@ -54,6 +54,11 @@ func TestRealServicesHealthMatrix(t *testing.T) {
if byKey["weknora/r"] != ReadNotConfigured || byKey["mineru/r"] != ReadNotConfigured {
t.Fatalf("unconfigured deps must be explicit: %v %v", byKey["weknora/r"], byKey["mineru/r"])
}
// Production WeKnora is probed separately; with no address configured it is
// an explicit not-configured state, never a fake "reachable".
if byKey["weknora-production/r"] != ReadNotConfigured || byKey["weknora-production/l"] != LiveUnknown {
t.Fatalf("unconfigured production endpoint = %v/%v", byKey["weknora-production/l"], byKey["weknora-production/r"])
}
for _, key := range []string{"redis", "oss", "embedding", "llm"} {
if byKey[key+"/r"] != ReadNotApplicable || byKey[key+"/l"] != LiveUnknown {
t.Fatalf("not-deployed %s = %v/%v", key, byKey[key+"/l"], byKey[key+"/r"])
+51 -10
View File
@@ -30,6 +30,20 @@ type RealProviderConfig struct {
HTTPClient *http.Client
WeKnoraBaseURL string
MinerUBaseURL string
// TestWeKnoraResolver reads the test endpoint an admin saved in the web
// settings, so 「服务配置」is the single place the console probes. The env
// value above stays the bootstrap fallback for containers wired before the
// UI existed.
TestWeKnoraResolver func(ctx context.Context) string
// ProductionWeKnoraBaseURL lets the console show the real state of the
// production WeKnora endpoint. Publishing itself keeps reading its target
// from the release runtime config, never from here.
ProductionWeKnoraBaseURL string
// ProductionWeKnoraResolver reads the endpoint an admin saved in the web
// settings. That value is what the console probes — the web page is the
// 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
@@ -39,14 +53,40 @@ type RealProviderConfig struct {
}
type RealProvider struct {
db Database
now func() time.Time
httpClient *http.Client
weknoraBaseURL string
minerUBaseURL string
weknoraReadiness func(ctx context.Context) error
workerStaleAfter time.Duration
health *healthTracker
db Database
now func() time.Time
httpClient *http.Client
weknoraBaseURL string
minerUBaseURL string
testWeKnoraResolver func(ctx context.Context) string
productionWeKnoraBaseURL string
productionWeKnoraResolver func(ctx context.Context) string
weknoraReadiness func(ctx context.Context) error
workerStaleAfter time.Duration
health *healthTracker
}
// resolveTestWeKnoraBaseURL prefers the admin-saved web setting and falls back to
// the env bootstrap value, so the page is the place to change the test endpoint.
func (provider *RealProvider) resolveTestWeKnoraBaseURL(ctx context.Context) string {
if provider.testWeKnoraResolver != nil {
if value := strings.TrimSpace(provider.testWeKnoraResolver(ctx)); value != "" {
return value
}
}
return provider.weknoraBaseURL
}
// resolveProductionWeKnoraBaseURL prefers the admin-saved web setting and falls
// back to the env bootstrap value: the page wins, the container env only fills in
// when nobody configured it in the UI.
func (provider *RealProvider) resolveProductionWeKnoraBaseURL(ctx context.Context) string {
if provider.productionWeKnoraResolver != nil {
if value := strings.TrimSpace(provider.productionWeKnoraResolver(ctx)); value != "" {
return value
}
}
return provider.productionWeKnoraBaseURL
}
func NewRealProvider(config RealProviderConfig) (*RealProvider, error) {
@@ -63,7 +103,7 @@ func NewRealProvider(config RealProviderConfig) (*RealProvider, error) {
if stale <= 0 {
stale = time.Minute
}
return &RealProvider{db: config.DB, now: config.Now, httpClient: config.HTTPClient, weknoraBaseURL: strings.TrimSpace(config.WeKnoraBaseURL), minerUBaseURL: strings.TrimSpace(config.MinerUBaseURL), weknoraReadiness: config.WeKnoraReadiness, workerStaleAfter: stale, health: newHealthTracker()}, nil
return &RealProvider{db: config.DB, now: config.Now, httpClient: config.HTTPClient, weknoraBaseURL: strings.TrimSpace(config.WeKnoraBaseURL), minerUBaseURL: strings.TrimSpace(config.MinerUBaseURL), testWeKnoraResolver: config.TestWeKnoraResolver, productionWeKnoraBaseURL: strings.TrimSpace(config.ProductionWeKnoraBaseURL), productionWeKnoraResolver: config.ProductionWeKnoraResolver, weknoraReadiness: config.WeKnoraReadiness, workerStaleAfter: stale, health: newHealthTracker()}, nil
}
func (provider *RealProvider) Overview(ctx context.Context) (governance.MonitorOverview, error) {
@@ -73,7 +113,8 @@ func (provider *RealProvider) Overview(ctx context.Context) (governance.MonitorO
overview.Services = append(overview.Services, provider.postgresHealth(ctx, now), provider.queueHealth(ctx, now))
overview.Health = provider.Services(ctx)
overview.Services = append(overview.Services,
provider.httpHealth(ctx, "weknora", "WeKnora API", provider.weknoraBaseURL, now),
provider.httpHealth(ctx, "weknora", "WeKnora API", provider.resolveTestWeKnoraBaseURL(ctx), now),
provider.httpHealth(ctx, "weknora-production", "生产 WeKnora", provider.productionWeKnoraBaseURL, now),
governance.MonitorService{Key: "embedding", Name: "Embedding模型", State: "unknown", Detail: "由WeKnora管理,尚无独立探测端点", ObservedAt: now},
governance.MonitorService{Key: "llm", Name: "LLM模型", State: "unknown", Detail: "由WeKnora管理,尚无独立探测端点", ObservedAt: now},
provider.httpHealth(ctx, "mineru", "MinerU", provider.minerUBaseURL, now),