feat(storage): add multi-instance storage backends per workspace

Introduce tenant-scoped storage backend registry so workspaces can register
multiple storage instances and bind each knowledge base to a specific backend,
with migration from legacy tenant-level storage config and new settings UI.
This commit is contained in:
wizardchen
2026-07-15 13:26:29 +08:00
committed by lyingbug
parent 139ec1e6b8
commit f8b3e5f148
58 changed files with 2863 additions and 470 deletions
@@ -0,0 +1,113 @@
package file
import (
"context"
"fmt"
"io"
"mime/multipart"
"net/url"
"strconv"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
secutils "github.com/Tencent/WeKnora/internal/utils"
)
// backendScopedFileService makes the storage instance part of every newly
// persisted path while delegating actual I/O to the existing provider driver.
type backendScopedFileService struct {
backendID string
inner interfaces.FileService
}
func NewBackendScopedFileService(backendID string, inner interfaces.FileService) interfaces.FileService {
return &backendScopedFileService{backendID: backendID, inner: inner}
}
func (s *backendScopedFileService) unwrap(path string) (string, error) {
id, inner, ok := types.ParseStorageBackendPath(path)
if !ok {
return path, nil
}
if id != s.backendID {
return "", fmt.Errorf("storage backend mismatch")
}
return inner, nil
}
func (s *backendScopedFileService) wrap(path string) string {
return types.BuildStorageBackendPath(s.backendID, path)
}
func (s *backendScopedFileService) CheckConnectivity(ctx context.Context) error {
return s.inner.CheckConnectivity(ctx)
}
func (s *backendScopedFileService) SaveFile(ctx context.Context, f *multipart.FileHeader, tenantID uint64, knowledgeID string) (string, error) {
p, err := s.inner.SaveFile(ctx, f, tenantID, knowledgeID)
if err != nil {
return "", err
}
return s.wrap(p), nil
}
func (s *backendScopedFileService) SaveBytes(ctx context.Context, data []byte, tenantID uint64, name string, temp bool) (string, error) {
p, err := s.inner.SaveBytes(ctx, data, tenantID, name, temp)
if err != nil {
return "", err
}
return s.wrap(p), nil
}
func (s *backendScopedFileService) GetFile(ctx context.Context, path string) (io.ReadCloser, error) {
p, err := s.unwrap(path)
if err != nil {
return nil, err
}
return s.inner.GetFile(ctx, p)
}
func (s *backendScopedFileService) GetFileURL(ctx context.Context, path string) (string, error) {
p, err := s.unwrap(path)
if err != nil {
return "", err
}
result, err := s.inner.GetFileURL(ctx, p)
if err != nil {
return "", err
}
scoped := s.wrap(p)
if result == p {
return scoped, nil
}
// Local storage may return an app-level presigned URL. Re-sign it with
// the scoped path so the proxy resolves the exact local instance instead
// of falling back to another backend of the same provider.
if u, parseErr := url.Parse(result); parseErr == nil && strings.HasSuffix(u.Path, "/api/v1/files/presigned") && u.Query().Get("file_path") == p {
basePath := strings.TrimSuffix(u.Path, "/api/v1/files/presigned")
baseURL := u.Scheme + "://" + u.Host + basePath
ttl := time.Duration(0)
if expires, convErr := strconv.ParseInt(u.Query().Get("expires"), 10, 64); convErr == nil {
ttl = time.Until(time.Unix(expires, 0))
}
if signed, signErr := secutils.SignFileURL(baseURL, scoped, secutils.ParseTenantIDFromStoragePath(scoped), ttl); signErr == nil {
return signed, nil
}
}
return result, nil
}
func (s *backendScopedFileService) DeleteFile(ctx context.Context, path string) error {
p, err := s.unwrap(path)
if err != nil {
return err
}
return s.inner.DeleteFile(ctx, p)
}
func (s *backendScopedFileService) CopyFile(ctx context.Context, path string, tenantID uint64, knowledgeID string) (string, error) {
p, err := s.unwrap(path)
if err != nil {
return "", err
}
result, err := s.inner.CopyFile(ctx, p, tenantID, knowledgeID)
if err != nil {
return "", err
}
return s.wrap(result), nil
}
@@ -0,0 +1,34 @@
package file
import (
"context"
"io"
"net/url"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestBackendScopedLocalURLRetainsBackendID(t *testing.T) {
t.Setenv("SYSTEM_AES_KEY", "0123456789abcdef0123456789abcdef")
inner := NewLocalFileService(t.TempDir(), "https://weknora.example.com/base")
svc := NewBackendScopedFileService("backend-local-a", inner)
path, err := svc.SaveBytes(context.Background(), []byte("hello"), 7, "exports/image.txt", false)
require.NoError(t, err)
assert.Contains(t, path, "storage://backend-local-a/local://")
signed, err := svc.GetFileURL(context.Background(), path)
require.NoError(t, err)
u, err := url.Parse(signed)
require.NoError(t, err)
assert.Equal(t, path, u.Query().Get("file_path"))
reader, err := svc.GetFile(context.Background(), path)
require.NoError(t, err)
defer reader.Close()
data, err := io.ReadAll(reader)
require.NoError(t, err)
assert.Equal(t, "hello", string(data))
}
+31 -9
View File
@@ -82,14 +82,14 @@ func NewFileServiceFromStorageConfig(
if pathPrefix == "" {
pathPrefix = "weknora"
}
svc, err := NewCosFileService(sec.COS.BucketName, sec.COS.Region, sec.COS.SecretID, sec.COS.SecretKey, pathPrefix)
svc, err := NewCosFileServiceWithTempBucket(sec.COS.BucketName, sec.COS.Region, sec.COS.SecretID, sec.COS.SecretKey, pathPrefix, sec.COS.TempBucketName, sec.COS.TempRegion)
return svc, p, err
case "tos":
if sec == nil || sec.TOS == nil || sec.TOS.Endpoint == "" || sec.TOS.Region == "" || sec.TOS.AccessKey == "" || sec.TOS.SecretKey == "" || sec.TOS.BucketName == "" {
return nil, p, fmt.Errorf("incomplete tos config")
}
svc, err := NewTosFileService(sec.TOS.Endpoint, sec.TOS.Region, sec.TOS.AccessKey, sec.TOS.SecretKey, sec.TOS.BucketName, sec.TOS.PathPrefix)
svc, err := NewTosFileServiceWithTempBucket(sec.TOS.Endpoint, sec.TOS.Region, sec.TOS.AccessKey, sec.TOS.SecretKey, sec.TOS.BucketName, sec.TOS.PathPrefix, sec.TOS.TempBucketName, sec.TOS.TempRegion)
return svc, p, err
case "s3":
if sec == nil || sec.S3 == nil || sec.S3.Endpoint == "" || sec.S3.Region == "" || sec.S3.AccessKey == "" || sec.S3.SecretKey == "" || sec.S3.BucketName == "" {
@@ -99,16 +99,38 @@ func NewFileServiceFromStorageConfig(
if pathPrefix == "" {
pathPrefix = "weknora/"
}
svc, err := NewS3FileService(sec.S3.Endpoint, sec.S3.AccessKey, sec.S3.SecretKey, sec.S3.BucketName, sec.S3.Region, pathPrefix)
svc, err := NewS3FileServiceWithOptions(sec.S3.Endpoint, sec.S3.AccessKey, sec.S3.SecretKey, sec.S3.BucketName, sec.S3.Region, pathPrefix, sec.S3.ForcePathStyle)
return svc, p, err
case "obs":
obsEndpoint := strings.TrimSpace(os.Getenv("OBS_ENDPOINT"))
obsRegion := strings.TrimSpace(os.Getenv("OBS_REGION"))
obsAccessKey := strings.TrimSpace(os.Getenv("OBS_ACCESS_KEY"))
obsSecretKey := strings.TrimSpace(os.Getenv("OBS_SECRET_KEY"))
obsBucketName := strings.TrimSpace(os.Getenv("OBS_BUCKET_NAME"))
obsPathPrefix := strings.TrimSpace(os.Getenv("OBS_PATH_PREFIX"))
obsEndpoint, obsRegion, obsAccessKey := "", "", ""
obsSecretKey, obsBucketName, obsPathPrefix := "", "", ""
if sec != nil && sec.OBS != nil {
obsEndpoint = strings.TrimSpace(sec.OBS.Endpoint)
obsRegion = strings.TrimSpace(sec.OBS.Region)
obsAccessKey = strings.TrimSpace(sec.OBS.AccessKey)
obsSecretKey = strings.TrimSpace(sec.OBS.SecretKey)
obsBucketName = strings.TrimSpace(sec.OBS.BucketName)
obsPathPrefix = strings.TrimSpace(sec.OBS.PathPrefix)
}
if obsEndpoint == "" {
obsEndpoint = strings.TrimSpace(os.Getenv("OBS_ENDPOINT"))
}
if obsRegion == "" {
obsRegion = strings.TrimSpace(os.Getenv("OBS_REGION"))
}
if obsAccessKey == "" {
obsAccessKey = strings.TrimSpace(os.Getenv("OBS_ACCESS_KEY"))
}
if obsSecretKey == "" {
obsSecretKey = strings.TrimSpace(os.Getenv("OBS_SECRET_KEY"))
}
if obsBucketName == "" {
obsBucketName = strings.TrimSpace(os.Getenv("OBS_BUCKET_NAME"))
}
if obsPathPrefix == "" {
obsPathPrefix = strings.TrimSpace(os.Getenv("OBS_PATH_PREFIX"))
}
if obsPathPrefix == "" {
obsPathPrefix = "weknora/"
}
+27 -4
View File
@@ -30,7 +30,7 @@ type s3FileService struct {
}
// newS3Client creates a bare s3FileService with just the SDK client initialised.
func newS3Client(endpoint, accessKey, secretKey, bucketName, region, pathPrefix string) (*s3FileService, error) {
func newS3Client(endpoint, accessKey, secretKey, bucketName, region, pathPrefix string, forcePathStyle bool) (*s3FileService, error) {
var cfg aws.Config
var err error
@@ -49,7 +49,7 @@ func newS3Client(endpoint, accessKey, secretKey, bucketName, region, pathPrefix
// (endpoint/bucket/key) instead of virtual-hosted style (bucket.endpoint/key).
var client *s3.Client
if endpoint != "" {
usePathStyle := !strings.Contains(endpoint, "amazonaws.com")
usePathStyle := forcePathStyle || !strings.Contains(endpoint, "amazonaws.com")
client = s3.NewFromConfig(cfg, func(o *s3.Options) {
o.BaseEndpoint = aws.String(endpoint)
o.UsePathStyle = usePathStyle
@@ -76,7 +76,7 @@ func newS3Client(endpoint, accessKey, secretKey, bucketName, region, pathPrefix
func NewS3FileService(endpoint,
accessKey, secretKey, bucketName, region, pathPrefix string,
) (interfaces.FileService, error) {
svc, err := newS3Client(endpoint, accessKey, secretKey, bucketName, region, pathPrefix)
svc, err := newS3Client(endpoint, accessKey, secretKey, bucketName, region, pathPrefix, false)
if err != nil {
return nil, err
}
@@ -96,6 +96,25 @@ func NewS3FileService(endpoint,
return svc, nil
}
// NewS3FileServiceWithOptions is the instance-aware S3 constructor. Existing
// callers keep the historical endpoint-based path-style inference.
func NewS3FileServiceWithOptions(endpoint, accessKey, secretKey, bucketName, region, pathPrefix string, forcePathStyle bool) (interfaces.FileService, error) {
svc, err := newS3Client(endpoint, accessKey, secretKey, bucketName, region, pathPrefix, forcePathStyle)
if err != nil {
return nil, err
}
exists, err := svc.bucketExists(context.Background())
if err != nil {
return nil, fmt.Errorf("failed to check bucket: %w", err)
}
if !exists {
if err = svc.createBucket(context.Background()); err != nil {
return nil, fmt.Errorf("failed to create bucket: %w", err)
}
}
return svc, nil
}
// bucketExists checks if the bucket exists
func (s *s3FileService) bucketExists(ctx context.Context) (bool, error) {
_, err := s.client.HeadBucket(ctx, &s3.HeadBucketInput{
@@ -145,7 +164,11 @@ func (s *s3FileService) CheckConnectivity(ctx context.Context) error {
// CheckS3Connectivity tests S3 connectivity using the provided credentials.
// It creates a temporary service instance internally and delegates to CheckConnectivity.
func CheckS3Connectivity(ctx context.Context, endpoint, accessKey, secretKey, bucketName, region string) error {
svc, err := newS3Client(endpoint, accessKey, secretKey, bucketName, region, "")
return CheckS3ConnectivityWithOptions(ctx, endpoint, accessKey, secretKey, bucketName, region, false)
}
func CheckS3ConnectivityWithOptions(ctx context.Context, endpoint, accessKey, secretKey, bucketName, region string, forcePathStyle bool) error {
svc, err := newS3Client(endpoint, accessKey, secretKey, bucketName, region, "", forcePathStyle)
if err != nil {
return err
}