feat(obs): 支持华为云obs存储

This commit is contained in:
Li Xianggang
2026-05-18 18:54:57 +08:00
committed by lyingbug
parent 5cee0d0921
commit b3dbf86bf5
21 changed files with 626 additions and 30 deletions
@@ -102,6 +102,25 @@ func NewFileServiceFromStorageConfig(
svc, err := NewS3FileService(sec.S3.Endpoint, sec.S3.AccessKey, sec.S3.SecretKey, sec.S3.BucketName, sec.S3.Region, pathPrefix)
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"))
if obsPathPrefix == "" {
obsPathPrefix = "weknora/"
}
if obsEndpoint == "" || obsAccessKey == "" || obsSecretKey == "" || obsBucketName == "" {
return nil, p, fmt.Errorf("incomplete obs config")
}
if obsRegion == "" {
obsRegion = "cn-north-4"
}
svc, err := NewObsFileService(obsEndpoint, obsRegion, obsAccessKey, obsSecretKey, obsBucketName, obsPathPrefix)
return svc, p, err
case "oss":
if sec == nil || sec.OSS == nil || sec.OSS.Endpoint == "" || sec.OSS.Region == "" || sec.OSS.AccessKey == "" || sec.OSS.SecretKey == "" || sec.OSS.BucketName == "" {
return nil, p, fmt.Errorf("incomplete oss config")
+266
View File
@@ -0,0 +1,266 @@
package file
import (
"context"
"fmt"
"io"
"mime/multipart"
"os"
"path/filepath"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/google/uuid"
)
type obsFileService struct {
client *s3.Client
bucketName string
endpoint string
region string
pathPrefix string
proxyDomain string
}
type obsEndpointResolver struct {
url string
}
func (r *obsEndpointResolver) ResolveEndpoint(region string, options s3.EndpointResolverOptions) (aws.Endpoint, error) {
return aws.Endpoint{
URL: r.url,
SigningRegion: region,
HostnameImmutable: true,
}, nil
}
func NewObsFileService(
endpoint, region, accessKeyID, secretAccessKey, bucketName string,
pathPrefix string,
) (interfaces.FileService, error) {
client := s3.New(s3.Options{
Region: region,
EndpointResolver: &obsEndpointResolver{url: endpoint},
Credentials: credentials.NewStaticCredentialsProvider(accessKeyID, secretAccessKey, ""),
UsePathStyle: true,
})
_, err := client.HeadBucket(context.Background(), &s3.HeadBucketInput{
Bucket: aws.String(bucketName),
})
if err != nil {
_, createErr := client.CreateBucket(context.Background(), &s3.CreateBucketInput{
Bucket: aws.String(bucketName),
})
if createErr != nil {
fmt.Printf("Warning: bucket %s may not exist or cannot be created: %v\n", bucketName, createErr)
}
}
proxyDomain := strings.TrimSuffix(os.Getenv("OBS_PROXY_DOMAIN"), "/")
return &obsFileService{
client: client,
bucketName: bucketName,
endpoint: endpoint,
region: region,
pathPrefix: strings.Trim(pathPrefix, "/"),
proxyDomain: proxyDomain,
}, nil
}
func CheckObsConnectivity(ctx context.Context, endpoint, region, accessKey, secretKey, bucketName string) error {
checkCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
client := s3.New(s3.Options{
Region: region,
EndpointResolver: &obsEndpointResolver{url: endpoint},
Credentials: credentials.NewStaticCredentialsProvider(accessKey, secretKey, ""),
UsePathStyle: true,
})
_, err := client.HeadBucket(checkCtx, &s3.HeadBucketInput{
Bucket: aws.String(bucketName),
})
if err != nil {
return fmt.Errorf("OBS connectivity check failed: %w", err)
}
return nil
}
func (s *obsFileService) CheckConnectivity(ctx context.Context) error {
checkCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
_, err := s.client.HeadBucket(checkCtx, &s3.HeadBucketInput{
Bucket: aws.String(s.bucketName),
})
if err != nil {
return fmt.Errorf("OBS connectivity check failed: %w", err)
}
return nil
}
func (s *obsFileService) parseObsFilePath(filePath string) (string, error) {
prefix := s.getPrifix()
if strings.HasPrefix(filePath, prefix) {
rest := strings.TrimPrefix(filePath, prefix)
// With proxy domain: path is {prefix}/{objectKey} (no bucket name)
if s.proxyDomain != "" {
rest = strings.TrimPrefix(rest, "/")
if rest != "" {
return rest, nil
}
return "", fmt.Errorf("invalid OBS file path: %s", filePath)
}
// Without proxy domain: path is {prefix}/{bucketName}/{objectKey}
parts := strings.SplitN(rest, "/", 2)
if len(parts) == 2 && parts[0] == s.bucketName && parts[1] != "" {
return parts[1], nil
}
return "", fmt.Errorf("invalid OBS file path: %s", filePath)
}
return filePath, nil
}
func (s *obsFileService) getPrifix() string {
if s.proxyDomain != "" {
return s.proxyDomain + "/"
}
return "obs://"
}
func (s *obsFileService) SaveFile(ctx context.Context,
file *multipart.FileHeader, tenantID uint64, knowledgeID string,
) (string, error) {
ext := filepath.Ext(file.Filename)
var objectKey string
if s.pathPrefix != "" {
objectKey = fmt.Sprintf("%s/%d/%s/%s%s", s.pathPrefix, tenantID, knowledgeID, uuid.New().String(), ext)
} else {
objectKey = fmt.Sprintf("%d/%s/%s%s", tenantID, knowledgeID, uuid.New().String(), ext)
}
src, err := file.Open()
if err != nil {
return "", fmt.Errorf("failed to open file: %w", err)
}
defer src.Close()
contentType := file.Header.Get("Content-Type")
if contentType == "" {
contentType = "application/octet-stream"
}
_, err = s.client.PutObject(ctx, &s3.PutObjectInput{
Bucket: aws.String(s.bucketName),
Key: aws.String(objectKey),
Body: src,
ContentLength: aws.Int64(file.Size),
ContentType: aws.String(contentType),
// ACL: "private",
})
if err != nil {
return "", fmt.Errorf("failed to upload file to OBS: %w", err)
}
prefix := s.getPrifix()
if s.proxyDomain != "" {
return fmt.Sprintf("%s%s", prefix, objectKey), nil
}
return fmt.Sprintf("%s%s/%s", prefix, s.bucketName, objectKey), nil
}
func (s *obsFileService) GetFile(ctx context.Context, filePath string) (io.ReadCloser, error) {
objectKey, err := s.parseObsFilePath(filePath)
if err != nil {
return nil, err
}
output, err := s.client.GetObject(ctx, &s3.GetObjectInput{
Bucket: aws.String(s.bucketName),
Key: aws.String(objectKey),
})
if err != nil {
return nil, fmt.Errorf("failed to get file from OBS: %w", err)
}
return output.Body, nil
}
func (s *obsFileService) DeleteFile(ctx context.Context, filePath string) error {
objectKey, err := s.parseObsFilePath(filePath)
if err != nil {
return err
}
_, err = s.client.DeleteObject(ctx, &s3.DeleteObjectInput{
Bucket: aws.String(s.bucketName),
Key: aws.String(objectKey),
})
if err != nil {
return fmt.Errorf("failed to delete file from OBS: %w", err)
}
return nil
}
func (s *obsFileService) GetFileURL(ctx context.Context, filePath string) (string, error) {
if strings.HasPrefix(filePath, "http://") || strings.HasPrefix(filePath, "https://") {
return filePath, nil
}
objectKey, err := s.parseObsFilePath(filePath)
if err != nil {
return "", err
}
if s.proxyDomain != "" {
return s.proxyDomain + "/" + strings.TrimPrefix(objectKey, "/"), nil
}
return fmt.Sprintf("%s/%s/%s", s.endpoint, s.bucketName, strings.TrimPrefix(objectKey, "/")), nil
}
func (s *obsFileService) SaveBytes(ctx context.Context, data []byte, tenantID uint64, fileName string, temp bool) (string, error) {
ext := filepath.Ext(fileName)
var objectKey string
if temp {
if s.pathPrefix != "" {
objectKey = fmt.Sprintf("%s/temp/%d/%s%s", s.pathPrefix, tenantID, uuid.New().String(), ext)
} else {
objectKey = fmt.Sprintf("temp/%d/%s%s", tenantID, uuid.New().String(), ext)
}
} else {
if s.pathPrefix != "" {
objectKey = fmt.Sprintf("%s/%d/%s%s", s.pathPrefix, tenantID, uuid.New().String(), ext)
} else {
objectKey = fmt.Sprintf("%d/%s%s", tenantID, uuid.New().String(), ext)
}
}
_, err := s.client.PutObject(ctx, &s3.PutObjectInput{
Bucket: aws.String(s.bucketName),
Key: aws.String(objectKey),
Body: strings.NewReader(string(data)),
ContentType: aws.String("application/octet-stream"),
ACL: "public-read",
})
if err != nil {
return "", fmt.Errorf("failed to upload bytes to OBS: %w", err)
}
prefix := s.getPrifix()
if s.proxyDomain != "" {
return fmt.Sprintf("%s%s", prefix, objectKey), nil
}
return fmt.Sprintf("%s%s/%s", prefix, s.bucketName, objectKey), nil
}
@@ -143,7 +143,7 @@ func (s *ImageMultimodalService) Handle(ctx context.Context, task *asynq.Task) e
prompt = vlmOCRScannedPDFPrompt
logger.Infof(ctx, "[ImageMultimodal] Using scanned PDF prompt for OCR: %s", payload.ImageURL)
}
ocrText, ocrErr := vlmModel.Predict(ctx, [][]byte{imgBytes}, prompt)
if ocrErr != nil {
logger.Warnf(ctx, "[ImageMultimodal] OCR failed for %s: %v", payload.ImageURL, ocrErr)
@@ -430,7 +430,7 @@ func (s *ImageMultimodalService) checkAndFinalizeAllImages(ctx context.Context,
}
redisKey := fmt.Sprintf("multimodal:pending:%s", payload.KnowledgeID)
pendingCount, err := s.redisClient.Decr(ctx, redisKey).Result()
if err != nil && err != redis.Nil {
logger.Warnf(ctx, "[ImageMultimodal] Failed to decrement pending count for %s: %v", payload.KnowledgeID, err)
@@ -449,7 +449,7 @@ func (s *ImageMultimodalService) enqueueKnowledgePostProcessTask(ctx context.Con
if s.taskEnqueuer == nil {
return
}
taskPayload := types.KnowledgePostProcessPayload{
TenantID: payload.TenantID,
KnowledgeID: payload.KnowledgeID,
+20
View File
@@ -746,6 +746,26 @@ func initFileService(cfg *config.Config) (interfaces.FileService, error) {
os.Getenv("S3_REGION"),
pathPrefix,
)
case "obs":
if os.Getenv("OBS_ENDPOINT") == "" ||
os.Getenv("OBS_ACCESS_KEY") == "" ||
os.Getenv("OBS_SECRET_KEY") == "" ||
os.Getenv("OBS_BUCKET_NAME") == "" {
return nil, fmt.Errorf("missing OBS configuration")
}
obsRegion := os.Getenv("OBS_REGION")
obsPathPrefix := os.Getenv("OBS_PATH_PREFIX")
if obsPathPrefix == "" {
obsPathPrefix = "weknora/"
}
return file.NewObsFileService(
os.Getenv("OBS_ENDPOINT"),
obsRegion,
os.Getenv("OBS_ACCESS_KEY"),
os.Getenv("OBS_SECRET_KEY"),
os.Getenv("OBS_BUCKET_NAME"),
obsPathPrefix,
)
case "oss":
if os.Getenv("OSS_ENDPOINT") == "" ||
os.Getenv("OSS_REGION") == "" ||
+1 -1
View File
@@ -7,7 +7,7 @@ import (
const storageAllowListEnv = "STORAGE_ALLOW_LIST"
var supportedStorageProviders = []string{"local", "minio", "cos", "tos", "s3", "oss", "ks3"}
var supportedStorageProviders = []string{"local", "minio", "cos", "tos", "s3", "oss", "ks3", "obs"}
func getSupportedStorageProviders() []string {
providers := make([]string, len(supportedStorageProviders))
+50 -1
View File
@@ -614,13 +614,14 @@ func isBlockedStorageEndpoint(endpoint string) (bool, string) {
// StorageCheckRequest is the body for POST /system/storage-engine-check.
type StorageCheckRequest struct {
Provider string `json:"provider"` // "minio", "cos", "tos", "s3", "oss", "ks3"
Provider string `json:"provider"` // "minio", "cos", "tos", "s3", "oss", "ks3", "obs"
MinIO *types.MinIOEngineConfig `json:"minio,omitempty"`
COS *types.COSEngineConfig `json:"cos,omitempty"`
TOS *types.TOSEngineConfig `json:"tos,omitempty"`
S3 *types.S3EngineConfig `json:"s3,omitempty"`
OSS *types.OSSEngineConfig `json:"oss,omitempty"`
KS3 *types.KS3EngineConfig `json:"ks3,omitempty"`
OBS *types.OBSEngineConfig `json:"obs,omitempty"`
}
// StorageCheckResponse is the response for a single-engine connectivity check.
@@ -665,6 +666,8 @@ func (h *SystemHandler) CheckStorageEngine(c *gin.Context) {
h.checkOSS(c, ctx, req.OSS)
case "ks3":
h.checkKS3(c, ctx, req.KS3)
case "obs":
h.checkOBS(c, ctx, req.OBS)
default:
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: true, Message: "本地存储无需检测"}})
}
@@ -934,6 +937,52 @@ func (h *SystemHandler) checkKS3(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) checkOBS(c *gin.Context, ctx context.Context, cfg *types.OBSEngineConfig) {
if cfg == nil {
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: "未提供 OBS 配置"}})
return
}
endpoint, region, accessKey, secretKey := cfg.Endpoint, cfg.Region, cfg.AccessKey, cfg.SecretKey
if endpoint == "" || region == "" || accessKey == "" || secretKey == "" || cfg.BucketName == "" {
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: "Endpoint、Region、Access Key、Secret Key、Bucket 名称不能为空"}})
return
}
ssrfEndpoint := strings.TrimPrefix(strings.TrimPrefix(endpoint, "https://"), "http://")
if blocked, reason := isBlockedStorageEndpoint(ssrfEndpoint); blocked {
logger.Warnf(ctx, "Storage check: OBS endpoint blocked by SSRF protection, endpoint: %s", endpoint)
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: reason}})
return
}
if !ossFieldPattern.MatchString(cfg.Region) {
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: "Region 格式不正确,仅允许字母、数字、点、连字符"}})
return
}
if !ossFieldPattern.MatchString(cfg.BucketName) {
c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: "Bucket 名称格式不正确,仅允许字母、数字、点、连字符"}})
return
}
err := file.CheckObsConnectivity(ctx, endpoint, region, accessKey, secretKey, cfg.BucketName)
if err != nil {
logger.Errorf(ctx, "Storage check: OBS connectivity failed, bucket: %s, error: %v", cfg.BucketName, err)
errMsg := err.Error()
if strings.Contains(errMsg, "403") || strings.Contains(errMsg, "AccessDenied") {
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") {
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)}})
}
func (h *SystemHandler) ResolveDocumentReader(ctx context.Context, addr string) interfaces.DocumentReader {
if addr == "" {
return h.documentReader
@@ -187,7 +187,7 @@ func extFromMime(mime string) string {
// isProviderScheme checks if the path uses a provider:// scheme (local://, minio://, cos://, tos://).
func isProviderScheme(p string) bool {
for _, prefix := range []string{"local://", "minio://", "cos://", "tos://", "s3://"} {
for _, prefix := range []string{"local://", "minio://", "cos://", "tos://", "s3://", "obs://"} {
if strings.HasPrefix(p, prefix) {
return true
}
+20 -7
View File
@@ -199,7 +199,7 @@ func (c ChunkingConfig) ResolveParserEngine(fileType string) string {
// StorageProviderConfig stores the KB-level storage provider selection.
// Credentials are managed at the tenant level (StorageEngineConfig).
type StorageProviderConfig struct {
Provider string `yaml:"provider" json:"provider"` // "local", "minio", "cos", "tos", "s3", "oss", "ks3"
Provider string `yaml:"provider" json:"provider"` // "local", "minio", "cos", "tos", "s3", "oss", "ks3", "obs"
}
func (c StorageProviderConfig) Value() (driver.Value, error) {
@@ -220,13 +220,26 @@ func (c *StorageProviderConfig) Scan(value interface{}) error {
// Deprecated: StorageConfig is the legacy COS configuration stored in the cos_config column.
// New code should use StorageProviderConfig. Kept for backward compatibility with old data.
type StorageConfig struct {
SecretID string `yaml:"secret_id" json:"secret_id"`
SecretKey string `yaml:"secret_key" json:"secret_key"`
Region string `yaml:"region" json:"region"`
// Secret ID (COS) / Access Key ID (S3, MinIO)
SecretID string `yaml:"secret_id" json:"secret_id"`
// Secret Key (COS) / Secret Access Key (S3, MinIO)
SecretKey string `yaml:"secret_key" json:"secret_key"`
// Region
Region string `yaml:"region" json:"region"`
// Bucket Name
BucketName string `yaml:"bucket_name" json:"bucket_name"`
AppID string `yaml:"app_id" json:"app_id"`
// App ID (COS specific)
AppID string `yaml:"app_id" json:"app_id"`
// Path Prefix
PathPrefix string `yaml:"path_prefix" json:"path_prefix"`
Provider string `yaml:"provider" json:"provider"`
// Provider: "cos", "minio", "s3"
Provider string `yaml:"provider" json:"provider"`
// Endpoint (S3 specific) - e.g., s3.amazonaws.com, oss-cn-hangzhou.aliyuncs.com
Endpoint string `yaml:"endpoint" json:"endpoint,omitempty"`
// UseSSL (S3 specific) - whether to use HTTPS
UseSSL bool `yaml:"use_ssl" json:"use_ssl,omitempty"`
// ForcePathStyle (S3 specific) - whether to use path-style URLs
ForcePathStyle bool `yaml:"force_path_style" json:"force_path_style,omitempty"`
}
func (c StorageConfig) Value() (driver.Value, error) {
@@ -313,7 +326,7 @@ func InferStorageFromFilePath(filePath string) string {
// e.g. "minio://bucket/key" → "minio", "local://tenant/file.pdf" → "local"
// Returns "" if the path does not use a known provider scheme.
func ParseProviderScheme(filePath string) string {
for _, provider := range []string{"local", "minio", "cos", "tos", "s3", "oss", "ks3"} {
for _, provider := range []string{"local", "minio", "cos", "tos", "s3", "oss", "ks3", "obs"} {
if strings.HasPrefix(filePath, provider+"://") {
return provider
}
+22 -8
View File
@@ -351,10 +351,10 @@ func (c *ParserEngineConfig) Scan(value interface{}) error {
return json.Unmarshal(b, c)
}
// StorageEngineConfig holds tenant-level storage engine parameters for Local, MinIO, COS, TOS, S3, OSS, and KS3.
// StorageEngineConfig holds tenant-level storage engine parameters for Local, MinIO, COS, TOS, S3, OSS, KS3, and OBS.
// Knowledge bases select which provider to use; parameters are read from here.
type StorageEngineConfig struct {
DefaultProvider string `json:"default_provider"` // "local", "minio", "cos", "tos", "s3", "oss", "ks3"
DefaultProvider string `json:"default_provider"` // "local", "minio", "cos", "tos", "s3", "oss", "ks3", "obs"
Local *LocalEngineConfig `json:"local,omitempty"`
MinIO *MinIOEngineConfig `json:"minio,omitempty"`
COS *COSEngineConfig `json:"cos,omitempty"`
@@ -362,6 +362,7 @@ type StorageEngineConfig struct {
S3 *S3EngineConfig `json:"s3,omitempty"`
OSS *OSSEngineConfig `json:"oss,omitempty"`
KS3 *KS3EngineConfig `json:"ks3,omitempty"`
OBS *OBSEngineConfig `json:"obs,omitempty"`
}
// LocalEngineConfig is for local file system storage (single-machine deployment only).
@@ -403,12 +404,14 @@ type TOSEngineConfig struct {
// S3EngineConfig is for AWS S3 and S3-compatible object storage.
type S3EngineConfig 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"`
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"`
UseSSL bool `json:"use_ssl"`
ForcePathStyle bool `json:"force_path_style"`
}
// OSSEngineConfig is for Alibaba Cloud OSS (对象存储服务).
@@ -434,6 +437,17 @@ type KS3EngineConfig struct {
PathPrefix string `json:"path_prefix"`
}
// OBSEngineConfig is for Huawei Cloud OBS (对象存储服务).
type OBSEngineConfig 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"`
UseSSL bool `json:"use_ssl"`
}
// Value implements the driver.Valuer interface for StorageEngineConfig
func (c *StorageEngineConfig) Value() (driver.Value, error) {
if c == nil {