feat(resource): add stable resource registry with LLM-context alias compaction
Introduce resource://<handle> as the stable application identity for stored objects, decoupling API responses, persisted rich text, and LLM prompts from physical storage paths. Adds a resource catalog service (register/resolve/bind, revocable expiring access grants), a request-local alias registry that compacts resource references while in the LLM context and restores them (including across streaming chunks), plus router, IM, chat-pipeline, and multimodal integration. Includes schema migrations (resources, resource_bindings, resource_access_grants) for sqlite, and hardens URL/output security handling.
This commit is contained in:
@@ -0,0 +1,97 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
type resourceRepository struct{ db *gorm.DB }
|
||||
|
||||
// NewResourceRepository creates the persistence adapter for resource metadata.
|
||||
func NewResourceRepository(db *gorm.DB) interfaces.ResourceRepository {
|
||||
return &resourceRepository{db: db}
|
||||
}
|
||||
|
||||
func (r *resourceRepository) Create(ctx context.Context, resource *types.StoredResource) error {
|
||||
return r.db.WithContext(ctx).Create(resource).Error
|
||||
}
|
||||
|
||||
func (r *resourceRepository) GetByID(ctx context.Context, id string) (*types.StoredResource, error) {
|
||||
var resource types.StoredResource
|
||||
err := r.db.WithContext(ctx).Where("id = ? AND state = ?", id, types.ResourceStateActive).First(&resource).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return &resource, err
|
||||
}
|
||||
|
||||
func (r *resourceRepository) GetByHandle(ctx context.Context, handle string) (*types.StoredResource, error) {
|
||||
var resource types.StoredResource
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("handle = ? AND state = ?", handle, types.ResourceStateActive).
|
||||
First(&resource).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return &resource, err
|
||||
}
|
||||
|
||||
func (r *resourceRepository) GetByTenantLocation(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
locationHash string,
|
||||
) (*types.StoredResource, error) {
|
||||
var resource types.StoredResource
|
||||
err := r.db.WithContext(ctx).
|
||||
Where(
|
||||
"tenant_id = ? AND location_hash = ? AND state = ?",
|
||||
tenantID,
|
||||
locationHash,
|
||||
types.ResourceStateActive,
|
||||
).
|
||||
First(&resource).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return &resource, err
|
||||
}
|
||||
|
||||
func (r *resourceRepository) MarkDeleted(ctx context.Context, id string) error {
|
||||
return r.db.WithContext(ctx).Model(&types.StoredResource{}).Where("id = ?", id).
|
||||
Updates(map[string]interface{}{"state": types.ResourceStateDeleted, "deleted_at": time.Now()}).Error
|
||||
}
|
||||
|
||||
func (r *resourceRepository) CreateBinding(ctx context.Context, binding *types.ResourceBinding) error {
|
||||
return r.db.WithContext(ctx).Clauses(clause.OnConflict{DoNothing: true}).Create(binding).Error
|
||||
}
|
||||
|
||||
func (r *resourceRepository) CreateGrant(ctx context.Context, grant *types.ResourceAccessGrant) error {
|
||||
return r.db.WithContext(ctx).Create(grant).Error
|
||||
}
|
||||
|
||||
func (r *resourceRepository) GetValidGrant(
|
||||
ctx context.Context,
|
||||
tokenHash string,
|
||||
now time.Time,
|
||||
) (*types.ResourceAccessGrant, error) {
|
||||
var grant types.ResourceAccessGrant
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("token_hash = ? AND revoked_at IS NULL AND expires_at > ?", tokenHash, now).
|
||||
First(&grant).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return &grant, err
|
||||
}
|
||||
|
||||
func (r *resourceRepository) DeleteExpiredGrants(ctx context.Context, before time.Time) error {
|
||||
return r.db.WithContext(ctx).
|
||||
Where("expires_at <= ? OR revoked_at IS NOT NULL", before).
|
||||
Delete(&types.ResourceAccessGrant{}).Error
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package chatpipeline
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/llmresource"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
@@ -51,6 +52,8 @@ func (p *PluginChatCompletion) OnEvent(
|
||||
"message_count": len(chatManage.History) + 2,
|
||||
})
|
||||
chatMessages := prepareMessagesWithHistory(chatManage)
|
||||
resourceRefs := llmresource.NewRegistry()
|
||||
chatMessages = resourceRefs.EncodeMessages(chatMessages)
|
||||
|
||||
// Call the chat model to generate response
|
||||
pipelineInfo(ctx, "Completion", "model_call", map[string]interface{}{
|
||||
@@ -64,6 +67,7 @@ func (p *PluginChatCompletion) OnEvent(
|
||||
})
|
||||
return ErrModelCall.WithError(err)
|
||||
}
|
||||
resourceRefs.DecodeResponse(chatResponse)
|
||||
|
||||
pipelineInfo(ctx, "Completion", "output", map[string]interface{}{
|
||||
"answer_preview": chatResponse.Content,
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/event"
|
||||
"github.com/Tencent/WeKnora/internal/llmresource"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/google/uuid"
|
||||
@@ -55,6 +56,8 @@ func (p *PluginChatCompletionStream) OnEvent(ctx context.Context,
|
||||
// Prepare base messages without history
|
||||
|
||||
chatMessages := prepareMessagesWithHistory(chatManage)
|
||||
resourceRefs := llmresource.NewRegistry()
|
||||
chatMessages = resourceRefs.EncodeMessages(chatMessages)
|
||||
pipelineInfo(ctx, "Stream", "messages_ready", map[string]interface{}{
|
||||
"message_count": len(chatMessages),
|
||||
"system_prompt": chatMessages[0].Content,
|
||||
@@ -105,6 +108,8 @@ func (p *PluginChatCompletionStream) OnEvent(ctx context.Context,
|
||||
// The goroutine monitors ctx.Done() to avoid leaking when the context is cancelled
|
||||
// and the upstream channel is not closed promptly.
|
||||
go func() {
|
||||
answerDecoder := llmresource.NewStreamDecoder(resourceRefs)
|
||||
thinkingDecoder := llmresource.NewStreamDecoder(resourceRefs)
|
||||
thinkingID := fmt.Sprintf("%s-thinking", uuid.New().String()[:8])
|
||||
answerID := fmt.Sprintf("%s-answer", uuid.New().String()[:8])
|
||||
thinkingOpen := false
|
||||
@@ -135,6 +140,22 @@ func (p *PluginChatCompletionStream) OnEvent(ctx context.Context,
|
||||
|
||||
case response, ok := <-responseChan:
|
||||
if !ok {
|
||||
if tail := thinkingDecoder.Flush(); tail != "" {
|
||||
_ = eventBus.Emit(ctx, types.Event{
|
||||
ID: thinkingID,
|
||||
Type: types.EventType(event.EventAgentThought),
|
||||
SessionID: chatManage.SessionID,
|
||||
Data: event.AgentThoughtData{Content: tail},
|
||||
})
|
||||
}
|
||||
if tail := answerDecoder.Flush(); tail != "" {
|
||||
_ = eventBus.Emit(ctx, types.Event{
|
||||
ID: answerID,
|
||||
Type: types.EventType(event.EventAgentFinalAnswer),
|
||||
SessionID: chatManage.SessionID,
|
||||
Data: event.AgentFinalAnswerData{Content: tail},
|
||||
})
|
||||
}
|
||||
closeThinking()
|
||||
pipelineInfo(ctx, "Stream", "channel_close", map[string]interface{}{
|
||||
"session_id": chatManage.SessionID,
|
||||
@@ -161,6 +182,7 @@ func (p *PluginChatCompletionStream) OnEvent(ctx context.Context,
|
||||
}
|
||||
|
||||
if response.ResponseType == types.ResponseTypeThinking {
|
||||
response.Content = thinkingDecoder.Feed(response.Content)
|
||||
if response.Content != "" {
|
||||
thinkingOpen = true
|
||||
eventBus.Emit(ctx, types.Event{
|
||||
@@ -180,6 +202,7 @@ func (p *PluginChatCompletionStream) OnEvent(ctx context.Context,
|
||||
}
|
||||
|
||||
if response.ResponseType == types.ResponseTypeAnswer {
|
||||
response.Content = answerDecoder.Feed(response.Content)
|
||||
closeThinking()
|
||||
eventBus.Emit(ctx, types.Event{
|
||||
ID: answerID,
|
||||
|
||||
@@ -3,6 +3,7 @@ package file
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
|
||||
@@ -30,7 +31,7 @@ func NewDummyFileService() interfaces.FileService {
|
||||
func (s *DummyFileService) SaveFile(ctx context.Context,
|
||||
file *multipart.FileHeader, tenantID uint64, knowledgeID string,
|
||||
) (string, error) {
|
||||
return uuid.New().String(), nil
|
||||
return fmt.Sprintf("dummy://%d/%s", tenantID, uuid.New().String()), nil
|
||||
}
|
||||
|
||||
// GetFile always returns an error as dummy service doesn't store files
|
||||
@@ -45,7 +46,7 @@ func (s *DummyFileService) DeleteFile(ctx context.Context, filePath string) erro
|
||||
|
||||
// SaveBytes pretends to save bytes but just returns a random UUID
|
||||
func (s *DummyFileService) SaveBytes(ctx context.Context, data []byte, tenantID uint64, fileName string, temp bool) (string, error) {
|
||||
return uuid.New().String(), nil
|
||||
return fmt.Sprintf("dummy://%d/%s", tenantID, uuid.New().String()), nil
|
||||
}
|
||||
|
||||
// CopyFile is a no-op for the dummy service: it logs a warning and returns the
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
package file
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"mime/multipart"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// resourceCatalogFileService keeps provider drivers physical-path-only while
|
||||
// exposing stable resource:// references to the application layer.
|
||||
type resourceCatalogFileService struct {
|
||||
inner interfaces.FileService
|
||||
catalog interfaces.ResourceCatalog
|
||||
externalURL string
|
||||
}
|
||||
|
||||
// NewResourceCatalogFileService decorates a physical FileService with stable
|
||||
// resource registration and resolution.
|
||||
func NewResourceCatalogFileService(
|
||||
inner interfaces.FileService,
|
||||
catalog interfaces.ResourceCatalog,
|
||||
) interfaces.FileService {
|
||||
if inner == nil || catalog == nil {
|
||||
return inner
|
||||
}
|
||||
return &resourceCatalogFileService{
|
||||
inner: inner,
|
||||
catalog: catalog,
|
||||
externalURL: strings.TrimRight(strings.TrimSpace(os.Getenv("APP_EXTERNAL_URL")), "/"),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *resourceCatalogFileService) CheckConnectivity(ctx context.Context) error {
|
||||
return s.inner.CheckConnectivity(ctx)
|
||||
}
|
||||
|
||||
func resourceKind(name string) (string, string) {
|
||||
mimeType := mime.TypeByExtension(strings.ToLower(filepath.Ext(name)))
|
||||
kind := "file"
|
||||
switch {
|
||||
case strings.HasPrefix(mimeType, "image/"):
|
||||
kind = "image"
|
||||
case strings.HasPrefix(mimeType, "audio/"):
|
||||
kind = "audio"
|
||||
case strings.HasPrefix(mimeType, "video/"):
|
||||
kind = "video"
|
||||
}
|
||||
return kind, mimeType
|
||||
}
|
||||
|
||||
func (s *resourceCatalogFileService) register(
|
||||
ctx context.Context,
|
||||
physical string,
|
||||
tenantID uint64,
|
||||
name string,
|
||||
size int64,
|
||||
temporary bool,
|
||||
contentHash string,
|
||||
) (string, error) {
|
||||
kind, mimeType := resourceKind(name)
|
||||
ref, err := s.catalog.Register(ctx, tenantID, physical, interfaces.ResourceRegistration{
|
||||
Kind: kind,
|
||||
MimeType: mimeType,
|
||||
OriginalName: filepath.Base(name),
|
||||
Size: size,
|
||||
ContentHash: contentHash,
|
||||
Temporary: temporary,
|
||||
})
|
||||
if err != nil {
|
||||
_ = s.inner.DeleteFile(ctx, physical)
|
||||
return "", fmt.Errorf("register stored resource: %w", err)
|
||||
}
|
||||
return ref, nil
|
||||
}
|
||||
|
||||
func (s *resourceCatalogFileService) SaveFile(
|
||||
ctx context.Context,
|
||||
file *multipart.FileHeader,
|
||||
tenantID uint64,
|
||||
knowledgeID string,
|
||||
) (string, error) {
|
||||
physical, err := s.inner.SaveFile(ctx, file, tenantID, knowledgeID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
ref, err := s.register(ctx, physical, tenantID, file.Filename, file.Size, false, "")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if knowledgeID != "" {
|
||||
if err := s.catalog.Bind(ctx, ref, "knowledge", knowledgeID, "source_file"); err != nil {
|
||||
_ = s.DeleteFile(ctx, ref)
|
||||
return "", fmt.Errorf("bind stored resource: %w", err)
|
||||
}
|
||||
}
|
||||
return ref, nil
|
||||
}
|
||||
|
||||
func (s *resourceCatalogFileService) SaveBytes(
|
||||
ctx context.Context,
|
||||
data []byte,
|
||||
tenantID uint64,
|
||||
fileName string,
|
||||
temp bool,
|
||||
) (string, error) {
|
||||
physical, err := s.inner.SaveBytes(ctx, data, tenantID, fileName, temp)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
sum := sha256.Sum256(data)
|
||||
return s.register(ctx, physical, tenantID, fileName, int64(len(data)), temp, hex.EncodeToString(sum[:]))
|
||||
}
|
||||
|
||||
func (s *resourceCatalogFileService) resolve(ctx context.Context, value string) (string, bool, error) {
|
||||
physical, resource, err := s.catalog.ResolvePath(ctx, value)
|
||||
return physical, resource != nil, err
|
||||
}
|
||||
|
||||
func (s *resourceCatalogFileService) GetFile(ctx context.Context, filePath string) (io.ReadCloser, error) {
|
||||
physical, _, err := s.resolve(ctx, filePath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.inner.GetFile(ctx, physical)
|
||||
}
|
||||
|
||||
func (s *resourceCatalogFileService) GetFileURL(ctx context.Context, filePath string) (string, error) {
|
||||
physical, isResource, err := s.resolve(ctx, filePath)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if isResource && s.externalURL != "" {
|
||||
token, grantErr := s.catalog.CreateAccessGrant(ctx, filePath, 2*time.Hour)
|
||||
if grantErr != nil {
|
||||
return "", grantErr
|
||||
}
|
||||
return s.externalURL + "/r/" + token, nil
|
||||
}
|
||||
return s.inner.GetFileURL(ctx, physical)
|
||||
}
|
||||
|
||||
func (s *resourceCatalogFileService) DeleteFile(ctx context.Context, filePath string) error {
|
||||
physical, isResource, err := s.resolve(ctx, filePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.inner.DeleteFile(ctx, physical); err != nil {
|
||||
return err
|
||||
}
|
||||
if isResource {
|
||||
return s.catalog.MarkDeleted(ctx, filePath)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *resourceCatalogFileService) CopyFile(
|
||||
ctx context.Context,
|
||||
filePath string,
|
||||
tenantID uint64,
|
||||
knowledgeID string,
|
||||
) (string, error) {
|
||||
physical, _, err := s.resolve(ctx, filePath)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
copied, err := s.inner.CopyFile(ctx, physical, tenantID, knowledgeID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
ref, err := s.register(ctx, copied, tenantID, filepath.Base(physical), 0, false, "")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if knowledgeID != "" {
|
||||
if err := s.catalog.Bind(ctx, ref, "knowledge", knowledgeID, "source_file"); err != nil {
|
||||
_ = s.DeleteFile(ctx, ref)
|
||||
return "", fmt.Errorf("bind copied resource: %w", err)
|
||||
}
|
||||
}
|
||||
return ref, nil
|
||||
}
|
||||
|
||||
var _ interfaces.FileService = (*resourceCatalogFileService)(nil)
|
||||
@@ -0,0 +1,107 @@
|
||||
package file
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type catalogStub struct {
|
||||
resource *types.StoredResource
|
||||
ref string
|
||||
}
|
||||
|
||||
func (c *catalogStub) Register(
|
||||
_ context.Context,
|
||||
tenantID uint64,
|
||||
physicalPath string,
|
||||
meta interfaces.ResourceRegistration,
|
||||
) (string, error) {
|
||||
c.resource = &types.StoredResource{
|
||||
ID: "resource-1",
|
||||
Handle: "AbCdEfGhIjKlMnOpQrStUv",
|
||||
TenantID: tenantID,
|
||||
PhysicalPath: physicalPath,
|
||||
OriginalName: meta.OriginalName,
|
||||
}
|
||||
c.ref = types.BuildResourcePath(c.resource.Handle)
|
||||
return c.ref, nil
|
||||
}
|
||||
|
||||
func (c *catalogStub) Resolve(_ context.Context, _ string) (*types.StoredResource, error) {
|
||||
return c.resource, nil
|
||||
}
|
||||
|
||||
func (c *catalogStub) ResolvePath(_ context.Context, value string) (string, *types.StoredResource, error) {
|
||||
if value == c.ref {
|
||||
return c.resource.PhysicalPath, c.resource, nil
|
||||
}
|
||||
return value, nil, nil
|
||||
}
|
||||
func (c *catalogStub) Bind(context.Context, string, string, string, string) error { return nil }
|
||||
func (c *catalogStub) MarkDeleted(context.Context, string) error { return nil }
|
||||
func (c *catalogStub) CreateAccessGrant(context.Context, string, time.Duration) (string, error) {
|
||||
return "GrantTokenAbCdEfGhIjKl", nil
|
||||
}
|
||||
|
||||
func (c *catalogStub) ResolveAccessGrant(context.Context, string) (*types.StoredResource, error) {
|
||||
return c.resource, nil
|
||||
}
|
||||
|
||||
type physicalFileStub struct {
|
||||
savedPath string
|
||||
readPath string
|
||||
}
|
||||
|
||||
func (s *physicalFileStub) CheckConnectivity(context.Context) error { return nil }
|
||||
func (s *physicalFileStub) SaveFile(context.Context, *multipart.FileHeader, uint64, string) (string, error) {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func (s *physicalFileStub) SaveBytes(context.Context, []byte, uint64, string, bool) (string, error) {
|
||||
return s.savedPath, nil
|
||||
}
|
||||
|
||||
func (s *physicalFileStub) GetFile(_ context.Context, path string) (io.ReadCloser, error) {
|
||||
s.readPath = path
|
||||
return io.NopCloser(strings.NewReader("body")), nil
|
||||
}
|
||||
func (s *physicalFileStub) GetFileURL(context.Context, string) (string, error) { return "", nil }
|
||||
func (s *physicalFileStub) DeleteFile(context.Context, string) error { return nil }
|
||||
func (s *physicalFileStub) CopyFile(context.Context, string, uint64, string) (string, error) {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func TestResourceCatalogFileServiceReturnsReferenceAndResolvesReads(t *testing.T) {
|
||||
inner := &physicalFileStub{savedPath: "local://7/exports/a.png"}
|
||||
catalog := &catalogStub{}
|
||||
svc := NewResourceCatalogFileService(inner, catalog)
|
||||
|
||||
ref, err := svc.SaveBytes(context.Background(), []byte("image"), 7, "a.png", false)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "resource://AbCdEfGhIjKlMnOpQrStUv", ref)
|
||||
reader, err := svc.GetFile(context.Background(), ref)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, reader.Close())
|
||||
require.Equal(t, inner.savedPath, inner.readPath)
|
||||
}
|
||||
|
||||
func TestResourceCatalogFileServiceReturnsShortExternalGrantURL(t *testing.T) {
|
||||
t.Setenv("APP_EXTERNAL_URL", "https://weknora.example.com/")
|
||||
inner := &physicalFileStub{savedPath: "local://7/exports/a.png"}
|
||||
catalog := &catalogStub{}
|
||||
svc := NewResourceCatalogFileService(inner, catalog)
|
||||
|
||||
ref, err := svc.SaveBytes(context.Background(), []byte("image"), 7, "a.png", false)
|
||||
require.NoError(t, err)
|
||||
externalURL, err := svc.GetFileURL(context.Background(), ref)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "https://weknora.example.com/r/GrantTokenAbCdEfGhIjKl", externalURL)
|
||||
}
|
||||
@@ -80,6 +80,10 @@ type ImageMultimodalService struct {
|
||||
// fallback in knowledgeService.resolveFileService.
|
||||
fileSvc interfaces.FileService
|
||||
storageResolver interfaces.StorageBackendResolver
|
||||
// resourceCatalog resolves resource:// references to their owning storage
|
||||
// backend so multimodal reads target the resource's real backend instead of
|
||||
// the knowledge base's currently configured one.
|
||||
resourceCatalog interfaces.ResourceCatalog
|
||||
|
||||
// spanTracker records this image's subspan under the parent attempt's
|
||||
// multimodal stage. nil-safe — falls back to no-op via tracker().
|
||||
@@ -99,6 +103,7 @@ func NewImageMultimodalService(
|
||||
redisClient *redis.Client,
|
||||
fileSvc interfaces.FileService,
|
||||
storageResolver interfaces.StorageBackendResolver,
|
||||
resourceCatalog interfaces.ResourceCatalog,
|
||||
spanTracker SpanTracker,
|
||||
) interfaces.TaskHandler {
|
||||
return &ImageMultimodalService{
|
||||
@@ -114,6 +119,7 @@ func NewImageMultimodalService(
|
||||
redisClient: redisClient,
|
||||
fileSvc: fileSvc,
|
||||
storageResolver: storageResolver,
|
||||
resourceCatalog: resourceCatalog,
|
||||
spanTracker: spanTracker,
|
||||
}
|
||||
}
|
||||
@@ -554,6 +560,18 @@ func (s *ImageMultimodalService) resolveFileServiceForPayload(ctx context.Contex
|
||||
|
||||
backendID, _, _ := types.ParseStorageBackendPath(payload.ImageURL)
|
||||
provider := types.ParseProviderScheme(payload.ImageURL)
|
||||
// A resource:// reference carries no provider/backend in the URL itself; the
|
||||
// authoritative backend lives on the stored resource record. Using the KB's
|
||||
// currently configured backend here would break reads when the resource was
|
||||
// stored on a different backend (multi-backend / post-migration).
|
||||
if _, isResourceRef := types.ParseResourcePath(payload.ImageURL); isResourceRef && s.resourceCatalog != nil {
|
||||
if resource, resErr := s.resourceCatalog.Resolve(ctx, payload.ImageURL); resErr != nil {
|
||||
logger.Warnf(ctx, "[ImageMultimodal] resolve resource reference failed: url=%s err=%v", payload.ImageURL, resErr)
|
||||
} else if resource != nil {
|
||||
backendID = resource.StorageBackendID
|
||||
provider = strings.ToLower(strings.TrimSpace(resource.Provider))
|
||||
}
|
||||
}
|
||||
if provider == "" {
|
||||
kb, kbErr := s.kbService.GetKnowledgeBaseByIDOnly(ctx, payload.KnowledgeBaseID)
|
||||
if kbErr != nil {
|
||||
@@ -590,7 +608,8 @@ func (s *ImageMultimodalService) resolveFileServiceForPayload(ctx context.Contex
|
||||
// file before falling back to the URL.
|
||||
// - For plain http(s):// URLs it uses the SSRF-safe downloader.
|
||||
func (s *ImageMultimodalService) readImageBytes(ctx context.Context, payload types.ImageMultimodalPayload) ([]byte, error) {
|
||||
if types.ParseProviderScheme(payload.ImageURL) != "" {
|
||||
_, isResourceRef := types.ParseResourcePath(payload.ImageURL)
|
||||
if isResourceRef || types.ParseProviderScheme(payload.ImageURL) != "" {
|
||||
fileSvc := s.resolveFileServiceForPayload(ctx, payload)
|
||||
if fileSvc == nil {
|
||||
return nil, fmt.Errorf("no file service available for %s", payload.ImageURL)
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
const defaultResourceGrantTTL = 2 * time.Hour
|
||||
|
||||
type resourceCatalog struct {
|
||||
repo interfaces.ResourceRepository
|
||||
}
|
||||
|
||||
// NewResourceCatalog creates the stable resource-reference domain service.
|
||||
func NewResourceCatalog(repo interfaces.ResourceRepository) interfaces.ResourceCatalog {
|
||||
return &resourceCatalog{repo: repo}
|
||||
}
|
||||
|
||||
func randomResourceToken() (string, error) {
|
||||
buf := make([]byte, 16)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(buf), nil
|
||||
}
|
||||
|
||||
func resourceLocationHash(path string) string {
|
||||
sum := sha256.Sum256([]byte(path))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func (s *resourceCatalog) Register(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
physicalPath string,
|
||||
meta interfaces.ResourceRegistration,
|
||||
) (string, error) {
|
||||
physicalPath = strings.TrimSpace(physicalPath)
|
||||
if tenantID == 0 || physicalPath == "" {
|
||||
return "", fmt.Errorf("resource registration requires tenant and physical path")
|
||||
}
|
||||
if _, ok := types.ParseResourcePath(physicalPath); ok {
|
||||
return physicalPath, nil
|
||||
}
|
||||
locationHash := resourceLocationHash(physicalPath)
|
||||
existing, err := s.repo.GetByTenantLocation(ctx, tenantID, locationHash)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if existing != nil {
|
||||
return types.BuildResourcePath(existing.Handle), nil
|
||||
}
|
||||
|
||||
backendID, inner, scoped := types.ParseStorageBackendPath(physicalPath)
|
||||
providerPath := physicalPath
|
||||
if scoped {
|
||||
providerPath = inner
|
||||
}
|
||||
provider := types.ParseProviderScheme(providerPath)
|
||||
if provider == "" {
|
||||
return "", fmt.Errorf("resource physical path has unsupported provider scheme")
|
||||
}
|
||||
lifecycle := types.ResourceLifecyclePersistent
|
||||
if meta.Temporary {
|
||||
lifecycle = types.ResourceLifecycleTemporary
|
||||
}
|
||||
for attempt := 0; attempt < 4; attempt++ {
|
||||
handle, tokenErr := randomResourceToken()
|
||||
if tokenErr != nil {
|
||||
return "", tokenErr
|
||||
}
|
||||
resource := &types.StoredResource{
|
||||
Handle: handle,
|
||||
TenantID: tenantID,
|
||||
StorageBackendID: backendID,
|
||||
Provider: provider,
|
||||
PhysicalPath: physicalPath,
|
||||
LocationHash: locationHash,
|
||||
Kind: meta.Kind,
|
||||
MimeType: meta.MimeType,
|
||||
OriginalName: meta.OriginalName,
|
||||
Size: meta.Size,
|
||||
ContentHash: meta.ContentHash,
|
||||
Lifecycle: lifecycle,
|
||||
}
|
||||
if err := s.repo.Create(ctx, resource); err == nil {
|
||||
return types.BuildResourcePath(handle), nil
|
||||
} else if !strings.Contains(strings.ToLower(err.Error()), "unique") {
|
||||
return "", err
|
||||
}
|
||||
existing, lookupErr := s.repo.GetByTenantLocation(ctx, tenantID, locationHash)
|
||||
if lookupErr == nil && existing != nil {
|
||||
return types.BuildResourcePath(existing.Handle), nil
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("failed to allocate unique resource handle")
|
||||
}
|
||||
|
||||
func (s *resourceCatalog) Resolve(ctx context.Context, reference string) (*types.StoredResource, error) {
|
||||
handle, ok := types.ParseResourcePath(reference)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("invalid resource reference")
|
||||
}
|
||||
resource, err := s.repo.GetByHandle(ctx, handle)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resource == nil {
|
||||
return nil, fmt.Errorf("resource not found")
|
||||
}
|
||||
return resource, nil
|
||||
}
|
||||
|
||||
func (s *resourceCatalog) ResolvePath(ctx context.Context, value string) (string, *types.StoredResource, error) {
|
||||
if _, ok := types.ParseResourcePath(value); !ok {
|
||||
return value, nil, nil
|
||||
}
|
||||
resource, err := s.Resolve(ctx, value)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
return resource.PhysicalPath, resource, nil
|
||||
}
|
||||
|
||||
func (s *resourceCatalog) Bind(ctx context.Context, reference, ownerType, ownerID, relation string) error {
|
||||
resource, err := s.Resolve(ctx, reference)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if strings.TrimSpace(ownerType) == "" || strings.TrimSpace(ownerID) == "" {
|
||||
return fmt.Errorf("resource binding requires owner type and id")
|
||||
}
|
||||
if relation == "" {
|
||||
relation = "attachment"
|
||||
}
|
||||
return s.repo.CreateBinding(ctx, &types.ResourceBinding{
|
||||
ResourceID: resource.ID,
|
||||
TenantID: resource.TenantID,
|
||||
OwnerType: ownerType,
|
||||
OwnerID: ownerID,
|
||||
Relation: relation,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *resourceCatalog) MarkDeleted(ctx context.Context, reference string) error {
|
||||
resource, err := s.Resolve(ctx, reference)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.repo.MarkDeleted(ctx, resource.ID)
|
||||
}
|
||||
|
||||
func (s *resourceCatalog) CreateAccessGrant(ctx context.Context, reference string, ttl time.Duration) (string, error) {
|
||||
resource, err := s.Resolve(ctx, reference)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if ttl <= 0 {
|
||||
ttl = defaultResourceGrantTTL
|
||||
}
|
||||
// Opportunistic cleanup keeps high-volume IM rendering from accumulating
|
||||
// expired capability rows; failure is non-fatal to the current grant.
|
||||
_ = s.repo.DeleteExpiredGrants(ctx, time.Now())
|
||||
for attempt := 0; attempt < 4; attempt++ {
|
||||
token, tokenErr := randomResourceToken()
|
||||
if tokenErr != nil {
|
||||
return "", tokenErr
|
||||
}
|
||||
grant := &types.ResourceAccessGrant{
|
||||
TokenHash: resourceLocationHash(token),
|
||||
ResourceID: resource.ID,
|
||||
AccessScope: "read",
|
||||
ExpiresAt: time.Now().Add(ttl),
|
||||
}
|
||||
if err := s.repo.CreateGrant(ctx, grant); err == nil {
|
||||
return token, nil
|
||||
} else if !strings.Contains(strings.ToLower(err.Error()), "unique") {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("failed to allocate unique resource access token")
|
||||
}
|
||||
|
||||
func (s *resourceCatalog) ResolveAccessGrant(ctx context.Context, token string) (*types.StoredResource, error) {
|
||||
grant, err := s.repo.GetValidGrant(ctx, resourceLocationHash(strings.TrimSpace(token)), time.Now())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if grant == nil {
|
||||
return nil, fmt.Errorf("resource access grant is invalid or expired")
|
||||
}
|
||||
resource, err := s.repo.GetByID(ctx, grant.ResourceID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resource == nil {
|
||||
return nil, fmt.Errorf("resource not found")
|
||||
}
|
||||
return resource, nil
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/application/repository"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func newResourceCatalogForTest(t *testing.T) (interfaces.ResourceCatalog, *gorm.DB) {
|
||||
t.Helper()
|
||||
db, err := gorm.Open(sqlite.Open("file:"+t.Name()+"?mode=memory&cache=shared"), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.AutoMigrate(&types.StoredResource{}, &types.ResourceBinding{}, &types.ResourceAccessGrant{}))
|
||||
return NewResourceCatalog(repository.NewResourceRepository(db)), db
|
||||
}
|
||||
|
||||
func TestResourceCatalogRegisterResolveAndDeduplicate(t *testing.T) {
|
||||
catalog, _ := newResourceCatalogForTest(t)
|
||||
ctx := context.Background()
|
||||
physical := "storage://backend-a/local://7/exports/a.png"
|
||||
|
||||
ref, err := catalog.Register(ctx, 7, physical, interfaces.ResourceRegistration{Kind: "image", OriginalName: "a.png"})
|
||||
require.NoError(t, err)
|
||||
require.Regexp(t, `^resource://[0-9A-Za-z_-]{22}$`, ref)
|
||||
|
||||
again, err := catalog.Register(ctx, 7, physical, interfaces.ResourceRegistration{})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, ref, again)
|
||||
|
||||
resolvedPath, resource, err := catalog.ResolvePath(ctx, ref)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, physical, resolvedPath)
|
||||
require.Equal(t, uint64(7), resource.TenantID)
|
||||
require.Equal(t, "backend-a", resource.StorageBackendID)
|
||||
require.Equal(t, "local", resource.Provider)
|
||||
}
|
||||
|
||||
func TestResourceCatalogBindingAndAccessGrant(t *testing.T) {
|
||||
catalog, db := newResourceCatalogForTest(t)
|
||||
ctx := context.Background()
|
||||
ref, err := catalog.Register(
|
||||
ctx,
|
||||
9,
|
||||
"local://9/exports/report.pdf",
|
||||
interfaces.ResourceRegistration{OriginalName: "report.pdf"},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, catalog.Bind(ctx, ref, "knowledge", "knowledge-1", "source_file"))
|
||||
|
||||
token, err := catalog.CreateAccessGrant(ctx, ref, time.Minute)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, token, 22)
|
||||
var storedGrant types.ResourceAccessGrant
|
||||
require.NoError(t, db.First(&storedGrant).Error)
|
||||
require.NotEqual(t, token, storedGrant.TokenHash)
|
||||
require.Len(t, storedGrant.TokenHash, 64)
|
||||
resource, err := catalog.ResolveAccessGrant(ctx, token)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, uint64(9), resource.TenantID)
|
||||
}
|
||||
|
||||
func TestResourceCatalogRejectsUnsupportedPhysicalPath(t *testing.T) {
|
||||
catalog, _ := newResourceCatalogForTest(t)
|
||||
_, err := catalog.Register(context.Background(), 7, "https://example.com/a.png", interfaces.ResourceRegistration{})
|
||||
require.ErrorContains(t, err, "unsupported provider")
|
||||
}
|
||||
@@ -19,12 +19,35 @@ import (
|
||||
)
|
||||
|
||||
type StorageBackendService struct {
|
||||
repo interfaces.StorageBackendRepository
|
||||
db *gorm.DB
|
||||
repo interfaces.StorageBackendRepository
|
||||
db *gorm.DB
|
||||
resourceCatalog interfaces.ResourceCatalog
|
||||
}
|
||||
|
||||
func NewStorageBackendService(repo interfaces.StorageBackendRepository, db *gorm.DB) *StorageBackendService {
|
||||
return &StorageBackendService{repo: repo, db: db}
|
||||
// NewStorageBackendService creates a storage backend service. The optional
|
||||
// catalog keeps focused tests compatible while production uses the explicit
|
||||
// constructor below.
|
||||
func NewStorageBackendService(
|
||||
repo interfaces.StorageBackendRepository,
|
||||
db *gorm.DB,
|
||||
catalogs ...interfaces.ResourceCatalog,
|
||||
) *StorageBackendService {
|
||||
service := &StorageBackendService{repo: repo, db: db}
|
||||
if len(catalogs) > 0 {
|
||||
service.resourceCatalog = catalogs[0]
|
||||
}
|
||||
return service
|
||||
}
|
||||
|
||||
// NewStorageBackendServiceWithResources is the production DI constructor.
|
||||
// The variadic constructor above remains convenient for focused tests that do
|
||||
// not exercise resource registration.
|
||||
func NewStorageBackendServiceWithResources(
|
||||
repo interfaces.StorageBackendRepository,
|
||||
db *gorm.DB,
|
||||
catalog interfaces.ResourceCatalog,
|
||||
) *StorageBackendService {
|
||||
return NewStorageBackendService(repo, db, catalog)
|
||||
}
|
||||
|
||||
func (s *StorageBackendService) Create(ctx context.Context, backend *types.StorageBackend) error {
|
||||
@@ -76,6 +99,18 @@ func (s *StorageBackendService) Update(ctx context.Context, incoming *types.Stor
|
||||
return err
|
||||
}
|
||||
}
|
||||
if references == 0 {
|
||||
if err := s.db.WithContext(ctx).Model(&types.StoredResource{}).
|
||||
Where(
|
||||
"tenant_id = ? AND storage_backend_id = ? AND state = ?",
|
||||
incoming.TenantID,
|
||||
incoming.ID,
|
||||
types.ResourceStateActive,
|
||||
).
|
||||
Count(&references).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if references > 0 {
|
||||
return apperrors.NewBadRequestError("a default or bound storage backend cannot be disabled")
|
||||
}
|
||||
@@ -123,6 +158,15 @@ func (s *StorageBackendService) Delete(ctx context.Context, tenantID uint64, id
|
||||
if kbCount > 0 {
|
||||
return apperrors.NewBadRequestError(fmt.Sprintf("storage backend still has %d knowledge base(s) bound to it", kbCount))
|
||||
}
|
||||
var resourceCount int64
|
||||
if err := tx.Model(&types.StoredResource{}).
|
||||
Where("tenant_id = ? AND storage_backend_id = ? AND state = ?", tenantID, id, types.ResourceStateActive).
|
||||
Count(&resourceCount).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if resourceCount > 0 {
|
||||
return apperrors.NewBadRequestError(fmt.Sprintf("storage backend still has %d active resource(s)", resourceCount))
|
||||
}
|
||||
if backend.LegacyAlias {
|
||||
return apperrors.NewBadRequestError("legacy storage backend cannot be deleted while old file paths may reference it")
|
||||
}
|
||||
@@ -247,12 +291,21 @@ func (s *StorageBackendService) ResolveFileService(ctx context.Context, tenant *
|
||||
if err != nil {
|
||||
return nil, provider, err
|
||||
}
|
||||
return filesvc.NewBackendScopedFileService(backend.ID, inner), provider, nil
|
||||
scoped := filesvc.NewBackendScopedFileService(backend.ID, inner)
|
||||
return filesvc.NewResourceCatalogFileService(scoped, s.resourceCatalog), provider, nil
|
||||
}
|
||||
if tenant == nil {
|
||||
return nil, "", fmt.Errorf("workspace context missing")
|
||||
}
|
||||
return filesvc.NewFileServiceFromStorageConfig(provider, tenant.StorageEngineConfig, localBaseDir)
|
||||
inner, resolvedProvider, err := filesvc.NewFileServiceFromStorageConfig(
|
||||
provider,
|
||||
tenant.StorageEngineConfig,
|
||||
localBaseDir,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, resolvedProvider, err
|
||||
}
|
||||
return filesvc.NewResourceCatalogFileService(inner, s.resourceCatalog), resolvedProvider, nil
|
||||
}
|
||||
|
||||
func validateStorageBackendEndpoint(backend *types.StorageBackend) error {
|
||||
@@ -276,5 +329,7 @@ func validateStorageBackendEndpoint(backend *types.StorageBackend) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
var _ interfaces.StorageBackendService = (*StorageBackendService)(nil)
|
||||
var _ interfaces.StorageBackendResolver = (*StorageBackendService)(nil)
|
||||
var (
|
||||
_ interfaces.StorageBackendService = (*StorageBackendService)(nil)
|
||||
_ interfaces.StorageBackendResolver = (*StorageBackendService)(nil)
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user