feat: standardize storage configuration and enhance backward compatibility

- Updated the `KnowledgeBase` struct to rename `cos_config` to `storage_config` for consistency across the application.
- Implemented a custom `UnmarshalJSON` method to maintain backward compatibility with legacy responses that still use `cos_config`.
- Modified various frontend components to reflect the new `storage_config` naming, ensuring seamless integration with the updated backend structure.
- Enhanced Dockerfiles and service configurations to support the new storage engine setup.

This update improves the clarity of storage configurations and ensures compatibility with existing data structures.
This commit is contained in:
wizardchen
2026-02-28 17:39:59 +08:00
committed by lyingbug
parent 31755726a0
commit 393ebf9f92
13 changed files with 168 additions and 25 deletions
+28 -2
View File
@@ -7,6 +7,7 @@ import (
"mime/multipart"
"os"
"path/filepath"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/logger"
@@ -101,7 +102,8 @@ func (s *localFileService) SaveFile(ctx context.Context,
func (s *localFileService) GetFile(ctx context.Context, filePath string) (io.ReadCloser, error) {
logger.Infof(ctx, "Getting file: %s", filePath)
resolved, err := secutils.SafePathUnderBase(s.baseDir, filePath)
candidate := s.normalizePathForBase(filePath)
resolved, err := secutils.SafePathUnderBase(s.baseDir, candidate)
if err != nil {
logger.Errorf(ctx, "Path traversal denied for GetFile: %v", err)
return nil, fmt.Errorf("invalid file path: %w", err)
@@ -123,7 +125,8 @@ func (s *localFileService) GetFile(ctx context.Context, filePath string) (io.Rea
func (s *localFileService) DeleteFile(ctx context.Context, filePath string) error {
logger.Infof(ctx, "Deleting file: %s", filePath)
resolved, err := secutils.SafePathUnderBase(s.baseDir, filePath)
candidate := s.normalizePathForBase(filePath)
resolved, err := secutils.SafePathUnderBase(s.baseDir, candidate)
if err != nil {
logger.Errorf(ctx, "Path traversal denied for DeleteFile: %v", err)
return fmt.Errorf("invalid file path: %w", err)
@@ -180,3 +183,26 @@ func (s *localFileService) GetFileURL(ctx context.Context, filePath string) (str
// Local storage doesn't support URLs, return the path
return filePath, nil
}
// normalizePathForBase keeps backward compatibility for legacy file paths:
// - absolute path: "/data/files/tenant/.."
// - path under base dir: "tenant/.."
// - legacy relative with base prefix: "data/files/tenant/.."
func (s *localFileService) normalizePathForBase(filePath string) string {
clean := filepath.Clean(strings.TrimSpace(filePath))
if clean == "." || clean == "" {
return clean
}
if filepath.IsAbs(clean) {
return clean
}
// Strip duplicated base prefix in legacy relative paths, e.g. "data/files/..."
baseClean := filepath.Clean(s.baseDir)
baseNoSlash := strings.Trim(baseClean, string(filepath.Separator))
cleanNoDot := strings.TrimPrefix(clean, "."+string(filepath.Separator))
if strings.HasPrefix(cleanNoDot, baseNoSlash+string(filepath.Separator)) {
cleanNoDot = strings.TrimPrefix(cleanNoDot, baseNoSlash+string(filepath.Separator))
}
return filepath.Join(baseClean, cleanNoDot)
}
@@ -92,7 +92,13 @@ func (s *ImageMultimodalService) Handle(ctx context.Context, task *asynq.Task) e
logger.Infof(ctx, "[ImageMultimodal] Image downloaded from URL, len=%d", len(imgBytes))
} else {
logger.Infof(ctx, "[ImageMultimodal] Image bytes read from %s, len=%d", payload.ImageLocalPath, len(imgBytes))
defer os.Remove(payload.ImageLocalPath)
// Only clean up the local file when images have been re-uploaded to
// external object storage (COS/TOS) — the serving URL will be an
// absolute http(s) URL in that case. For local and MinIO storage the
// local file IS the serving file and must be kept.
if strings.HasPrefix(payload.ImageURL, "http://") || strings.HasPrefix(payload.ImageURL, "https://") {
defer os.Remove(payload.ImageLocalPath)
}
}
imageInfo := types.ImageInfo{
+44 -4
View File
@@ -6756,6 +6756,8 @@ func (s *knowledgeService) buildStorageConfig(ctx context.Context, kb *types.Kno
}
if hasKBFull {
logger.Infof(ctx, "[storage] buildStorageConfig use kb config: kb=%s provider=%s bucket=%s path_prefix=%s",
kb.ID, provider, sc.BucketName, sc.PathPrefix)
return &types.DocParserStorageConfig{
Provider: strings.ToUpper(provider),
Region: sc.Region,
@@ -6809,6 +6811,8 @@ func (s *knowledgeService) buildStorageConfig(ctx context.Context, kb *types.Kno
}
}
logger.Infof(ctx, "[storage] buildStorageConfig use merged tenant/global config: kb=%s provider=%s bucket=%s path_prefix=%s endpoint=%s",
kb.ID, strings.ToLower(out.Provider), out.BucketName, out.PathPrefix, out.Endpoint)
return &out
}
@@ -6817,6 +6821,7 @@ func (s *knowledgeService) buildStorageConfig(ctx context.Context, kb *types.Kno
// Falls back to the global fileSvc when no tenant-level storage config is found.
func (s *knowledgeService) resolveFileService(ctx context.Context, kb *types.KnowledgeBase) interfaces.FileService {
if kb == nil {
logger.Infof(ctx, "[storage] resolveFileService fallback default: kb=nil")
return s.fileSvc
}
@@ -6828,6 +6833,8 @@ func (s *knowledgeService) resolveFileService(ctx context.Context, kb *types.Kno
}
if provider == "" || tenant == nil || tenant.StorageEngineConfig == nil {
logger.Infof(ctx, "[storage] resolveFileService fallback default: kb=%s provider=%q tenant_cfg=%v",
kb.ID, provider, tenant != nil && tenant.StorageEngineConfig != nil)
return s.fileSvc
}
@@ -6837,10 +6844,28 @@ func (s *knowledgeService) resolveFileService(ctx context.Context, kb *types.Kno
switch provider {
case "local":
baseDir := "/data/files"
if sec.Local != nil && sec.Local.PathPrefix != "" {
baseDir = sec.Local.PathPrefix
baseDir := strings.TrimSpace(os.Getenv("LOCAL_STORAGE_BASE_DIR"))
if baseDir == "" {
baseDir = "/data/files"
}
if sec.Local != nil && sec.Local.PathPrefix != "" {
// path_prefix is a subdirectory under local storage base dir, not a replacement.
// Validate it cannot escape baseDir (e.g. path traversal via "..").
rawPrefix := strings.TrimSpace(sec.Local.PathPrefix)
prefix := strings.Trim(rawPrefix, "/\\")
if prefix != "" {
candidate := filepath.Join(baseDir, prefix)
safeBaseDir, pathErr := secutils.SafePathUnderBase(baseDir, candidate)
if pathErr != nil {
logger.Warnf(ctx,
"[storage] invalid local path_prefix ignored: kb=%s raw_prefix=%q err=%v",
kb.ID, rawPrefix, pathErr)
} else {
baseDir = safeBaseDir
}
}
}
logger.Infof(ctx, "[storage] resolveFileService local: kb=%s base_dir=%s", kb.ID, baseDir)
return filesvc.NewLocalFileService(baseDir)
case "minio":
@@ -6886,6 +6911,7 @@ func (s *knowledgeService) resolveFileService(ctx context.Context, kb *types.Kno
logger.Errorf(ctx, "Failed to create %s file service from tenant config: %v, falling back to default", provider, err)
return s.fileSvc
}
logger.Infof(ctx, "[storage] resolveFileService selected: kb=%s provider=%s", kb.ID, provider)
return svc
}
@@ -7275,13 +7301,27 @@ func (s *knowledgeService) convert(
return nil, nil
}
imageStorage := s.buildImageStorageConfig(ctx, kb)
if imageStorage == nil {
logger.Infof(ctx, "[storage] chunk image storage: kb=%s provider=%s image_storage=nil(use local temp/files)",
kb.ID, strings.ToLower(strings.TrimSpace(kb.StorageConfig.Provider)))
} else {
logger.Infof(ctx, "[storage] chunk image storage: kb=%s provider=%s bucket=%s endpoint=%s path_prefix=%s",
kb.ID,
imageStorage["provider"],
imageStorage["bucket_name"],
imageStorage["endpoint"],
imageStorage["path_prefix"],
)
}
req := &types.ReadRequest{
URL: payload.URL,
Title: knowledge.Title,
ParserEngine: parserEngine,
RequestID: payload.RequestId,
ParserEngineOverrides: overrides,
ImageStorage: s.buildImageStorageConfig(ctx, kb),
ImageStorage: imageStorage,
}
if !isURL {