Merge branch 'main' into storage-allow-list
This commit is contained in:
@@ -166,8 +166,26 @@ func (h *CustomAgentHandler) ListAgents(c *gin.Context) {
|
||||
}
|
||||
|
||||
// Per-tenant "disabled by me" for own agents (only affects this tenant's conversation dropdown)
|
||||
tenantID, _ := c.Get(types.TenantIDContextKey.String())
|
||||
disabledOwnIDs, _ := h.disabledRepo.ListDisabledOwnAgentIDs(ctx, tenantID.(uint64))
|
||||
tenantIDVal, exists := c.Get(types.TenantIDContextKey.String())
|
||||
if !exists {
|
||||
logger.Error(ctx, "Tenant ID not found in context")
|
||||
c.Error(errors.NewUnauthorizedError("Missing tenant context"))
|
||||
return
|
||||
}
|
||||
tenantID, ok := tenantIDVal.(uint64)
|
||||
if !ok {
|
||||
logger.Errorf(ctx, "Tenant ID has unexpected type %T in context", tenantIDVal)
|
||||
c.Error(errors.NewInternalServerError("Invalid tenant context type"))
|
||||
return
|
||||
}
|
||||
disabledOwnIDs, err := h.disabledRepo.ListDisabledOwnAgentIDs(ctx, tenantID)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"tenant_id": tenantID,
|
||||
})
|
||||
c.Error(errors.NewInternalServerError("Failed to list disabled agent IDs: " + err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
@@ -379,6 +397,25 @@ func (h *CustomAgentHandler) GetPlaceholders(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// GetAgentTypePresets godoc
|
||||
// @Summary 获取智能体类型预设列表
|
||||
// @Description 返回所有 smart-reasoning 下可用的智能体类型预设(RAG/Wiki/Hybrid/Custom),用于编辑器自动填充系统提示词、工具和 KB 兼容性
|
||||
// @Tags 智能体
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} map[string]interface{} "预设列表"
|
||||
// @Security Bearer
|
||||
// @Security ApiKeyAuth
|
||||
// @Router /agents/type-presets [get]
|
||||
func (h *CustomAgentHandler) GetAgentTypePresets(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
presets := types.ListAgentTypePresetsWithContext(ctx)
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": presets,
|
||||
})
|
||||
}
|
||||
|
||||
// GetSuggestedQuestions godoc
|
||||
// @Summary 获取推荐问题
|
||||
// @Description 基于智能体关联的知识库,返回推荐问题供用户快捷提问
|
||||
|
||||
+127
-166
@@ -89,7 +89,7 @@ func NewInitializationHandler(
|
||||
// KBModelConfigRequest 知识库模型配置请求(简化版,只传模型ID)
|
||||
type KBModelConfigRequest struct {
|
||||
LLMModelID string `json:"llmModelId" binding:"required"`
|
||||
EmbeddingModelID string `json:"embeddingModelId" binding:"required"`
|
||||
EmbeddingModelID string `json:"embeddingModelId"` // optional when RAG indexing is disabled
|
||||
VLMConfig *types.VLMConfig `json:"vlm_config"`
|
||||
ASRConfig *types.ASRConfig `json:"asr_config"`
|
||||
|
||||
@@ -236,7 +236,7 @@ func (h *InitializationHandler) UpdateKBConfig(c *gin.Context) {
|
||||
}
|
||||
|
||||
// 检查Embedding模型是否可以修改
|
||||
if kb.EmbeddingModelID != "" && kb.EmbeddingModelID != req.EmbeddingModelID {
|
||||
if kb.EmbeddingModelID != "" && req.EmbeddingModelID != "" && kb.EmbeddingModelID != req.EmbeddingModelID {
|
||||
// 检查是否已有文件
|
||||
knowledgeList, err := h.knowledgeService.ListPagedKnowledgeByKnowledgeBaseID(ctx,
|
||||
kbIdStr, &types.Pagination{
|
||||
@@ -258,16 +258,21 @@ func (h *InitializationHandler) UpdateKBConfig(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
embeddingModel, err := h.modelService.GetModelByID(ctx, req.EmbeddingModelID)
|
||||
if err != nil || embeddingModel == nil {
|
||||
logger.Error(ctx, "Embedding model not found")
|
||||
c.Error(errors.NewBadRequestError("Embedding模型不存在"))
|
||||
return
|
||||
// Embedding模型仅在需要时验证(RAG检索启用时)
|
||||
if req.EmbeddingModelID != "" {
|
||||
embeddingModel, err := h.modelService.GetModelByID(ctx, req.EmbeddingModelID)
|
||||
if err != nil || embeddingModel == nil {
|
||||
logger.Error(ctx, "Embedding model not found")
|
||||
c.Error(errors.NewBadRequestError("Embedding模型不存在"))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 更新知识库的模型ID
|
||||
kb.SummaryModelID = req.LLMModelID
|
||||
kb.EmbeddingModelID = req.EmbeddingModelID
|
||||
if req.EmbeddingModelID != "" {
|
||||
kb.EmbeddingModelID = req.EmbeddingModelID
|
||||
}
|
||||
|
||||
// 处理多模态模型配置
|
||||
kb.VLMConfig = types.VLMConfig{}
|
||||
@@ -1467,12 +1472,76 @@ func (h *InitializationHandler) buildConfigResponse(ctx context.Context, models
|
||||
return config
|
||||
}
|
||||
|
||||
// RemoteModelCheckRequest 远程模型检查请求结构
|
||||
type RemoteModelCheckRequest struct {
|
||||
ModelName string `json:"modelName" binding:"required"`
|
||||
BaseURL string `json:"baseUrl" binding:"required"`
|
||||
APIKey string `json:"apiKey"`
|
||||
Provider string `json:"provider"`
|
||||
// ModelTestRequest 统一的"测试连接"请求体。
|
||||
//
|
||||
// 四种模型(chat/embedding/rerank/asr)的测试接口共享同一份结构,以便:
|
||||
// - 前端只需维护一份表单 → 后端映射。
|
||||
// - 后端可以直接把请求转成 *types.Model,再调用各包的 ConfigFromModel,
|
||||
// 与生产路径(service.modelService.GetXxxModel)走完全相同的装配流程,
|
||||
// 彻底消除过去每个测试端点手工拼 Config 的样板代码。
|
||||
//
|
||||
// 所有 provider/model 通用字段都在这里集中声明;若未来新增字段(比如现在的
|
||||
// custom_headers),只需改一处,生产路径和测试路径会同时生效。
|
||||
type ModelTestRequest struct {
|
||||
Source string `json:"source"` // 为空时按需默认为 "remote"
|
||||
ModelName string `json:"modelName" binding:"required"`
|
||||
BaseURL string `json:"baseUrl"`
|
||||
APIKey string `json:"apiKey"`
|
||||
Provider string `json:"provider"`
|
||||
InterfaceType string `json:"interfaceType,omitempty"`
|
||||
Dimension int `json:"dimension,omitempty"`
|
||||
CustomHeaders map[string]string `json:"customHeaders,omitempty"`
|
||||
ExtraConfig map[string]string `json:"extraConfig,omitempty"`
|
||||
}
|
||||
|
||||
// RemoteModelCheckRequest 兼容旧 swagger 定义。
|
||||
//
|
||||
// Deprecated: 保留是为了不破坏已生成的 API 文档,新代码请直接使用 ModelTestRequest。
|
||||
type RemoteModelCheckRequest = ModelTestRequest
|
||||
|
||||
// buildTestModel 把测试连接请求转成一个临时的 *types.Model(不落库),
|
||||
// 供 ConfigFromModel 使用。source 为空时按 defaultSource 兜底(chat/rerank/asr
|
||||
// 默认 remote,embedding 会根据前端传入的 source 决定)。
|
||||
func (h *InitializationHandler) buildTestModel(
|
||||
req *ModelTestRequest, modelType types.ModelType, defaultSource types.ModelSource,
|
||||
) *types.Model {
|
||||
source := types.ModelSource(strings.ToLower(req.Source))
|
||||
if source == "" {
|
||||
source = defaultSource
|
||||
}
|
||||
return &types.Model{
|
||||
Name: req.ModelName,
|
||||
Type: modelType,
|
||||
Source: source,
|
||||
Parameters: types.ModelParameters{
|
||||
BaseURL: req.BaseURL,
|
||||
APIKey: req.APIKey,
|
||||
Provider: req.Provider,
|
||||
InterfaceType: req.InterfaceType,
|
||||
ExtraConfig: req.ExtraConfig,
|
||||
CustomHeaders: req.CustomHeaders,
|
||||
EmbeddingParameters: types.EmbeddingParameters{
|
||||
Dimension: req.Dimension,
|
||||
TruncatePromptTokens: 256,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// resolveTenantWeKnoraCloudCreds 从当前租户上下文里取出 WeKnoraCloud 凭证,
|
||||
// 供测试连接端点补齐 appID/appSecret。与 service.resolveWeKnoraCloudCredentials
|
||||
// 对应,但因为 handler 还没有被注入 tenantService(历史原因),暂时从
|
||||
// TenantInfoFromContext 读取,等效果相同。
|
||||
func (h *InitializationHandler) resolveTenantWeKnoraCloudCreds(ctx context.Context) (string, string, bool) {
|
||||
tenantInfo, ok := types.TenantInfoFromContext(ctx)
|
||||
if !ok {
|
||||
return "", "", false
|
||||
}
|
||||
creds := tenantInfo.Credentials.GetWeKnoraCloud()
|
||||
if creds == nil {
|
||||
return "", "", true
|
||||
}
|
||||
return creds.AppID, creds.AppSecret, true
|
||||
}
|
||||
|
||||
// CheckRemoteModel godoc
|
||||
@@ -1492,54 +1561,33 @@ func (h *InitializationHandler) CheckRemoteModel(c *gin.Context) {
|
||||
|
||||
logger.Info(ctx, "Checking remote model connection")
|
||||
|
||||
var req RemoteModelCheckRequest
|
||||
var req ModelTestRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.Error(ctx, "Failed to parse remote model check request", err)
|
||||
c.Error(errors.NewBadRequestError(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
// 验证请求参数
|
||||
if req.ModelName == "" || req.BaseURL == "" {
|
||||
logger.Error(ctx, "Model name and base URL are required")
|
||||
c.Error(errors.NewBadRequestError("模型名称和Base URL不能为空"))
|
||||
return
|
||||
}
|
||||
|
||||
// SSRF validation
|
||||
if err := utils.ValidateURLForSSRF(req.BaseURL); err != nil {
|
||||
logger.Warnf(ctx, "SSRF validation failed for remote model BaseURL: %v", err)
|
||||
c.Error(errors.NewBadRequestError(fmt.Sprintf("Base URL 未通过安全校验: %v", err)))
|
||||
return
|
||||
}
|
||||
tenantInfo, ok := types.TenantInfoFromContext(ctx)
|
||||
appID, appSecret, ok := h.resolveTenantWeKnoraCloudCreds(ctx)
|
||||
if !ok {
|
||||
logger.Error(ctx, "Tenant info not found")
|
||||
c.Error(errors.NewBadRequestError("租户信息未找到"))
|
||||
return
|
||||
}
|
||||
var appID, appSecret string
|
||||
if creds := tenantInfo.Credentials.GetWeKnoraCloud(); creds != nil {
|
||||
appID = creds.AppID
|
||||
appSecret = creds.AppSecret
|
||||
}
|
||||
|
||||
// 创建模型配置进行测试
|
||||
modelConfig := &types.Model{
|
||||
Name: req.ModelName,
|
||||
Source: "remote",
|
||||
Parameters: types.ModelParameters{
|
||||
BaseURL: req.BaseURL,
|
||||
APIKey: req.APIKey,
|
||||
Provider: req.Provider,
|
||||
AppID: appID,
|
||||
AppSecret: appSecret,
|
||||
},
|
||||
Type: "llm", // 默认类型,实际检查时不区分具体类型
|
||||
}
|
||||
|
||||
// 检查远程模型连接
|
||||
available, message := h.checkRemoteModelConnection(ctx, modelConfig)
|
||||
model := h.buildTestModel(&req, types.ModelTypeKnowledgeQA, types.ModelSourceRemote)
|
||||
available, message := h.checkChatModelConnection(ctx, model, appID, appSecret)
|
||||
|
||||
logger.Infof(ctx, "Remote model check completed, available: %v, message: %s", available, message)
|
||||
|
||||
@@ -1569,22 +1617,16 @@ func (h *InitializationHandler) TestEmbeddingModel(c *gin.Context) {
|
||||
|
||||
logger.Info(ctx, "Testing embedding model connectivity and functionality")
|
||||
|
||||
var req struct {
|
||||
Source string `json:"source" binding:"required"`
|
||||
ModelName string `json:"modelName" binding:"required"`
|
||||
BaseURL string `json:"baseUrl"`
|
||||
APIKey string `json:"apiKey"`
|
||||
Dimension int `json:"dimension"`
|
||||
Provider string `json:"provider"`
|
||||
}
|
||||
|
||||
var req ModelTestRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.Error(ctx, "Failed to parse embedding test request", err)
|
||||
c.Error(errors.NewBadRequestError(err.Error()))
|
||||
return
|
||||
}
|
||||
if req.Source == "" {
|
||||
req.Source = string(types.ModelSourceRemote)
|
||||
}
|
||||
|
||||
// SSRF validation for embedding BaseURL
|
||||
if req.BaseURL != "" {
|
||||
if err := utils.ValidateURLForSSRF(req.BaseURL); err != nil {
|
||||
logger.Warnf(ctx, "SSRF validation failed for embedding BaseURL: %v", err)
|
||||
@@ -1593,7 +1635,7 @@ func (h *InitializationHandler) TestEmbeddingModel(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
// 检查是否是阿里云多模态 embedding 模型(暂不支持)
|
||||
// 阿里云多模态 Embedding 模型暂不支持
|
||||
if strings.ToLower(req.Provider) == "aliyun" {
|
||||
modelNameLower := strings.ToLower(req.ModelName)
|
||||
if strings.Contains(modelNameLower, "vision") || strings.Contains(modelNameLower, "multimodal") {
|
||||
@@ -1609,33 +1651,16 @@ func (h *InitializationHandler) TestEmbeddingModel(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
}
|
||||
tenantInfo, ok := types.TenantInfoFromContext(ctx)
|
||||
|
||||
appID, appSecret, ok := h.resolveTenantWeKnoraCloudCreds(ctx)
|
||||
if !ok {
|
||||
logger.Error(ctx, "Tenant info not found")
|
||||
c.Error(errors.NewBadRequestError("租户信息未找到"))
|
||||
return
|
||||
}
|
||||
var appID, appSecret string
|
||||
if creds := tenantInfo.Credentials.GetWeKnoraCloud(); creds != nil {
|
||||
appID = creds.AppID
|
||||
appSecret = creds.AppSecret
|
||||
}
|
||||
|
||||
// 构造 embedder 配置
|
||||
cfg := embedding.Config{
|
||||
Source: types.ModelSource(strings.ToLower(req.Source)),
|
||||
BaseURL: req.BaseURL,
|
||||
ModelName: req.ModelName,
|
||||
APIKey: req.APIKey,
|
||||
TruncatePromptTokens: 256,
|
||||
Dimensions: req.Dimension,
|
||||
ModelID: "",
|
||||
Provider: req.Provider,
|
||||
AppID: appID,
|
||||
AppSecret: appSecret,
|
||||
}
|
||||
|
||||
emb, err := embedding.NewEmbedder(cfg, h.pooler, h.ollamaService)
|
||||
model := h.buildTestModel(&req, types.ModelTypeEmbedding, types.ModelSourceRemote)
|
||||
emb, err := embedding.NewEmbedder(embedding.ConfigFromModel(model, appID, appSecret), h.pooler, h.ollamaService)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{"model": utils.SanitizeForLog(req.ModelName)})
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
@@ -1645,11 +1670,9 @@ func (h *InitializationHandler) TestEmbeddingModel(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// 执行一次最小化 embedding 调用
|
||||
sample := "hello"
|
||||
vec, err := emb.Embed(ctx, sample)
|
||||
vec, err := emb.Embed(ctx, "hello")
|
||||
if err != nil {
|
||||
logger.Error(ctx, "Failed to create embedder", err)
|
||||
logger.Error(ctx, "Failed to call embedder", err)
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": gin.H{`available`: false, `message`: fmt.Sprintf("调用Embedding失败: %v", err), `dimension`: 0},
|
||||
@@ -1664,44 +1687,23 @@ func (h *InitializationHandler) TestEmbeddingModel(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// checkRemoteModelConnection 检查远程模型连接的内部方法
|
||||
func (h *InitializationHandler) checkRemoteModelConnection(ctx context.Context,
|
||||
model *types.Model,
|
||||
// checkChatModelConnection 使用 chat 模块做一次最小化调用来测试连通性与鉴权。
|
||||
// 与生产路径走完全相同的 ConfigFromModel → NewChat 流程,因此 CustomHeaders、
|
||||
// ExtraConfig、Provider 等字段都会被正确透传。
|
||||
func (h *InitializationHandler) checkChatModelConnection(
|
||||
ctx context.Context, model *types.Model, appID, appSecret string,
|
||||
) (bool, string) {
|
||||
// 使用 models/chat 进行连接检查
|
||||
// 创建聊天配置
|
||||
chatConfig := &chat.ChatConfig{
|
||||
Source: types.ModelSourceRemote,
|
||||
BaseURL: model.Parameters.BaseURL,
|
||||
ModelName: model.Name,
|
||||
APIKey: model.Parameters.APIKey,
|
||||
ModelID: model.Name,
|
||||
Provider: model.Parameters.Provider,
|
||||
AppID: model.Parameters.AppID,
|
||||
AppSecret: model.Parameters.AppSecret,
|
||||
}
|
||||
|
||||
// 创建聊天实例
|
||||
chatInstance, err := chat.NewChat(chatConfig, h.ollamaService)
|
||||
chatInstance, err := chat.NewChat(chat.ConfigFromModel(model, appID, appSecret), h.ollamaService)
|
||||
if err != nil {
|
||||
return false, fmt.Sprintf("创建聊天实例失败: %v", err)
|
||||
}
|
||||
|
||||
// 构造测试消息
|
||||
testMessages := []chat.Message{
|
||||
{
|
||||
Role: "user",
|
||||
Content: "test",
|
||||
},
|
||||
}
|
||||
|
||||
// 构造测试选项
|
||||
testMessages := []chat.Message{{Role: "user", Content: "test"}}
|
||||
testOptions := &chat.ChatOptions{
|
||||
MaxTokens: 1,
|
||||
Thinking: &[]bool{false}[0], // for dashscope.aliyuncs qwen3-32b
|
||||
}
|
||||
|
||||
// 使用聊天实例进行测试
|
||||
_, err = chatInstance.Chat(ctx, testMessages, testOptions)
|
||||
if err != nil {
|
||||
errMsg := err.Error()
|
||||
@@ -1727,54 +1729,24 @@ func (h *InitializationHandler) checkRemoteModelConnection(ctx context.Context,
|
||||
return true, "连接正常,模型可用"
|
||||
}
|
||||
|
||||
// checkRerankModelConnection 检查Rerank模型连接和功能的内部方法
|
||||
func (h *InitializationHandler) checkRerankModelConnection(ctx context.Context,
|
||||
modelName, baseURL, apiKey string,
|
||||
// checkRerankModelConnection 使用 rerank 模块做一次最小化调用来测试连通性与鉴权。
|
||||
// 与生产路径共用 ConfigFromModel,所有字段(CustomHeaders 等)都透传。
|
||||
func (h *InitializationHandler) checkRerankModelConnection(
|
||||
ctx context.Context, model *types.Model, appID, appSecret string,
|
||||
) (bool, string) {
|
||||
// 创建Reranker配置
|
||||
config := &rerank.RerankerConfig{
|
||||
APIKey: apiKey,
|
||||
BaseURL: baseURL,
|
||||
ModelName: modelName,
|
||||
Source: types.ModelSourceRemote, // 默认值,实际会根据URL判断
|
||||
}
|
||||
tenantInfo, ok := types.TenantInfoFromContext(ctx)
|
||||
if !ok {
|
||||
logger.Error(ctx, "Tenant info not found")
|
||||
return false, "租户信息未找到"
|
||||
}
|
||||
var appID, appSecret string
|
||||
if creds := tenantInfo.Credentials.GetWeKnoraCloud(); creds != nil {
|
||||
appID = creds.AppID
|
||||
appSecret = creds.AppSecret
|
||||
}
|
||||
config.AppID = appID
|
||||
config.AppSecret = appSecret
|
||||
|
||||
// 创建Reranker实例
|
||||
reranker, err := rerank.NewReranker(config)
|
||||
reranker, err := rerank.NewReranker(rerank.ConfigFromModel(model, appID, appSecret))
|
||||
if err != nil {
|
||||
return false, fmt.Sprintf("创建Reranker失败: %v", err)
|
||||
}
|
||||
|
||||
// 简化的测试数据
|
||||
testQuery := "ping"
|
||||
testDocuments := []string{
|
||||
"pong",
|
||||
}
|
||||
|
||||
// 使用Reranker进行测试
|
||||
results, err := reranker.Rerank(ctx, testQuery, testDocuments)
|
||||
results, err := reranker.Rerank(ctx, "ping", []string{"pong"})
|
||||
if err != nil {
|
||||
return false, fmt.Sprintf("重排测试失败: %v", err)
|
||||
}
|
||||
|
||||
// 检查结果
|
||||
if len(results) > 0 {
|
||||
return true, fmt.Sprintf("重排功能正常,返回%d个结果", len(results))
|
||||
} else {
|
||||
return false, "重排接口连接成功,但未返回重排结果"
|
||||
}
|
||||
return false, "重排接口连接成功,但未返回重排结果"
|
||||
}
|
||||
|
||||
// CheckRerankModel godoc
|
||||
@@ -1794,36 +1766,34 @@ func (h *InitializationHandler) CheckRerankModel(c *gin.Context) {
|
||||
|
||||
logger.Info(ctx, "Checking rerank model connection and functionality")
|
||||
|
||||
var req struct {
|
||||
ModelName string `json:"modelName" binding:"required"`
|
||||
BaseURL string `json:"baseUrl" binding:"required"`
|
||||
APIKey string `json:"apiKey"`
|
||||
}
|
||||
|
||||
var req ModelTestRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.Error(ctx, "Failed to parse rerank model check request", err)
|
||||
c.Error(errors.NewBadRequestError(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
// 验证请求参数
|
||||
if req.ModelName == "" || req.BaseURL == "" {
|
||||
logger.Error(ctx, "Model name and base URL are required")
|
||||
c.Error(errors.NewBadRequestError("模型名称和Base URL不能为空"))
|
||||
return
|
||||
}
|
||||
|
||||
// SSRF validation
|
||||
if err := utils.ValidateURLForSSRF(req.BaseURL); err != nil {
|
||||
logger.Warnf(ctx, "SSRF validation failed for rerank BaseURL: %v", err)
|
||||
c.Error(errors.NewBadRequestError(fmt.Sprintf("Base URL 未通过安全校验: %v", err)))
|
||||
return
|
||||
}
|
||||
|
||||
// 检查Rerank模型连接和功能
|
||||
available, message := h.checkRerankModelConnection(
|
||||
ctx, req.ModelName, req.BaseURL, req.APIKey,
|
||||
)
|
||||
appID, appSecret, ok := h.resolveTenantWeKnoraCloudCreds(ctx)
|
||||
if !ok {
|
||||
logger.Error(ctx, "Tenant info not found")
|
||||
c.Error(errors.NewBadRequestError("租户信息未找到"))
|
||||
return
|
||||
}
|
||||
|
||||
model := h.buildTestModel(&req, types.ModelTypeRerank, types.ModelSourceRemote)
|
||||
available, message := h.checkRerankModelConnection(ctx, model, appID, appSecret)
|
||||
|
||||
logger.Infof(ctx, "Rerank model check completed, available: %v, message: %s", available, message)
|
||||
|
||||
@@ -1853,12 +1823,7 @@ func (h *InitializationHandler) CheckASRModel(c *gin.Context) {
|
||||
|
||||
logger.Info(ctx, "Checking ASR model connection")
|
||||
|
||||
var req struct {
|
||||
ModelName string `json:"modelName" binding:"required"`
|
||||
BaseURL string `json:"baseUrl" binding:"required"`
|
||||
APIKey string `json:"apiKey"`
|
||||
}
|
||||
|
||||
var req ModelTestRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.Error(ctx, "Failed to parse ASR model check request", err)
|
||||
c.Error(errors.NewBadRequestError(err.Error()))
|
||||
@@ -1871,20 +1836,16 @@ func (h *InitializationHandler) CheckASRModel(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// SSRF validation
|
||||
if err := utils.ValidateURLForSSRF(req.BaseURL); err != nil {
|
||||
logger.Warnf(ctx, "SSRF validation failed for ASR BaseURL: %v", err)
|
||||
c.Error(errors.NewBadRequestError(fmt.Sprintf("Base URL 未通过安全校验: %v", err)))
|
||||
return
|
||||
}
|
||||
|
||||
// 使用 ASR 模块测试连接:发送一段极短的静默 WAV 音频
|
||||
asrInstance, err := asr.NewASR(&asr.Config{
|
||||
BaseURL: req.BaseURL,
|
||||
ModelName: req.ModelName,
|
||||
APIKey: req.APIKey,
|
||||
Source: "remote",
|
||||
})
|
||||
// 用统一构造器生成测试用 *types.Model(ASR 不涉及 WeKnoraCloud 凭证),
|
||||
// 发送一段极短的静默 WAV 音频验证 /v1/audio/transcriptions 端点可达。
|
||||
model := h.buildTestModel(&req, types.ModelTypeASR, types.ModelSourceRemote)
|
||||
asrInstance, err := asr.NewASR(asr.ConfigFromModel(model))
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to create ASR instance for check: %v", err)
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
|
||||
+151
-17
@@ -13,10 +13,12 @@ import (
|
||||
|
||||
goerrors "errors"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/agent/tools"
|
||||
"github.com/Tencent/WeKnora/internal/application/repository"
|
||||
"github.com/Tencent/WeKnora/internal/application/service"
|
||||
"github.com/Tencent/WeKnora/internal/errors"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/tracing/langfuse"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/Tencent/WeKnora/internal/utils"
|
||||
@@ -185,6 +187,29 @@ func (h *KnowledgeHandler) handleDuplicateKnowledgeError(c *gin.Context,
|
||||
return false
|
||||
}
|
||||
|
||||
// enqueueKnowledgeListDelete enqueues an async batch-delete task for the
|
||||
// given knowledge IDs and returns the asynq task ID.
|
||||
func (h *KnowledgeHandler) enqueueKnowledgeListDelete(
|
||||
ctx context.Context, tenantID uint64, ids []string,
|
||||
) (string, error) {
|
||||
payload := types.KnowledgeListDeletePayload{
|
||||
TenantID: tenantID,
|
||||
KnowledgeIDs: ids,
|
||||
}
|
||||
langfuse.InjectTracing(ctx, &payload)
|
||||
payloadBytes, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("marshal payload: %w", err)
|
||||
}
|
||||
task := asynq.NewTask(types.TypeKnowledgeListDelete, payloadBytes,
|
||||
asynq.Queue("low"), asynq.MaxRetry(3))
|
||||
info, err := h.asynqClient.Enqueue(task)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("enqueue task: %w", err)
|
||||
}
|
||||
return info.ID, nil
|
||||
}
|
||||
|
||||
// CreateKnowledgeFromFile godoc
|
||||
// @Summary 从文件创建知识
|
||||
// @Description 上传文件并创建知识条目
|
||||
@@ -627,6 +652,112 @@ func (h *KnowledgeHandler) DeleteKnowledge(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// BatchDeleteKnowledgeRequest is the body schema for POST /knowledge/batch-delete.
|
||||
type BatchDeleteKnowledgeRequest struct {
|
||||
KBID string `json:"kb_id" binding:"required"`
|
||||
IDs []string `json:"ids" binding:"required"`
|
||||
}
|
||||
|
||||
// BatchDeleteKnowledge godoc
|
||||
// @Summary 批量删除知识
|
||||
// @Description 按 ID 列表批量删除单个知识库下的多个知识条目
|
||||
// @Tags 知识管理
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param request body BatchDeleteKnowledgeRequest true "批量删除请求"
|
||||
// @Success 200 {object} map[string]interface{} "删除成功"
|
||||
// @Failure 400 {object} errors.AppError "请求参数错误"
|
||||
// @Failure 403 {object} errors.AppError "权限不足"
|
||||
// @Security Bearer
|
||||
// @Security ApiKeyAuth
|
||||
// @Router /knowledge/batch-delete [post]
|
||||
func (h *KnowledgeHandler) BatchDeleteKnowledge(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
var req BatchDeleteKnowledgeRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.Error(errors.NewBadRequestError("Invalid request parameters: " + err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
// Deduplicate and drop empty IDs.
|
||||
seen := make(map[string]struct{}, len(req.IDs))
|
||||
ids := make([]string, 0, len(req.IDs))
|
||||
for _, raw := range req.IDs {
|
||||
id := strings.TrimSpace(raw)
|
||||
if id == "" {
|
||||
continue
|
||||
}
|
||||
if _, ok := seen[id]; ok {
|
||||
continue
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
c.Error(errors.NewBadRequestError("ids cannot be empty"))
|
||||
return
|
||||
}
|
||||
const maxBatch = 200
|
||||
if len(ids) > maxBatch {
|
||||
c.Error(errors.NewBadRequestError(fmt.Sprintf("too many ids (max %d per batch)", maxBatch)))
|
||||
return
|
||||
}
|
||||
|
||||
// Validate KB access (editor or admin) using the kb_id from body.
|
||||
_, kbID, effectiveTenantID, permission, err := h.validateKnowledgeBaseAccessWithKBID(c, req.KBID)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
if permission != types.OrgRoleAdmin && permission != types.OrgRoleEditor {
|
||||
c.Error(errors.NewForbiddenError("No permission to delete knowledge"))
|
||||
return
|
||||
}
|
||||
ctx = context.WithValue(ctx, types.TenantIDContextKey, effectiveTenantID)
|
||||
|
||||
// Single batch fetch to validate that every id exists and belongs to the
|
||||
// requested KB. The service-layer DeleteKnowledgeList only enforces tenant
|
||||
// scope, not KB scope, so the handler must guard against cross-KB deletion.
|
||||
knowledgeList, err := h.kgService.GetKnowledgeBatch(ctx, effectiveTenantID, ids)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
}
|
||||
if len(knowledgeList) != len(ids) {
|
||||
c.Error(errors.NewBadRequestError("One or more knowledge entries not found"))
|
||||
return
|
||||
}
|
||||
for _, k := range knowledgeList {
|
||||
if k.KnowledgeBaseID != kbID {
|
||||
c.Error(errors.NewBadRequestError(
|
||||
fmt.Sprintf("Knowledge %s does not belong to knowledge base %s",
|
||||
secutils.SanitizeForLog(k.ID), secutils.SanitizeForLog(kbID))))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
taskID, err := h.enqueueKnowledgeListDelete(ctx, effectiveTenantID, ids)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to enqueue batch knowledge delete task: %v", err)
|
||||
c.Error(errors.NewInternalServerError("Failed to enqueue batch delete task"))
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Batch knowledge delete task enqueued: %s, kb_id: %s, count: %d",
|
||||
taskID, secutils.SanitizeForLog(kbID), len(ids))
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": "Batch delete task submitted",
|
||||
"data": gin.H{
|
||||
"task_id": taskID,
|
||||
"deleted_count": len(ids),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// ClearKnowledgeBaseContents godoc
|
||||
// @Summary 清空知识库内容
|
||||
// @Description 删除知识库下的所有知识条目(异步任务)。知识库本身保留,仅清空其中的内容
|
||||
@@ -681,20 +812,7 @@ func (h *KnowledgeHandler) ClearKnowledgeBaseContents(c *gin.Context) {
|
||||
knowledgeIDs = append(knowledgeIDs, knowledge.ID)
|
||||
}
|
||||
|
||||
payload := types.KnowledgeListDeletePayload{
|
||||
TenantID: effectiveTenantID,
|
||||
KnowledgeIDs: knowledgeIDs,
|
||||
}
|
||||
payloadBytes, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to marshal knowledge list delete payload: %v", err)
|
||||
c.Error(errors.NewInternalServerError("Failed to create cleanup task"))
|
||||
return
|
||||
}
|
||||
|
||||
task := asynq.NewTask(types.TypeKnowledgeListDelete, payloadBytes,
|
||||
asynq.Queue("low"), asynq.MaxRetry(3))
|
||||
info, err := h.asynqClient.Enqueue(task)
|
||||
taskID, err := h.enqueueKnowledgeListDelete(ctx, effectiveTenantID, knowledgeIDs)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to enqueue knowledge list delete task: %v", err)
|
||||
c.Error(errors.NewInternalServerError("Failed to enqueue cleanup task"))
|
||||
@@ -702,7 +820,7 @@ func (h *KnowledgeHandler) ClearKnowledgeBaseContents(c *gin.Context) {
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Knowledge base contents clear task enqueued: %s, kb_id: %s, count: %d",
|
||||
info.ID, secutils.SanitizeForLog(kbID), len(knowledgeIDs))
|
||||
taskID, secutils.SanitizeForLog(kbID), len(knowledgeIDs))
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
@@ -1397,10 +1515,25 @@ func (h *KnowledgeHandler) SearchKnowledge(c *gin.Context) {
|
||||
c.Error(errors.NewInternalServerError("Failed to list knowledge bases").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
// `all` mode: authoritative server-side capability filter. Mirrors the
|
||||
// logic in ListKnowledgeBases so @file search, KB listing, and runtime
|
||||
// all agree on what "mode=all" actually means for this agent.
|
||||
filter := tools.DeriveKBFilterFromTools(agent.Config.AllowedTools)
|
||||
removed := 0
|
||||
for _, kb := range kbs {
|
||||
if kb != nil && kb.Type == types.KnowledgeBaseTypeDocument {
|
||||
scopes = append(scopes, types.KnowledgeSearchScope{TenantID: sourceTenantID, KBID: kb.ID})
|
||||
if kb == nil || kb.Type != types.KnowledgeBaseTypeDocument {
|
||||
continue
|
||||
}
|
||||
if !filter.IsEmpty() && !tools.KBSatisfiesToolRequirements(kb.Capabilities(), agent.Config.AllowedTools) {
|
||||
removed++
|
||||
continue
|
||||
}
|
||||
scopes = append(scopes, types.KnowledgeSearchScope{TenantID: sourceTenantID, KBID: kb.ID})
|
||||
}
|
||||
if removed > 0 {
|
||||
logger.Infof(ctx,
|
||||
"SearchKnowledge(agent=%s, mode=all): tool-capability filter removed %d KBs",
|
||||
agentID, removed)
|
||||
}
|
||||
}
|
||||
knowledges, hasMore, err := h.kgService.SearchKnowledgeForScopes(ctx, scopes, keyword, offset, limit, fileTypes)
|
||||
@@ -1543,6 +1676,7 @@ func (h *KnowledgeHandler) MoveKnowledge(c *gin.Context) {
|
||||
TargetKBID: req.TargetKBID,
|
||||
Mode: req.Mode,
|
||||
}
|
||||
langfuse.InjectTracing(ctx, &payload)
|
||||
|
||||
payloadBytes, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
|
||||
@@ -8,11 +8,13 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/agent/tools"
|
||||
"github.com/Tencent/WeKnora/internal/application/repository"
|
||||
"github.com/Tencent/WeKnora/internal/application/service"
|
||||
"github.com/Tencent/WeKnora/internal/errors"
|
||||
apperrors "github.com/Tencent/WeKnora/internal/errors"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/tracing/langfuse"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/Tencent/WeKnora/internal/utils"
|
||||
@@ -352,6 +354,30 @@ func (h *KnowledgeBaseHandler) ListKnowledgeBases(c *gin.Context) {
|
||||
}
|
||||
kbs = filtered
|
||||
}
|
||||
|
||||
// `all` mode: authoritative server-side capability filter so a client
|
||||
// that bypassed the frontend (old tab, curl, rogue plugin) can't @ a
|
||||
// KB whose capabilities don't match any allowed tool of this agent.
|
||||
// Non-`all` modes already constrain the scope explicitly.
|
||||
if mode == "all" && len(agent.Config.AllowedTools) > 0 {
|
||||
filter := tools.DeriveKBFilterFromTools(agent.Config.AllowedTools)
|
||||
if !filter.IsEmpty() {
|
||||
before := len(kbs)
|
||||
kept := make([]*types.KnowledgeBase, 0, before)
|
||||
for _, kb := range kbs {
|
||||
if tools.KBSatisfiesToolRequirements(kb.Capabilities(), agent.Config.AllowedTools) {
|
||||
kept = append(kept, kb)
|
||||
}
|
||||
}
|
||||
if removed := before - len(kept); removed > 0 {
|
||||
logger.Infof(ctx,
|
||||
"ListKnowledgeBases(agent=%s, mode=all): tool-capability filter removed %d of %d KBs",
|
||||
agentID, removed, before)
|
||||
}
|
||||
kbs = kept
|
||||
}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": kbs,
|
||||
@@ -636,6 +662,7 @@ func (h *KnowledgeBaseHandler) CopyKnowledgeBase(c *gin.Context) {
|
||||
SourceID: req.SourceID,
|
||||
TargetID: req.TargetID,
|
||||
}
|
||||
langfuse.InjectTracing(ctx, &payload)
|
||||
|
||||
payloadBytes, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
@@ -846,4 +873,4 @@ func (h *KnowledgeBaseHandler) ListMoveTargets(c *gin.Context) {
|
||||
"success": true,
|
||||
"data": targets,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1262,7 +1262,7 @@ func (h *OrganizationHandler) ShareAgent(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
if errors.Is(err, service.ErrAgentNotConfigured) {
|
||||
c.Error(apperrors.NewValidationError("Agent is not fully configured. Please set the chat model and, if using knowledge bases, the rerank model in agent settings."))
|
||||
c.Error(apperrors.NewValidationError("Agent is not fully configured. Please set the chat model, and set the rerank model if the knowledge_search tool is enabled in agent settings."))
|
||||
return
|
||||
}
|
||||
c.Error(apperrors.NewForbiddenError("Permission denied or invalid operation"))
|
||||
|
||||
@@ -213,9 +213,13 @@ func (h *Handler) setupStopEventHandler(
|
||||
eventBus.On(event.EventStop, func(ctx context.Context, evt event.Event) error {
|
||||
logger.Infof(ctx, "Received stop event, cancelling async operations for session: %s", sessionID)
|
||||
cancel()
|
||||
assistantMessage.Content = "用户停止了本次对话"
|
||||
// Use session's tenant for message update (ctx may have effectiveTenantID when using shared agent)
|
||||
updateCtx := context.WithValue(ctx, types.TenantIDContextKey, sessionTenantID)
|
||||
// Preserve whatever has been streamed so far; do not overwrite Content.
|
||||
// Use session's tenant for message update (ctx may have effectiveTenantID when using shared agent).
|
||||
// Use WithoutCancel so the GORM UPDATE survives the upcoming ctx.Done triggered by cancel()/client disconnect.
|
||||
updateCtx := context.WithValue(
|
||||
context.WithoutCancel(ctx),
|
||||
types.TenantIDContextKey, sessionTenantID,
|
||||
)
|
||||
h.completeAssistantMessage(updateCtx, assistantMessage, "") // empty query: stopped conversations are not indexed
|
||||
return nil
|
||||
})
|
||||
|
||||
@@ -615,7 +615,15 @@ func (h *Handler) executeQA(reqCtx *qaRequestContext, mode qaMode, generateTitle
|
||||
}
|
||||
// Agent mode: complete the assistant message in defer (normal mode does it via event handler)
|
||||
if mode == qaModeAgent {
|
||||
updateCtx := context.WithValue(streamCtx.asyncCtx, types.TenantIDContextKey, reqCtx.session.TenantID)
|
||||
// Use WithoutCancel so a user-triggered stop (which cancels
|
||||
// asyncCtx) doesn't also cancel the GORM UPDATE that persists
|
||||
// AgentSteps/Content. Without this, cancelled-ctx makes
|
||||
// GORM skip the write and the agent's intermediate steps
|
||||
// (thinking / tool_call history) are lost on page refresh.
|
||||
updateCtx := context.WithValue(
|
||||
context.WithoutCancel(streamCtx.asyncCtx),
|
||||
types.TenantIDContextKey, reqCtx.session.TenantID,
|
||||
)
|
||||
h.completeAssistantMessage(updateCtx, streamCtx.assistantMessage, reqCtx.query)
|
||||
logger.Infof(streamCtx.asyncCtx, "Agent QA service completed for session: %s", sessionID)
|
||||
}
|
||||
|
||||
+15
-227
@@ -2,7 +2,6 @@ package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
@@ -442,18 +441,6 @@ func (h *SystemHandler) isTOSEnvAvailable() bool {
|
||||
os.Getenv("TOS_BUCKET_NAME") != ""
|
||||
}
|
||||
|
||||
// MinioBucketInfo represents bucket information with access policy
|
||||
type MinioBucketInfo struct {
|
||||
Name string `json:"name"`
|
||||
Policy string `json:"policy"` // "public", "private", "custom"
|
||||
CreatedAt string `json:"created_at,omitempty"`
|
||||
}
|
||||
|
||||
// ListMinioBucketsResponse defines the response structure for listing buckets
|
||||
type ListMinioBucketsResponse struct {
|
||||
Buckets []MinioBucketInfo `json:"buckets"`
|
||||
}
|
||||
|
||||
// StorageEngineStatusItem describes one storage engine's availability and description.
|
||||
type StorageEngineStatusItem struct {
|
||||
Name string `json:"name"` // "local", "minio", "cos", "tos"
|
||||
@@ -505,188 +492,7 @@ func (h *SystemHandler) GetStorageEngineStatus(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// ListMinioBuckets godoc
|
||||
// @Summary 列出 MinIO 存储桶
|
||||
// @Description 获取所有 MinIO 存储桶及其访问权限
|
||||
// @Tags 系统
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} ListMinioBucketsResponse "存储桶列表"
|
||||
// @Failure 400 {object} map[string]interface{} "MinIO 未启用"
|
||||
// @Failure 500 {object} map[string]interface{} "服务器错误"
|
||||
// @Router /system/minio/buckets [get]
|
||||
func (h *SystemHandler) ListMinioBuckets(c *gin.Context) {
|
||||
ctx := logger.CloneContext(c.Request.Context())
|
||||
|
||||
endpoint, accessKeyID, secretAccessKey := h.getMinioConfig(c)
|
||||
if endpoint == "" || accessKeyID == "" || secretAccessKey == "" {
|
||||
logger.Warn(ctx, "MinIO is not configured")
|
||||
c.JSON(400, gin.H{
|
||||
"code": 400,
|
||||
"msg": "MinIO is not configured",
|
||||
"success": false,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
useSSL := os.Getenv("MINIO_USE_SSL") == "true"
|
||||
if v, exists := c.Get(types.TenantInfoContextKey.String()); exists {
|
||||
if tenant, ok := v.(*types.Tenant); ok && tenant != nil && tenant.StorageEngineConfig != nil && tenant.StorageEngineConfig.MinIO != nil {
|
||||
useSSL = tenant.StorageEngineConfig.MinIO.UseSSL
|
||||
}
|
||||
}
|
||||
|
||||
// Create MinIO client
|
||||
minioClient, err := minio.New(endpoint, &minio.Options{
|
||||
Creds: credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
|
||||
Secure: useSSL,
|
||||
})
|
||||
if err != nil {
|
||||
logger.Error(ctx, "Failed to create MinIO client", "error", err)
|
||||
c.JSON(500, gin.H{
|
||||
"code": 500,
|
||||
"msg": "Failed to connect to MinIO",
|
||||
"success": false,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// List all buckets
|
||||
buckets, err := minioClient.ListBuckets(context.Background())
|
||||
if err != nil {
|
||||
logger.Error(ctx, "Failed to list MinIO buckets", "error", err)
|
||||
c.JSON(500, gin.H{
|
||||
"code": 500,
|
||||
"msg": "Failed to list buckets",
|
||||
"success": false,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Get policy for each bucket
|
||||
bucketInfos := make([]MinioBucketInfo, 0, len(buckets))
|
||||
for _, bucket := range buckets {
|
||||
policy := "private" // default: no policy means private
|
||||
|
||||
// Try to get bucket policy
|
||||
policyStr, err := minioClient.GetBucketPolicy(context.Background(), bucket.Name)
|
||||
if err == nil && policyStr != "" {
|
||||
policy = parseBucketPolicy(policyStr)
|
||||
}
|
||||
// If err != nil or policyStr is empty, bucket has no policy (private)
|
||||
|
||||
bucketInfos = append(bucketInfos, MinioBucketInfo{
|
||||
Name: bucket.Name,
|
||||
Policy: policy,
|
||||
CreatedAt: bucket.CreationDate.Format("2006-01-02 15:04:05"),
|
||||
})
|
||||
}
|
||||
|
||||
logger.Info(ctx, "Listed MinIO buckets successfully", "count", len(bucketInfos))
|
||||
c.JSON(200, gin.H{
|
||||
"code": 0,
|
||||
"msg": "success",
|
||||
"success": true,
|
||||
"data": ListMinioBucketsResponse{Buckets: bucketInfos},
|
||||
})
|
||||
}
|
||||
|
||||
// BucketPolicy represents the S3 bucket policy structure
|
||||
type BucketPolicy struct {
|
||||
Version string `json:"Version"`
|
||||
Statement []PolicyStatement `json:"Statement"`
|
||||
}
|
||||
|
||||
// PolicyStatement represents a single statement in the bucket policy
|
||||
type PolicyStatement struct {
|
||||
Effect string `json:"Effect"`
|
||||
Principal interface{} `json:"Principal"` // Can be "*" or {"AWS": [...]}
|
||||
Action interface{} `json:"Action"` // Can be string or []string
|
||||
Resource interface{} `json:"Resource"` // Can be string or []string
|
||||
}
|
||||
|
||||
// parseBucketPolicy parses the policy JSON and determines the access type
|
||||
func parseBucketPolicy(policyStr string) string {
|
||||
var policy BucketPolicy
|
||||
if err := json.Unmarshal([]byte(policyStr), &policy); err != nil {
|
||||
// If we can't parse the policy, treat it as custom
|
||||
return "custom"
|
||||
}
|
||||
|
||||
// Check if any statement grants public read access
|
||||
hasPublicRead := false
|
||||
for _, stmt := range policy.Statement {
|
||||
if stmt.Effect != "Allow" {
|
||||
continue
|
||||
}
|
||||
|
||||
// Check if Principal is "*" (public)
|
||||
if !isPrincipalPublic(stmt.Principal) {
|
||||
continue
|
||||
}
|
||||
|
||||
// Check if Action includes s3:GetObject
|
||||
if !hasGetObjectAction(stmt.Action) {
|
||||
continue
|
||||
}
|
||||
|
||||
hasPublicRead = true
|
||||
break
|
||||
}
|
||||
|
||||
if hasPublicRead {
|
||||
return "public"
|
||||
}
|
||||
|
||||
// Has policy but not public read
|
||||
return "custom"
|
||||
}
|
||||
|
||||
// isPrincipalPublic checks if the principal allows public access
|
||||
func isPrincipalPublic(principal interface{}) bool {
|
||||
switch p := principal.(type) {
|
||||
case string:
|
||||
return p == "*"
|
||||
case map[string]interface{}:
|
||||
// Check for {"AWS": "*"} or {"AWS": ["*"]}
|
||||
if aws, ok := p["AWS"]; ok {
|
||||
switch a := aws.(type) {
|
||||
case string:
|
||||
return a == "*"
|
||||
case []interface{}:
|
||||
for _, v := range a {
|
||||
if s, ok := v.(string); ok && s == "*" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// hasGetObjectAction checks if the action includes s3:GetObject
|
||||
func hasGetObjectAction(action interface{}) bool {
|
||||
checkAction := func(a string) bool {
|
||||
a = strings.ToLower(a)
|
||||
return a == "s3:getobject" || a == "s3:*" || a == "*"
|
||||
}
|
||||
|
||||
switch act := action.(type) {
|
||||
case string:
|
||||
return checkAction(act)
|
||||
case []interface{}:
|
||||
for _, v := range act {
|
||||
if s, ok := v.(string); ok && checkAction(s) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// --- Storage engine helpers ---
|
||||
|
||||
// cosFieldPattern validates COS region and bucket name format to prevent URL injection.
|
||||
var cosFieldPattern = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._-]{0,62}$`)
|
||||
|
||||
@@ -849,6 +655,11 @@ func (h *SystemHandler) checkMinio(c *gin.Context, ctx context.Context, cfg *typ
|
||||
return
|
||||
}
|
||||
|
||||
if cfg.BucketName != "" && !cosFieldPattern.MatchString(cfg.BucketName) {
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: "Bucket 名称格式不正确,仅允许字母、数字、点、连字符"}})
|
||||
return
|
||||
}
|
||||
|
||||
endpoint, accessKeyID, secretAccessKey := cfg.Endpoint, cfg.AccessKeyID, cfg.SecretAccessKey
|
||||
if cfg.Mode != "remote" {
|
||||
endpoint = os.Getenv("MINIO_ENDPOINT")
|
||||
@@ -862,7 +673,7 @@ func (h *SystemHandler) checkMinio(c *gin.Context, ctx context.Context, cfg *typ
|
||||
|
||||
if cfg.Mode == "remote" {
|
||||
if blocked, reason := isBlockedStorageEndpoint(endpoint); blocked {
|
||||
logger.Warnf(ctx, "Storage check: MinIO endpoint blocked by SSRF protection endpoint=%s", endpoint)
|
||||
logger.Warnf(ctx, "Storage check: MinIO endpoint blocked by SSRF protection, endpoint: %s", endpoint)
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: reason}})
|
||||
return
|
||||
}
|
||||
@@ -871,7 +682,7 @@ func (h *SystemHandler) checkMinio(c *gin.Context, ctx context.Context, cfg *typ
|
||||
err := file.CheckMinioConnectivity(ctx, endpoint, accessKeyID, secretAccessKey, cfg.BucketName, cfg.UseSSL)
|
||||
if err != nil {
|
||||
errMsg := err.Error()
|
||||
// If bucket does not exist, auto-create it with public-read policy
|
||||
// If bucket does not exist, auto-create it
|
||||
if strings.Contains(errMsg, "does not exist") && cfg.BucketName != "" {
|
||||
logger.Info(ctx, "Storage check: bucket does not exist, attempting auto-creation", "bucket", cfg.BucketName)
|
||||
minioClient, clientErr := minio.New(endpoint, &minio.Options{
|
||||
@@ -879,39 +690,16 @@ func (h *SystemHandler) checkMinio(c *gin.Context, ctx context.Context, cfg *typ
|
||||
Secure: cfg.UseSSL,
|
||||
})
|
||||
if clientErr != nil {
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: fmt.Sprintf("创建 MinIO 客户端失败: %s", sanitizeStorageCheckError(clientErr))}})
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: fmt.Sprintf("Failed to create MinIO client: %s", sanitizeStorageCheckError(clientErr))}})
|
||||
return
|
||||
}
|
||||
if mkErr := minioClient.MakeBucket(ctx, cfg.BucketName, minio.MakeBucketOptions{}); mkErr != nil {
|
||||
logger.Error(ctx, "Storage check: failed to create bucket", "bucket", cfg.BucketName, "error", mkErr)
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: fmt.Sprintf("自动创建 Bucket「%s」失败: %s", cfg.BucketName, sanitizeStorageCheckError(mkErr))}})
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: fmt.Sprintf("Failed to auto-create Bucket '%s': %s", cfg.BucketName, sanitizeStorageCheckError(mkErr))}})
|
||||
return
|
||||
}
|
||||
// Set public-read policy
|
||||
publicReadPolicy := fmt.Sprintf(`{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Principal": {"AWS": ["*"]},
|
||||
"Action": ["s3:GetBucketLocation", "s3:ListBucket"],
|
||||
"Resource": ["arn:aws:s3:::%s"]
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Principal": {"AWS": ["*"]},
|
||||
"Action": ["s3:GetObject"],
|
||||
"Resource": ["arn:aws:s3:::%s/*"]
|
||||
}
|
||||
]
|
||||
}`, cfg.BucketName, cfg.BucketName)
|
||||
if policyErr := minioClient.SetBucketPolicy(ctx, cfg.BucketName, publicReadPolicy); policyErr != nil {
|
||||
logger.Error(ctx, "Storage check: bucket created but failed to set public-read policy", "bucket", cfg.BucketName, "error", policyErr)
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: true, BucketCreated: true, Message: fmt.Sprintf("Bucket「%s」已自动创建,但设置公有读策略失败,请手动配置权限", cfg.BucketName)}})
|
||||
return
|
||||
}
|
||||
logger.Info(ctx, "Storage check: bucket created with public-read policy", "bucket", cfg.BucketName)
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: true, BucketCreated: true, Message: fmt.Sprintf("Bucket「%s」不存在,已自动创建并设置公有读权限", cfg.BucketName)}})
|
||||
logger.Info(ctx, "Storage check: bucket created", "bucket", cfg.BucketName)
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: true, BucketCreated: true, Message: fmt.Sprintf("Bucket '%s' does not exist, and has been automatically created", cfg.BucketName)}})
|
||||
return
|
||||
}
|
||||
logger.Error(ctx, "Storage check: MinIO connectivity failed", "error", err)
|
||||
@@ -1045,7 +833,7 @@ func (h *SystemHandler) checkOSS(c *gin.Context, ctx context.Context, cfg *types
|
||||
// Strip URL scheme before SSRF check — OSS endpoint may include http:// or https://
|
||||
ssrfEndpoint := strings.TrimPrefix(strings.TrimPrefix(endpoint, "https://"), "http://")
|
||||
if blocked, reason := isBlockedStorageEndpoint(ssrfEndpoint); blocked {
|
||||
logger.Warnf(ctx, "Storage check: OSS endpoint blocked by SSRF protection", "endpoint", endpoint)
|
||||
logger.Warnf(ctx, "Storage check: OSS endpoint blocked by SSRF protection, endpoint: %s", endpoint)
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: reason}})
|
||||
return
|
||||
}
|
||||
@@ -1062,16 +850,16 @@ func (h *SystemHandler) checkOSS(c *gin.Context, ctx context.Context, cfg *types
|
||||
if err != nil {
|
||||
errMsg := err.Error()
|
||||
if strings.Contains(errMsg, "403") || strings.Contains(errMsg, "AccessDenied") {
|
||||
logger.Errorf(ctx, "Storage check: OSS auth failed", "endpoint", endpoint, "bucket", cfg.BucketName)
|
||||
logger.Errorf(ctx, "Storage check: OSS auth failed, endpoint: %s, bucket: %s", endpoint, cfg.BucketName)
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: "认证失败,请检查 Access Key / Secret Key 是否正确"}})
|
||||
return
|
||||
}
|
||||
if strings.Contains(errMsg, "404") || strings.Contains(errMsg, "NoSuchBucket") {
|
||||
logger.Errorf(ctx, "Storage check: OSS bucket not found", "bucket", cfg.BucketName)
|
||||
logger.Errorf(ctx, "Storage check: OSS bucket not found, bucket: %s", cfg.BucketName)
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: fmt.Sprintf("Bucket「%s」不存在", cfg.BucketName)}})
|
||||
return
|
||||
}
|
||||
logger.Errorf(ctx, "Storage check: OSS connectivity failed", "endpoint", endpoint, "bucket", cfg.BucketName, "error", err)
|
||||
logger.Errorf(ctx, "Storage check: OSS connectivity failed, endpoint: %s, bucket: %s, error: %v", endpoint, cfg.BucketName, err)
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: fmt.Sprintf("OSS 连通性检测失败: %s", sanitizeStorageCheckError(err))}})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -0,0 +1,560 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
stderrors "errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/application/repository"
|
||||
"github.com/Tencent/WeKnora/internal/application/service"
|
||||
"github.com/Tencent/WeKnora/internal/errors"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
secutils "github.com/Tencent/WeKnora/internal/utils"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// WikiPageHandler handles HTTP requests for wiki page operations
|
||||
type WikiPageHandler struct {
|
||||
wikiService interfaces.WikiPageService
|
||||
kbService interfaces.KnowledgeBaseService
|
||||
lintService *service.WikiLintService
|
||||
}
|
||||
|
||||
// NewWikiPageHandler creates a new wiki page handler
|
||||
func NewWikiPageHandler(
|
||||
wikiService interfaces.WikiPageService,
|
||||
kbService interfaces.KnowledgeBaseService,
|
||||
lintService *service.WikiLintService,
|
||||
) *WikiPageHandler {
|
||||
return &WikiPageHandler{
|
||||
wikiService: wikiService,
|
||||
kbService: kbService,
|
||||
lintService: lintService,
|
||||
}
|
||||
}
|
||||
|
||||
// validateWikiKB validates that the KB exists and is a wiki type
|
||||
func (h *WikiPageHandler) validateWikiKB(c *gin.Context) (string, uint64, error) {
|
||||
ctx := c.Request.Context()
|
||||
kbID := secutils.SanitizeForLog(c.Param("kb_id"))
|
||||
tenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||
|
||||
if kbID == "" {
|
||||
return "", 0, errors.NewBadRequestError("Knowledge base ID is required")
|
||||
}
|
||||
|
||||
kb, err := h.kbService.GetKnowledgeBaseByID(ctx, kbID)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
return "", 0, errors.NewNotFoundError("Knowledge base not found")
|
||||
}
|
||||
|
||||
if !kb.IsWikiEnabled() {
|
||||
return "", 0, errors.NewBadRequestError("Wiki feature is not enabled for this knowledge base")
|
||||
}
|
||||
|
||||
return kbID, tenantID, nil
|
||||
}
|
||||
|
||||
// getSlugParam extracts and cleans the slug from gin's wildcard path param
|
||||
func getSlugParam(c *gin.Context) string {
|
||||
slug := c.Param("slug")
|
||||
// gin wildcard params include a leading "/"
|
||||
slug = strings.TrimPrefix(slug, "/")
|
||||
return strings.TrimSpace(slug)
|
||||
}
|
||||
|
||||
// ListPages godoc
|
||||
// @Summary List wiki pages
|
||||
// @Description List wiki pages with optional filtering and pagination
|
||||
// @Tags Wiki
|
||||
// @Produce json
|
||||
// @Param kb_id path string true "Knowledge base ID"
|
||||
// @Param page_type query string false "Filter by page type"
|
||||
// @Param status query string false "Filter by status"
|
||||
// @Param query query string false "Full-text search"
|
||||
// @Param page query int false "Page number"
|
||||
// @Param page_size query int false "Page size"
|
||||
// @Param sort_by query string false "Sort field"
|
||||
// @Param sort_order query string false "Sort order (asc/desc)"
|
||||
// @Success 200 {object} types.WikiPageListResponse
|
||||
// @Failure 400 {object} errors.AppError
|
||||
// @Security Bearer
|
||||
// @Router /api/v1/knowledgebase/{kb_id}/wiki/pages [get]
|
||||
func (h *WikiPageHandler) ListPages(c *gin.Context) {
|
||||
kbID, _, err := h.validateWikiKB(c)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
|
||||
|
||||
req := &types.WikiPageListRequest{
|
||||
KnowledgeBaseID: kbID,
|
||||
PageType: c.Query("page_type"),
|
||||
Status: c.Query("status"),
|
||||
Query: c.Query("query"),
|
||||
Page: page,
|
||||
PageSize: pageSize,
|
||||
SortBy: c.DefaultQuery("sort_by", "updated_at"),
|
||||
SortOrder: c.DefaultQuery("sort_order", "desc"),
|
||||
}
|
||||
|
||||
resp, err := h.wikiService.ListPages(c.Request.Context(), req)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
|
||||
// CreatePage godoc
|
||||
// @Summary Create a wiki page
|
||||
// @Description Create a new wiki page in the knowledge base
|
||||
// @Tags Wiki
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param kb_id path string true "Knowledge base ID"
|
||||
// @Param page body types.WikiPage true "Wiki page data"
|
||||
// @Success 201 {object} types.WikiPage
|
||||
// @Failure 400 {object} errors.AppError
|
||||
// @Security Bearer
|
||||
// @Router /api/v1/knowledgebase/{kb_id}/wiki/pages [post]
|
||||
func (h *WikiPageHandler) CreatePage(c *gin.Context) {
|
||||
kbID, tenantID, err := h.validateWikiKB(c)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
var page types.WikiPage
|
||||
if err := c.ShouldBindJSON(&page); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body: " + err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
page.KnowledgeBaseID = kbID
|
||||
page.TenantID = tenantID
|
||||
|
||||
created, err := h.wikiService.CreatePage(c.Request.Context(), &page)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, created)
|
||||
}
|
||||
|
||||
// GetPage godoc
|
||||
// @Summary Get a wiki page by slug
|
||||
// @Description Retrieve a wiki page by its slug
|
||||
// @Tags Wiki
|
||||
// @Produce json
|
||||
// @Param kb_id path string true "Knowledge base ID"
|
||||
// @Param slug path string true "Page slug"
|
||||
// @Success 200 {object} types.WikiPage
|
||||
// @Failure 404 {object} errors.AppError
|
||||
// @Security Bearer
|
||||
// @Router /api/v1/knowledgebase/{kb_id}/wiki/pages/{slug} [get]
|
||||
func (h *WikiPageHandler) GetPage(c *gin.Context) {
|
||||
kbID, _, err := h.validateWikiKB(c)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
slug := getSlugParam(c)
|
||||
if slug == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Page slug is required"})
|
||||
return
|
||||
}
|
||||
|
||||
page, err := h.wikiService.GetPageBySlug(c.Request.Context(), kbID, slug)
|
||||
if err != nil {
|
||||
if stderrors.Is(err, repository.ErrWikiPageNotFound) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Wiki page not found"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, page)
|
||||
}
|
||||
|
||||
// UpdatePage godoc
|
||||
// @Summary Update a wiki page
|
||||
// @Description Update an existing wiki page by slug
|
||||
// @Tags Wiki
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param kb_id path string true "Knowledge base ID"
|
||||
// @Param slug path string true "Page slug"
|
||||
// @Param page body types.WikiPage true "Updated wiki page data"
|
||||
// @Success 200 {object} types.WikiPage
|
||||
// @Failure 404 {object} errors.AppError
|
||||
// @Security Bearer
|
||||
// @Router /api/v1/knowledgebase/{kb_id}/wiki/pages/{slug} [put]
|
||||
func (h *WikiPageHandler) UpdatePage(c *gin.Context) {
|
||||
kbID, tenantID, err := h.validateWikiKB(c)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
slug := getSlugParam(c)
|
||||
if slug == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Page slug is required"})
|
||||
return
|
||||
}
|
||||
|
||||
var page types.WikiPage
|
||||
if err := c.ShouldBindJSON(&page); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body: " + err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
page.KnowledgeBaseID = kbID
|
||||
page.TenantID = tenantID
|
||||
page.Slug = slug
|
||||
|
||||
updated, err := h.wikiService.UpdatePage(c.Request.Context(), &page)
|
||||
if err != nil {
|
||||
if stderrors.Is(err, repository.ErrWikiPageNotFound) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Wiki page not found"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, updated)
|
||||
}
|
||||
|
||||
// DeletePage godoc
|
||||
// @Summary Delete a wiki page
|
||||
// @Description Soft-delete a wiki page by slug
|
||||
// @Tags Wiki
|
||||
// @Param kb_id path string true "Knowledge base ID"
|
||||
// @Param slug path string true "Page slug"
|
||||
// @Success 204
|
||||
// @Failure 404 {object} errors.AppError
|
||||
// @Security Bearer
|
||||
// @Router /api/v1/knowledgebase/{kb_id}/wiki/pages/{slug} [delete]
|
||||
func (h *WikiPageHandler) DeletePage(c *gin.Context) {
|
||||
kbID, _, err := h.validateWikiKB(c)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
slug := getSlugParam(c)
|
||||
if slug == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Page slug is required"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.wikiService.DeletePage(c.Request.Context(), kbID, slug); err != nil {
|
||||
if stderrors.Is(err, repository.ErrWikiPageNotFound) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Wiki page not found"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// GetIndex godoc
|
||||
// @Summary Get wiki index page
|
||||
// @Description Returns the wiki index page (creates default if not exists)
|
||||
// @Tags Wiki
|
||||
// @Produce json
|
||||
// @Param kb_id path string true "Knowledge base ID"
|
||||
// @Success 200 {object} types.WikiPage
|
||||
// @Security Bearer
|
||||
// @Router /api/v1/knowledgebase/{kb_id}/wiki/index [get]
|
||||
func (h *WikiPageHandler) GetIndex(c *gin.Context) {
|
||||
kbID, _, err := h.validateWikiKB(c)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
page, err := h.wikiService.GetIndex(c.Request.Context(), kbID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, page)
|
||||
}
|
||||
|
||||
// GetLog godoc
|
||||
// @Summary Get wiki operation log
|
||||
// @Description Returns the wiki operation log page (creates default if not exists)
|
||||
// @Tags Wiki
|
||||
// @Produce json
|
||||
// @Param kb_id path string true "Knowledge base ID"
|
||||
// @Success 200 {object} types.WikiPage
|
||||
// @Security Bearer
|
||||
// @Router /api/v1/knowledgebase/{kb_id}/wiki/log [get]
|
||||
func (h *WikiPageHandler) GetLog(c *gin.Context) {
|
||||
kbID, _, err := h.validateWikiKB(c)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
page, err := h.wikiService.GetLog(c.Request.Context(), kbID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, page)
|
||||
}
|
||||
|
||||
// GetGraph godoc
|
||||
// @Summary Get wiki link graph
|
||||
// @Description Returns the wiki link graph data for visualization
|
||||
// @Tags Wiki
|
||||
// @Produce json
|
||||
// @Param kb_id path string true "Knowledge base ID"
|
||||
// @Success 200 {object} types.WikiGraphData
|
||||
// @Security Bearer
|
||||
// @Router /api/v1/knowledgebase/{kb_id}/wiki/graph [get]
|
||||
func (h *WikiPageHandler) GetGraph(c *gin.Context) {
|
||||
kbID, _, err := h.validateWikiKB(c)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
graph, err := h.wikiService.GetGraph(c.Request.Context(), kbID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, graph)
|
||||
}
|
||||
|
||||
// GetStats godoc
|
||||
// @Summary Get wiki statistics
|
||||
// @Description Returns aggregate statistics about the wiki
|
||||
// @Tags Wiki
|
||||
// @Produce json
|
||||
// @Param kb_id path string true "Knowledge base ID"
|
||||
// @Success 200 {object} types.WikiStats
|
||||
// @Security Bearer
|
||||
// @Router /api/v1/knowledgebase/{kb_id}/wiki/stats [get]
|
||||
func (h *WikiPageHandler) GetStats(c *gin.Context) {
|
||||
kbID, _, err := h.validateWikiKB(c)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
stats, err := h.wikiService.GetStats(c.Request.Context(), kbID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, stats)
|
||||
}
|
||||
|
||||
// ListIssues godoc
|
||||
// @Summary List wiki page issues
|
||||
// @Description List issues flagged on wiki pages with optional filtering
|
||||
// @Tags Wiki
|
||||
// @Produce json
|
||||
// @Param kb_id path string true "Knowledge base ID"
|
||||
// @Param slug query string false "Filter by page slug"
|
||||
// @Param status query string false "Filter by status (pending, ignored, resolved)"
|
||||
// @Success 200 {array} types.WikiPageIssue
|
||||
// @Security Bearer
|
||||
// @Router /api/v1/knowledgebase/{kb_id}/wiki/issues [get]
|
||||
func (h *WikiPageHandler) ListIssues(c *gin.Context) {
|
||||
kbID, _, err := h.validateWikiKB(c)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
slug := c.Query("slug")
|
||||
status := c.Query("status")
|
||||
|
||||
issues, err := h.wikiService.ListIssues(c.Request.Context(), kbID, slug, status)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, issues)
|
||||
}
|
||||
|
||||
// UpdateIssueStatus godoc
|
||||
// @Summary Update wiki page issue status
|
||||
// @Description Update the status of a flagged wiki page issue
|
||||
// @Tags Wiki
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param kb_id path string true "Knowledge base ID"
|
||||
// @Param issue_id path string true "Issue ID"
|
||||
// @Param status body object true "New status {'status': 'ignored'}"
|
||||
// @Success 200 {object} map[string]string
|
||||
// @Failure 400 {object} errors.AppError
|
||||
// @Security Bearer
|
||||
// @Router /api/v1/knowledgebase/{kb_id}/wiki/issues/{issue_id}/status [put]
|
||||
func (h *WikiPageHandler) UpdateIssueStatus(c *gin.Context) {
|
||||
_, _, err := h.validateWikiKB(c)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
issueID := secutils.SanitizeForLog(c.Param("issue_id"))
|
||||
if issueID == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Issue ID is required"})
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Status string `json:"status" binding:"required"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body: " + err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
validStatuses := map[string]bool{"pending": true, "ignored": true, "resolved": true}
|
||||
if !validStatuses[req.Status] {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid status. Must be pending, ignored, or resolved"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.wikiService.UpdateIssueStatus(c.Request.Context(), issueID, req.Status); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"message": "Issue status updated successfully"})
|
||||
}
|
||||
|
||||
// SearchPages godoc
|
||||
// @Summary Search wiki pages
|
||||
// @Description Full-text search over wiki pages
|
||||
// @Tags Wiki
|
||||
// @Produce json
|
||||
// @Param kb_id path string true "Knowledge base ID"
|
||||
// @Param q query string true "Search query"
|
||||
// @Param limit query int false "Max results (default 10)"
|
||||
// @Success 200 {array} types.WikiPage
|
||||
// @Security Bearer
|
||||
// @Router /api/v1/knowledgebase/{kb_id}/wiki/search [get]
|
||||
func (h *WikiPageHandler) SearchPages(c *gin.Context) {
|
||||
kbID, _, err := h.validateWikiKB(c)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
query := c.Query("q")
|
||||
if query == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Search query 'q' is required"})
|
||||
return
|
||||
}
|
||||
|
||||
limit, _ := strconv.Atoi(c.DefaultQuery("limit", "10"))
|
||||
|
||||
pages, err := h.wikiService.SearchPages(c.Request.Context(), kbID, query, limit)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"pages": pages})
|
||||
}
|
||||
|
||||
// RebuildLinks godoc
|
||||
// @Summary Rebuild wiki links
|
||||
// @Description Re-parse all pages and rebuild bidirectional link references
|
||||
// @Tags Wiki
|
||||
// @Param kb_id path string true "Knowledge base ID"
|
||||
// @Success 200 {object} map[string]string
|
||||
// @Security Bearer
|
||||
// @Router /api/v1/knowledgebase/{kb_id}/wiki/rebuild-links [post]
|
||||
func (h *WikiPageHandler) RebuildLinks(c *gin.Context) {
|
||||
kbID, _, err := h.validateWikiKB(c)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.wikiService.RebuildLinks(c.Request.Context(), kbID); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"message": "Links rebuilt successfully"})
|
||||
}
|
||||
|
||||
// Lint godoc
|
||||
// @Summary Run wiki lint
|
||||
// @Description Perform a comprehensive health check on the wiki
|
||||
// @Tags Wiki
|
||||
// @Produce json
|
||||
// @Param kb_id path string true "Knowledge base ID"
|
||||
// @Success 200 {object} service.WikiLintReport
|
||||
// @Security Bearer
|
||||
// @Router /api/v1/knowledgebase/{kb_id}/wiki/lint [get]
|
||||
func (h *WikiPageHandler) Lint(c *gin.Context) {
|
||||
kbID, _, err := h.validateWikiKB(c)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
report, err := h.lintService.RunLint(c.Request.Context(), kbID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, report)
|
||||
}
|
||||
|
||||
// AutoFix godoc
|
||||
// @Summary Auto-fix wiki issues
|
||||
// @Description Automatically fix fixable wiki issues (broken links, etc.)
|
||||
// @Tags Wiki
|
||||
// @Produce json
|
||||
// @Param kb_id path string true "Knowledge base ID"
|
||||
// @Success 200 {object} map[string]interface{}
|
||||
// @Security Bearer
|
||||
// @Router /api/v1/knowledgebase/{kb_id}/wiki/auto-fix [post]
|
||||
func (h *WikiPageHandler) AutoFix(c *gin.Context) {
|
||||
kbID, _, err := h.validateWikiKB(c)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
fixed, err := h.lintService.AutoFix(c.Request.Context(), kbID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"fixed": fixed, "message": fmt.Sprintf("Auto-fixed %d issues", fixed)})
|
||||
}
|
||||
Reference in New Issue
Block a user