feat(ECR-023): AICoreConfig KnowledgeSource 只读并 Closed

运营可观测知识源目录(knowledge_sources + admin /ai),不含 Chunk/Embedding。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
jackyu66git
2026-08-08 01:49:58 +08:00
co-authored by Cursor
parent dd4d644eaa
commit bf1ae8bc53
25 changed files with 555 additions and 3 deletions
@@ -16,6 +16,8 @@ func (h *AdminHandler) registerAIConfig(authed *gin.RouterGroup) {
g := authed.Group("/ai")
g.GET("/system-prompts", middleware.RequireAdminPermission(h.Svc, admin.PermAIConfigRead), h.ListSystemPrompts)
g.GET("/system-prompts/:id", middleware.RequireAdminPermission(h.Svc, admin.PermAIConfigRead), h.GetSystemPrompt)
g.GET("/knowledge-sources", middleware.RequireAdminPermission(h.Svc, admin.PermAIConfigRead), h.ListKnowledgeSources)
g.GET("/knowledge-sources/:id", middleware.RequireAdminPermission(h.Svc, admin.PermAIConfigRead), h.GetKnowledgeSource)
}
func (h *AdminHandler) ListSystemPrompts(c *gin.Context) {
@@ -44,3 +46,30 @@ func (h *AdminHandler) GetSystemPrompt(c *gin.Context) {
}
response.OK(c, row)
}
func (h *AdminHandler) ListKnowledgeSources(c *gin.Context) {
items, err := h.Svc.ListKnowledgeSources(c.Request.Context())
if err != nil {
response.Fail(c, http.StatusInternalServerError, 50029, "list knowledge sources failed")
return
}
response.OK(c, gin.H{"items": items})
}
func (h *AdminHandler) GetKnowledgeSource(c *gin.Context) {
id, err := uuid.Parse(c.Param("id"))
if err != nil {
response.Fail(c, http.StatusBadRequest, 40002, "invalid id")
return
}
row, err := h.Svc.GetKnowledgeSource(c.Request.Context(), id)
if errors.Is(err, admin.ErrKnowledgeSourceNotFound) {
response.Fail(c, http.StatusNotFound, 40405, "knowledge source not found")
return
}
if err != nil {
response.Fail(c, http.StatusInternalServerError, 50030, "get knowledge source failed")
return
}
response.OK(c, row)
}
@@ -0,0 +1,105 @@
package integration_test
import (
"context"
"encoding/json"
"fmt"
"net/http"
"testing"
"time"
"github.com/google/uuid"
"golang.org/x/crypto/bcrypt"
)
func TestAICoreKnowledgeSources(t *testing.T) {
r, pool := setupAPIPool(t)
ctx := context.Background()
tok := adminLogin(t, r, "admin", "change-me")
_, code := doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/ai/knowledge-sources", nil, "")
if code != http.StatusUnauthorized {
t.Fatalf("expected 401, got %d", code)
}
limitedRoleID := uuid.New()
_, err := pool.Exec(ctx, `
INSERT INTO admin_roles(id, name, system) VALUES ($1,$2,false)`,
limitedRoleID, "ks_lim_"+limitedRoleID.String()[:8])
if err != nil {
t.Fatal(err)
}
_, err = pool.Exec(ctx, `
INSERT INTO admin_role_permissions(role_id, code) VALUES ($1,'admin.users.read')`, limitedRoleID)
if err != nil {
t.Fatal(err)
}
hash, err := bcrypt.GenerateFromPassword([]byte("limited-pass"), bcrypt.DefaultCost)
if err != nil {
t.Fatal(err)
}
limUser := fmt.Sprintf("kslim_%d", time.Now().UnixNano())
_, err = pool.Exec(ctx, `
INSERT INTO admin_accounts(username, password_hash, role_id) VALUES ($1,$2,$3)`,
limUser, string(hash), limitedRoleID)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_, _ = pool.Exec(ctx, `DELETE FROM admin_accounts WHERE username=$1`, limUser)
_, _ = pool.Exec(ctx, `DELETE FROM admin_roles WHERE id=$1`, limitedRoleID)
})
limTok := adminLogin(t, r, limUser, "limited-pass")
_, code = doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/ai/knowledge-sources", nil, limTok)
if code != http.StatusForbidden {
t.Fatalf("expected 403, got %d", code)
}
start := time.Now()
env, code := doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/ai/knowledge-sources", nil, tok)
if code != 200 || env.Code != 0 {
t.Fatalf("list http=%d msg=%s", code, env.Message)
}
if time.Since(start) > 500*time.Millisecond {
t.Fatalf("list too slow %v", time.Since(start))
}
var list struct {
Items []struct {
ID string `json:"id"`
Code string `json:"code"`
SourceKind string `json:"source_kind"`
} `json:"items"`
}
_ = json.Unmarshal(env.Data, &list)
var srcID string
for _, it := range list.Items {
if it.Code == "ask_grounding" {
srcID = it.ID
if it.SourceKind != "faq" && it.SourceKind != "policy" && it.SourceKind != "guide" {
t.Fatalf("bad source_kind %q", it.SourceKind)
}
break
}
}
if srcID == "" {
t.Fatalf("missing ask_grounding: %#v", list.Items)
}
env, code = doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/ai/knowledge-sources/"+srcID, nil, tok)
if code != 200 {
t.Fatalf("get %d", code)
}
var detail struct {
Code string `json:"code"`
SourceKind string `json:"source_kind"`
}
_ = json.Unmarshal(env.Data, &detail)
if detail.Code != "ask_grounding" || detail.SourceKind == "" {
t.Fatalf("bad detail %#v", detail)
}
_, code = doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/ai/knowledge-sources/"+fakeUUID(), nil, tok)
if code != http.StatusNotFound {
t.Fatalf("expected 404, got %d", code)
}
}
@@ -60,3 +60,59 @@ func (r *AdminRepo) GetSystemPrompt(ctx context.Context, id uuid.UUID) (*SystemP
}
return &p, nil
}
// KnowledgeSourceRow is AICoreConfig KnowledgeSource catalog row.
type KnowledgeSourceRow struct {
ID uuid.UUID `json:"id"`
Code string `json:"code"`
Title string `json:"title"`
Description *string `json:"description,omitempty"`
SourceKind string `json:"source_kind"`
Version int `json:"version"`
Active bool `json:"active"`
System bool `json:"system"`
UpdatedAt time.Time `json:"updated_at"`
}
// ListKnowledgeSources returns knowledge source catalog.
func (r *AdminRepo) ListKnowledgeSources(ctx context.Context) ([]KnowledgeSourceRow, error) {
rows, err := r.Pool.Query(ctx, `
SELECT id, code, title, description, source_kind, version, active, system, updated_at
FROM knowledge_sources
ORDER BY active DESC, code ASC`)
if err != nil {
return nil, err
}
defer rows.Close()
var out []KnowledgeSourceRow
for rows.Next() {
var k KnowledgeSourceRow
if err := rows.Scan(
&k.ID, &k.Code, &k.Title, &k.Description, &k.SourceKind,
&k.Version, &k.Active, &k.System, &k.UpdatedAt,
); err != nil {
return nil, err
}
out = append(out, k)
}
return out, rows.Err()
}
// GetKnowledgeSource loads one source by id.
func (r *AdminRepo) GetKnowledgeSource(ctx context.Context, id uuid.UUID) (*KnowledgeSourceRow, error) {
var k KnowledgeSourceRow
err := r.Pool.QueryRow(ctx, `
SELECT id, code, title, description, source_kind, version, active, system, updated_at
FROM knowledge_sources WHERE id=$1`, id,
).Scan(
&k.ID, &k.Code, &k.Title, &k.Description, &k.SourceKind,
&k.Version, &k.Active, &k.System, &k.UpdatedAt,
)
if errors.Is(err, pgx.ErrNoRows) {
return nil, err
}
if err != nil {
return nil, err
}
return &k, nil
}
@@ -11,6 +11,7 @@ import (
)
var ErrSystemPromptNotFound = errString("system prompt not found")
var ErrKnowledgeSourceNotFound = errString("knowledge source not found")
// ListSystemPrompts returns SystemPrompt catalog.
func (s *Service) ListSystemPrompts(ctx context.Context) ([]repository.SystemPromptRow, error) {
@@ -32,3 +33,24 @@ func (s *Service) GetSystemPrompt(ctx context.Context, id uuid.UUID) (*repositor
}
return row, err
}
// ListKnowledgeSources returns KnowledgeSource catalog.
func (s *Service) ListKnowledgeSources(ctx context.Context) ([]repository.KnowledgeSourceRow, error) {
items, err := s.Repo.ListKnowledgeSources(ctx)
if err != nil {
return nil, err
}
if items == nil {
items = []repository.KnowledgeSourceRow{}
}
return items, nil
}
// GetKnowledgeSource loads one source.
func (s *Service) GetKnowledgeSource(ctx context.Context, id uuid.UUID) (*repository.KnowledgeSourceRow, error) {
row, err := s.Repo.GetKnowledgeSource(ctx, id)
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrKnowledgeSourceNotFound
}
return row, err
}