feat: enhance storage engine configuration and UI updates
- Updated `.air.toml` to include additional CGO flags for improved build settings. - Expanded `StorageEngineConfig` interface to support "tos" (火山引擎 TOS) as a new storage provider. - Modified related components and views to accommodate the new storage engine, including updates to `ListSpaceSidebar`, `AgentList`, `KnowledgeBaseList`, and `OrganizationList`. - Improved UI elements for batch management in the menu and sidebar components. - Added internationalization support for new memory features and storage engine descriptions across multiple languages. This update enhances the flexibility of storage options and improves user experience with better UI interactions.
This commit is contained in:
@@ -12,6 +12,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/Tencent/WeKnora/internal/utils"
|
||||
"github.com/google/uuid"
|
||||
"github.com/volcengine/ve-tos-golang-sdk/v2/tos"
|
||||
"github.com/volcengine/ve-tos-golang-sdk/v2/tos/enum"
|
||||
@@ -71,6 +72,34 @@ func NewTosFileServiceWithTempBucket(endpoint, region, accessKey, secretKey, buc
|
||||
}, nil
|
||||
}
|
||||
|
||||
// CheckConnectivity verifies TOS is reachable by performing a HeadBucket request.
|
||||
func (s *tosFileService) CheckConnectivity(ctx context.Context) error {
|
||||
checkCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
defer cancel()
|
||||
_, err := s.client.HeadBucket(checkCtx, &tos.HeadBucketInput{
|
||||
Bucket: s.bucketName,
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
// CheckTosConnectivity tests TOS connectivity using the provided credentials.
|
||||
func CheckTosConnectivity(ctx context.Context, endpoint, region, accessKey, secretKey, bucketName string) error {
|
||||
client, err := tos.NewClientV2(
|
||||
endpoint,
|
||||
tos.WithRegion(region),
|
||||
tos.WithCredentials(tos.NewStaticCredentials(accessKey, secretKey)),
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to initialize TOS client: %w", err)
|
||||
}
|
||||
checkCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
defer cancel()
|
||||
_, err = client.HeadBucket(checkCtx, &tos.HeadBucketInput{
|
||||
Bucket: bucketName,
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func ensureTOSBucket(client *tos.ClientV2, bucketName string) error {
|
||||
_, err := client.HeadBucket(context.Background(), &tos.HeadBucketInput{
|
||||
Bucket: bucketName,
|
||||
@@ -152,7 +181,11 @@ func (s *tosFileService) SaveFile(ctx context.Context, file *multipart.FileHeade
|
||||
}
|
||||
|
||||
func (s *tosFileService) SaveBytes(ctx context.Context, data []byte, tenantID uint64, fileName string, temp bool) (string, error) {
|
||||
ext := filepath.Ext(fileName)
|
||||
safeName, err := utils.SafeFileName(fileName)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("invalid file name: %w", err)
|
||||
}
|
||||
ext := filepath.Ext(safeName)
|
||||
reader := bytes.NewReader(data)
|
||||
|
||||
targetBucket := s.bucketName
|
||||
@@ -172,7 +205,7 @@ func (s *tosFileService) SaveBytes(ctx context.Context, data []byte, tenantID ui
|
||||
)
|
||||
}
|
||||
|
||||
_, err := s.client.PutObjectV2(ctx, &tos.PutObjectV2Input{
|
||||
_, err = s.client.PutObjectV2(ctx, &tos.PutObjectV2Input{
|
||||
PutObjectBasicInput: tos.PutObjectBasicInput{
|
||||
Bucket: targetBucket,
|
||||
Key: objectName,
|
||||
@@ -192,6 +225,9 @@ func (s *tosFileService) GetFile(ctx context.Context, filePath string) (io.ReadC
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := utils.SafeObjectKey(objectName); err != nil {
|
||||
return nil, fmt.Errorf("invalid file path: %w", err)
|
||||
}
|
||||
|
||||
output, err := s.client.GetObjectV2(ctx, &tos.GetObjectV2Input{
|
||||
Bucket: bucketName,
|
||||
@@ -208,6 +244,9 @@ func (s *tosFileService) DeleteFile(ctx context.Context, filePath string) error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := utils.SafeObjectKey(objectName); err != nil {
|
||||
return fmt.Errorf("invalid file path: %w", err)
|
||||
}
|
||||
|
||||
_, err = s.client.DeleteObjectV2(ctx, &tos.DeleteObjectV2Input{
|
||||
Bucket: bucketName,
|
||||
@@ -224,6 +263,9 @@ func (s *tosFileService) GetFileURL(ctx context.Context, filePath string) (strin
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := utils.SafeObjectKey(objectName); err != nil {
|
||||
return "", fmt.Errorf("invalid file path: %w", err)
|
||||
}
|
||||
|
||||
output, err := s.client.PreSignedURL(&tos.PreSignedURLInput{
|
||||
HTTPMethod: enum.HttpMethodGet,
|
||||
|
||||
@@ -473,7 +473,7 @@ func (s *sessionService) KnowledgeQA(
|
||||
knowledgeIDs = nil
|
||||
logger.Infof(ctx, "RetrieveKBOnlyWhenMentioned is enabled and no @ mention found, KB retrieval disabled for this request")
|
||||
} else {
|
||||
knowledgeBaseIDs = s.resolveKnowledgeBasesFromAgent(ctx, customAgent)
|
||||
knowledgeBaseIDs = s.resolveKnowledgeBasesFromAgent(ctx, customAgent, session.TenantID)
|
||||
}
|
||||
|
||||
// Determine chat model ID: prioritize request's summaryModelID, then Remote models
|
||||
@@ -861,7 +861,11 @@ func (s *sessionService) selectChatModelID(
|
||||
return "", errors.New("no chat model ID available: no knowledge bases configured and no available models")
|
||||
}
|
||||
|
||||
// resolveKnowledgeBasesFromAgent resolves knowledge base IDs based on agent's KBSelectionMode
|
||||
// resolveKnowledgeBasesFromAgent resolves knowledge base IDs based on agent's KBSelectionMode.
|
||||
// sessionTenantID is the tenant of the current session (caller); it is compared with
|
||||
// customAgent.TenantID to detect the shared-agent scenario and avoid leaking the
|
||||
// current user's personal shared KBs into the agent's retrieval scope.
|
||||
//
|
||||
// Returns the resolved knowledge base IDs based on the selection mode:
|
||||
// - "all": fetches all knowledge bases for the tenant
|
||||
// - "selected": uses the explicitly configured knowledge bases
|
||||
@@ -870,6 +874,7 @@ func (s *sessionService) selectChatModelID(
|
||||
func (s *sessionService) resolveKnowledgeBasesFromAgent(
|
||||
ctx context.Context,
|
||||
customAgent *types.CustomAgent,
|
||||
sessionTenantID uint64,
|
||||
) []string {
|
||||
if customAgent == nil {
|
||||
return nil
|
||||
@@ -877,7 +882,7 @@ func (s *sessionService) resolveKnowledgeBasesFromAgent(
|
||||
|
||||
switch customAgent.Config.KBSelectionMode {
|
||||
case "all":
|
||||
// Get own knowledge bases
|
||||
// Get own knowledge bases (uses ctx TenantID = agent's tenant)
|
||||
allKBs, err := s.knowledgeBaseService.ListKnowledgeBases(ctx)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to list all knowledge bases: %v", err)
|
||||
@@ -889,23 +894,31 @@ func (s *sessionService) resolveKnowledgeBasesFromAgent(
|
||||
kbIDSet[kb.ID] = true
|
||||
}
|
||||
|
||||
// Also include shared knowledge bases the user has access to
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
userIDVal := ctx.Value(types.UserIDContextKey)
|
||||
if userIDVal != nil {
|
||||
if userID, ok := userIDVal.(string); ok && userID != "" && s.kbShareService != nil {
|
||||
sharedList, err := s.kbShareService.ListSharedKnowledgeBases(ctx, userID, tenantID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to list shared knowledge bases: %v", err)
|
||||
} else {
|
||||
for _, info := range sharedList {
|
||||
if info != nil && info.KnowledgeBase != nil && !kbIDSet[info.KnowledgeBase.ID] {
|
||||
kbIDs = append(kbIDs, info.KnowledgeBase.ID)
|
||||
kbIDSet[info.KnowledgeBase.ID] = true
|
||||
// For shared agents (session tenant != agent tenant), only use the agent
|
||||
// tenant's own KBs. Including the current user's shared KBs would leak
|
||||
// unrelated KBs from other organisations into the agent's retrieval scope.
|
||||
isSharedAgent := sessionTenantID != 0 && sessionTenantID != customAgent.TenantID
|
||||
if !isSharedAgent {
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
userIDVal := ctx.Value(types.UserIDContextKey)
|
||||
if userIDVal != nil {
|
||||
if userID, ok := userIDVal.(string); ok && userID != "" && s.kbShareService != nil {
|
||||
sharedList, err := s.kbShareService.ListSharedKnowledgeBases(ctx, userID, tenantID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to list shared knowledge bases: %v", err)
|
||||
} else {
|
||||
for _, info := range sharedList {
|
||||
if info != nil && info.KnowledgeBase != nil && !kbIDSet[info.KnowledgeBase.ID] {
|
||||
kbIDs = append(kbIDs, info.KnowledgeBase.ID)
|
||||
kbIDSet[info.KnowledgeBase.ID] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
logger.Infof(ctx, "Shared agent detected (session tenant %d != agent tenant %d): skipping user's shared KBs",
|
||||
sessionTenantID, customAgent.TenantID)
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "KBSelectionMode=all: loaded %d knowledge bases (own + shared)", len(kbIDs))
|
||||
@@ -1352,7 +1365,7 @@ func (s *sessionService) AgentQA(
|
||||
logger.Infof(ctx, "RetrieveKBOnlyWhenMentioned is enabled and no @ mention found, KB retrieval disabled for this request")
|
||||
} else {
|
||||
// Use agent's configured knowledge bases based on KBSelectionMode
|
||||
agentConfig.KnowledgeBases = s.resolveKnowledgeBasesFromAgent(ctx, customAgent)
|
||||
agentConfig.KnowledgeBases = s.resolveKnowledgeBasesFromAgent(ctx, customAgent, session.TenantID)
|
||||
}
|
||||
|
||||
// Use custom agent's allowed tools if specified, otherwise use defaults
|
||||
|
||||
@@ -342,6 +342,26 @@ func (h *SystemHandler) isCOSConfigured(c *gin.Context) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// isTOSConfigured checks whether TOS connection info is available from tenant config or env.
|
||||
func (h *SystemHandler) isTOSConfigured(c *gin.Context) bool {
|
||||
if v, exists := c.Get(types.TenantInfoContextKey.String()); exists {
|
||||
if tenant, ok := v.(*types.Tenant); ok && tenant != nil && tenant.StorageEngineConfig != nil && tenant.StorageEngineConfig.TOS != nil {
|
||||
tosConf := tenant.StorageEngineConfig.TOS
|
||||
return tosConf.Endpoint != "" && tosConf.Region != "" && tosConf.AccessKey != "" && tosConf.SecretKey != "" && tosConf.BucketName != ""
|
||||
}
|
||||
}
|
||||
return h.isTOSEnvAvailable()
|
||||
}
|
||||
|
||||
// isTOSEnvAvailable checks whether TOS env vars are set.
|
||||
func (h *SystemHandler) isTOSEnvAvailable() bool {
|
||||
return os.Getenv("TOS_ENDPOINT") != "" &&
|
||||
os.Getenv("TOS_REGION") != "" &&
|
||||
os.Getenv("TOS_ACCESS_KEY") != "" &&
|
||||
os.Getenv("TOS_SECRET_KEY") != "" &&
|
||||
os.Getenv("TOS_BUCKET_NAME") != ""
|
||||
}
|
||||
|
||||
// MinioBucketInfo represents bucket information with access policy
|
||||
type MinioBucketInfo struct {
|
||||
Name string `json:"name"`
|
||||
@@ -356,7 +376,7 @@ type ListMinioBucketsResponse struct {
|
||||
|
||||
// StorageEngineStatusItem describes one storage engine's availability and description.
|
||||
type StorageEngineStatusItem struct {
|
||||
Name string `json:"name"` // "local", "minio", "cos"
|
||||
Name string `json:"name"` // "local", "minio", "cos", "tos"
|
||||
Available bool `json:"available"` // whether the engine can be used
|
||||
Description string `json:"description"` // short description for UI
|
||||
}
|
||||
@@ -378,10 +398,12 @@ func (h *SystemHandler) GetStorageEngineStatus(c *gin.Context) {
|
||||
minioConfigured := h.isMinioConfigured(c)
|
||||
minioEnvAvailable := h.isMinioEnvAvailable()
|
||||
cosConfigured := h.isCOSConfigured(c)
|
||||
tosConfigured := h.isTOSConfigured(c)
|
||||
engines := []StorageEngineStatusItem{
|
||||
{Name: "local", Available: true, Description: "本地文件系统存储,仅适合单机部署"},
|
||||
{Name: "minio", Available: minioConfigured || minioEnvAvailable, Description: "S3 兼容的自托管对象存储,适合内网和私有云部署"},
|
||||
{Name: "cos", Available: cosConfigured, Description: "腾讯云对象存储服务,适合公有云部署,支持 CDN 加速"},
|
||||
{Name: "tos", Available: tosConfigured, Description: "火山引擎对象存储服务,适合公有云部署"},
|
||||
}
|
||||
c.JSON(200, gin.H{
|
||||
"code": 0,
|
||||
@@ -654,9 +676,10 @@ func isBlockedStorageEndpoint(endpoint string) (bool, string) {
|
||||
|
||||
// StorageCheckRequest is the body for POST /system/storage-engine-check.
|
||||
type StorageCheckRequest struct {
|
||||
Provider string `json:"provider"` // "minio" or "cos"
|
||||
Provider string `json:"provider"` // "minio", "cos", or "tos"
|
||||
MinIO *types.MinIOEngineConfig `json:"minio,omitempty"`
|
||||
COS *types.COSEngineConfig `json:"cos,omitempty"`
|
||||
TOS *types.TOSEngineConfig `json:"tos,omitempty"`
|
||||
}
|
||||
|
||||
// StorageCheckResponse is the response for a single-engine connectivity check.
|
||||
@@ -688,6 +711,8 @@ func (h *SystemHandler) CheckStorageEngine(c *gin.Context) {
|
||||
h.checkMinio(c, ctx, req.MinIO)
|
||||
case "cos":
|
||||
h.checkCOS(c, ctx, req.COS)
|
||||
case "tos":
|
||||
h.checkTOS(c, ctx, req.TOS)
|
||||
default:
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: true, Message: "本地存储无需检测"}})
|
||||
}
|
||||
@@ -772,3 +797,37 @@ func (h *SystemHandler) checkCOS(c *gin.Context, ctx context.Context, cfg *types
|
||||
}
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: true, Message: fmt.Sprintf("连接成功,Bucket「%s」已确认存在", cfg.BucketName)}})
|
||||
}
|
||||
|
||||
func (h *SystemHandler) checkTOS(c *gin.Context, ctx context.Context, cfg *types.TOSEngineConfig) {
|
||||
if cfg == nil {
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: "未提供 TOS 配置"}})
|
||||
return
|
||||
}
|
||||
if cfg.Endpoint == "" || cfg.Region == "" || cfg.AccessKey == "" || cfg.SecretKey == "" || cfg.BucketName == "" {
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: "Endpoint、Region、Access Key、Secret Key、Bucket 名称不能为空"}})
|
||||
return
|
||||
}
|
||||
|
||||
if blocked, reason := isBlockedStorageEndpoint(cfg.Endpoint); blocked {
|
||||
logger.Warnf(ctx, "Storage check: TOS endpoint blocked by SSRF protection, endpoint: %s", cfg.Endpoint)
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: reason}})
|
||||
return
|
||||
}
|
||||
|
||||
err := file.CheckTosConnectivity(ctx, cfg.Endpoint, cfg.Region, cfg.AccessKey, cfg.SecretKey, cfg.BucketName)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Storage check: TOS connectivity failed, bucket: %s, error: %v", cfg.BucketName, err)
|
||||
errMsg := err.Error()
|
||||
if strings.Contains(errMsg, "403") {
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: "认证失败,请检查 Access Key / Secret Key 是否正确"}})
|
||||
return
|
||||
}
|
||||
if strings.Contains(errMsg, "404") {
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: fmt.Sprintf("Bucket「%s」不存在,请检查名称和 Region", cfg.BucketName)}})
|
||||
return
|
||||
}
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: sanitizeStorageCheckError(err)}})
|
||||
return
|
||||
}
|
||||
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: true, Message: fmt.Sprintf("连接成功,Bucket「%s」已确认存在", cfg.BucketName)}})
|
||||
}
|
||||
|
||||
@@ -294,13 +294,14 @@ func (c *ParserEngineConfig) Scan(value interface{}) error {
|
||||
return json.Unmarshal(b, c)
|
||||
}
|
||||
|
||||
// StorageEngineConfig holds tenant-level storage engine parameters for Local, MinIO, and COS.
|
||||
// StorageEngineConfig holds tenant-level storage engine parameters for Local, MinIO, COS, and TOS.
|
||||
// Knowledge bases select which provider to use; parameters are read from here.
|
||||
type StorageEngineConfig struct {
|
||||
DefaultProvider string `json:"default_provider"` // "local", "minio", "cos"
|
||||
DefaultProvider string `json:"default_provider"` // "local", "minio", "cos", "tos"
|
||||
Local *LocalEngineConfig `json:"local,omitempty"`
|
||||
MinIO *MinIOEngineConfig `json:"minio,omitempty"`
|
||||
COS *COSEngineConfig `json:"cos,omitempty"`
|
||||
TOS *TOSEngineConfig `json:"tos,omitempty"`
|
||||
}
|
||||
|
||||
// LocalEngineConfig is for local file system storage (single-machine deployment only).
|
||||
@@ -330,6 +331,16 @@ type COSEngineConfig struct {
|
||||
PathPrefix string `json:"path_prefix"`
|
||||
}
|
||||
|
||||
// TOSEngineConfig is for Volcengine TOS (火山引擎对象存储).
|
||||
type TOSEngineConfig struct {
|
||||
Endpoint string `json:"endpoint"`
|
||||
Region string `json:"region"`
|
||||
AccessKey string `json:"access_key"`
|
||||
SecretKey string `json:"secret_key"`
|
||||
BucketName string `json:"bucket_name"`
|
||||
PathPrefix string `json:"path_prefix"`
|
||||
}
|
||||
|
||||
// Value implements the driver.Valuer interface for StorageEngineConfig
|
||||
func (c *StorageEngineConfig) Value() (driver.Value, error) {
|
||||
if c == nil {
|
||||
|
||||
Reference in New Issue
Block a user