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 }