fix(worker): 单次任务固定同一 WeKnora 连接
TargetIdentity 与业务调用原先各自 Resolve:身份核验通过后,上传/轮询/验收/ 移除的后续调用仍可能在下一次解析时切到新实例。现在 BeginTask 只解析一次, 用同一连接读取对象租户并把该不可变连接钉进返回 context;后续上传、列库恢复、 查询、chunk 读取、删除与删除后重查全部复用它。 TaskConnector 优先于 IdentityProvider;仅实现 TargetIdentity 的窄假客户端仍可 工作,生产路径不会走双解析。新增假端点测试断言一次处理只解析一次、绑定后改 当前实例仍全部打到原实例;四个 handler 的 TaskConnector 假客户端断言所有业务 调用携带同一连接令牌,覆盖上传恢复和删除重查。
This commit is contained in:
@@ -1,5 +1,15 @@
|
||||
# Changelog
|
||||
|
||||
## 开发快照 0.1.404(单次任务固定同一 WeKnora 连接)
|
||||
|
||||
### Fixed
|
||||
|
||||
- 上传、轮询、验收、移除先 `BeginTask` 解析一次并核验对象租户,返回的 context 钉住同一
|
||||
不可变连接;后续上传、列库恢复、查询、chunk 读取、删除与删除后重查都复用它,不再
|
||||
各自 `Resolve`。任务开始后页面改绑实例,旧任务也不会中途切到新实例。
|
||||
- 回归:真实客户端假端点断言一次处理只解析一次且全部打到同一实例;四个 handler 用
|
||||
TaskConnector 假客户端断言所有业务调用携带同一连接令牌,含上传恢复和删除重查。
|
||||
|
||||
## 开发快照 0.1.403(实例身份约束:绑定、发布与测试对象不跨实例)
|
||||
|
||||
### Added
|
||||
|
||||
@@ -262,6 +262,7 @@
|
||||
- 兼容:没有新配置行的旧部署继续使用文件凭据/默认绑定;保存新密钥需要独立主密钥文件 `WEKNORA_BINDING_MASTER_KEY_FILE`
|
||||
- 实例约束:网页在实例 A 核验的绑定会冻结地址/租户;文档发布执行器连实例 B 时,即使知识库 ID/租户相同也拒绝写入(`release_contract_mismatch`)。测试对象改绑实例/租户后,旧对象不会被轮询/验收/移除。
|
||||
- 证据:`internal/kbbinding`(单元 + 隔离 PostgreSQL 集成)、`KnowledgeBaseBinding.test.tsx`、`TestStartReleaseExecutionFreezesTheBindingInstanceIdentity`、`TestDocumentTargetRejectsBindingVerifiedOnAnotherInstance`
|
||||
- 单次任务连接:`TestBeginTaskPinsOneResolvedConnectionForAllCalls`;`TestPollUsesOneVerifiedConnectionForAllCalls`、`TestValidateUsesOneVerifiedConnectionForAllCalls`、`TestRemoveUsesOneVerifiedConnectionForDeleteAndReadBack`、`TestUploadUsesOneVerifiedConnectionForWrite`、`TestUploadRecoveryUsesTheSameVerifiedConnection`
|
||||
- 状态:✅ 本地验证(未做业务验收)
|
||||
|
||||
### D2 测试知识库绑定(折叠诊断;主入口已并入 D1)
|
||||
|
||||
@@ -15,15 +15,71 @@ var ErrNotConfigured = errors.New("WeKnora 有效端点/凭据未配置")
|
||||
// The readiness probe has its own 10s cap; it must not bound upload/poll calls.
|
||||
const defaultBusinessTimeout = 60 * time.Second
|
||||
|
||||
// Client resolves the effective WeKnora target on every call. It deliberately
|
||||
// owns no cached *weknora.Client: endpoint, key and binding are console-managed.
|
||||
// Client resolves the effective WeKnora target on every call. Direct calls are
|
||||
// intentionally dynamic so console-managed endpoint/key/binding changes take
|
||||
// effect. A job that performs several calls must call BeginTask first: it
|
||||
// resolves once, verifies the owning tenant and pins that immutable connection
|
||||
// in the returned context, so no later call can silently switch instances.
|
||||
type Client struct {
|
||||
Resolver readiness.Resolver
|
||||
Timeout time.Duration
|
||||
AllowDockerHTTP bool
|
||||
}
|
||||
|
||||
type taskConnection struct {
|
||||
remote *weknora.Client
|
||||
baseURL string
|
||||
}
|
||||
|
||||
type taskConnectionKey struct{}
|
||||
|
||||
func taskConnectionFrom(ctx context.Context) *taskConnection {
|
||||
connection, _ := ctx.Value(taskConnectionKey{}).(*taskConnection)
|
||||
return connection
|
||||
}
|
||||
|
||||
func (client *Client) newRemote(target readiness.Target) (*weknora.Client, error) {
|
||||
timeout := client.Timeout
|
||||
if timeout <= 0 {
|
||||
timeout = defaultBusinessTimeout
|
||||
}
|
||||
return weknora.NewClient(weknora.ClientConfig{
|
||||
BaseURL: target.BaseURL,
|
||||
APIKey: target.APIKey,
|
||||
Timeout: timeout,
|
||||
AllowDockerHTTP: client.AllowDockerHTTP,
|
||||
})
|
||||
}
|
||||
|
||||
// BeginTask resolves the endpoint/key/binding exactly once, reads the owning
|
||||
// tenant through that same connection and returns a context that pins it.
|
||||
// Upload, poll, validate and remove must pass the returned context to every
|
||||
// follow-up call and re-read, including recovery and delete read-back.
|
||||
func (client *Client) BeginTask(ctx context.Context, knowledgeBaseID string) (context.Context, weknora.InstanceIdentity, error) {
|
||||
target, err := client.Resolver.Resolve(ctx)
|
||||
if err != nil {
|
||||
return ctx, weknora.InstanceIdentity{}, err
|
||||
}
|
||||
if target.BaseURL == "" || target.APIKey == "" || knowledgeBaseID == "" {
|
||||
return ctx, weknora.InstanceIdentity{}, ErrNotConfigured
|
||||
}
|
||||
remote, err := client.newRemote(target)
|
||||
if err != nil {
|
||||
return ctx, weknora.InstanceIdentity{}, err
|
||||
}
|
||||
base, err := remote.GetKnowledgeBase(ctx, knowledgeBaseID)
|
||||
if err != nil {
|
||||
return ctx, weknora.InstanceIdentity{}, err
|
||||
}
|
||||
connection := &taskConnection{remote: remote, baseURL: weknora.NormalizeInstanceURL(target.BaseURL)}
|
||||
bound := context.WithValue(ctx, taskConnectionKey{}, connection)
|
||||
return bound, weknora.InstanceIdentity{BaseURL: connection.baseURL, TenantID: base.TenantID}, nil
|
||||
}
|
||||
|
||||
func (client *Client) with(ctx context.Context, call func(*weknora.Client) error) error {
|
||||
if connection := taskConnectionFrom(ctx); connection != nil && connection.remote != nil {
|
||||
return call(connection.remote)
|
||||
}
|
||||
target, err := client.Resolver.Resolve(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -31,16 +87,7 @@ func (client *Client) with(ctx context.Context, call func(*weknora.Client) error
|
||||
if target.BaseURL == "" || target.APIKey == "" {
|
||||
return ErrNotConfigured
|
||||
}
|
||||
timeout := client.Timeout
|
||||
if timeout <= 0 {
|
||||
timeout = defaultBusinessTimeout
|
||||
}
|
||||
remote, err := weknora.NewClient(weknora.ClientConfig{
|
||||
BaseURL: target.BaseURL,
|
||||
APIKey: target.APIKey,
|
||||
Timeout: timeout,
|
||||
AllowDockerHTTP: client.AllowDockerHTTP,
|
||||
})
|
||||
remote, err := client.newRemote(target)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -48,34 +95,25 @@ func (client *Client) with(ctx context.Context, call func(*weknora.Client) error
|
||||
}
|
||||
|
||||
func (client *Client) TargetIdentity(ctx context.Context, knowledgeBaseID string) (weknora.InstanceIdentity, error) {
|
||||
target, err := client.Resolver.Resolve(ctx)
|
||||
if err != nil {
|
||||
return weknora.InstanceIdentity{}, err
|
||||
if connection := taskConnectionFrom(ctx); connection != nil && connection.remote != nil {
|
||||
if knowledgeBaseID == "" {
|
||||
return weknora.InstanceIdentity{}, ErrNotConfigured
|
||||
}
|
||||
base, err := connection.remote.GetKnowledgeBase(ctx, knowledgeBaseID)
|
||||
if err != nil {
|
||||
return weknora.InstanceIdentity{}, err
|
||||
}
|
||||
return weknora.InstanceIdentity{BaseURL: connection.baseURL, TenantID: base.TenantID}, nil
|
||||
}
|
||||
if target.BaseURL == "" || target.APIKey == "" || knowledgeBaseID == "" {
|
||||
return weknora.InstanceIdentity{}, ErrNotConfigured
|
||||
}
|
||||
timeout := client.Timeout
|
||||
if timeout <= 0 {
|
||||
timeout = defaultBusinessTimeout
|
||||
}
|
||||
remote, err := weknora.NewClient(weknora.ClientConfig{
|
||||
BaseURL: target.BaseURL,
|
||||
APIKey: target.APIKey,
|
||||
Timeout: timeout,
|
||||
AllowDockerHTTP: client.AllowDockerHTTP,
|
||||
})
|
||||
if err != nil {
|
||||
return weknora.InstanceIdentity{}, err
|
||||
}
|
||||
base, err := remote.GetKnowledgeBase(ctx, knowledgeBaseID)
|
||||
if err != nil {
|
||||
return weknora.InstanceIdentity{}, err
|
||||
}
|
||||
return weknora.InstanceIdentity{
|
||||
BaseURL: weknora.NormalizeInstanceURL(target.BaseURL),
|
||||
TenantID: base.TenantID,
|
||||
}, nil
|
||||
return client.identityOnce(ctx, knowledgeBaseID)
|
||||
}
|
||||
|
||||
// identityOnce is the pre-task entry used by callers that only need identity.
|
||||
// Multi-call jobs use BeginTask so verification and every later call share the
|
||||
// same connection.
|
||||
func (client *Client) identityOnce(ctx context.Context, knowledgeBaseID string) (weknora.InstanceIdentity, error) {
|
||||
_, identity, err := client.BeginTask(ctx, knowledgeBaseID)
|
||||
return identity, err
|
||||
}
|
||||
|
||||
func (client *Client) UploadFile(ctx context.Context, request weknora.UploadRequest) (weknora.Knowledge, error) {
|
||||
|
||||
@@ -1,12 +1,17 @@
|
||||
package weknoraaccess
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
|
||||
"knowledge-governance/internal/readiness"
|
||||
)
|
||||
|
||||
@@ -131,3 +136,91 @@ func TestTargetIdentityReadsTheOwnedTenantFromTheCurrentBinding(t *testing.T) {
|
||||
t.Fatalf("identity = %#v", identity)
|
||||
}
|
||||
}
|
||||
|
||||
// 一次任务处理只能解析一次。BeginTask 在绑定时刻读取对象所属 tenant 并把同一个
|
||||
// 不可变连接钉进返回的 context;之后即使控制台已切到另一实例,上传、查询、
|
||||
// chunk 列表和删除(以及删除后的重查)仍必须走原实例。
|
||||
func TestBeginTaskPinsOneResolvedConnectionForAllCalls(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
hits := map[string]int{}
|
||||
serve := func(name string) *httptest.Server {
|
||||
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
mu.Lock()
|
||||
hits[name]++
|
||||
mu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch {
|
||||
case r.Method == http.MethodGet && r.URL.Path == "/api/v1/knowledge-bases/kb-1":
|
||||
_, _ = w.Write([]byte(`{"success":true,"data":{"id":"kb-1","name":"KB","tenant_id":10000}}`))
|
||||
case r.Method == http.MethodPost && r.URL.Path == "/api/v1/knowledge-bases/kb-1/knowledge/file":
|
||||
_, _ = io.Copy(io.Discard, r.Body)
|
||||
_, _ = w.Write([]byte(`{"success":true,"data":{"id":"kn-1","knowledge_base_id":"kb-1","parse_status":"pending"}}`))
|
||||
case r.Method == http.MethodGet && r.URL.Path == "/api/v1/knowledge/kn-1":
|
||||
_, _ = w.Write([]byte(`{"success":true,"data":{"id":"kn-1","knowledge_base_id":"kb-1"}}`))
|
||||
case r.Method == http.MethodGet && r.URL.Path == "/api/v1/chunks/kn-1":
|
||||
_, _ = w.Write([]byte(`{"success":true,"data":[],"total":1}`))
|
||||
case r.Method == http.MethodDelete && r.URL.Path == "/api/v1/knowledge/kn-1":
|
||||
_, _ = w.Write([]byte(`{"success":true}`))
|
||||
default:
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
}))
|
||||
}
|
||||
first, second := serve("first"), serve("second")
|
||||
defer first.Close()
|
||||
defer second.Close()
|
||||
current := first.URL
|
||||
resolves := 0
|
||||
client := &Client{Resolver: readiness.Resolver{
|
||||
Endpoint: func(context.Context) string { resolves++; return current },
|
||||
ReadKey: func() (string, error) { return "isolated-test-key", nil },
|
||||
DefaultKB: "kb-1",
|
||||
}, Timeout: time.Second}
|
||||
|
||||
taskCtx, identity, err := client.BeginTask(context.Background(), "kb-1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if identity.BaseURL != first.URL || identity.TenantID != 10000 || resolves != 1 {
|
||||
t.Fatalf("identity=%#v resolves=%d", identity, resolves)
|
||||
}
|
||||
current = second.URL // 任务开始后控制台改绑到另一实例
|
||||
|
||||
if _, err := client.UploadFile(taskCtx, weknora.UploadRequest{KnowledgeBaseID: "kb-1", FileName: "a.md", Content: bytes.NewReader([]byte("x"))}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := client.GetKnowledge(taskCtx, "kn-1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := client.ListChunks(taskCtx, "kn-1", 1, 1, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := client.DeleteKnowledge(taskCtx, "kn-1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := client.GetKnowledge(taskCtx, "kn-1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
again, err := client.TargetIdentity(taskCtx, "kb-1")
|
||||
if err != nil || again != identity {
|
||||
t.Fatalf("identity on task connection=%#v err=%v", again, err)
|
||||
}
|
||||
mu.Lock()
|
||||
firstHits, secondHits := hits["first"], hits["second"]
|
||||
mu.Unlock()
|
||||
if resolves != 1 || secondHits != 0 || firstHits != 7 {
|
||||
t.Fatalf("resolves=%d first=%d second=%d", resolves, firstHits, secondHits)
|
||||
}
|
||||
|
||||
// 反例:没有 BeginTask 的直接调用仍是动态解析,会走新当前实例。证明上面的
|
||||
// 单次解析/同一连接不是测试假阳性。
|
||||
if _, err := client.GetKnowledge(context.Background(), "kn-1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mu.Lock()
|
||||
secondHits = hits["second"]
|
||||
mu.Unlock()
|
||||
if resolves != 2 || secondHits != 1 {
|
||||
t.Fatalf("direct call resolves=%d second=%d", resolves, secondHits)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,24 +6,42 @@ import (
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
)
|
||||
|
||||
// IdentityProvider is implemented by the production WeKnora access client. Unit
|
||||
// fakes may omit it; a handler must then treat stored identities as unverifiable
|
||||
// and never write/delete/adopt an object across instances.
|
||||
// TaskConnector is implemented by the production client. BeginTask resolves the
|
||||
// endpoint/key/binding exactly once, verifies the object's owning tenant through
|
||||
// that connection and returns a context that pins the same immutable connection
|
||||
// for every later call of this job (including recovery and read-back).
|
||||
type TaskConnector interface {
|
||||
BeginTask(context.Context, string) (context.Context, weknora.InstanceIdentity, error)
|
||||
}
|
||||
|
||||
// IdentityProvider remains for narrow fakes/tests that only expose identity.
|
||||
type IdentityProvider interface {
|
||||
TargetIdentity(context.Context, string) (weknora.InstanceIdentity, error)
|
||||
}
|
||||
|
||||
func resolveIdentity(ctx context.Context, client any, knowledgeBaseID string) (weknora.InstanceIdentity, bool, error) {
|
||||
// resolveIdentity prefers BeginTask so upload/poll/validate/remove pass the
|
||||
// pinned context to every follow-up call. Returning the original ctx for
|
||||
// identity-only fakes keeps the unit seam simple; production never takes that
|
||||
// path.
|
||||
func resolveIdentity(ctx context.Context, client any, knowledgeBaseID string) (context.Context, weknora.InstanceIdentity, bool, error) {
|
||||
if connector, ok := client.(TaskConnector); ok {
|
||||
bound, identity, err := connector.BeginTask(ctx, knowledgeBaseID)
|
||||
if err != nil {
|
||||
return ctx, weknora.InstanceIdentity{}, true, err
|
||||
}
|
||||
identity.BaseURL = weknora.NormalizeInstanceURL(identity.BaseURL)
|
||||
return bound, identity, true, nil
|
||||
}
|
||||
provider, ok := client.(IdentityProvider)
|
||||
if !ok {
|
||||
return weknora.InstanceIdentity{}, false, nil
|
||||
return ctx, weknora.InstanceIdentity{}, false, nil
|
||||
}
|
||||
identity, err := provider.TargetIdentity(ctx, knowledgeBaseID)
|
||||
if err != nil {
|
||||
return weknora.InstanceIdentity{}, true, err
|
||||
return ctx, weknora.InstanceIdentity{}, true, err
|
||||
}
|
||||
identity.BaseURL = weknora.NormalizeInstanceURL(identity.BaseURL)
|
||||
return identity, true, nil
|
||||
return ctx, identity, true, nil
|
||||
}
|
||||
|
||||
// identityMatches requires BOTH the instance address and the owning tenant to
|
||||
|
||||
@@ -2,13 +2,19 @@ package testweknora
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/jobs"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/platform/spool"
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
)
|
||||
|
||||
@@ -150,3 +156,211 @@ func TestUploadRefusesToWriteAfterRebindingToAnotherInstance(t *testing.T) {
|
||||
t.Fatalf("uploadCalls=%d failure=%q", client.uploadCalls, store.uploadFailureCode)
|
||||
}
|
||||
}
|
||||
|
||||
type taskTokenKey struct{}
|
||||
|
||||
// taskClient is a normal fake TaskConnector. BeginTask pins a token in the
|
||||
// context; every business method records which token it received.
|
||||
type taskClient struct {
|
||||
identity weknora.InstanceIdentity
|
||||
identityErr error
|
||||
beginCalls int
|
||||
tokens []string
|
||||
|
||||
knowledge weknora.Knowledge
|
||||
uploadResult weknora.Knowledge
|
||||
listItems []weknora.Knowledge
|
||||
chunkTotal int64
|
||||
deleteGone bool
|
||||
getCalls int
|
||||
chunkCalls int
|
||||
deleteCalls int
|
||||
uploadCalls int
|
||||
listCalls int
|
||||
}
|
||||
|
||||
func (client *taskClient) BeginTask(ctx context.Context, _ string) (context.Context, weknora.InstanceIdentity, error) {
|
||||
client.beginCalls++
|
||||
if client.identityErr != nil {
|
||||
return ctx, weknora.InstanceIdentity{}, client.identityErr
|
||||
}
|
||||
return context.WithValue(ctx, taskTokenKey{}, "connection-1"), client.identity, nil
|
||||
}
|
||||
|
||||
func (client *taskClient) record(ctx context.Context) {
|
||||
token, _ := ctx.Value(taskTokenKey{}).(string)
|
||||
client.tokens = append(client.tokens, token)
|
||||
}
|
||||
|
||||
func (client *taskClient) GetKnowledge(ctx context.Context, _ string) (weknora.Knowledge, error) {
|
||||
client.record(ctx)
|
||||
client.getCalls++
|
||||
if client.deleteGone {
|
||||
return weknora.Knowledge{}, &weknora.HTTPError{StatusCode: 404}
|
||||
}
|
||||
return client.knowledge, nil
|
||||
}
|
||||
|
||||
func (client *taskClient) ListChunks(ctx context.Context, _ string, _, _ int, _ []string) ([]weknora.Chunk, int64, error) {
|
||||
client.record(ctx)
|
||||
client.chunkCalls++
|
||||
return []weknora.Chunk{{ID: "chunk-1"}}, client.chunkTotal, nil
|
||||
}
|
||||
|
||||
func (client *taskClient) DeleteKnowledge(ctx context.Context, _ string) error {
|
||||
client.record(ctx)
|
||||
client.deleteCalls++
|
||||
client.deleteGone = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func (client *taskClient) UploadFile(ctx context.Context, request weknora.UploadRequest) (weknora.Knowledge, error) {
|
||||
client.record(ctx)
|
||||
client.uploadCalls++
|
||||
if request.Content != nil {
|
||||
_, _ = io.Copy(io.Discard, request.Content)
|
||||
}
|
||||
return client.uploadResult, nil
|
||||
}
|
||||
|
||||
func (client *taskClient) ListKnowledge(ctx context.Context, _ string, _, _ int) ([]weknora.Knowledge, int64, error) {
|
||||
client.record(ctx)
|
||||
client.listCalls++
|
||||
return client.listItems, int64(len(client.listItems)), nil
|
||||
}
|
||||
|
||||
func (client *taskClient) assertOneConnection(t *testing.T) {
|
||||
t.Helper()
|
||||
if client.beginCalls != 1 {
|
||||
t.Fatalf("BeginTask calls=%d, want 1", client.beginCalls)
|
||||
}
|
||||
if len(client.tokens) == 0 {
|
||||
t.Fatal("no business call recorded")
|
||||
}
|
||||
for index, token := range client.tokens {
|
||||
if token != "connection-1" {
|
||||
t.Fatalf("call %d used connection %q, want pinned connection-1", index, token)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPollUsesOneVerifiedConnectionForAllCalls(t *testing.T) {
|
||||
now := time.Date(2026, 11, 19, 9, 0, 0, 0, time.UTC)
|
||||
store := &pollStoreStub{publication: postgresstore.PublicationForPoll{
|
||||
ID: "publication-1", TestKBID: "kb-1", KnowledgeID: "knowledge-1",
|
||||
TestInstanceURL: instanceA, TestInstanceTenant: 10000,
|
||||
ProcessingState: governance.ProcessingProcessing, PollSequence: 2,
|
||||
}}
|
||||
client := &taskClient{identity: weknora.InstanceIdentity{BaseURL: instanceA, TenantID: 10000},
|
||||
knowledge: weknora.Knowledge{ID: "knowledge-1", KnowledgeBaseID: "kb-1", ParseStatus: "finalizing"}}
|
||||
handler, _ := NewPollHandler(PollHandlerConfig{Store: store, Client: client, PollDelay: time.Second, StallAfter: time.Hour, Now: func() time.Time { return now }})
|
||||
if err := handler.Handle(context.Background(), jobs.Job{Payload: []byte(`{"publication_id":"publication-1","sequence":2}`)}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client.assertOneConnection(t)
|
||||
if client.getCalls != 1 || store.recordedState != governance.ProcessingFinalizing {
|
||||
t.Fatalf("getCalls=%d state=%v", client.getCalls, store.recordedState)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateUsesOneVerifiedConnectionForAllCalls(t *testing.T) {
|
||||
store := &validateStoreStub{publication: postgresstore.PublicationForValidation{
|
||||
ID: "publication-1", TestKBID: "kb-1", KnowledgeID: "knowledge-1",
|
||||
TestInstanceURL: instanceA, TestInstanceTenant: 10000,
|
||||
}}
|
||||
client := &taskClient{identity: weknora.InstanceIdentity{BaseURL: instanceA, TenantID: 10000},
|
||||
knowledge: weknora.Knowledge{ID: "knowledge-1", KnowledgeBaseID: "kb-1"}, chunkTotal: 3}
|
||||
handler, _ := NewValidateHandler(ValidateHandlerConfig{Store: store, Client: client, PolicyVersion: "structural-v1"})
|
||||
if err := handler.Handle(context.Background(), jobs.Job{Payload: []byte(`{"publication_id":"publication-1"}`)}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client.assertOneConnection(t)
|
||||
if client.getCalls != 1 || client.chunkCalls != 1 {
|
||||
t.Fatalf("get=%d chunks=%d", client.getCalls, client.chunkCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoveUsesOneVerifiedConnectionForDeleteAndReadBack(t *testing.T) {
|
||||
store := &removalStoreStub{candidate: postgresstore.PublicationForRemoval{
|
||||
ID: "publication-1", TestKBID: "kb-1", KnowledgeID: "knowledge-1",
|
||||
TestInstanceURL: instanceA, TestInstanceTenant: 10000,
|
||||
}}
|
||||
client := &taskClient{identity: weknora.InstanceIdentity{BaseURL: instanceA, TenantID: 10000},
|
||||
knowledge: weknora.Knowledge{ID: "knowledge-1", KnowledgeBaseID: "kb-1"}}
|
||||
handler, _ := NewRemoveHandler(RemoveHandlerConfig{Store: store, Client: client})
|
||||
if err := handler.Handle(context.Background(), jobs.Job{Payload: []byte(`{"publication_id":"publication-1"}`)}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client.assertOneConnection(t)
|
||||
if client.getCalls != 2 || client.deleteCalls != 1 || store.completed != "publication-1" {
|
||||
t.Fatalf("get=%d delete=%d completed=%q", client.getCalls, client.deleteCalls, store.completed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUploadUsesOneVerifiedConnectionForWrite(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
if err := os.Mkdir(filepath.Join(root, "objects"), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body := []byte("one connection only\n")
|
||||
if err := os.WriteFile(filepath.Join(root, "objects", "artifact.md"), body, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
digest := sha256.Sum256(body)
|
||||
sha := hex.EncodeToString(digest[:])
|
||||
if inspected, inspectErr := spool.InspectVerified(root, "objects/artifact.md", "md", 1024); inspectErr != nil {
|
||||
t.Fatalf("inspect fixture: %v", inspectErr)
|
||||
} else if inspected.SHA256 != sha || inspected.SizeBytes != int64(len(body)) {
|
||||
t.Fatalf("inspect fixture = %#v", inspected)
|
||||
}
|
||||
store := &uploadStoreStub{candidate: postgresstore.PublicationForUpload{
|
||||
ID: "publication-1", TestKBID: "kb-1", IngestState: governance.IngestPending,
|
||||
ProcessingState: governance.ProcessingPending, TargetScope: governance.VisibilityInternal,
|
||||
SHA256: sha, SizeBytes: int64(len(body)), ValidatedFormat: "md",
|
||||
LocalSpoolRef: "objects/artifact.md", Title: "One connection",
|
||||
}}
|
||||
client := &taskClient{identity: weknora.InstanceIdentity{BaseURL: instanceA, TenantID: 10000},
|
||||
uploadResult: weknora.Knowledge{ID: "knowledge-1", KnowledgeBaseID: "kb-1", ParseStatus: "pending"}}
|
||||
handler, err := NewUploadHandler(UploadHandlerConfig{
|
||||
Store: store, Client: client, SpoolRoot: root, MaxUploadBytes: 1024, FirstPollDelay: time.Second,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := handler.Handle(context.Background(), jobs.Job{Payload: []byte(`{"publication_id":"publication-1","target_kb_id":"kb-1","target_scope":"internal"}`)}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client.assertOneConnection(t)
|
||||
if client.uploadCalls != 1 || store.markedInstanceURL != instanceA || store.markedInstanceTenant != 10000 {
|
||||
t.Fatalf("uploads=%d marked=%s/%d", client.uploadCalls, store.markedInstanceURL, store.markedInstanceTenant)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUploadRecoveryUsesTheSameVerifiedConnection(t *testing.T) {
|
||||
store := &uploadStoreStub{candidate: postgresstore.PublicationForUpload{
|
||||
ID: "publication-1", TestKBID: "kb-1", IngestState: governance.IngestUploading,
|
||||
ProcessingState: governance.ProcessingPending, TargetScope: governance.VisibilityInternal,
|
||||
TestInstanceURL: instanceA, TestInstanceTenant: 10000,
|
||||
SHA256: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", SizeBytes: 10,
|
||||
ValidatedFormat: "md", LocalSpoolRef: "objects/artifact.md", Title: "Recovery",
|
||||
}}
|
||||
recovered := weknora.Knowledge{
|
||||
ID: "knowledge-1", KnowledgeBaseID: "kb-1",
|
||||
Metadata: map[string]any{"publication_id": "publication-1", "content_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
|
||||
}
|
||||
client := &taskClient{identity: weknora.InstanceIdentity{BaseURL: instanceA, TenantID: 10000},
|
||||
knowledge: recovered, listItems: []weknora.Knowledge{recovered}}
|
||||
handler, err := NewUploadHandler(UploadHandlerConfig{
|
||||
Store: store, Client: client, SpoolRoot: t.TempDir(), MaxUploadBytes: 1024, FirstPollDelay: time.Second,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := handler.Handle(context.Background(), jobs.Job{Payload: []byte(`{"publication_id":"publication-1","target_kb_id":"kb-1","target_scope":"internal"}`)}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client.assertOneConnection(t)
|
||||
if client.listCalls != 1 || client.uploadCalls != 0 || store.recordedKnowledgeID != "knowledge-1" {
|
||||
t.Fatalf("list=%d upload=%d recorded=%q", client.listCalls, client.uploadCalls, store.recordedKnowledgeID)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,7 +82,7 @@ func (handler *PollHandler) Handle(ctx context.Context, job jobs.Job) error {
|
||||
return ErrPollStateConflict
|
||||
}
|
||||
now := handler.now()
|
||||
identity, hasProvider, identityErr := resolveIdentity(ctx, handler.client, publication.TestKBID)
|
||||
ctx, identity, hasProvider, identityErr := resolveIdentity(ctx, handler.client, publication.TestKBID)
|
||||
if identityErr != nil {
|
||||
return ErrPollRemoteFailed
|
||||
}
|
||||
|
||||
@@ -65,7 +65,7 @@ func (handler *RemoveHandler) Handle(ctx context.Context, job jobs.Job) error {
|
||||
if err != nil {
|
||||
return ErrRemoveStateConflict
|
||||
}
|
||||
identity, hasProvider, identityErr := resolveIdentity(ctx, handler.client, candidate.TestKBID)
|
||||
ctx, identity, hasProvider, identityErr := resolveIdentity(ctx, handler.client, candidate.TestKBID)
|
||||
if identityErr != nil {
|
||||
return ErrRemoveRemoteFailed
|
||||
}
|
||||
|
||||
@@ -93,7 +93,7 @@ func (handler *UploadHandler) Handle(ctx context.Context, job jobs.Job) error {
|
||||
if payload.TargetScope != "" && payload.TargetScope != string(candidate.TargetScope) {
|
||||
return ErrUploadStateConflict
|
||||
}
|
||||
identity, hasProvider, identityErr := resolveIdentity(ctx, handler.client, candidate.TestKBID)
|
||||
ctx, identity, hasProvider, identityErr := resolveIdentity(ctx, handler.client, candidate.TestKBID)
|
||||
if identityErr != nil {
|
||||
return ErrUploadRemoteFailed
|
||||
}
|
||||
|
||||
@@ -101,7 +101,7 @@ func (handler *ValidateHandler) Handle(ctx context.Context, job jobs.Job) error
|
||||
runID = job.ID
|
||||
}
|
||||
|
||||
identity, hasProvider, identityErr := resolveIdentity(ctx, handler.client, publication.TestKBID)
|
||||
ctx, identity, hasProvider, identityErr := resolveIdentity(ctx, handler.client, publication.TestKBID)
|
||||
identityOK := !hasProvider || (identityErr == nil &&
|
||||
identityMatches(publication.TestInstanceURL, publication.TestInstanceTenant, identity))
|
||||
identityReason := ""
|
||||
|
||||
Reference in New Issue
Block a user