feat(govai): 0617 优化首批 — 安全/私有化/深度研究/服务层/可观测性
借鉴 odysseus 的能力设计,全程净室实现、零 AGPL 代码、不引入 AGPL 依赖。
T1 提示注入防护: pkg/promptguard 包裹外部/知识库内容为不可信数据,buildMessages 移出 system 指令区。 T2 安全 CI: .github/workflows(ci+security: govulncheck/gitleaks/actionlint/hadolint/trivy)+dependabot+.hadolint.yaml;go.mod 加 toolchain go1.25.11 修复 20 个 stdlib CVE。 T3 管理员 2FA: 迁移 000016 + RFC6238 TOTP/备份码(pkg/auth, 零依赖) + 登录流程集成(后端)。 T4 本地模型: LLM/embedding 支持本地 vLLM/Ollama(OpenAI 兼容, 鉴权头条件发送, NoAuth) + docs/local-deploy.md。 T6 深度研究: 迁移 000017 + Python research-worker(净室多步流水线, 检索避开 SearXNG) + Go research 服务/handler/路由。 T7 service 层: 新增 internal/service/{research,twofa}, 2FA 业务逻辑从胖 handler 下沉, 接口注入可单测。 T10 缓存/可观测性: internal/cache(Redis+内存, 优雅降级) 接入 store 热点列表; Prometheus 指标+/metrics; docs/openapi.yaml。 验证: go build/vet/test ./... 全绿(8 包); research-worker 12 单测过; 真实 PG 应用迁移并烟测。
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
package research
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strconv"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
const (
|
||||
taskQueueKey = "research:tasks"
|
||||
statusKeyPrefix = "research:status:"
|
||||
)
|
||||
|
||||
// redisBackend 同时实现 Queue 与 Cache:任务下发到列表队列、快速状态读自 hash。
|
||||
// 与 research-worker 的 TASK_QUEUE / TASK_STATUS_PREFIX 约定保持一致。
|
||||
type redisBackend struct {
|
||||
rdb *redis.Client
|
||||
}
|
||||
|
||||
func NewRedisBackend(rdb *redis.Client) *redisBackend {
|
||||
return &redisBackend{rdb: rdb}
|
||||
}
|
||||
|
||||
func (b *redisBackend) Enqueue(ctx context.Context, taskID string) error {
|
||||
msg, _ := json.Marshal(map[string]string{"task_id": taskID})
|
||||
return b.rdb.LPush(ctx, taskQueueKey, msg).Err()
|
||||
}
|
||||
|
||||
func (b *redisBackend) GetStatus(ctx context.Context, taskID string) (*CachedStatus, bool) {
|
||||
m, err := b.rdb.HGetAll(ctx, statusKeyPrefix+taskID).Result()
|
||||
if err != nil || len(m) == 0 {
|
||||
return nil, false
|
||||
}
|
||||
progress, _ := strconv.Atoi(m["progress"])
|
||||
return &CachedStatus{
|
||||
Status: m["status"],
|
||||
Progress: progress,
|
||||
Message: m["message"],
|
||||
}, true
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package research
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// pgxRepository 是基于 pgx 连接池的 Repository 实现。
|
||||
type pgxRepository struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewPgxRepository(pool *pgxpool.Pool) Repository {
|
||||
return &pgxRepository{pool: pool}
|
||||
}
|
||||
|
||||
func (r *pgxRepository) Insert(ctx context.Context, id, userID string, appID *string, topic string, config map[string]any) error {
|
||||
if config == nil {
|
||||
config = map[string]any{}
|
||||
}
|
||||
configJSON, err := json.Marshal(config)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = r.pool.Exec(ctx,
|
||||
`INSERT INTO research_tasks (id, user_id, app_id, topic, config)
|
||||
VALUES ($1, $2, $3, $4, $5)`,
|
||||
id, userID, appID, topic, configJSON,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *pgxRepository) Get(ctx context.Context, userID, taskID string) (*Task, error) {
|
||||
var t Task
|
||||
var sources []byte
|
||||
err := r.pool.QueryRow(ctx,
|
||||
`SELECT id, topic, status, progress, status_message, error_message, report, sources, tokens_used, created_at
|
||||
FROM research_tasks WHERE id = $1 AND user_id = $2`, taskID, userID,
|
||||
).Scan(&t.ID, &t.Topic, &t.Status, &t.Progress, &t.StatusMessage, &t.ErrorMessage,
|
||||
&t.Report, &sources, &t.TokensUsed, &t.CreatedAt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
t.Sources = sources
|
||||
return &t, nil
|
||||
}
|
||||
|
||||
func (r *pgxRepository) List(ctx context.Context, userID string, limit int) ([]Task, error) {
|
||||
rows, err := r.pool.Query(ctx,
|
||||
`SELECT id, topic, status, progress, status_message, error_message, tokens_used, created_at
|
||||
FROM research_tasks WHERE user_id = $1 ORDER BY created_at DESC LIMIT $2`, userID, limit,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var tasks []Task
|
||||
for rows.Next() {
|
||||
var t Task
|
||||
if err := rows.Scan(&t.ID, &t.Topic, &t.Status, &t.Progress, &t.StatusMessage,
|
||||
&t.ErrorMessage, &t.TokensUsed, &t.CreatedAt); err != nil {
|
||||
continue
|
||||
}
|
||||
tasks = append(tasks, t)
|
||||
}
|
||||
return tasks, nil
|
||||
}
|
||||
|
||||
func (r *pgxRepository) Cancel(ctx context.Context, userID, taskID string) (bool, error) {
|
||||
tag, err := r.pool.Exec(ctx,
|
||||
`UPDATE research_tasks SET status = 'canceled', updated_at = NOW()
|
||||
WHERE id = $1 AND user_id = $2
|
||||
AND status IN ('pending','planning','searching','reading','synthesizing')`,
|
||||
taskID, userID,
|
||||
)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return tag.RowsAffected() > 0, nil
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
// Package research 提供深度研究任务的业务编排(service 层)。
|
||||
//
|
||||
// 该层与具体存储/队列解耦:依赖 Repository(任务持久化)、Queue(任务下发)、
|
||||
// Cache(快速状态)三个接口,便于单测与替换实现。HTTP handler 仅做参数解析与
|
||||
// 响应,业务规则集中在这里。
|
||||
package research
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Task 是研究任务的领域模型(用于查询/列表返回)。
|
||||
type Task struct {
|
||||
ID string
|
||||
Topic string
|
||||
Status string
|
||||
Progress int
|
||||
StatusMessage *string
|
||||
ErrorMessage *string
|
||||
Report *string
|
||||
Sources []byte // 原始 JSON([{title,url,snippet}])
|
||||
TokensUsed int
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// CreateInput 创建研究任务的入参。
|
||||
type CreateInput struct {
|
||||
UserID string
|
||||
AppID *string
|
||||
Topic string
|
||||
Config map[string]any
|
||||
}
|
||||
|
||||
// CachedStatus 来自 Redis 的快速状态(worker 实时写入)。
|
||||
type CachedStatus struct {
|
||||
Status string
|
||||
Progress int
|
||||
Message string
|
||||
}
|
||||
|
||||
// Repository 任务持久化接口。
|
||||
type Repository interface {
|
||||
Insert(ctx context.Context, id, userID string, appID *string, topic string, config map[string]any) error
|
||||
Get(ctx context.Context, userID, taskID string) (*Task, error)
|
||||
List(ctx context.Context, userID string, limit int) ([]Task, error)
|
||||
// Cancel 仅取消进行中的任务;found 表示是否有可取消的任务被更新。
|
||||
Cancel(ctx context.Context, userID, taskID string) (found bool, err error)
|
||||
}
|
||||
|
||||
// Queue 任务下发接口(worker 消费)。
|
||||
type Queue interface {
|
||||
Enqueue(ctx context.Context, taskID string) error
|
||||
}
|
||||
|
||||
// Cache 快速状态读取接口(可选)。
|
||||
type Cache interface {
|
||||
GetStatus(ctx context.Context, taskID string) (*CachedStatus, bool)
|
||||
}
|
||||
|
||||
var (
|
||||
ErrEmptyTopic = errors.New("研究题目不能为空")
|
||||
ErrNotFound = errors.New("任务不存在")
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
repo Repository
|
||||
queue Queue
|
||||
cache Cache // 可为 nil
|
||||
}
|
||||
|
||||
func NewService(repo Repository, queue Queue, cache Cache) *Service {
|
||||
return &Service{repo: repo, queue: queue, cache: cache}
|
||||
}
|
||||
|
||||
// Create 校验入参、落库并下发到队列,返回任务 ID。
|
||||
func (s *Service) Create(ctx context.Context, in CreateInput) (string, error) {
|
||||
topic := strings.TrimSpace(in.Topic)
|
||||
if topic == "" {
|
||||
return "", ErrEmptyTopic
|
||||
}
|
||||
id := uuid.New().String()
|
||||
if err := s.repo.Insert(ctx, id, in.UserID, in.AppID, topic, in.Config); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := s.queue.Enqueue(ctx, id); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// Status 返回任务(先按所有权从库中取,再用 Redis 快速状态覆盖以保证新鲜度)。
|
||||
func (s *Service) Status(ctx context.Context, userID, taskID string) (*Task, error) {
|
||||
t, err := s.repo.Get(ctx, userID, taskID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if s.cache != nil {
|
||||
if cs, ok := s.cache.GetStatus(ctx, taskID); ok {
|
||||
t.Status = cs.Status
|
||||
t.Progress = cs.Progress
|
||||
if cs.Message != "" {
|
||||
msg := cs.Message
|
||||
t.StatusMessage = &msg
|
||||
}
|
||||
}
|
||||
}
|
||||
return t, nil
|
||||
}
|
||||
|
||||
// List 返回用户最近的研究任务。
|
||||
func (s *Service) List(ctx context.Context, userID string) ([]Task, error) {
|
||||
return s.repo.List(ctx, userID, 50)
|
||||
}
|
||||
|
||||
// Cancel 取消进行中的任务;任务不存在/不可取消时返回 ErrNotFound。
|
||||
func (s *Service) Cancel(ctx context.Context, userID, taskID string) error {
|
||||
found, err := s.repo.Cancel(ctx, userID, taskID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !found {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package research
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// ---- 测试替身 ----
|
||||
|
||||
type fakeRepo struct {
|
||||
inserted map[string]bool
|
||||
getResult *Task
|
||||
getErr error
|
||||
cancelOK bool
|
||||
cancelErr error
|
||||
lastInsert struct {
|
||||
id, userID, topic string
|
||||
}
|
||||
}
|
||||
|
||||
func newFakeRepo() *fakeRepo { return &fakeRepo{inserted: map[string]bool{}} }
|
||||
|
||||
func (f *fakeRepo) Insert(ctx context.Context, id, userID string, appID *string, topic string, config map[string]any) error {
|
||||
f.inserted[id] = true
|
||||
f.lastInsert.id = id
|
||||
f.lastInsert.userID = userID
|
||||
f.lastInsert.topic = topic
|
||||
return nil
|
||||
}
|
||||
func (f *fakeRepo) Get(ctx context.Context, userID, taskID string) (*Task, error) {
|
||||
return f.getResult, f.getErr
|
||||
}
|
||||
func (f *fakeRepo) List(ctx context.Context, userID string, limit int) ([]Task, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (f *fakeRepo) Cancel(ctx context.Context, userID, taskID string) (bool, error) {
|
||||
return f.cancelOK, f.cancelErr
|
||||
}
|
||||
|
||||
type fakeQueue struct{ enqueued []string }
|
||||
|
||||
func (q *fakeQueue) Enqueue(ctx context.Context, taskID string) error {
|
||||
q.enqueued = append(q.enqueued, taskID)
|
||||
return nil
|
||||
}
|
||||
|
||||
type fakeCache struct{ cs *CachedStatus }
|
||||
|
||||
func (c *fakeCache) GetStatus(ctx context.Context, taskID string) (*CachedStatus, bool) {
|
||||
if c.cs == nil {
|
||||
return nil, false
|
||||
}
|
||||
return c.cs, true
|
||||
}
|
||||
|
||||
// ---- 测试 ----
|
||||
|
||||
func TestCreate_EmptyTopicRejected(t *testing.T) {
|
||||
svc := NewService(newFakeRepo(), &fakeQueue{}, nil)
|
||||
_, err := svc.Create(context.Background(), CreateInput{UserID: "u1", Topic: " "})
|
||||
if !errors.Is(err, ErrEmptyTopic) {
|
||||
t.Fatalf("空题目应返回 ErrEmptyTopic,实际: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreate_InsertsAndEnqueues(t *testing.T) {
|
||||
repo := newFakeRepo()
|
||||
q := &fakeQueue{}
|
||||
svc := NewService(repo, q, nil)
|
||||
|
||||
id, err := svc.Create(context.Background(), CreateInput{UserID: "u1", Topic: "数字政府研究"})
|
||||
if err != nil {
|
||||
t.Fatalf("Create 出错: %v", err)
|
||||
}
|
||||
if id == "" || !repo.inserted[id] {
|
||||
t.Fatal("应已插入任务记录")
|
||||
}
|
||||
if len(q.enqueued) != 1 || q.enqueued[0] != id {
|
||||
t.Fatalf("应已用相同 id 下发到队列,实际: %v", q.enqueued)
|
||||
}
|
||||
if repo.lastInsert.topic != "数字政府研究" {
|
||||
t.Fatalf("题目透传错误: %q", repo.lastInsert.topic)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatus_CacheOverlaysDB(t *testing.T) {
|
||||
repo := newFakeRepo()
|
||||
repo.getResult = &Task{ID: "t1", Status: "pending", Progress: 0}
|
||||
cache := &fakeCache{cs: &CachedStatus{Status: "searching", Progress: 30, Message: "检索中"}}
|
||||
svc := NewService(repo, &fakeQueue{}, cache)
|
||||
|
||||
got, err := svc.Status(context.Background(), "u1", "t1")
|
||||
if err != nil {
|
||||
t.Fatalf("Status 出错: %v", err)
|
||||
}
|
||||
if got.Status != "searching" || got.Progress != 30 {
|
||||
t.Fatalf("缓存状态应覆盖 DB,实际 status=%s progress=%d", got.Status, got.Progress)
|
||||
}
|
||||
if got.StatusMessage == nil || *got.StatusMessage != "检索中" {
|
||||
t.Fatal("应带上缓存的状态消息")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatus_DBErrorPropagates(t *testing.T) {
|
||||
repo := newFakeRepo()
|
||||
repo.getErr = errors.New("not found")
|
||||
svc := NewService(repo, &fakeQueue{}, &fakeCache{})
|
||||
if _, err := svc.Status(context.Background(), "u1", "missing"); err == nil {
|
||||
t.Fatal("DB 错误应向上传播")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCancel_NotFound(t *testing.T) {
|
||||
repo := newFakeRepo()
|
||||
repo.cancelOK = false
|
||||
svc := NewService(repo, &fakeQueue{}, nil)
|
||||
if err := svc.Cancel(context.Background(), "u1", "t1"); !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("不可取消时应返回 ErrNotFound,实际: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCancel_Success(t *testing.T) {
|
||||
repo := newFakeRepo()
|
||||
repo.cancelOK = true
|
||||
svc := NewService(repo, &fakeQueue{}, nil)
|
||||
if err := svc.Cancel(context.Background(), "u1", "t1"); err != nil {
|
||||
t.Fatalf("可取消时应返回 nil,实际: %v", err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user