- 为什么:运行时读另用 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:
@@ -2,6 +2,10 @@ package reconciliation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -9,9 +13,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
|
||||
@@ -19,8 +26,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
|
||||
@@ -32,26 +38,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,
|
||||
@@ -62,6 +70,28 @@ func (p *RuntimeProvider) client(ctx context.Context) (*weknora.RuntimeClient, e
|
||||
return client, nil
|
||||
}
|
||||
|
||||
// classifyRuntimeFailure separates the reasons an operator can act on. 401/403
|
||||
// means the bound key lacks system_runtime_read; DNS/timeout/connection failures
|
||||
// mean the instance is unreachable. Everything else keeps the legacy
|
||||
// "unavailable" code so existing callers do not lose their 503 contract.
|
||||
func classifyRuntimeFailure(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
switch weknora.StatusCode(err) {
|
||||
case http.StatusUnauthorized, http.StatusForbidden:
|
||||
return fmt.Errorf("%w: %v", ErrRuntimeForbidden, err)
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
return fmt.Errorf("%w: %v", ErrRuntimeUnreachable, err)
|
||||
}
|
||||
var networkErr net.Error
|
||||
if errors.As(err, &networkErr) {
|
||||
return fmt.Errorf("%w: %v", ErrRuntimeUnreachable, err)
|
||||
}
|
||||
return ErrRuntimeUnavailable
|
||||
}
|
||||
|
||||
func (p *RuntimeProvider) Queues(ctx context.Context) (*governance.WeKnoraQueueSummary, error) {
|
||||
client, err := p.client(ctx)
|
||||
if err != nil {
|
||||
@@ -73,7 +103,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, classifyRuntimeFailure(err)
|
||||
}
|
||||
summary := &governance.WeKnoraQueueSummary{
|
||||
Available: queues.Available, QueuesError: queues.QueuesError, WorkersError: queues.WorkersError,
|
||||
@@ -99,7 +129,7 @@ func (p *RuntimeProvider) DocumentProgress(ctx context.Context, documentID strin
|
||||
if weknora.IsNotFound(err) {
|
||||
return governance.ReconciliationProgress{}, err
|
||||
}
|
||||
return governance.ReconciliationProgress{}, ErrRuntimeUnavailable
|
||||
return governance.ReconciliationProgress{}, classifyRuntimeFailure(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,8 +21,25 @@ var (
|
||||
ErrActionNotAllowed = errors.New("reconciliation action not allowed")
|
||||
ErrRemoteFailed = errors.New("reconciliation remote call failed")
|
||||
ErrRuntimeUnavailable = errors.New("weknora runtime read unavailable")
|
||||
ErrRuntimeForbidden = errors.New("weknora runtime read permission missing")
|
||||
ErrRuntimeUnreachable = errors.New("weknora runtime endpoint 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_read_forbidden"
|
||||
case errors.Is(err, ErrRuntimeUnreachable):
|
||||
return "runtime_read_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)
|
||||
@@ -328,6 +345,11 @@ func (s *Service) Progress(ctx context.Context, documentID string) (governance.R
|
||||
return progress, nil
|
||||
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
|
||||
}
|
||||
|
||||
@@ -580,3 +580,39 @@ func TestCreateRunEnqueuesJobWithinJobIDLimit(t *testing.T) {
|
||||
t.Fatalf("payload = %s", request.Payload)
|
||||
}
|
||||
}
|
||||
|
||||
type failingRuntime struct{ err error }
|
||||
|
||||
func (runtime failingRuntime) DocumentProgress(context.Context, string) (governance.ReconciliationProgress, error) {
|
||||
return governance.ReconciliationProgress{}, runtime.err
|
||||
}
|
||||
|
||||
// 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