feat(settings): bind internal/external knowledge bases from the UI
Routing targets move from env-only to a UI-managed binding (migration 000034 routing_kb_bindings, single active row): - GET/PUT /api/v1/routing-bindings + /options: env defaults act as the bootstrap fallback; a UI binding wins and takes effect immediately (per-request resolution, no restart), and clearing falls back to env - PUT validates against the connected WeKnora instance (real knowledge base list via the scoped API key) and rejects same-KB bindings; saves require the admin role - route/catalog capabilities now resolve through the binding so both annotation paths share one source of truth - system settings > 服务配置 gains a 知识库绑定 panel: dropdown picker (or raw ID when WeKnora is unreachable) showing bound name, origin (UI vs env default) and last author - contract tests: OpenAPI, handler matrix (fallback, validation, same-KB rejection, capability resolution), frontend fetch/save layer
This commit is contained in:
@@ -117,6 +117,11 @@ func classifyRole(method, path string) string {
|
||||
if strings.Contains(path, "/settings/revisions") {
|
||||
return roleAdmin
|
||||
}
|
||||
// Binding the internal/external knowledge bases re-routes every future
|
||||
// annotation: admin-only, like the roster and production authority.
|
||||
if path == "/api/v1/routing-bindings" && method != http.MethodGet {
|
||||
return roleAdmin
|
||||
}
|
||||
// Everything else that mutates (review, batch, seal, confirm, start, retry,
|
||||
// route visibility, disable) is engineer work; viewers cannot POST at all.
|
||||
return roleEngineer
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
)
|
||||
|
||||
// RoutingBindingStore persists the UI-managed knowledge base bindings
|
||||
// (migration 000034). Empty stored values fall back to env defaults.
|
||||
type RoutingBindingStore interface {
|
||||
LoadRoutingKBBindings(context.Context) (string, string, string, error)
|
||||
SaveRoutingKBBindings(context.Context, string, string, string) error
|
||||
}
|
||||
|
||||
// KnowledgeBaseLister enumerates candidate knowledge bases in the connected
|
||||
// WeKnora so the settings page offers a picker instead of raw UUIDs.
|
||||
type KnowledgeBaseLister interface {
|
||||
ListKnowledgeBases(context.Context) ([]weknora.KnowledgeBase, error)
|
||||
}
|
||||
|
||||
type routingBindingView struct {
|
||||
InternalKBID string `json:"internal_kb_id"`
|
||||
ExternalKBID string `json:"external_kb_id"`
|
||||
InternalEnvFallback bool `json:"internal_env_fallback"`
|
||||
ExternalEnvFallback bool `json:"external_env_fallback"`
|
||||
InternalBoundByUI bool `json:"internal_bound_by_ui"`
|
||||
ExternalBoundByUI bool `json:"external_bound_by_ui"`
|
||||
InternalKBName string `json:"internal_kb_name"`
|
||||
ExternalKBName string `json:"external_kb_name"`
|
||||
UpdatedBy string `json:"updated_by"`
|
||||
WeKnoraConnected bool `json:"weknora_connected"`
|
||||
}
|
||||
|
||||
type routingKnowledgeBaseOption struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
KnowledgeCount int64 `json:"knowledge_count"`
|
||||
}
|
||||
|
||||
// effectiveRoutingTargets resolves (internal, external) WeKnora knowledge
|
||||
// base ids for this request: UI bindings win, environment defaults fill the
|
||||
// unbound side. Load failures behave as "unbound" (fail toward env, never
|
||||
// toward a half-configured new target).
|
||||
func (config Config) effectiveRoutingTargets(ctx context.Context) (string, string) {
|
||||
internal, external := config.InternalRoutingKnowledgeBaseID, config.ExternalRoutingKnowledgeBaseID
|
||||
if config.RoutingBindings == nil {
|
||||
return internal, external
|
||||
}
|
||||
storedInternal, storedExternal, _, err := config.RoutingBindings.LoadRoutingKBBindings(ctx)
|
||||
if err != nil {
|
||||
return internal, external
|
||||
}
|
||||
if storedInternal != "" {
|
||||
internal = storedInternal
|
||||
}
|
||||
if storedExternal != "" {
|
||||
external = storedExternal
|
||||
}
|
||||
return internal, external
|
||||
}
|
||||
|
||||
func (config Config) routingBindingNames(ctx context.Context) (map[string]string, bool) {
|
||||
if config.KnowledgeBases == nil {
|
||||
return nil, false
|
||||
}
|
||||
bases, err := config.KnowledgeBases.ListKnowledgeBases(ctx)
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
names := make(map[string]string, len(bases))
|
||||
for _, base := range bases {
|
||||
names[base.ID] = base.Name
|
||||
}
|
||||
return names, true
|
||||
}
|
||||
|
||||
func (config Config) handleRoutingBindings(w http.ResponseWriter, r *http.Request) {
|
||||
names, connected := config.routingBindingNames(r.Context())
|
||||
storedInternal, storedExternal, updatedBy, err := config.RoutingBindings.LoadRoutingKBBindings(r.Context())
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not load routing bindings"})
|
||||
return
|
||||
}
|
||||
internal, external := config.effectiveRoutingTargets(r.Context())
|
||||
view := routingBindingView{
|
||||
InternalKBID: internal, ExternalKBID: external,
|
||||
InternalBoundByUI: storedInternal != "", ExternalBoundByUI: storedExternal != "",
|
||||
InternalEnvFallback: storedInternal == "" && config.InternalRoutingKnowledgeBaseID != "",
|
||||
ExternalEnvFallback: storedExternal == "" && config.ExternalRoutingKnowledgeBaseID != "",
|
||||
InternalKBName: names[storedInternal], ExternalKBName: names[storedExternal],
|
||||
UpdatedBy: updatedBy, WeKnoraConnected: connected,
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": view})
|
||||
}
|
||||
|
||||
func (config Config) handleRoutingKnowledgeBaseOptions(w http.ResponseWriter, r *http.Request) {
|
||||
if config.KnowledgeBases == nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "WeKnora connection is not configured"})
|
||||
return
|
||||
}
|
||||
bases, err := config.KnowledgeBases.ListKnowledgeBases(r.Context())
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusBadGateway, map[string]string{"error": "could not list WeKnora knowledge bases"})
|
||||
return
|
||||
}
|
||||
options := make([]routingKnowledgeBaseOption, 0, len(bases))
|
||||
for _, base := range bases {
|
||||
options = append(options, routingKnowledgeBaseOption{ID: base.ID, Name: base.Name, KnowledgeCount: base.KnowledgeCount})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": options})
|
||||
}
|
||||
|
||||
func (config Config) handleSaveRoutingBindings(w http.ResponseWriter, r *http.Request) {
|
||||
var input struct {
|
||||
InternalKBID string `json:"internal_kb_id"`
|
||||
ExternalKBID string `json:"external_kb_id"`
|
||||
}
|
||||
if err := decodeStrictJSON(r, &input); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid request body"})
|
||||
return
|
||||
}
|
||||
internal := strings.TrimSpace(input.InternalKBID)
|
||||
external := strings.TrimSpace(input.ExternalKBID)
|
||||
for _, id := range []string{internal, external} {
|
||||
if id != "" && !validCatalogID(id) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "knowledge base ID is invalid"})
|
||||
return
|
||||
}
|
||||
}
|
||||
if internal != "" && internal == external {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "对内与对外必须绑定不同的知识库"})
|
||||
return
|
||||
}
|
||||
// When WeKnora is reachable the binding must name a real knowledge base;
|
||||
// offline saves fall through to the DB so the page never hard-fails, but
|
||||
// the response reports connected=false honestly.
|
||||
names, connected := config.routingBindingNames(r.Context())
|
||||
if connected {
|
||||
if internal != "" {
|
||||
if _, ok := names[internal]; !ok {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "对内绑定的知识库在该 WeKnora 实例中不存在"})
|
||||
return
|
||||
}
|
||||
}
|
||||
if external != "" {
|
||||
if _, ok := names[external]; !ok {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "对外绑定的知识库在该 WeKnora 实例中不存在"})
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := config.RoutingBindings.SaveRoutingKBBindings(r.Context(), internal, external, actorFor(r)); err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not save routing bindings"})
|
||||
return
|
||||
}
|
||||
config.handleRoutingBindings(w, r)
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
)
|
||||
|
||||
type bindingStoreFake struct {
|
||||
internal string
|
||||
external string
|
||||
saver string
|
||||
}
|
||||
|
||||
func (fake *bindingStoreFake) LoadRoutingKBBindings(context.Context) (string, string, string, error) {
|
||||
return fake.internal, fake.external, fake.saver, nil
|
||||
}
|
||||
|
||||
func (fake *bindingStoreFake) SaveRoutingKBBindings(_ context.Context, internal, external, updatedBy string) error {
|
||||
fake.internal, fake.external, fake.saver = internal, external, updatedBy
|
||||
return nil
|
||||
}
|
||||
|
||||
type kbListerFake struct {
|
||||
bases []weknora.KnowledgeBase
|
||||
err error
|
||||
}
|
||||
|
||||
func (fake *kbListerFake) ListKnowledgeBases(context.Context) ([]weknora.KnowledgeBase, error) {
|
||||
return fake.bases, fake.err
|
||||
}
|
||||
|
||||
func bindingsTestHandler(t *testing.T, store RoutingBindingStore, lister KnowledgeBaseLister, envInternal, envExternal string) http.Handler {
|
||||
t.Helper()
|
||||
handler, err := NewHandler(Config{
|
||||
Store: &fakeJobStore{}, Monitor: nil,
|
||||
InternalRoutingKnowledgeBaseID: envInternal, ExternalRoutingKnowledgeBaseID: envExternal,
|
||||
RoutingBindings: store, KnowledgeBases: lister,
|
||||
Now: func() time.Time { return time.Date(2026, time.September, 13, 8, 0, 0, 0, time.UTC) },
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewHandler: %v", err)
|
||||
}
|
||||
return handler
|
||||
}
|
||||
|
||||
func TestRoutingBindingsReadFallsBackToEnv(t *testing.T) {
|
||||
store := &bindingStoreFake{internal: "", external: "fd-ext"}
|
||||
handler := bindingsTestHandler(t, store, &kbListerFake{bases: []weknora.KnowledgeBase{{ID: "fd-ext", Name: "对外库"}}}, "sn-internal", "env-external")
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/routing-bindings", nil))
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d body %s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
var envelope struct {
|
||||
Data routingBindingView `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &envelope); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
view := envelope.Data
|
||||
if view.InternalKBID != "sn-internal" || !view.InternalEnvFallback || view.InternalBoundByUI {
|
||||
t.Fatalf("internal side = %#v", view)
|
||||
}
|
||||
if view.ExternalKBID != "fd-ext" || !view.ExternalBoundByUI || view.ExternalKBName != "对外库" {
|
||||
t.Fatalf("external side = %#v", view)
|
||||
}
|
||||
if !view.WeKnoraConnected {
|
||||
t.Fatalf("connected must be true: %#v", view)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoutingBindingsSaveValidatesAgainstWeKnora(t *testing.T) {
|
||||
store := &bindingStoreFake{}
|
||||
lister := &kbListerFake{bases: []weknora.KnowledgeBase{{ID: "kb-in", Name: "对内库"}, {ID: "kb-ex", Name: "对外库"}}}
|
||||
handler := bindingsTestHandler(t, store, lister, "", "")
|
||||
body := `{"internal_kb_id":"kb-in","external_kb_id":"missing"}`
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodPut, "/api/v1/routing-bindings", strings.NewReader(body)))
|
||||
if recorder.Code != http.StatusBadRequest || !strings.Contains(recorder.Body.String(), "对外绑定的知识库") {
|
||||
t.Fatalf("unknown target must be rejected: %d %s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
if store.internal != "" {
|
||||
t.Fatalf("rejected save must not persist: %#v", store)
|
||||
}
|
||||
recorder = httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodPut, "/api/v1/routing-bindings", strings.NewReader(`{"internal_kb_id":"kb-in","external_kb_id":"kb-in"}`)))
|
||||
if recorder.Code != http.StatusBadRequest || !strings.Contains(recorder.Body.String(), "不同的知识库") {
|
||||
t.Fatalf("same-kb binding must be rejected: %d %s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
recorder = httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodPut, "/api/v1/routing-bindings", strings.NewReader(`{"internal_kb_id":"kb-in","external_kb_id":"kb-ex"}`)))
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("valid binding must save: %d %s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
if store.internal != "kb-in" || store.external != "kb-ex" {
|
||||
t.Fatalf("store = %#v", store)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteCatalogFilesUsesUIBinding(t *testing.T) {
|
||||
store := &bindingStoreFake{internal: "ui-internal", external: "ui-external"}
|
||||
handler := bindingsTestHandler(t, store, &kbListerFake{}, "env-internal", "env-external")
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/source-catalog/routing-capabilities", nil))
|
||||
var envelope struct {
|
||||
Data map[string]bool `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &envelope); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !envelope.Data["internal_enabled"] || !envelope.Data["external_enabled"] {
|
||||
t.Fatalf("capabilities = %#v", envelope.Data)
|
||||
}
|
||||
}
|
||||
+33
-11
@@ -99,6 +99,8 @@ type Config struct {
|
||||
Monitor MonitorProvider
|
||||
InternalRoutingKnowledgeBaseID string
|
||||
ExternalRoutingKnowledgeBaseID string
|
||||
RoutingBindings RoutingBindingStore
|
||||
KnowledgeBases KnowledgeBaseLister
|
||||
Now func() time.Time
|
||||
RequireWeKnoraReady bool
|
||||
ProductionReleaseRequestsEnabled bool
|
||||
@@ -202,8 +204,26 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
mux.HandleFunc("GET /api/v1/source-catalog/change-sets/latest", func(w http.ResponseWriter, r *http.Request) {
|
||||
getLatestCatalogChangeSet(w, r, config.Store)
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/source-catalog/routing-capabilities", func(w http.ResponseWriter, _ *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]bool{"internal_enabled": config.InternalRoutingKnowledgeBaseID != "", "external_enabled": config.ExternalRoutingKnowledgeBaseID != ""}})
|
||||
mux.HandleFunc("GET /api/v1/source-catalog/routing-capabilities", func(w http.ResponseWriter, r *http.Request) {
|
||||
internal, external := config.effectiveRoutingTargets(r.Context())
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]bool{"internal_enabled": internal != "", "external_enabled": external != ""}})
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/routing-bindings", func(w http.ResponseWriter, r *http.Request) {
|
||||
if config.RoutingBindings == nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "routing bindings storage unavailable"})
|
||||
return
|
||||
}
|
||||
config.handleRoutingBindings(w, r)
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/routing-bindings/options", func(w http.ResponseWriter, r *http.Request) {
|
||||
config.handleRoutingKnowledgeBaseOptions(w, r)
|
||||
})
|
||||
mux.HandleFunc("PUT /api/v1/routing-bindings", func(w http.ResponseWriter, r *http.Request) {
|
||||
if config.RoutingBindings == nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "routing bindings storage unavailable"})
|
||||
return
|
||||
}
|
||||
config.handleSaveRoutingBindings(w, r)
|
||||
})
|
||||
mux.HandleFunc("POST /api/v1/source-catalog/route", func(w http.ResponseWriter, r *http.Request) {
|
||||
routeCatalogFiles(w, r, config)
|
||||
@@ -651,22 +671,23 @@ func routeCatalogFiles(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
policy = strings.TrimSpace(input.Visibility)
|
||||
}
|
||||
visibility := governance.Visibility(policy)
|
||||
effectiveInternal, effectiveExternal := config.effectiveRoutingTargets(r.Context())
|
||||
targetKnowledgeBaseIDs := make([]string, 0, 2)
|
||||
switch visibility {
|
||||
case governance.VisibilityInternal:
|
||||
if config.InternalRoutingKnowledgeBaseID != "" {
|
||||
targetKnowledgeBaseIDs = append(targetKnowledgeBaseIDs, config.InternalRoutingKnowledgeBaseID)
|
||||
if effectiveInternal != "" {
|
||||
targetKnowledgeBaseIDs = append(targetKnowledgeBaseIDs, effectiveInternal)
|
||||
}
|
||||
case governance.VisibilityExternal:
|
||||
if config.ExternalRoutingKnowledgeBaseID != "" {
|
||||
targetKnowledgeBaseIDs = append(targetKnowledgeBaseIDs, config.ExternalRoutingKnowledgeBaseID)
|
||||
if effectiveExternal != "" {
|
||||
targetKnowledgeBaseIDs = append(targetKnowledgeBaseIDs, effectiveExternal)
|
||||
}
|
||||
case governance.VisibilityBoth:
|
||||
if config.InternalRoutingKnowledgeBaseID != "" {
|
||||
targetKnowledgeBaseIDs = append(targetKnowledgeBaseIDs, config.InternalRoutingKnowledgeBaseID)
|
||||
if effectiveInternal != "" {
|
||||
targetKnowledgeBaseIDs = append(targetKnowledgeBaseIDs, effectiveInternal)
|
||||
}
|
||||
if config.ExternalRoutingKnowledgeBaseID != "" {
|
||||
targetKnowledgeBaseIDs = append(targetKnowledgeBaseIDs, config.ExternalRoutingKnowledgeBaseID)
|
||||
if effectiveExternal != "" {
|
||||
targetKnowledgeBaseIDs = append(targetKnowledgeBaseIDs, effectiveExternal)
|
||||
}
|
||||
case governance.VisibilityBlocked:
|
||||
default:
|
||||
@@ -1728,10 +1749,11 @@ func confirmCatalogChangeSet(w http.ResponseWriter, r *http.Request, config Conf
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid change set confirmation"})
|
||||
return
|
||||
}
|
||||
internalTarget, externalTarget := config.effectiveRoutingTargets(r.Context())
|
||||
result, replayed, err := config.Store.ConfirmCatalogChangeSetWithOperation(r.Context(), governance.ConfirmCatalogChangeSetRequest{
|
||||
ChangeSetID: r.PathValue("id"), ItemSeqs: input.ItemSeqs,
|
||||
OperatorRef: actorFor(r), Reason: input.Reason,
|
||||
InternalTargetKBID: config.InternalRoutingKnowledgeBaseID, ExternalTargetKBID: config.ExternalRoutingKnowledgeBaseID,
|
||||
InternalTargetKBID: internalTarget, ExternalTargetKBID: externalTarget,
|
||||
Now: config.Now().UTC(),
|
||||
}, operationID)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
DROP TABLE IF EXISTS routing_kb_bindings;
|
||||
@@ -0,0 +1,14 @@
|
||||
-- Policy-driven ingestion, step 3: routable knowledge-base bindings move from
|
||||
-- environment-only configuration into the UI. A single row stores which
|
||||
-- WeKnora knowledge base receives 对内 and which receives 对外 annotations.
|
||||
-- The env-supplied defaults stay as a bootstrap fallback only.
|
||||
CREATE TABLE routing_kb_bindings (
|
||||
id TEXT PRIMARY KEY DEFAULT 'active' CHECK (id = 'active'),
|
||||
internal_kb_id VARCHAR(64) NOT NULL DEFAULT '',
|
||||
external_kb_id VARCHAR(64) NOT NULL DEFAULT '',
|
||||
updated_by VARCHAR(64) NOT NULL DEFAULT '',
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
INSERT INTO routing_kb_bindings(id,internal_kb_id,external_kb_id,updated_by)
|
||||
VALUES('active','','','system:migration');
|
||||
@@ -11,8 +11,8 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("loadMigrations() error = %v", err)
|
||||
}
|
||||
if len(migrations) != 33 {
|
||||
t.Fatalf("migration count = %d, want 33", len(migrations))
|
||||
if len(migrations) != 34 {
|
||||
t.Fatalf("migration count = %d, want 34", len(migrations))
|
||||
}
|
||||
if migrations[0].Version != 1 || !strings.Contains(migrations[0].UpSQL, "CREATE TABLE IF NOT EXISTS jobs") {
|
||||
t.Fatalf("migration 1 = %#v", migrations[0])
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
// RoutingBinding is the UI-managed knowledge base binding row. Empty ids mean
|
||||
// "not bound in the UI"; callers fall back to their environment defaults.
|
||||
type RoutingBinding struct {
|
||||
InternalKBID string
|
||||
ExternalKBID string
|
||||
UpdatedBy string
|
||||
}
|
||||
|
||||
// LoadRoutingKBBindings reads the single active binding row. A missing row
|
||||
// reads back as unbound rather than an error.
|
||||
func (s *Store) LoadRoutingKBBindings(ctx context.Context) (string, string, string, error) {
|
||||
var binding RoutingBinding
|
||||
err := s.db.QueryRow(ctx, `SELECT internal_kb_id,external_kb_id,updated_by FROM routing_kb_bindings WHERE id='active'`).
|
||||
Scan(&binding.InternalKBID, &binding.ExternalKBID, &binding.UpdatedBy)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return "", "", "", nil
|
||||
}
|
||||
if err != nil {
|
||||
return "", "", "", errors.New("load routing kb bindings")
|
||||
}
|
||||
return binding.InternalKBID, binding.ExternalKBID, binding.UpdatedBy, nil
|
||||
}
|
||||
|
||||
// SaveRoutingKBBindings upserts the binding row. Each side is either empty
|
||||
// (unbind, fall back to env) or a knowledge base id validated by the caller.
|
||||
func (s *Store) SaveRoutingKBBindings(ctx context.Context, internalID, externalID, updatedBy string) error {
|
||||
_, err := s.db.Exec(ctx, `
|
||||
INSERT INTO routing_kb_bindings(id,internal_kb_id,external_kb_id,updated_by,updated_at)
|
||||
VALUES('active',$1,$2,$3,NOW())
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
internal_kb_id=EXCLUDED.internal_kb_id,
|
||||
external_kb_id=EXCLUDED.external_kb_id,
|
||||
updated_by=EXCLUDED.updated_by,
|
||||
updated_at=NOW()`, internalID, externalID, updatedBy)
|
||||
if err != nil {
|
||||
return errors.New("save routing kb bindings")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -221,6 +221,19 @@ func (c *Client) ListKnowledge(ctx context.Context, knowledgeBaseID string, page
|
||||
return response.Data, response.Total, nil
|
||||
}
|
||||
|
||||
// ListKnowledgeBases lists the knowledge bases visible to this API key so the
|
||||
// UI can bind routing targets without humans copying UUIDs.
|
||||
func (c *Client) ListKnowledgeBases(ctx context.Context) ([]KnowledgeBase, error) {
|
||||
var response knowledgeBaseListResponse
|
||||
if err := c.doJSON(ctx, http.MethodGet, "/api/v1/knowledge-bases", nil, &response); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !response.Success {
|
||||
return nil, errors.New("WeKnora returned an unsuccessful knowledge base list")
|
||||
}
|
||||
return response.Data, nil
|
||||
}
|
||||
|
||||
func (c *Client) ListChunks(ctx context.Context, knowledgeID string, page, pageSize int, chunkTypes []string) ([]Chunk, int64, error) {
|
||||
if !validPathSegment(knowledgeID) || !validPage(page, pageSize) {
|
||||
return nil, 0, errors.New("invalid chunk list request")
|
||||
|
||||
@@ -62,6 +62,20 @@ type knowledgeListResponse struct {
|
||||
PageSize int `json:"page_size"`
|
||||
}
|
||||
|
||||
// KnowledgeBase is the routing-relevant projection of a WeKnora knowledge
|
||||
// base as listed by GET /api/v1/knowledge-bases.
|
||||
type KnowledgeBase struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
KnowledgeCount int64 `json:"knowledge_count"`
|
||||
ChunkCount int64 `json:"chunk_count"`
|
||||
}
|
||||
|
||||
type knowledgeBaseListResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Data []KnowledgeBase `json:"data"`
|
||||
}
|
||||
|
||||
type chunkListResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Data []Chunk `json:"data"`
|
||||
|
||||
Reference in New Issue
Block a user