fix(reconciliation): 运行时读复用知识库绑定 Key
- 为什么:运行时读另用 WEKNORA_RUNTIME_KEY_FILE(0400 文件、启动读一次),当前部署没有该文件,队列与处理详情恒不可用;换 Key 还要重启,且与绑定页不同步。 - 做什么:RuntimeProvider 改为每次请求经 kbbinding.Resolve(EnvTest) 取地址与 Key,与 reconciliationRemote 共用同一 resolver;删除配置字段/校验、ReadRuntimeKeyFile 与测试、compose/env、启动 WARN。 - 三态:绑定不可用→503 runtime_read_unavailable;上游 401/403→502 runtime_read_forbidden;超时/DNS→502 runtime_read_unreachable;overview 增 weknora_queue_error,页面三句不同文案并保留 WeKnora 跳转链接。 - 同步:openapi progress 契约与 502、需求书 §5/Q7、阶段计划、运维手册、CHANGELOG。 - 验证:make verify 17 项 success;新增换 Key 二次请求头、401/403/不可达分类、Service 透传、overview 原因码、页面三文案用例。
This commit is contained in:
@@ -59,9 +59,6 @@ type Config struct {
|
||||
// WeKnoraBindingMasterKeyFile 是「知识库绑定」密文的独立主密钥文件(0600、32字节)。
|
||||
// 未配置时新页面仍可读旧部署的 file 凭据,但保存新密钥会被拒绝(不落明文)。
|
||||
WeKnoraBindingMasterKeyFile string
|
||||
// WeKnoraRuntimeKeyFile 是测试实例平台级只读 Key(0400,绝对路径)。空值=
|
||||
// runtime/* 与 overview 队列降级为不可用;对账本身只用租户 Key。
|
||||
WeKnoraRuntimeKeyFile string
|
||||
// ReconciliationSettings:批次执行参数。全部可配,但都有安全默认值。
|
||||
// ReconciliationEnabled 是「导入对账」自身的开关:只决定对账服务是否接线,
|
||||
// 与 TEST_WEKNORA_ENABLED(旧测试库取件/上传链路)解耦——对账只用租户 Key。
|
||||
@@ -242,7 +239,6 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
ExternalRoutingKnowledgeBaseID: strings.TrimSpace(getenv("TEST_EXTERNAL_WEKNORA_KB_ID")),
|
||||
TestWeKnoraAPIKeyFile: valueOrDefault(getenv("TEST_WEKNORA_API_KEY_FILE"), "/run/secrets/test_weknora_api_key"),
|
||||
WeKnoraBindingMasterKeyFile: strings.TrimSpace(getenv("WEKNORA_BINDING_MASTER_KEY_FILE")),
|
||||
WeKnoraRuntimeKeyFile: strings.TrimSpace(getenv("WEKNORA_RUNTIME_KEY_FILE")),
|
||||
ReconciliationDailyAt: valueOrDefault(strings.TrimSpace(getenv("RECONCILIATION_DAILY_AT")), "02:00"),
|
||||
ReconciliationTimezone: valueOrDefault(strings.TrimSpace(getenv("RECONCILIATION_TIMEZONE")), "Asia/Shanghai"),
|
||||
ReconciliationScheduleEnabled: true,
|
||||
@@ -406,9 +402,6 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
if config.WeKnoraBindingMasterKeyFile != "" && !filepath.IsAbs(config.WeKnoraBindingMasterKeyFile) {
|
||||
return Config{}, errors.New("WEKNORA_BINDING_MASTER_KEY_FILE must be an absolute path")
|
||||
}
|
||||
if config.WeKnoraRuntimeKeyFile != "" && !filepath.IsAbs(config.WeKnoraRuntimeKeyFile) {
|
||||
return Config{}, errors.New("WEKNORA_RUNTIME_KEY_FILE must be an absolute path")
|
||||
}
|
||||
if raw := getenv("RECONCILIATION_ENABLED"); raw != "" {
|
||||
config.ReconciliationEnabled, err = strconv.ParseBool(raw)
|
||||
if err != nil {
|
||||
|
||||
@@ -115,6 +115,10 @@ type MonitorOverview struct {
|
||||
// WeKnoraQueues is a safe projection of the test instance runtime queues.
|
||||
// nil means "not configured or unreadable", never "healthy empty".
|
||||
WeKnoraQueues *WeKnoraQueueSummary `json:"weknora_queues"`
|
||||
// WeKnoraQueueError carries the classified reason when WeKnoraQueues is nil
|
||||
// (binding missing, key lacks permission, or instance unreachable). Empty
|
||||
// means no runtime queue reader was wired.
|
||||
WeKnoraQueueError string `json:"weknora_queue_error,omitempty"`
|
||||
}
|
||||
|
||||
// WeKnoraQueueSummary is the bounded queue projection the console may show.
|
||||
|
||||
@@ -47,9 +47,9 @@ func writeReconciliationError(w http.ResponseWriter, err error) {
|
||||
case errors.Is(err, reconciliation.ErrActionConflict), errors.Is(err, reconciliation.ErrActionNotAllowed):
|
||||
writeJSON(w, http.StatusConflict, map[string]string{"error": "reconciliation_state_changed", "code": "reconciliation_state_changed"})
|
||||
case errors.Is(err, reconciliation.ErrRuntimeForbidden):
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "runtime_key_forbidden", "code": "runtime_key_forbidden"})
|
||||
writeJSON(w, http.StatusBadGateway, map[string]string{"error": "runtime_key_forbidden", "code": "runtime_key_forbidden"})
|
||||
case errors.Is(err, reconciliation.ErrRuntimeUnreachable):
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "runtime_unreachable", "code": "runtime_unreachable"})
|
||||
writeJSON(w, http.StatusBadGateway, map[string]string{"error": "runtime_unreachable", "code": "runtime_unreachable"})
|
||||
case errors.Is(err, reconciliation.ErrRuntimeUnavailable):
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "runtime_read_unavailable", "code": "runtime_read_unavailable"})
|
||||
case errors.Is(err, reconciliation.ErrRemoteFailed):
|
||||
|
||||
@@ -147,12 +147,13 @@ func TestReconciliationProgressRejectsMalformedDocumentIDWith400(t *testing.T) {
|
||||
|
||||
func TestReconciliationProgressClassifiesRuntimeFailures(t *testing.T) {
|
||||
cases := []struct {
|
||||
err error
|
||||
code string
|
||||
err error
|
||||
status int
|
||||
code string
|
||||
}{
|
||||
{reconciliation.ErrRuntimeForbidden, "runtime_key_forbidden"},
|
||||
{reconciliation.ErrRuntimeUnreachable, "runtime_unreachable"},
|
||||
{reconciliation.ErrRuntimeUnavailable, "runtime_read_unavailable"},
|
||||
{reconciliation.ErrRuntimeForbidden, http.StatusBadGateway, "runtime_key_forbidden"},
|
||||
{reconciliation.ErrRuntimeUnreachable, http.StatusBadGateway, "runtime_unreachable"},
|
||||
{reconciliation.ErrRuntimeUnavailable, http.StatusServiceUnavailable, "runtime_read_unavailable"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
handler, err := NewHandler(Config{Store: &fakeJobStore{}, Reconciliation: &reconciliationServiceStub{err: tc.err}})
|
||||
@@ -161,8 +162,8 @@ func TestReconciliationProgressClassifiesRuntimeFailures(t *testing.T) {
|
||||
}
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, reconciliationRequest(http.MethodGet, "/api/v1/reconciliation/documents/doc-1/progress", roleViewer, ""))
|
||||
if recorder.Code != http.StatusServiceUnavailable || !strings.Contains(recorder.Body.String(), tc.code) {
|
||||
t.Fatalf("%v = %d %s, want 503 %s", tc.err, recorder.Code, recorder.Body.String(), tc.code)
|
||||
if recorder.Code != tc.status || !strings.Contains(recorder.Body.String(), tc.code) {
|
||||
t.Fatalf("%v = %d %s, want %d %s", tc.err, recorder.Code, recorder.Body.String(), tc.status, tc.code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/reconciliation"
|
||||
)
|
||||
|
||||
type Database interface {
|
||||
@@ -133,9 +134,7 @@ func (provider *RealProvider) Overview(ctx context.Context) (governance.MonitorO
|
||||
governance.MonitorService{Key: "oss", Name: "OSS", State: "unknown", Detail: "未配置独立健康探测", ObservedAt: now},
|
||||
)
|
||||
if provider.runtimeQueues != nil {
|
||||
if queues, queueErr := provider.runtimeQueues.Queues(ctx); queueErr == nil {
|
||||
overview.WeKnoraQueues = queues
|
||||
}
|
||||
overview.WeKnoraQueues, overview.WeKnoraQueueError = runtimeQueueProjection(ctx, provider.runtimeQueues)
|
||||
}
|
||||
rows, err := provider.db.Query(ctx, `SELECT p.test_kb_id,
|
||||
CASE WHEN COUNT(DISTINCT p.target_scope)=1 THEN MIN(p.target_scope) ELSE 'mixed' END,
|
||||
@@ -396,3 +395,16 @@ func monitorStageDetail(ingestState, processingState, errorCode string) string {
|
||||
return "等待远端状态更新"
|
||||
}
|
||||
}
|
||||
|
||||
// runtimeQueueProjection keeps the overview at 200 while stating why the queue
|
||||
// is absent: nil queues + the classified code, never a healthy empty queue.
|
||||
func runtimeQueueProjection(ctx context.Context, reader QueueReader) (*governance.WeKnoraQueueSummary, string) {
|
||||
if reader == nil {
|
||||
return nil, ""
|
||||
}
|
||||
queues, err := reader.Queues(ctx)
|
||||
if err != nil {
|
||||
return nil, reconciliation.RuntimeErrorCode(err)
|
||||
}
|
||||
return queues, ""
|
||||
}
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
package monitoring
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/reconciliation"
|
||||
)
|
||||
|
||||
func TestParseCPUStatAndMemoryInfo(t *testing.T) {
|
||||
idle, total, err := parseCPUStat("cpu 100 20 30 400 50 6 7 8 0 0\n")
|
||||
@@ -22,3 +29,41 @@ func TestCPUPercentUsesTwoMonotonicSamples(t *testing.T) {
|
||||
t.Fatal("non-monotonic CPU counters must fail closed to zero")
|
||||
}
|
||||
}
|
||||
|
||||
type stubQueueReader struct {
|
||||
summary *governance.WeKnoraQueueSummary
|
||||
err error
|
||||
}
|
||||
|
||||
func (reader stubQueueReader) Queues(context.Context) (*governance.WeKnoraQueueSummary, error) {
|
||||
return reader.summary, reader.err
|
||||
}
|
||||
|
||||
func TestRuntimeQueueProjectionStatesWhyQueueIsAbsent(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
err error
|
||||
code string
|
||||
}{
|
||||
{name: "binding unavailable", err: reconciliation.ErrRuntimeUnavailable, code: "runtime_read_unavailable"},
|
||||
{name: "key forbidden", err: reconciliation.ErrRuntimeForbidden, code: "runtime_read_forbidden"},
|
||||
{name: "unreachable", err: reconciliation.ErrRuntimeUnreachable, code: "runtime_read_unreachable"},
|
||||
{name: "unclassified", err: errors.New("boom"), code: ""},
|
||||
}
|
||||
for _, testCase := range cases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
queues, code := runtimeQueueProjection(context.Background(), stubQueueReader{err: testCase.err})
|
||||
if queues != nil || code != testCase.code {
|
||||
t.Fatalf("queues=%v code=%q, want nil/%q", queues, code, testCase.code)
|
||||
}
|
||||
})
|
||||
}
|
||||
summary := &governance.WeKnoraQueueSummary{Available: true}
|
||||
queues, code := runtimeQueueProjection(context.Background(), stubQueueReader{summary: summary})
|
||||
if queues != summary || code != "" {
|
||||
t.Fatalf("available queue projection = %v/%q", queues, code)
|
||||
}
|
||||
if queues, code := runtimeQueueProjection(context.Background(), nil); queues != nil || code != "" {
|
||||
t.Fatalf("unwired projection = %v/%q", queues, code)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,42 +47,3 @@ func ReadAPIKeyFile(path string) (string, error) {
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
|
||||
// ReadRuntimeKeyFile reads the platform-level read-only key. Q7 fixes the
|
||||
// contract at mode 0400: unlike tenant keys (0600), this key must not be
|
||||
// readable by the process owner's group and never leaves the API process.
|
||||
func ReadRuntimeKeyFile(path string) (string, error) {
|
||||
fd, err := syscall.Open(path, syscall.O_RDONLY|syscall.O_NOFOLLOW, 0)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("open runtime key file: %w", err)
|
||||
}
|
||||
file := os.NewFile(uintptr(fd), "weknora-runtime-key")
|
||||
if file == nil {
|
||||
_ = syscall.Close(fd)
|
||||
return "", errors.New("open runtime key file: invalid file descriptor")
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
info, err := file.Stat()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("inspect runtime key file: %w", err)
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
return "", errors.New("runtime key file must be a regular file")
|
||||
}
|
||||
if info.Mode().Perm() != 0o400 {
|
||||
return "", errors.New("runtime key file permissions must be 0400")
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(file, maxAPIKeyFileBytes+1))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read runtime key file: %w", err)
|
||||
}
|
||||
if len(body) > maxAPIKeyFileBytes {
|
||||
return "", errors.New("runtime key file is too large")
|
||||
}
|
||||
key := strings.TrimSpace(string(body))
|
||||
if key == "" {
|
||||
return "", errors.New("runtime key file is empty")
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
|
||||
@@ -53,20 +53,3 @@ func TestReadAPIKeyFileRejectsUnsafeInputsWithoutLeakingContent(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadRuntimeKeyFileRequires0400(t *testing.T) {
|
||||
path := t.TempDir() + "/runtime-key"
|
||||
if err := os.WriteFile(path, []byte("runtime-secret\n"), 0o400); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
key, err := ReadRuntimeKeyFile(path)
|
||||
if err != nil || key != "runtime-secret" {
|
||||
t.Fatalf("key=%q err=%v", key, err)
|
||||
}
|
||||
if err := os.Chmod(path, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := ReadRuntimeKeyFile(path); err == nil {
|
||||
t.Fatal("0600 runtime key must be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package reconciliation
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -10,9 +11,12 @@ import (
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
)
|
||||
|
||||
// RuntimeConfig.Resolve runs for every request instead of once at startup: the
|
||||
// runtime read uses the same knowledge-base binding (test environment) as the
|
||||
// reconciliation remote, so an admin saving a new key must take effect on the
|
||||
// next request without restarting the API.
|
||||
type RuntimeConfig struct {
|
||||
BaseURL func(context.Context) string
|
||||
APIKey string
|
||||
Resolve func(context.Context) (baseURL, apiKey string, err error)
|
||||
Timeout time.Duration
|
||||
AllowDockerHTTP bool
|
||||
AllowPrivateHTTP bool
|
||||
@@ -20,8 +24,7 @@ type RuntimeConfig struct {
|
||||
}
|
||||
|
||||
type RuntimeProvider struct {
|
||||
baseURL func(context.Context) string
|
||||
apiKey string
|
||||
resolve func(context.Context) (baseURL, apiKey string, err error)
|
||||
timeout time.Duration
|
||||
allowDockerHTTP bool
|
||||
allowPrivateHTTP bool
|
||||
@@ -33,26 +36,28 @@ func NewRuntimeProvider(config RuntimeConfig) *RuntimeProvider {
|
||||
config.Now = time.Now
|
||||
}
|
||||
return &RuntimeProvider{
|
||||
baseURL: config.BaseURL, apiKey: strings.TrimSpace(config.APIKey), timeout: config.Timeout,
|
||||
resolve: config.Resolve, timeout: config.Timeout,
|
||||
allowDockerHTTP: config.AllowDockerHTTP, allowPrivateHTTP: config.AllowPrivateHTTP, now: config.Now,
|
||||
}
|
||||
}
|
||||
|
||||
func (p *RuntimeProvider) Available() bool {
|
||||
return p != nil && p.apiKey != "" && p.baseURL != nil
|
||||
}
|
||||
|
||||
func (p *RuntimeProvider) client(ctx context.Context) (*weknora.RuntimeClient, error) {
|
||||
if !p.Available() {
|
||||
if p == nil || p.resolve == nil {
|
||||
return nil, ErrRuntimeUnavailable
|
||||
}
|
||||
baseURL := strings.TrimSpace(p.baseURL(ctx))
|
||||
if baseURL == "" {
|
||||
baseURL, apiKey, err := p.resolve(ctx)
|
||||
if err != nil {
|
||||
// Not configured, storage locked, or the saved key cannot be opened:
|
||||
// all of them mean "no usable binding", never "upstream rejected us".
|
||||
return nil, ErrRuntimeUnavailable
|
||||
}
|
||||
baseURL, apiKey = strings.TrimSpace(baseURL), strings.TrimSpace(apiKey)
|
||||
if baseURL == "" || apiKey == "" {
|
||||
return nil, ErrRuntimeUnavailable
|
||||
}
|
||||
client, err := weknora.NewRuntimeClient(weknora.RuntimeClientConfig{
|
||||
BaseURL: baseURL,
|
||||
APIKey: p.apiKey,
|
||||
APIKey: apiKey,
|
||||
Timeout: p.timeout,
|
||||
AllowDockerHTTP: p.allowDockerHTTP,
|
||||
AllowPrivateHTTP: p.allowPrivateHTTP,
|
||||
@@ -63,6 +68,18 @@ func (p *RuntimeProvider) client(ctx context.Context) (*weknora.RuntimeClient, e
|
||||
return client, nil
|
||||
}
|
||||
|
||||
// classifyRuntimeReadFailure separates the two reasons an operator can act on:
|
||||
// 401/403 means the bound key lacks system_runtime_read; everything else
|
||||
// (timeout, DNS, connection, upstream error) means the read itself failed.
|
||||
func classifyRuntimeReadFailure(err error) error {
|
||||
switch weknora.StatusCode(err) {
|
||||
case http.StatusUnauthorized, http.StatusForbidden:
|
||||
return ErrRuntimeForbidden
|
||||
default:
|
||||
return ErrRuntimeUnreachable
|
||||
}
|
||||
}
|
||||
|
||||
func (p *RuntimeProvider) Queues(ctx context.Context) (*governance.WeKnoraQueueSummary, error) {
|
||||
client, err := p.client(ctx)
|
||||
if err != nil {
|
||||
@@ -74,7 +91,7 @@ func (p *RuntimeProvider) Queues(ctx context.Context) (*governance.WeKnoraQueueS
|
||||
defer cancel()
|
||||
queues, err := client.Queues(queueCtx)
|
||||
if err != nil {
|
||||
return nil, ErrRuntimeUnavailable
|
||||
return nil, classifyRuntimeReadFailure(err)
|
||||
}
|
||||
summary := &governance.WeKnoraQueueSummary{
|
||||
Available: queues.Available, QueuesError: queues.QueuesError, WorkersError: queues.WorkersError,
|
||||
@@ -97,14 +114,10 @@ func (p *RuntimeProvider) DocumentProgress(ctx context.Context, documentID strin
|
||||
}
|
||||
detail, err := client.DocumentProgress(ctx, documentID)
|
||||
if err != nil {
|
||||
switch {
|
||||
case weknora.IsNotFound(err):
|
||||
if weknora.IsNotFound(err) {
|
||||
return governance.ReconciliationProgress{}, err
|
||||
case weknora.StatusCode(err) == http.StatusUnauthorized || weknora.StatusCode(err) == http.StatusForbidden:
|
||||
return governance.ReconciliationProgress{}, ErrRuntimeForbidden
|
||||
default:
|
||||
return governance.ReconciliationProgress{}, ErrRuntimeUnreachable
|
||||
}
|
||||
return governance.ReconciliationProgress{}, classifyRuntimeReadFailure(err)
|
||||
}
|
||||
progress := governance.ReconciliationProgress{
|
||||
DocumentID: detail.Document.ID, ParseStatus: detail.Document.ParseStatus,
|
||||
|
||||
@@ -7,12 +7,17 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
)
|
||||
|
||||
func staticConnection(baseURL, apiKey string) func(context.Context) (string, string, error) {
|
||||
return func(context.Context) (string, string, error) { return baseURL, apiKey, nil }
|
||||
}
|
||||
|
||||
func TestRuntimeProviderMapsQueuesAndTruncatesFailures(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("X-API-Key") != "runtime-key" {
|
||||
@@ -37,8 +42,8 @@ func TestRuntimeProviderMapsQueuesAndTruncatesFailures(t *testing.T) {
|
||||
}))
|
||||
defer server.Close()
|
||||
provider := NewRuntimeProvider(RuntimeConfig{
|
||||
BaseURL: func(context.Context) string { return server.URL },
|
||||
APIKey: "runtime-key", Timeout: 5 * time.Second,
|
||||
Resolve: staticConnection(server.URL, "runtime-key"),
|
||||
Timeout: 5 * time.Second,
|
||||
})
|
||||
queues, err := provider.Queues(context.Background())
|
||||
if err != nil || !queues.Available || len(queues.Queues) != 1 || queues.Queues[0].Pending != 3 {
|
||||
@@ -53,22 +58,135 @@ func TestRuntimeProviderMapsQueuesAndTruncatesFailures(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// The binding is editable from the console, so the provider must ask for the
|
||||
// key on every request instead of freezing the first one it sees.
|
||||
func TestRuntimeProviderResolvesKeyOnEveryRequest(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
var seen []string
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
mu.Lock()
|
||||
seen = append(seen, r.Header.Get("X-API-Key"))
|
||||
mu.Unlock()
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"available": true, "queues": []map[string]any{}})
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
mu.Lock()
|
||||
key := "old-key"
|
||||
mu.Unlock()
|
||||
provider := NewRuntimeProvider(RuntimeConfig{
|
||||
Resolve: func(context.Context) (string, string, error) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return server.URL, key, nil
|
||||
},
|
||||
Timeout: 5 * time.Second,
|
||||
})
|
||||
if _, err := provider.Queues(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mu.Lock()
|
||||
key = "new-key"
|
||||
mu.Unlock()
|
||||
if _, err := provider.Queues(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if len(seen) != 2 || seen[0] != "old-key" || seen[1] != "new-key" {
|
||||
t.Fatalf("request keys = %v, want [old-key new-key]", seen)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntimeProviderClassifiesUpstreamFailures(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
status int
|
||||
want error
|
||||
}{
|
||||
{name: "unauthorized", status: http.StatusUnauthorized, want: ErrRuntimeForbidden},
|
||||
{name: "forbidden", status: http.StatusForbidden, want: ErrRuntimeForbidden},
|
||||
{name: "server error still unavailable", status: http.StatusInternalServerError, want: ErrRuntimeUnavailable},
|
||||
}
|
||||
for _, testCase := range cases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(testCase.status)
|
||||
}))
|
||||
defer server.Close()
|
||||
provider := NewRuntimeProvider(RuntimeConfig{
|
||||
Resolve: staticConnection(server.URL, "runtime-key"),
|
||||
Timeout: 5 * time.Second,
|
||||
})
|
||||
if _, err := provider.Queues(context.Background()); !errors.Is(err, testCase.want) {
|
||||
t.Fatalf("queues err = %v, want %v", err, testCase.want)
|
||||
}
|
||||
if _, err := provider.DocumentProgress(context.Background(), "doc-1"); !errors.Is(err, testCase.want) {
|
||||
t.Fatalf("progress err = %v, want %v", err, testCase.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntimeProviderClassifiesUnreachable(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
|
||||
url := server.URL
|
||||
server.Close()
|
||||
provider := NewRuntimeProvider(RuntimeConfig{
|
||||
Resolve: staticConnection(url, "runtime-key"),
|
||||
Timeout: time.Second,
|
||||
})
|
||||
if _, err := provider.Queues(context.Background()); !errors.Is(err, ErrRuntimeUnreachable) {
|
||||
t.Fatalf("queues err = %v, want %v", err, ErrRuntimeUnreachable)
|
||||
}
|
||||
if _, err := provider.DocumentProgress(context.Background(), "doc-1"); !errors.Is(err, ErrRuntimeUnreachable) {
|
||||
t.Fatalf("progress err = %v, want %v", err, ErrRuntimeUnreachable)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntimeProviderUnavailableAndNotFound(t *testing.T) {
|
||||
unavailable := NewRuntimeProvider(RuntimeConfig{BaseURL: func(context.Context) string { return "https://example.test" }})
|
||||
unavailable := NewRuntimeProvider(RuntimeConfig{
|
||||
Resolve: func(context.Context) (string, string, error) { return "", "", nil },
|
||||
})
|
||||
if _, err := unavailable.Queues(context.Background()); !errors.Is(err, ErrRuntimeUnavailable) {
|
||||
t.Fatalf("unconfigured queues err=%v", err)
|
||||
}
|
||||
broken := NewRuntimeProvider(RuntimeConfig{
|
||||
Resolve: func(context.Context) (string, string, error) {
|
||||
return "", "", errors.New("binding storage is not ready")
|
||||
},
|
||||
})
|
||||
if _, err := broken.DocumentProgress(context.Background(), "doc-1"); !errors.Is(err, ErrRuntimeUnavailable) {
|
||||
t.Fatalf("broken binding err=%v", err)
|
||||
}
|
||||
server := httptest.NewServer(http.NotFoundHandler())
|
||||
defer server.Close()
|
||||
provider := NewRuntimeProvider(RuntimeConfig{
|
||||
BaseURL: func(context.Context) string { return server.URL },
|
||||
APIKey: "runtime-key", Timeout: 5 * time.Second,
|
||||
Resolve: staticConnection(server.URL, "runtime-key"),
|
||||
Timeout: 5 * time.Second,
|
||||
})
|
||||
if _, err := provider.DocumentProgress(context.Background(), "missing"); err == nil || weknora.StatusCode(err) != 404 {
|
||||
t.Fatalf("missing document err=%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntimeErrorCodeDistinguishesStates(t *testing.T) {
|
||||
cases := map[string]error{
|
||||
"runtime_read_unavailable": ErrRuntimeUnavailable,
|
||||
"runtime_read_forbidden": ErrRuntimeForbidden,
|
||||
"runtime_read_unreachable": ErrRuntimeUnreachable,
|
||||
"": errors.New("unclassified"),
|
||||
}
|
||||
for want, err := range cases {
|
||||
if got := RuntimeErrorCode(err); got != want {
|
||||
t.Fatalf("RuntimeErrorCode(%v) = %q, want %q", err, got, want)
|
||||
}
|
||||
}
|
||||
if got := RuntimeErrorCode(nil); got != "" {
|
||||
t.Fatalf("RuntimeErrorCode(nil) = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// The progress passthrough is a projection, not a proxy: whatever extra fields
|
||||
// the platform endpoint returns (keys, authorization headers, token echoes) must
|
||||
// never reach the browser. This guards the shape if someone later switches to
|
||||
@@ -89,8 +207,8 @@ func TestRuntimeProviderDropsSensitiveUpstreamFields(t *testing.T) {
|
||||
}))
|
||||
defer server.Close()
|
||||
provider := NewRuntimeProvider(RuntimeConfig{
|
||||
BaseURL: func(context.Context) string { return server.URL },
|
||||
APIKey: "runtime-key", Timeout: 5 * time.Second,
|
||||
Resolve: staticConnection(server.URL, "runtime-key"),
|
||||
Timeout: 5 * time.Second,
|
||||
})
|
||||
progress, err := provider.DocumentProgress(context.Background(), "doc-1")
|
||||
if err != nil {
|
||||
|
||||
@@ -21,12 +21,27 @@ var (
|
||||
ErrActionNotAllowed = errors.New("reconciliation action not allowed")
|
||||
ErrRemoteFailed = errors.New("reconciliation remote call failed")
|
||||
ErrRuntimeUnavailable = errors.New("weknora runtime read unavailable")
|
||||
// ErrRuntimeForbidden / ErrRuntimeUnreachable 把「Key 无权限」与「连不上」
|
||||
// ErrRuntimeForbidden / ErrRuntimeUnreachable 把「Key 无权限」与「连不上」
|
||||
// 从 ErrRuntimeUnavailable 里拆出来:页面要给两种不同的中文,不能再折叠。
|
||||
ErrRuntimeForbidden = errors.New("weknora runtime key forbidden")
|
||||
ErrRuntimeUnreachable = errors.New("weknora runtime read unreachable")
|
||||
)
|
||||
|
||||
// RuntimeErrorCode is the stable code the browser branches on. Unclassified
|
||||
// failures return "" so callers keep their generic fallback instead of guessing.
|
||||
func RuntimeErrorCode(err error) string {
|
||||
switch {
|
||||
case errors.Is(err, ErrRuntimeForbidden):
|
||||
return "runtime_key_forbidden"
|
||||
case errors.Is(err, ErrRuntimeUnreachable):
|
||||
return "runtime_unreachable"
|
||||
case errors.Is(err, ErrRuntimeUnavailable):
|
||||
return "runtime_read_unavailable"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
type Store interface {
|
||||
ReapStaleReconciliationRuns(context.Context, time.Time, time.Duration) (int64, error)
|
||||
ClaimReconciliationRun(context.Context, governance.ReconciliationRun, time.Time) (governance.ReconciliationRun, error)
|
||||
@@ -335,6 +350,11 @@ func (s *Service) Progress(ctx context.Context, documentID string) (governance.R
|
||||
return governance.ReconciliationProgress{}, err
|
||||
case weknora.StatusCode(err) == 404:
|
||||
return governance.ReconciliationProgress{}, ErrNotFound
|
||||
case errors.Is(err, ErrRuntimeUnavailable), errors.Is(err, ErrRuntimeForbidden), errors.Is(err, ErrRuntimeUnreachable):
|
||||
// The provider already classified the failure; collapsing it here would
|
||||
// erase the distinction between "no binding", "no permission" and
|
||||
// "unreachable" that the page needs.
|
||||
return governance.ReconciliationProgress{}, err
|
||||
default:
|
||||
return governance.ReconciliationProgress{}, ErrRuntimeUnavailable
|
||||
}
|
||||
|
||||
@@ -581,17 +581,38 @@ func TestCreateRunEnqueuesJobWithinJobIDLimit(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
type progressRuntimeStub struct{ err error }
|
||||
type failingRuntime struct{ err error }
|
||||
|
||||
func (s progressRuntimeStub) DocumentProgress(context.Context, string) (governance.ReconciliationProgress, error) {
|
||||
return governance.ReconciliationProgress{}, s.err
|
||||
func (runtime failingRuntime) DocumentProgress(context.Context, string) (governance.ReconciliationProgress, error) {
|
||||
return governance.ReconciliationProgress{}, runtime.err
|
||||
}
|
||||
|
||||
func TestProgressPassesProviderClassificationInsteadOfRefolding(t *testing.T) {
|
||||
for _, want := range []error{ErrRuntimeForbidden, ErrRuntimeUnreachable, ErrRuntimeUnavailable} {
|
||||
service := &Service{runtime: progressRuntimeStub{err: want}}
|
||||
if _, err := service.Progress(context.Background(), "doc-1"); !errors.Is(err, want) {
|
||||
t.Fatalf("Progress err=%v, want %v", err, want)
|
||||
}
|
||||
// Progress must not re-collapse the provider's classification: the page needs
|
||||
// "no binding", "no permission" and "unreachable" to stay distinct.
|
||||
func TestProgressPreservesClassifiedRuntimeErrors(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
err error
|
||||
want error
|
||||
}{
|
||||
{name: "unavailable", err: ErrRuntimeUnavailable, want: ErrRuntimeUnavailable},
|
||||
{name: "forbidden", err: ErrRuntimeForbidden, want: ErrRuntimeForbidden},
|
||||
{name: "unreachable", err: ErrRuntimeUnreachable, want: ErrRuntimeUnreachable},
|
||||
{name: "not found", err: &weknora.HTTPError{StatusCode: http.StatusNotFound}, want: ErrNotFound},
|
||||
{name: "unclassified", err: errors.New("boom"), want: ErrRuntimeUnavailable},
|
||||
}
|
||||
for _, testCase := range cases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
service, err := New(Config{
|
||||
Store: &fakeReconciliationStore{}, Remote: &fakeReconciliationRemote{},
|
||||
Runtime: failingRuntime{err: testCase.err},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := service.Progress(context.Background(), "doc-1"); !errors.Is(err, testCase.want) {
|
||||
t.Fatalf("Progress err = %v, want %v", err, testCase.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user