aac8538372
build / build (push) Successful in 1m48s
- 迁移 000084 保存对内/对外绑定名称快照;清除密钥后仍显示已绑定库,不再只显示裸 ID - 测试/生产换绑只重指向同一侧的旧目标,避免测试保存误改另一环境的待入库 - 已保存连接但没有可用密钥时拒绝改绑定,禁止静默回落文件 Key - 生产换绑返回重指向/退休数量,页面提示与测试侧一致 验证:make verify(含隔离 PostgreSQL 集成用例)15/15 通过
246 lines
11 KiB
Go
246 lines
11 KiB
Go
package httpapi
|
||
|
||
import (
|
||
"context"
|
||
"net/http"
|
||
"strings"
|
||
"time"
|
||
|
||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||
"knowledge-governance/internal/platform/weknora"
|
||
)
|
||
|
||
// ProductionBindingStore persists the UI-managed 源库 → 目标库 mapping
|
||
// (migration 000044). An empty side means "unbound": the release then keeps the
|
||
// historical same-id semantics and fails closed at the contract check when no
|
||
// such base exists on the target.
|
||
type ProductionBindingStore interface {
|
||
LoadProductionKBBindings(context.Context) (string, string, string, error)
|
||
LoadProductionKBBindingNames(context.Context) (string, string, error)
|
||
// SaveProductionKBBindingsWithReplan also re-points 待入库 publications
|
||
// that were still waiting for the previous production target.
|
||
SaveProductionKBBindingsWithReplan(ctx context.Context, save postgresstore.ProductionBindingSave, previous, effective postgresstore.EffectiveKBIDs, now time.Time) (postgresstore.RoutingBindingReplanResult, error)
|
||
// ProductionExecutionCounts reports frozen vs still re-targetable release
|
||
// items. A binding change never rewrites a target that was already frozen
|
||
// when an execution started; the count is how the page says so.
|
||
ProductionExecutionCounts(ctx context.Context) (frozen int, retargetable int, err error)
|
||
}
|
||
|
||
// ProductionKnowledgeBaseLister enumerates the knowledge bases of the production
|
||
// WeKnora, resolved from the operator-managed service configuration.
|
||
type ProductionKnowledgeBaseLister interface {
|
||
ListProductionKnowledgeBases(ctx context.Context, baseURL string) ([]weknora.KnowledgeBase, error)
|
||
}
|
||
|
||
type productionBindingView struct {
|
||
InternalKBID string `json:"internal_kb_id"`
|
||
ExternalKBID string `json:"external_kb_id"`
|
||
InternalKBName string `json:"internal_kb_name"`
|
||
ExternalKBName string `json:"external_kb_name"`
|
||
UpdatedBy string `json:"updated_by"`
|
||
ProductionBaseURL string `json:"production_base_url"`
|
||
ProductionConnected bool `json:"production_connected"`
|
||
ProductionMessage string `json:"production_message"`
|
||
// Frozen / Retargetable describe what a binding change can still affect.
|
||
Frozen int `json:"frozen"`
|
||
Retargetable int `json:"retargetable"`
|
||
// Replanned / RetiredDuplicates describe what THIS save did to 待入库 items.
|
||
Replanned int `json:"replanned"`
|
||
RetiredDuplicates int `json:"retired_duplicates"`
|
||
}
|
||
|
||
// WeKnoraConnectionResolver reads the admin-managed connection for one
|
||
// environment. When it answers, that endpoint is the only truth.
|
||
type WeKnoraConnectionResolver interface {
|
||
Resolve(ctx context.Context, environment string) (endpoint string, apiKey string, ok bool)
|
||
Configured(ctx context.Context, environment string) (bool, error)
|
||
}
|
||
|
||
// connectionKeyUnusable distinguishes "a saved row whose key was cleared or
|
||
// cannot be decrypted" from "saved and usable, but the endpoint is down". Only
|
||
// the former must block a binding save; the latter stays an honest warning.
|
||
func (config Config) connectionKeyUnusable(ctx context.Context, environment string) bool {
|
||
if config.WeKnoraConnectionResolver == nil {
|
||
return false
|
||
}
|
||
if _, _, ok := config.WeKnoraConnectionResolver.Resolve(ctx, environment); ok {
|
||
return false
|
||
}
|
||
configured, err := config.WeKnoraConnectionResolver.Configured(ctx, environment)
|
||
return err == nil && configured
|
||
}
|
||
|
||
// productionTargetBaseURL is the production endpoint the picker reads from: the
|
||
// connection card first, the operator-managed 「服务配置 · 生产地址」 second, the
|
||
// deployment default last.
|
||
func (config Config) productionTargetBaseURL(ctx context.Context) string {
|
||
if config.WeKnoraConnectionResolver != nil {
|
||
if endpoint, _, ok := config.WeKnoraConnectionResolver.Resolve(ctx, "production"); ok {
|
||
return endpoint
|
||
}
|
||
}
|
||
if settings, err := config.Store.GetActiveUISettings(ctx); err == nil {
|
||
if resolved := strings.TrimSpace(settings.ProductionWeKnoraBaseURL); resolved != "" {
|
||
return resolved
|
||
}
|
||
}
|
||
return strings.TrimSpace(config.ProductionWeKnoraBaseURL)
|
||
}
|
||
|
||
// productionKnowledgeBases lists the production-side bases. The second return is
|
||
// the honest reason a listing was impossible, so the page can say why instead of
|
||
// pretending there are none.
|
||
func (config Config) productionKnowledgeBases(ctx context.Context) ([]weknora.KnowledgeBase, string) {
|
||
if config.ProductionKnowledgeBases == nil {
|
||
return nil, "生产知识库列表未接入(PRODUCTION_WEKNORA_BASE_URL / PRODUCTION_WEKNORA_API_KEY_FILE)"
|
||
}
|
||
baseURL := config.productionTargetBaseURL(ctx)
|
||
if baseURL == "" {
|
||
return nil, "未配置生产地址(系统设置 → 生产知识库绑定 → 连接卡)"
|
||
}
|
||
bases, err := config.ProductionKnowledgeBases.ListProductionKnowledgeBases(ctx, baseURL)
|
||
if err != nil {
|
||
return nil, "生产 WeKnora 不可用:" + err.Error()
|
||
}
|
||
return bases, ""
|
||
}
|
||
|
||
func (config Config) productionBindingPayload(ctx context.Context, replan postgresstore.RoutingBindingReplanResult) (productionBindingView, error) {
|
||
storedInternal, storedExternal, updatedBy, err := config.ProductionBindings.LoadProductionKBBindings(ctx)
|
||
if err != nil {
|
||
return productionBindingView{}, err
|
||
}
|
||
storedInternalName, storedExternalName, err := config.ProductionBindings.LoadProductionKBBindingNames(ctx)
|
||
if err != nil {
|
||
return productionBindingView{}, err
|
||
}
|
||
bases, message := config.productionKnowledgeBases(ctx)
|
||
names := make(map[string]string, len(bases))
|
||
for _, base := range bases {
|
||
names[base.ID] = base.Name
|
||
}
|
||
nameFor := func(id, storedName string) string {
|
||
if id == "" {
|
||
return ""
|
||
}
|
||
if message == "" {
|
||
return names[id]
|
||
}
|
||
return storedName
|
||
}
|
||
frozen, retargetable := 0, 0
|
||
if frozenItems, retargetableItems, countsErr := config.ProductionBindings.ProductionExecutionCounts(ctx); countsErr == nil {
|
||
frozen, retargetable = frozenItems, retargetableItems
|
||
}
|
||
return productionBindingView{
|
||
InternalKBID: storedInternal, ExternalKBID: storedExternal,
|
||
InternalKBName: nameFor(storedInternal, storedInternalName), ExternalKBName: nameFor(storedExternal, storedExternalName),
|
||
UpdatedBy: updatedBy, ProductionBaseURL: config.productionTargetBaseURL(ctx),
|
||
ProductionConnected: message == "", ProductionMessage: message,
|
||
Frozen: frozen, Retargetable: retargetable,
|
||
Replanned: replan.Replanned, RetiredDuplicates: replan.RetiredDuplicates,
|
||
}, nil
|
||
}
|
||
|
||
func (config Config) handleProductionBindings(w http.ResponseWriter, r *http.Request) {
|
||
if config.ProductionBindings == nil {
|
||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "production bindings are not configured"})
|
||
return
|
||
}
|
||
view, err := config.productionBindingPayload(r.Context(), postgresstore.RoutingBindingReplanResult{})
|
||
if err != nil {
|
||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not load production bindings"})
|
||
return
|
||
}
|
||
writeJSON(w, http.StatusOK, map[string]any{"data": view})
|
||
}
|
||
|
||
func (config Config) handleProductionKnowledgeBaseOptions(w http.ResponseWriter, r *http.Request) {
|
||
bases, message := config.productionKnowledgeBases(r.Context())
|
||
if message != "" {
|
||
writeJSON(w, http.StatusBadGateway, map[string]string{"error": message})
|
||
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})
|
||
}
|
||
|
||
// handleSaveProductionBindings stores the 源库 → 目标库 mapping. When the
|
||
// production endpoint answers, the chosen base must exist there; when it cannot
|
||
// be asked, the save still succeeds but the response says so honestly (a jittery
|
||
// production endpoint must not block the operator, a wrong ID must).
|
||
func (config Config) handleSaveProductionBindings(w http.ResponseWriter, r *http.Request) {
|
||
if config.ProductionBindings == nil {
|
||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "production bindings are not configured"})
|
||
return
|
||
}
|
||
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
|
||
}
|
||
bases, message := config.productionKnowledgeBases(r.Context())
|
||
if message != "" && config.connectionKeyUnusable(r.Context(), "production") {
|
||
writeJSON(w, http.StatusConflict, map[string]string{"error": "生产 WeKnora 已保存连接但没有可用密钥:请重新录入 API Key 并测通后再改发布目标"})
|
||
return
|
||
}
|
||
names := make(map[string]string, len(bases))
|
||
for _, base := range bases {
|
||
names[base.ID] = base.Name
|
||
}
|
||
if message == "" {
|
||
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
|
||
}
|
||
}
|
||
}
|
||
previousInternal, previousExternal, _, err := config.ProductionBindings.LoadProductionKBBindings(r.Context())
|
||
if err != nil {
|
||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not load production bindings"})
|
||
return
|
||
}
|
||
replan, err := config.ProductionBindings.SaveProductionKBBindingsWithReplan(r.Context(), postgresstore.ProductionBindingSave{
|
||
InternalID: internal, ExternalID: external,
|
||
InternalName: names[internal], ExternalName: names[external],
|
||
UpdatedBy: actorFor(r),
|
||
}, postgresstore.EffectiveKBIDs{Internal: previousInternal, External: previousExternal},
|
||
postgresstore.EffectiveKBIDs{Internal: internal, External: external},
|
||
config.Now().UTC())
|
||
if err != nil {
|
||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not save production bindings"})
|
||
return
|
||
}
|
||
view, err := config.productionBindingPayload(r.Context(), replan)
|
||
if err != nil {
|
||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not load production bindings"})
|
||
return
|
||
}
|
||
writeJSON(w, http.StatusOK, map[string]any{"data": view})
|
||
}
|