Files
knowledge-governance/internal/platform/weknora/runtime.go
T
Zhero & Rin 4528a55e6a feat(reconciliation): 实现导入对账后端
为什么:T6a 需要一张批次/差异表、全量只读扫描、R1-R8 判定和 finding 级处置;现有解析监控只转述台账状态,无法回答库内是否一致。
做什么:迁移 000084(upload_md5、runs/findings/actions、共享 removal_candidates 视图);WeKnora 字段与 1000/页扫描;runtime 只读客户端(0400 Key、503 降级);扫描/矩阵/动作/定时/僵死回收;9 条接口与 RBAC;overview 队列与删两张常量卡。
边界:只对测试库;对账零写请求;R1/R2 单条确认;R6 复用 /removal;R2 只管理员;生产链路未改。
验证:make verify 全绿(17 项);新增矩阵/扫描 R1-R8/零写/失败整批/动作/运行时/密钥权限测试。
2026-12-01 12:19:54 +08:00

172 lines
5.4 KiB
Go

package weknora
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
)
// RuntimeClient is the platform-level, read-only SystemAdmin client. It is a
// separate key from the tenant API key on purpose: capability
// system_runtime_read belongs to the test instance, not to one tenant.
type RuntimeClientConfig struct {
BaseURL string
APIKey string
Timeout time.Duration
MaxResponseBytes int64
AllowDockerHTTP bool
AllowPrivateHTTP bool
}
type RuntimeClient struct {
baseURL *url.URL
apiKey string
httpClient *http.Client
maxResponseBytes int64
}
func NewRuntimeClient(config RuntimeClientConfig) (*RuntimeClient, error) {
baseURL, err := url.Parse(strings.TrimSpace(config.BaseURL))
if err != nil || baseURL.Scheme == "" || baseURL.Host == "" || baseURL.User != nil ||
baseURL.RawQuery != "" || baseURL.Fragment != "" {
return nil, errors.New("invalid WeKnora runtime base URL")
}
if !HTTPAllowed(config.BaseURL, HTTPPolicy{AllowPrivateHTTP: config.AllowPrivateHTTP, AllowDockerHTTP: config.AllowDockerHTTP}) {
return nil, errors.New("WeKnora runtime base URL must use HTTPS")
}
if strings.TrimSpace(config.APIKey) == "" {
return nil, errors.New("WeKnora runtime API key is required")
}
if config.Timeout <= 0 {
return nil, errors.New("WeKnora runtime HTTP timeout must be positive")
}
if config.MaxResponseBytes <= 0 {
config.MaxResponseBytes = defaultMaxResponseBytes
}
baseURL.Path = strings.TrimRight(baseURL.Path, "/")
return &RuntimeClient{
baseURL: baseURL,
apiKey: config.APIKey,
httpClient: &http.Client{
Timeout: config.Timeout,
CheckRedirect: func(*http.Request, []*http.Request) error {
return http.ErrUseLastResponse
},
},
maxResponseBytes: config.MaxResponseBytes,
}, nil
}
type RuntimeQueues struct {
Available bool `json:"available"`
QueuesError bool `json:"queues_error"`
WorkersError bool `json:"workers_error"`
Queues []RuntimeQueue `json:"queues"`
Timestamp int64 `json:"timestamp"`
}
type RuntimeQueue struct {
Name string `json:"name"`
Pool string `json:"pool"`
Pending int `json:"pending"`
Active int `json:"active"`
Scheduled int `json:"scheduled"`
Retry int `json:"retry"`
Archived int `json:"archived"`
Processed int `json:"processed"`
Failed int `json:"failed"`
}
type RuntimeDocumentProgress struct {
Document RuntimeDocument `json:"document"`
Failures []RuntimeFailure `json:"failures"`
HasMoreFailures bool `json:"has_more_failures"`
}
type RuntimeDocument struct {
ID string `json:"id"`
KnowledgeBaseID string `json:"knowledge_base_id"`
Title string `json:"title"`
ParseStatus string `json:"parse_status"`
IngestionStatus string `json:"ingestion_status"`
WikiStatus string `json:"wiki_status"`
Stages []RuntimeStage `json:"stages"`
UpdatedAt time.Time `json:"updated_at"`
}
type RuntimeStage struct {
Name string `json:"name"`
Status string `json:"status"`
ErrorCode string `json:"error_code"`
FinishedAt *time.Time `json:"finished_at"`
}
type RuntimeFailure struct {
TaskType string `json:"task_type"`
FailCount int `json:"fail_count"`
FailedAt time.Time `json:"failed_at"`
LastError string `json:"last_error"`
}
func (c *RuntimeClient) Queues(ctx context.Context) (RuntimeQueues, error) {
var response RuntimeQueues
if err := c.get(ctx, "/api/v1/system/admin/runtime/queues", &response); err != nil {
return RuntimeQueues{}, err
}
return response, nil
}
func (c *RuntimeClient) DocumentProgress(ctx context.Context, knowledgeID string) (RuntimeDocumentProgress, error) {
if !validPathSegment(knowledgeID) || len(knowledgeID) > 64 {
return RuntimeDocumentProgress{}, errors.New("invalid knowledge ID")
}
var envelope struct {
Success bool `json:"success"`
Data RuntimeDocumentProgress `json:"data"`
}
if err := c.get(ctx, "/api/v1/system/admin/runtime/documents/"+knowledgeID, &envelope); err != nil {
return RuntimeDocumentProgress{}, err
}
if !envelope.Success {
return RuntimeDocumentProgress{}, errors.New("WeKnora returned an unsuccessful document progress response")
}
return envelope.Data, nil
}
func (c *RuntimeClient) get(ctx context.Context, path string, target any) error {
endpoint := *c.baseURL
endpoint.Path = strings.TrimRight(c.baseURL.Path, "/") + path
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint.String(), nil)
if err != nil {
return errors.New("create WeKnora runtime request")
}
req.Header.Set("Accept", "application/json")
req.Header.Set("X-API-Key", c.apiKey)
resp, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("send WeKnora runtime request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
return &HTTPError{StatusCode: resp.StatusCode}
}
payload, err := io.ReadAll(io.LimitReader(resp.Body, c.maxResponseBytes+1))
if err != nil {
return errors.New("read WeKnora runtime response")
}
if int64(len(payload)) > c.maxResponseBytes {
return errors.New("WeKnora runtime response exceeds size limit")
}
if err := json.Unmarshal(payload, target); err != nil {
return errors.New("decode WeKnora runtime response")
}
return nil
}