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:
wizardchen
2026-07-15 16:31:21 +08:00
committed by lyingbug
parent 9733bd28bf
commit 6d14cc3536
32 changed files with 1790 additions and 59 deletions
+3 -2
View File
@@ -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)
}