deploy-hxtesting / build-and-deploy (push) Successful in 1m15s
根因(26040006 等首用户空间零知识库): - 000000 初始迁移把 tenants_id_seq 起点设为 10000,恰好等于内置模型宿主 保留租户 id(DefaultBuiltinModelTenantID=10000):全新环境的第一个用户 空间必然撞上 SeedTenantDefaults 的「永不 seed」豁免,一个默认库都没有; 后续空间(10001+)正常。内置模型行(tenant_id=10000)被真实空间占住, 还存在归属歧义隐患 - 注册引导是创建时一次性动作,存量空间因引导当时失败(如模型未就绪)或 上述碰撞而缺库时,此后永不补建 修复: - migration 000160:租户序列推到 10001 之后——全新库从 10001 起号(10000 永久保留给内置模型宿主),存量库按 max(id) 连续续号不受影响 - SeedTenantDefaults 拆出 seedStarterKB 供创建时引导与自愈共用;保留租户 豁免注释同步更新 - 新增 EnsureTenantDefaultKnowledgeBases 惰性自愈:挂在知识库列表读路径 (幂等/fail-open/进程内互斥防并发重复建档)——企业培训课件/题库两库恒补 (Source 去重),「新手入门」仅零库空间补建(不复活用户主动删除的入门库) 效果:26040006(租户 10000)等存量用户打开「知识库」页即自动补齐 3 个默认 库;全新环境的首个用户空间不再撞保留 id
400 lines
16 KiB
Go
400 lines
16 KiB
Go
package service
|
||
|
||
import (
|
||
"bytes"
|
||
"context"
|
||
"errors"
|
||
"io"
|
||
"mime/multipart"
|
||
"strings"
|
||
"sync"
|
||
|
||
"academy/internal/logger"
|
||
"academy/internal/types"
|
||
"academy/internal/types/interfaces"
|
||
)
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// 新工作空间开箱即用初始化(tenant bootstrap)
|
||
//
|
||
// 目标:新用户注册/新建空间后,无需手动配置任何模型即可直接使用:
|
||
// 1. 解析系统默认模型(内置模型 is_builtin=true 全租户可见,is_default 优先);
|
||
// 2. 自动创建「新手入门」知识库,绑定默认对话/向量化模型;
|
||
// 3. 在该库中预置一份欢迎文档(走标准上传管道,自动切片/向量化);
|
||
// 4. 把租户级检索重排模型(retrieval_config.rerank_model_id)配成默认;
|
||
// 5. 确保企业培训「课件/题库」两个系统默认知识库(CASDOOR/OIDC 自动注册
|
||
// 用户进「知识库」页默认可见,与培训域共用同一对库)。
|
||
//
|
||
// 整体 fail-open:任何一步失败只记日志,绝不阻断注册/建租户主流程;
|
||
// 且整体幂等——租户下已存在同名入门库时直接跳过。
|
||
// ---------------------------------------------------------------------------
|
||
|
||
const (
|
||
// BootstrapKBName 开箱默认知识库名;幂等检查按此名匹配。
|
||
BootstrapKBName = "新手入门"
|
||
|
||
bootstrapWelcomeFileName = "欢迎使用指南.md"
|
||
)
|
||
|
||
// bootstrapWelcomeDocContent 预置欢迎文档内容。走标准文档解析管道,
|
||
// 处理完成后用户即可在「新手入门」库上直接问答验证开箱效果。
|
||
const bootstrapWelcomeDocContent = `# 欢迎使用 Academy
|
||
|
||
这是一份由系统自动创建的入门知识库,已经为你配置好默认的对话与向量化模型——
|
||
现在你可以直接开始提问了。
|
||
|
||
## 你现在就可以做什么
|
||
|
||
- **知识库问答**:进入任意知识库,右侧对话面板直接提问。本库已内置这份入门指南,
|
||
可以试试问它:"这个平台能做什么?"
|
||
- **智能体对话**:打开对话页面即可与 Academy 助手聊天,助手默认使用系统配置好的对话模型。
|
||
|
||
## 接下来你可能想做的事
|
||
|
||
1. **创建自己的知识库**:左侧知识库 → 新建知识库。系统会自动为你预填默认模型,
|
||
上传文档(支持 Markdown、Word、PDF、Excel 等)后即可对文档内容提问。
|
||
2. **创建智能体**:智能体页面 → 新建。主模型同样自动预填;你还可以为智能体单独配置
|
||
重排、视觉(图片理解)、语音(ASR)等模型。
|
||
3. **邀请团队成员**:右上角头像 → 设置 → 成员管理 → 邀请成员。支持单个邀请、
|
||
生成共享链接,以及按 Excel 模板批量导入成员。
|
||
4. **管理模型**:设置 → 模型管理。系统内置的默认模型已开箱可用;如需接入
|
||
自己的模型(OpenAI 兼容 API、Ollama 本地模型、各云厂商),在「添加模型」中配置即可。
|
||
|
||
## 小提示
|
||
|
||
- 带锁图标的模型是系统内置模型,所有空间共享,可直接使用。
|
||
- 新建知识库/智能体时,模型字段已自动填好默认值,不需要手动选择;当然你随时可以更换。
|
||
|
||
祝使用愉快!
|
||
`
|
||
|
||
// NewTenantBootstrapService wires the bootstrap service. All dependencies are
|
||
// optional at the DI level but each seeding step degrades gracefully when its
|
||
// service misbehaves (fail-open, see SeedTenantDefaults).
|
||
func NewTenantBootstrapService(
|
||
modelService interfaces.ModelService,
|
||
kbService interfaces.KnowledgeBaseService,
|
||
kgService interfaces.KnowledgeService,
|
||
tenantService interfaces.TenantService,
|
||
) interfaces.TenantBootstrapService {
|
||
return &tenantBootstrapService{
|
||
modelService: modelService,
|
||
kbService: kbService,
|
||
kgService: kgService,
|
||
tenantService: tenantService,
|
||
}
|
||
}
|
||
|
||
type tenantBootstrapService struct {
|
||
modelService interfaces.ModelService
|
||
kbService interfaces.KnowledgeBaseService
|
||
kgService interfaces.KnowledgeService
|
||
tenantService interfaces.TenantService
|
||
// ensureMu 串行化惰性自愈的补建段(见 EnsureTenantDefaultKnowledgeBases)。
|
||
ensureMu sync.Mutex
|
||
}
|
||
|
||
// SeedTenantDefaults implements interfaces.TenantBootstrapService. See the
|
||
// interface doc for the contract; every step logs and moves on.
|
||
func (s *tenantBootstrapService) SeedTenantDefaults(ctx context.Context, tenant *types.Tenant, ownerUserID string) {
|
||
// 整体兜底:seed 属于附加体验,任何 panic(如上游依赖 nil)都不能
|
||
// 波及注册/建租户主流程。
|
||
defer func() {
|
||
if r := recover(); r != nil {
|
||
logger.Errorf(ctx, "tenant bootstrap: recovered from panic: %v", r)
|
||
}
|
||
}()
|
||
|
||
if tenant == nil || tenant.ID == 0 {
|
||
return
|
||
}
|
||
// 内置模型的宿主租户(tenant 10000)不是用户空间,永不 seed。000160 起
|
||
// 租户序列已避开 10000(见 migration 000160_tenant_seq_reserve_builtin_host),
|
||
// 新环境不会再有真实空间拿到该 id;存量环境若首空间已占住 10000(引导因此
|
||
// 被跳过,一个默认库都没有),其默认库由 EnsureTenantDefaultKnowledgeBases
|
||
// 惰性自愈补齐——该路径不带本豁免。
|
||
if tenant.ID == types.DefaultBuiltinModelTenantID {
|
||
return
|
||
}
|
||
|
||
// 构造服务级 ctx:显式指定执行租户与租户信息(CreateKnowledgeFromFile
|
||
// 依赖 TenantInfo),并归因创建人(synthetic API-key 用户跳过,同 KB
|
||
// 服务的 CreatorID 语义)。必须先于所有服务调用——挂钩处的调用方 ctx
|
||
// 还停留在调用者的"当前空间",不是刚创建的新空间。
|
||
seedCtx := types.WithExecutionTenant(ctx, tenant.ID)
|
||
seedCtx = context.WithValue(seedCtx, types.TenantInfoContextKey, tenant)
|
||
if ownerUserID != "" && !types.IsSyntheticUserID(ownerUserID) {
|
||
seedCtx = context.WithValue(seedCtx, types.UserIDContextKey, ownerUserID)
|
||
}
|
||
|
||
// 幂等:已有同名入门库的工作空间视为已初始化。
|
||
kbs, err := s.kbService.ListKnowledgeBasesByTenantID(seedCtx, tenant.ID)
|
||
if err != nil {
|
||
logger.Warnf(ctx, "tenant bootstrap: list KBs failed, skip seeding: tenant=%d err=%v", tenant.ID, err)
|
||
return
|
||
}
|
||
|
||
// 企业培训(课件)/(题库)系统默认库:按 Source 标记独立幂等确保(与培训域
|
||
// ensureTrainingKnowledgeBases 同源),入门库已初始化的空间同样补齐 ——
|
||
// CASDOOR/OIDC 自动注册的用户进「知识库」页即可见两个培训默认库。
|
||
s.ensureTrainingKnowledgeBases(seedCtx, tenant.ID, kbs)
|
||
|
||
for _, kb := range kbs {
|
||
if kb != nil && kb.Name == BootstrapKBName {
|
||
logger.Infof(ctx, "tenant bootstrap: workspace already seeded, skip: tenant=%d", tenant.ID)
|
||
return
|
||
}
|
||
}
|
||
|
||
// 解析系统默认模型(内置 is_default 优先,否则该类型第一个 active)。
|
||
models, err := s.modelService.ListModels(seedCtx)
|
||
if err != nil {
|
||
logger.Warnf(ctx, "tenant bootstrap: list models failed, skip seeding: tenant=%d err=%v", tenant.ID, err)
|
||
return
|
||
}
|
||
chatID := PickDefaultModelID(models, types.ModelTypeKnowledgeQA)
|
||
embedID := PickDefaultModelID(models, types.ModelTypeEmbedding)
|
||
rerankID := PickDefaultModelID(models, types.ModelTypeRerank)
|
||
|
||
// 1) 默认知识库 + 欢迎文档(创建时引导与存量空间自愈共用同一实现)。
|
||
// 模型解析不到就留空——行为与用户手动不选一致。
|
||
if err := s.seedStarterKB(seedCtx, chatID, embedID); err != nil {
|
||
return
|
||
}
|
||
|
||
// 2) 租户级检索重排模型(RetrievalConfig 其余零值按 GetEffective* 回退默认)。
|
||
if rerankID != "" {
|
||
if tenant.RetrievalConfig == nil {
|
||
tenant.RetrievalConfig = &types.RetrievalConfig{}
|
||
}
|
||
if tenant.RetrievalConfig.RerankModelID == "" {
|
||
tenant.RetrievalConfig.RerankModelID = rerankID
|
||
if _, err := s.tenantService.UpdateTenant(ctx, tenant); err != nil {
|
||
logger.Warnf(ctx, "tenant bootstrap: set tenant rerank model failed: tenant=%d err=%v",
|
||
tenant.ID, err)
|
||
} else {
|
||
logger.Infof(ctx, "tenant bootstrap: tenant rerank model set: tenant=%d model=%s",
|
||
tenant.ID, rerankID)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// seedStarterKB 创建「新手入门」知识库并预置欢迎文档(标准上传管道,切片/
|
||
// 向量化由后台任务异步完成)。创建时引导(SeedTenantDefaults)与存量空间
|
||
// 惰性自愈(EnsureTenantDefaultKnowledgeBases)共用同一实现。fail-open:
|
||
// 失败仅记日志返回 error,由调用方决定是否中断后续步骤。
|
||
func (s *tenantBootstrapService) seedStarterKB(ctx context.Context, chatID, embedID string) error {
|
||
kb := &types.KnowledgeBase{
|
||
Name: BootstrapKBName,
|
||
Description: "系统自动创建的入门知识库,已绑定默认模型,可直接提问体验知识库问答。",
|
||
Type: types.KnowledgeBaseTypeDocument,
|
||
SummaryModelID: chatID,
|
||
EmbeddingModelID: embedID,
|
||
}
|
||
createdKB, err := s.kbService.CreateKnowledgeBase(ctx, kb)
|
||
if err != nil {
|
||
logger.Warnf(ctx, "tenant bootstrap: create starter KB failed: err=%v", err)
|
||
return err
|
||
}
|
||
logger.Infof(ctx, "tenant bootstrap: starter KB created: kb=%s", createdKB.ID)
|
||
|
||
if fh, fhErr := buildInMemoryFileHeader(bootstrapWelcomeFileName, bootstrapWelcomeDocContent); fhErr != nil {
|
||
logger.Warnf(ctx, "tenant bootstrap: build welcome file failed: kb=%s err=%v", createdKB.ID, fhErr)
|
||
} else if _, upErr := s.kgService.CreateKnowledgeFromFile(ctx, createdKB.ID, fh, nil, nil, "", nil, "", nil); upErr != nil {
|
||
logger.Warnf(ctx, "tenant bootstrap: upload welcome doc failed: kb=%s err=%v", createdKB.ID, upErr)
|
||
} else {
|
||
logger.Infof(ctx, "tenant bootstrap: welcome doc queued: kb=%s", createdKB.ID)
|
||
}
|
||
return nil
|
||
}
|
||
|
||
// EnsureTenantDefaultKnowledgeBases implements interfaces.TenantBootstrapService.
|
||
// 存量空间默认库惰性自愈:注册/建空间引导是一次性动作,历史空间会因引导
|
||
// 当时的失败(如模型尚未就绪)或保留租户 id 碰撞(migration 000160 前首空间
|
||
// 占住 10000 被豁免)而缺失默认库。知识库列表访问时幂等补齐:
|
||
// - 企业培训「课件/题库」两库恒补(Source 标记去重);
|
||
// - 「新手入门」仅空间为空时补建——零库说明引导从未成功;用户已在使用的
|
||
// 空间不复活其主动删除的入门库。
|
||
//
|
||
// 必须幂等且 fail-open:挂在列表读路径上,任何失败只记日志,不影响正常返回。
|
||
func (s *tenantBootstrapService) EnsureTenantDefaultKnowledgeBases(ctx context.Context) {
|
||
defer func() {
|
||
if r := recover(); r != nil {
|
||
logger.Errorf(ctx, "tenant bootstrap: lazy ensure recovered from panic: %v", r)
|
||
}
|
||
}()
|
||
|
||
tenantID, ok := types.TenantIDFromContext(ctx)
|
||
if !ok || tenantID == 0 || s.kbService == nil {
|
||
return
|
||
}
|
||
|
||
// 快路径:三项默认库齐备直接返回(一次只读列表,绝大多数请求止于此)。
|
||
kbs, err := s.kbService.ListKnowledgeBasesByTenantID(ctx, tenantID)
|
||
if err != nil {
|
||
logger.Warnf(ctx, "tenant bootstrap: lazy ensure list KBs failed: tenant=%d err=%v", tenantID, err)
|
||
return
|
||
}
|
||
if tenantDefaultsComplete(kbs) {
|
||
return
|
||
}
|
||
|
||
// 进程内串行化:并发的列表请求只允许一个进入补建段,防止同名默认库
|
||
// 重复建档(CreateKnowledgeBase 无名称唯一约束)。锁内复查双保险。
|
||
s.ensureMu.Lock()
|
||
defer s.ensureMu.Unlock()
|
||
kbs, err = s.kbService.ListKnowledgeBasesByTenantID(ctx, tenantID)
|
||
if err != nil {
|
||
logger.Warnf(ctx, "tenant bootstrap: lazy ensure list KBs failed: tenant=%d err=%v", tenantID, err)
|
||
return
|
||
}
|
||
if tenantDefaultsComplete(kbs) {
|
||
return
|
||
}
|
||
|
||
// 自愈上下文:执行租户落到目标空间;补建人取当前登录用户(与引导同口径,
|
||
// 合成 API-key 用户跳过);CreateKnowledgeFromFile 依赖 TenantInfo。
|
||
seedCtx := types.WithExecutionTenant(ctx, tenantID)
|
||
if tenant, tErr := s.tenantService.GetTenantByID(ctx, tenantID); tErr == nil && tenant != nil {
|
||
seedCtx = context.WithValue(seedCtx, types.TenantInfoContextKey, tenant)
|
||
}
|
||
if uid, ok := types.UserIDFromContext(ctx); ok && !types.IsSyntheticUserID(uid) {
|
||
seedCtx = context.WithValue(seedCtx, types.UserIDContextKey, uid)
|
||
}
|
||
logger.Infof(seedCtx, "tenant bootstrap: lazy ensure defaults, tenant=%d existing_kbs=%d", tenantID, len(kbs))
|
||
|
||
// 培训两库恒补;「新手入门」仅零库空间补建(见方法注释)。
|
||
s.ensureTrainingKnowledgeBases(seedCtx, tenantID, kbs)
|
||
if len(kbs) == 0 {
|
||
models, mErr := s.modelService.ListModels(seedCtx)
|
||
if mErr != nil {
|
||
logger.Warnf(seedCtx, "tenant bootstrap: lazy ensure list models failed: tenant=%d err=%v", tenantID, mErr)
|
||
return
|
||
}
|
||
_ = s.seedStarterKB(seedCtx,
|
||
PickDefaultModelID(models, types.ModelTypeKnowledgeQA),
|
||
PickDefaultModelID(models, types.ModelTypeEmbedding))
|
||
}
|
||
}
|
||
|
||
// tenantDefaultsComplete 判断空间的开箱默认库是否齐备:新手入门 + 培训课件 +
|
||
// 培训题库三项都在才算完整。
|
||
func tenantDefaultsComplete(kbs []*types.KnowledgeBase) bool {
|
||
var hasStarter, hasCourseware, hasBank bool
|
||
for _, kb := range kbs {
|
||
if kb == nil {
|
||
continue
|
||
}
|
||
switch {
|
||
case kb.Name == BootstrapKBName:
|
||
hasStarter = true
|
||
case kb.Source == types.KnowledgeBaseSourceTrainingCourseware:
|
||
hasCourseware = true
|
||
case kb.Source == types.KnowledgeBaseSourceTrainingQuestionBank:
|
||
hasBank = true
|
||
}
|
||
}
|
||
return hasStarter && hasCourseware && hasBank
|
||
}
|
||
|
||
// ensureTrainingKnowledgeBases 确保「企业培训(课件)/(题库)」两个系统默认库
|
||
// 存在(按 Source 标记去重,缺失即建,已存在跳过;模型由 CreateKnowledgeBase
|
||
// 的默认兜底自动绑定)。与培训域 trainingService.ensureTrainingKnowledgeBases
|
||
// 完全同源:后续培训上传/题库导入按同一 Source 标记复用这里的库,不会重复建档。
|
||
// fail-open:单库失败仅记日志,不阻断注册/建租户主流程。
|
||
func (s *tenantBootstrapService) ensureTrainingKnowledgeBases(ctx context.Context, tenantID uint64, existing []*types.KnowledgeBase) {
|
||
if s.kbService == nil {
|
||
return
|
||
}
|
||
hasSource := func(source string) bool {
|
||
for _, kb := range existing {
|
||
if kb != nil && kb.Source == source {
|
||
return true
|
||
}
|
||
}
|
||
return false
|
||
}
|
||
seeds := []struct {
|
||
source string
|
||
name string
|
||
description string
|
||
}{
|
||
{types.KnowledgeBaseSourceTrainingCourseware, trainingCoursewareKBName, trainingCoursewareKBDescription},
|
||
{types.KnowledgeBaseSourceTrainingQuestionBank, trainingQuestionBankKBName, trainingQuestionBankKBDescription},
|
||
}
|
||
for _, seed := range seeds {
|
||
if hasSource(seed.source) {
|
||
continue
|
||
}
|
||
created, err := s.kbService.CreateKnowledgeBase(ctx, &types.KnowledgeBase{
|
||
Name: seed.name,
|
||
Description: seed.description,
|
||
Source: seed.source,
|
||
})
|
||
if err != nil {
|
||
logger.Warnf(ctx, "tenant bootstrap: ensure training KB failed: tenant=%d source=%s err=%v",
|
||
tenantID, seed.source, err)
|
||
continue
|
||
}
|
||
logger.Infof(ctx, "tenant bootstrap: training KB ensured: tenant=%d kb=%s source=%s",
|
||
tenantID, created.ID, seed.source)
|
||
}
|
||
}
|
||
|
||
// PickDefaultModelID returns the tenant-visible default model of the given
|
||
// type: the is_default row first, then the first active row. Empty string
|
||
// when the deployment has no usable model of that type. Shared by the
|
||
// create-time fallbacks (KB / agent) so every path resolves defaults the
|
||
// same way.
|
||
func PickDefaultModelID(models []*types.Model, modelType types.ModelType) string {
|
||
first := ""
|
||
for _, m := range models {
|
||
if m == nil || m.Type != modelType || strings.TrimSpace(m.ID) == "" {
|
||
continue
|
||
}
|
||
if m.Status != "" && m.Status != types.ModelStatusActive {
|
||
continue
|
||
}
|
||
if m.IsDefault {
|
||
return m.ID
|
||
}
|
||
if first == "" {
|
||
first = m.ID
|
||
}
|
||
}
|
||
return first
|
||
}
|
||
|
||
// buildInMemoryFileHeader constructs a real *multipart.FileHeader for in-memory
|
||
// content so service paths that expect an uploaded file (CreateKnowledgeFromFile)
|
||
// can be reused without an HTTP round-trip. FileHeader's Open() reads unexported
|
||
// content captured by multipart form parsing, so the only reliable construction
|
||
// is a synthetic multipart round-trip in memory.
|
||
func buildInMemoryFileHeader(name, content string) (*multipart.FileHeader, error) {
|
||
if strings.TrimSpace(name) == "" {
|
||
return nil, errors.New("file name is required")
|
||
}
|
||
body := &bytes.Buffer{}
|
||
mw := multipart.NewWriter(body)
|
||
fw, err := mw.CreateFormFile("file", name)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
if _, err := io.Copy(fw, strings.NewReader(content)); err != nil {
|
||
return nil, err
|
||
}
|
||
if err := mw.Close(); err != nil {
|
||
return nil, err
|
||
}
|
||
form, err := multipart.NewReader(body, mw.Boundary()).ReadForm(int64(body.Len()) + 1<<20)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
fhs := form.File["file"]
|
||
if len(fhs) == 0 {
|
||
return nil, errors.New("multipart form contains no file part")
|
||
}
|
||
return fhs[0], nil
|
||
}
|