init commit
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
package file
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/google/uuid"
|
||||
"github.com/tencentyun/cos-go-sdk-v5"
|
||||
)
|
||||
|
||||
// cosFileService implements the FileService interface for Tencent Cloud COS
|
||||
type cosFileService struct {
|
||||
client *cos.Client
|
||||
bucketURL string
|
||||
cosPathPrefix string
|
||||
}
|
||||
|
||||
// NewCosFileService creates a new COS file service instance
|
||||
func NewCosFileService(appId, region, secretId, secretKey, cosPathPrefix string) (interfaces.FileService, error) {
|
||||
bucketURL := fmt.Sprintf("https://%s.cos.%s.myqcloud.com", appId, region)
|
||||
u, err := url.Parse(bucketURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse bucketURL: %w", err)
|
||||
}
|
||||
b := &cos.BaseURL{BucketURL: u}
|
||||
client := cos.NewClient(b, &http.Client{
|
||||
Transport: &cos.AuthorizationTransport{
|
||||
SecretID: secretId,
|
||||
SecretKey: secretKey,
|
||||
},
|
||||
})
|
||||
return &cosFileService{
|
||||
client: client,
|
||||
bucketURL: bucketURL,
|
||||
cosPathPrefix: cosPathPrefix,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// SaveFile saves a file to COS storage
|
||||
// It generates a unique name for the file and organizes it by tenant and knowledge ID
|
||||
func (s *cosFileService) SaveFile(ctx context.Context,
|
||||
file *multipart.FileHeader, tenantID uint, knowledgeID string,
|
||||
) (string, error) {
|
||||
ext := filepath.Ext(file.Filename)
|
||||
objectName := fmt.Sprintf("%s/%d/%s/%s%s", s.cosPathPrefix, 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()
|
||||
_, err = s.client.Object.Put(ctx, objectName, src, nil)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to upload file to COS: %w", err)
|
||||
}
|
||||
return fmt.Sprintf("https://%s/%s", s.bucketURL, objectName), nil
|
||||
}
|
||||
|
||||
// GetFile retrieves a file from COS storage by its path URL
|
||||
func (s *cosFileService) GetFile(ctx context.Context, filePathUrl string) (io.ReadCloser, error) {
|
||||
objectName := strings.TrimPrefix(filePathUrl, s.bucketURL)
|
||||
resp, err := s.client.Object.Get(ctx, objectName, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get file from COS: %w", err)
|
||||
}
|
||||
return resp.Body, nil
|
||||
}
|
||||
|
||||
// DeleteFile removes a file from COS storage
|
||||
func (s *cosFileService) DeleteFile(ctx context.Context, filePath string) error {
|
||||
objectName := strings.TrimPrefix(filePath, s.bucketURL)
|
||||
_, err := s.client.Object.Delete(ctx, objectName)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to delete file: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package file
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// DummyFileService is a no-op implementation of the FileService interface
|
||||
// used for testing or when file storage is not required
|
||||
type DummyFileService struct{}
|
||||
|
||||
// NewDummyFileService creates a new instance of DummyFileService
|
||||
func NewDummyFileService() interfaces.FileService {
|
||||
return &DummyFileService{}
|
||||
}
|
||||
|
||||
// SaveFile pretends to save a file but just returns a random UUID
|
||||
// This is useful for testing without actual file operations
|
||||
func (s *DummyFileService) SaveFile(ctx context.Context,
|
||||
file *multipart.FileHeader, tenantID uint, knowledgeID string,
|
||||
) (string, error) {
|
||||
return uuid.New().String(), nil
|
||||
}
|
||||
|
||||
// GetFile always returns an error as dummy service doesn't store files
|
||||
func (s *DummyFileService) GetFile(ctx context.Context, filePath string) (io.ReadCloser, error) {
|
||||
return nil, errors.New("not implemented")
|
||||
}
|
||||
|
||||
// DeleteFile is a no-op operation that always succeeds
|
||||
func (s *DummyFileService) DeleteFile(ctx context.Context, filePath string) error {
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package file
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// localFileService implements the FileService interface for local file system storage
|
||||
type localFileService struct {
|
||||
baseDir string // Base directory for file storage
|
||||
}
|
||||
|
||||
// NewLocalFileService creates a new local file service instance
|
||||
func NewLocalFileService(baseDir string) interfaces.FileService {
|
||||
return &localFileService{
|
||||
baseDir: baseDir,
|
||||
}
|
||||
}
|
||||
|
||||
// SaveFile stores an uploaded file to the local file system
|
||||
// The file is stored in a directory structure: baseDir/tenantID/knowledgeID/filename
|
||||
// Returns the full file path or an error if saving fails
|
||||
func (s *localFileService) SaveFile(ctx context.Context,
|
||||
file *multipart.FileHeader, tenantID uint, knowledgeID string,
|
||||
) (string, error) {
|
||||
logger.Info(ctx, "Starting to save file locally")
|
||||
logger.Infof(ctx, "File information: name=%s, size=%d, tenant ID=%d, knowledge ID=%s",
|
||||
file.Filename, file.Size, tenantID, knowledgeID)
|
||||
|
||||
// Create storage directory with tenant and knowledge ID
|
||||
dir := filepath.Join(s.baseDir, fmt.Sprintf("%d", tenantID), knowledgeID)
|
||||
logger.Infof(ctx, "Creating directory: %s", dir)
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
logger.Errorf(ctx, "Failed to create directory: %v", err)
|
||||
return "", fmt.Errorf("failed to create directory: %w", err)
|
||||
}
|
||||
|
||||
// Generate unique filename using timestamp
|
||||
ext := filepath.Ext(file.Filename)
|
||||
filename := fmt.Sprintf("%d%s", time.Now().UnixNano(), ext)
|
||||
filePath := filepath.Join(dir, filename)
|
||||
logger.Infof(ctx, "Generated file path: %s", filePath)
|
||||
|
||||
// Open source file for reading
|
||||
logger.Info(ctx, "Opening source file")
|
||||
src, err := file.Open()
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to open source file: %v", err)
|
||||
return "", fmt.Errorf("failed to open file: %w", err)
|
||||
}
|
||||
defer src.Close()
|
||||
|
||||
// Create destination file for writing
|
||||
logger.Info(ctx, "Creating destination file")
|
||||
dst, err := os.Create(filePath)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to create destination file: %v", err)
|
||||
return "", fmt.Errorf("failed to create file: %w", err)
|
||||
}
|
||||
defer dst.Close()
|
||||
|
||||
// Copy content from source to destination
|
||||
logger.Info(ctx, "Copying file content")
|
||||
if _, err := io.Copy(dst, src); err != nil {
|
||||
logger.Errorf(ctx, "Failed to copy file content: %v", err)
|
||||
return "", fmt.Errorf("failed to save file: %w", err)
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "File saved successfully: %s", filePath)
|
||||
return filePath, nil
|
||||
}
|
||||
|
||||
// GetFile retrieves a file from the local file system by its path
|
||||
// Returns a ReadCloser for reading the file content
|
||||
func (s *localFileService) GetFile(ctx context.Context, filePath string) (io.ReadCloser, error) {
|
||||
logger.Infof(ctx, "Getting file: %s", filePath)
|
||||
|
||||
// Open the file for reading
|
||||
file, err := os.Open(filePath)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to open file: %v", err)
|
||||
return nil, fmt.Errorf("failed to open file: %w", err)
|
||||
}
|
||||
|
||||
logger.Info(ctx, "File opened successfully")
|
||||
return file, nil
|
||||
}
|
||||
|
||||
// DeleteFile removes a file from the local file system
|
||||
// Returns an error if deletion fails
|
||||
func (s *localFileService) DeleteFile(ctx context.Context, filePath string) error {
|
||||
logger.Infof(ctx, "Deleting file: %s", filePath)
|
||||
|
||||
// Remove the file
|
||||
err := os.Remove(filePath)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to delete file: %v", err)
|
||||
return fmt.Errorf("failed to delete file: %w", err)
|
||||
}
|
||||
|
||||
logger.Info(ctx, "File deleted successfully")
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package file
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/google/uuid"
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
)
|
||||
|
||||
// minioFileService MinIO file service implementation
|
||||
type minioFileService struct {
|
||||
client *minio.Client
|
||||
bucketName string
|
||||
}
|
||||
|
||||
// NewMinioFileService creates a MinIO file service
|
||||
func NewMinioFileService(endpoint,
|
||||
accessKeyID, secretAccessKey, bucketName string, useSSL bool) (interfaces.FileService, error) {
|
||||
// Initialize MinIO client
|
||||
client, err := minio.New(endpoint, &minio.Options{
|
||||
Creds: credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
|
||||
Secure: useSSL,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to initialize MinIO client: %w", err)
|
||||
}
|
||||
|
||||
// Check if bucket exists, create if not
|
||||
exists, err := client.BucketExists(context.Background(), bucketName)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to check bucket: %w", err)
|
||||
}
|
||||
|
||||
if !exists {
|
||||
err = client.MakeBucket(context.Background(), bucketName, minio.MakeBucketOptions{})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create bucket: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return &minioFileService{
|
||||
client: client,
|
||||
bucketName: bucketName,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// SaveFile saves a file to MinIO
|
||||
func (s *minioFileService) SaveFile(ctx context.Context,
|
||||
file *multipart.FileHeader, tenantID uint, knowledgeID string,
|
||||
) (string, error) {
|
||||
// Generate object name
|
||||
ext := filepath.Ext(file.Filename)
|
||||
objectName := fmt.Sprintf("%d/%s/%s%s", tenantID, knowledgeID, uuid.New().String(), ext)
|
||||
|
||||
// Open file
|
||||
src, err := file.Open()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to open file: %w", err)
|
||||
}
|
||||
defer src.Close()
|
||||
|
||||
// Upload file to MinIO
|
||||
_, err = s.client.PutObject(ctx, s.bucketName, objectName, src, file.Size, minio.PutObjectOptions{
|
||||
ContentType: file.Header.Get("Content-Type"),
|
||||
})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to upload file to MinIO: %w", err)
|
||||
}
|
||||
|
||||
// Return the complete path to the object
|
||||
return fmt.Sprintf("minio://%s/%s", s.bucketName, objectName), nil
|
||||
}
|
||||
|
||||
// GetFile gets a file from MinIO
|
||||
func (s *minioFileService) GetFile(ctx context.Context, filePath string) (io.ReadCloser, error) {
|
||||
// Parse MinIO path
|
||||
// Format: minio://bucketName/objectName
|
||||
if len(filePath) < 9 || filePath[:8] != "minio://" {
|
||||
return nil, fmt.Errorf("invalid MinIO file path: %s", filePath)
|
||||
}
|
||||
|
||||
// Extract object name
|
||||
objectName := filePath[9+len(s.bucketName):]
|
||||
if objectName[0] == '/' {
|
||||
objectName = objectName[1:]
|
||||
}
|
||||
|
||||
// Get object
|
||||
obj, err := s.client.GetObject(ctx, s.bucketName, objectName, minio.GetObjectOptions{})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get file from MinIO: %w", err)
|
||||
}
|
||||
|
||||
return obj, nil
|
||||
}
|
||||
|
||||
// DeleteFile deletes a file
|
||||
func (s *minioFileService) DeleteFile(ctx context.Context, filePath string) error {
|
||||
// Parse MinIO path
|
||||
// Format: minio://bucketName/objectName
|
||||
if len(filePath) < 9 || filePath[:8] != "minio://" {
|
||||
return fmt.Errorf("invalid MinIO file path: %s", filePath)
|
||||
}
|
||||
|
||||
// Extract object name
|
||||
objectName := filePath[9+len(s.bucketName):]
|
||||
if objectName[0] == '/' {
|
||||
objectName = objectName[1:]
|
||||
}
|
||||
|
||||
// Delete object
|
||||
err := s.client.RemoveObject(ctx, s.bucketName, objectName, minio.RemoveObjectOptions{
|
||||
GovernanceBypass: true,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to delete file: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user