feat(resource): 相同图片字节复用一个 handle,不再重复写字节与重复注册 (#4419)

main
linus-liu-web 2026-10-17 23:16:40 +08:00 committed by GitHub
parent 42f91f7aa7
commit a7d915a70a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
15 changed files with 714 additions and 6 deletions

View File

@ -62,6 +62,32 @@ func (r *resourceRepository) GetByTenantLocation(
return &resource, err
}
// GetActiveByContentHash resolves identical bytes already registered under any
// physical location. The content hash is not unique — duplicates written before
// this lookup existed may share it — so the oldest live row is returned to keep
// the choice stable between calls.
func (r *resourceRepository) GetActiveByContentHash(
ctx context.Context,
tenantID uint64,
contentHash string,
) (*types.StoredResource, error) {
var resource types.StoredResource
err := r.db.WithContext(ctx).
Where(
"tenant_id = ? AND content_hash = ? AND content_hash <> '' "+
"AND state = ? AND deleted_at IS NULL",
tenantID,
contentHash,
types.ResourceStateActive,
).
Order("created_at ASC, id ASC").
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

View File

@ -0,0 +1,101 @@
package repository
import (
"context"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/require"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
func newResourceContentHashTestRepo(t *testing.T) *resourceRepository {
t.Helper()
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
require.NoError(t, err)
sqlDB, err := db.DB()
require.NoError(t, err)
// A single connection keeps the in-memory database from vanishing behind a
// second pooled connection.
sqlDB.SetMaxOpenConns(1)
t.Cleanup(func() { require.NoError(t, sqlDB.Close()) })
require.NoError(t, db.AutoMigrate(&types.StoredResource{}))
return NewResourceRepository(db).(*resourceRepository)
}
func storedResource(id, handle string, tenantID uint64, contentHash string, createdAt time.Time) *types.StoredResource {
return &types.StoredResource{
ID: id,
Handle: handle,
TenantID: tenantID,
Provider: "local",
PhysicalPath: "local://" + id + "/exports/" + id + ".png",
LocationHash: id,
Kind: "image",
ContentHash: contentHash,
CreatedAt: createdAt,
}
}
func TestGetActiveByContentHashFindsLiveRow(t *testing.T) {
ctx := context.Background()
repo := newResourceContentHashTestRepo(t)
require.NoError(t, repo.Create(ctx, storedResource("r1", "HandleAAAAAAAAAAAAAA01", 7, "hash-a", time.Now())))
found, err := repo.GetActiveByContentHash(ctx, 7, "hash-a")
require.NoError(t, err)
require.NotNil(t, found)
require.Equal(t, "r1", found.ID)
require.Equal(t, "hash-a", found.ContentHash)
}
func TestGetActiveByContentHashMisses(t *testing.T) {
ctx := context.Background()
repo := newResourceContentHashTestRepo(t)
require.NoError(t, repo.Create(ctx, storedResource("r1", "HandleAAAAAAAAAAAAAA01", 7, "hash-a", time.Now())))
require.NoError(t, repo.Create(ctx, storedResource("r2", "HandleAAAAAAAAAAAAAA02", 7, "", time.Now())))
for label, query := range map[string]struct {
tenantID uint64
hash string
}{
"unknown hash": {7, "hash-missing"},
"other tenant": {8, "hash-a"},
"zero tenant": {0, "hash-a"},
"blank hash": {7, ""},
} {
found, err := repo.GetActiveByContentHash(ctx, query.tenantID, query.hash)
require.NoError(t, err, label)
require.Nilf(t, found, "case %s", label)
}
}
func TestGetActiveByContentHashIgnoresDeletedRows(t *testing.T) {
ctx := context.Background()
repo := newResourceContentHashTestRepo(t)
require.NoError(t, repo.Create(ctx, storedResource("r1", "HandleAAAAAAAAAAAAAA01", 7, "hash-a", time.Now())))
require.NoError(t, repo.MarkDeleted(ctx, "r1"))
found, err := repo.GetActiveByContentHash(ctx, 7, "hash-a")
require.NoError(t, err)
require.Nil(t, found, "a soft-deleted resource must not be reused")
}
// Rows registered before this lookup existed can share a hash. The choice has to
// be deterministic or two identical requests could be handed different handles.
func TestGetActiveByContentHashPrefersOldestDuplicate(t *testing.T) {
ctx := context.Background()
repo := newResourceContentHashTestRepo(t)
now := time.Now()
require.NoError(t, repo.Create(ctx, storedResource("r-new", "HandleAAAAAAAAAAAAAA02", 7, "hash-a", now)))
require.NoError(t, repo.Create(ctx, storedResource(
"r-old", "HandleAAAAAAAAAAAAAA01", 7, "hash-a", now.Add(-time.Hour),
)))
found, err := repo.GetActiveByContentHash(ctx, 7, "hash-a")
require.NoError(t, err)
require.NotNil(t, found)
require.Equal(t, "r-old", found.ID)
}

View File

@ -172,6 +172,12 @@ func (c *fakeCatalog) Register(context.Context, uint64, string, interfaces.Resou
return "", nil
}
// ReuseByContentHash stays a miss: these tests exercise binding and release, not
// payload sharing, so the write path must keep running exactly as before.
func (c *fakeCatalog) ReuseByContentHash(context.Context, uint64, string) (string, bool, error) {
return "", false, nil
}
func (c *fakeCatalog) Resolve(context.Context, string) (*types.StoredResource, error) {
return nil, nil
}

View File

@ -8,6 +8,7 @@ import (
"io"
"mime"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"strings"
@ -107,6 +108,23 @@ func (s *resourceCatalogFileService) SaveFile(
return ref, nil
}
// isImagePayload reports whether data should be treated as image content.
//
// The rule is deliberately byte-first: two payloads can only be shared when
// their bytes are equal, so the decision must not hinge on a name the caller
// chose freely. The extension is still consulted as a fallback because some
// extracted image formats — SVG above all — have no signature
// http.DetectContentType recognises, and those are exactly the vector assets a
// document repeats across pages. A payload is therefore an image when its name
// maps to an image media type (the same rule register uses to derive Kind) or
// when its bytes sniff as image/*.
func isImagePayload(name string, data []byte) bool {
if kind, _ := resourceKind(name); kind == "image" {
return true
}
return strings.HasPrefix(http.DetectContentType(data), "image/")
}
func (s *resourceCatalogFileService) SaveBytes(
ctx context.Context,
data []byte,
@ -114,12 +132,35 @@ func (s *resourceCatalogFileService) SaveBytes(
fileName string,
temp bool,
) (string, error) {
sum := sha256.Sum256(data)
contentHash := hex.EncodeToString(sum[:])
// Identical bytes pulled out of one document — the same logo or mascot on
// several pages — used to be written once per occurrence and registered as
// a separate handle each time: duplicated storage, the same picture
// captioned repeatedly, and one identical gallery card per copy. Look the
// payload up before writing so every occurrence shares one handle.
//
// Reuse is restricted to images outside temporary scratch space. For a
// user upload or a generated artifact the original name is part of what
// the caller asked for, and sharing would surface the first name for the
// second file; extracted document images are named from a generated UUID,
// so sharing one is invisible. Temporary objects are excluded because
// their lifecycle is per-use.
if !temp && isImagePayload(fileName, data) {
ref, ok, err := s.catalog.ReuseByContentHash(ctx, tenantID, contentHash)
if err == nil && ok {
return ref, nil
}
// Fail open: a lookup failure or a miss must never stop bytes from
// being stored, so fall through to the normal write-and-register path.
}
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[:]))
return s.register(ctx, physical, tenantID, fileName, int64(len(data)), temp, contentHash)
}
func (s *resourceCatalogFileService) resolve(ctx context.Context, value string) (string, bool, error) {

View File

@ -39,6 +39,12 @@ func (c *catalogStub) Resolve(_ context.Context, _ string) (*types.StoredResourc
return c.resource, nil
}
// ReuseByContentHash never hits in this stub: these tests exercise reference
// shape and resolution, not payload deduplication.
func (c *catalogStub) ReuseByContentHash(context.Context, uint64, string) (string, bool, error) {
return "", false, nil
}
func (c *catalogStub) ResolvePath(_ context.Context, value string) (string, *types.StoredResource, error) {
if value == c.ref {
return c.resource.PhysicalPath, c.resource, nil

View File

@ -0,0 +1,214 @@
package file
import (
"context"
"errors"
"fmt"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/stretchr/testify/require"
)
// contentCatalogStub is an in-memory stand-in for the resource catalog that
// answers content-hash lookups the way the real one does: the first payload
// registered under a hash owns the handle for every later copy of those bytes.
// Register deliberately mints a fresh handle per call, since the production
// location-based dedup would otherwise mask the content-hash path under test.
type contentCatalogStub struct {
byHash map[string]string
registered []interfaces.ResourceRegistration
reuseCalls int
reuseErr error
}
func newContentCatalogStub() *contentCatalogStub {
return &contentCatalogStub{byHash: map[string]string{}}
}
func (c *contentCatalogStub) Register(
_ context.Context,
_ uint64,
_ string,
meta interfaces.ResourceRegistration,
) (string, error) {
// "Handle" + 16 digits is exactly types.ResourceHandleLength characters.
ref := types.BuildResourcePath(fmt.Sprintf("Handle%016d", len(c.registered)))
c.registered = append(c.registered, meta)
if meta.ContentHash != "" {
if _, exists := c.byHash[meta.ContentHash]; !exists {
c.byHash[meta.ContentHash] = ref
}
}
return ref, nil
}
func (c *contentCatalogStub) ReuseByContentHash(
_ context.Context, _ uint64, contentHash string,
) (string, bool, error) {
c.reuseCalls++
if c.reuseErr != nil {
return "", false, c.reuseErr
}
ref, ok := c.byHash[contentHash]
return ref, ok, nil
}
func (c *contentCatalogStub) Resolve(context.Context, string) (*types.StoredResource, error) {
return nil, nil
}
func (c *contentCatalogStub) ResolvePath(
_ context.Context, value string,
) (string, *types.StoredResource, error) {
return value, nil, nil
}
func (c *contentCatalogStub) Bind(context.Context, string, string, string, string) error { return nil }
func (c *contentCatalogStub) MarkDeleted(context.Context, string) error { return nil }
func (c *contentCatalogStub) Release(context.Context, string, string, string) (int64, error) {
return 0, nil
}
func (c *contentCatalogStub) ListReferencesByOwner(context.Context, string, ...string) ([]string, error) {
return nil, nil
}
func (c *contentCatalogStub) CreateAccessGrant(context.Context, string, time.Duration) (string, error) {
return "", nil
}
func (c *contentCatalogStub) ResolveAccessGrant(context.Context, string) (*types.StoredResource, error) {
return nil, nil
}
// countingFileStub counts how many payloads actually reached the provider, which
// is the observable effect of a reuse: the bytes are never written.
type countingFileStub struct {
physicalFileStub
saveBytesCalls int
}
func (s *countingFileStub) SaveBytes(_ context.Context, _ []byte, _ uint64, _ string, _ bool) (string, error) {
s.saveBytesCalls++
return fmt.Sprintf("local://7/exports/img-%d.bin", s.saveBytesCalls), nil
}
// pngPayload starts with the PNG signature so http.DetectContentType classifies
// the bytes as an image regardless of the name they are saved under.
func pngPayload() []byte {
return []byte("\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00")
}
func TestResourceCatalogFileServiceReusesIdenticalImageBytes(t *testing.T) {
ctx := context.Background()
inner := &countingFileStub{}
catalog := newContentCatalogStub()
svc := NewResourceCatalogFileService(inner, catalog)
first, err := svc.SaveBytes(ctx, pngPayload(), 7, "page-1.png", false)
require.NoError(t, err)
// The second occurrence carries the generated name an extractor would give
// the same logo on another page: different name, identical bytes.
second, err := svc.SaveBytes(ctx, pngPayload(), 7, "page-2.png", false)
require.NoError(t, err)
require.Equal(t, first, second)
require.Equal(t, 1, inner.saveBytesCalls, "identical bytes must be written once")
require.Len(t, catalog.registered, 1, "the reused payload must not be registered twice")
require.Equal(t, int64(len(pngPayload())), catalog.registered[0].Size)
require.NotEmpty(t, catalog.registered[0].ContentHash)
}
func TestResourceCatalogFileServiceWritesDistinctImageBytesSeparately(t *testing.T) {
ctx := context.Background()
inner := &countingFileStub{}
catalog := newContentCatalogStub()
svc := NewResourceCatalogFileService(inner, catalog)
first, err := svc.SaveBytes(ctx, pngPayload(), 7, "page-1.png", false)
require.NoError(t, err)
second, err := svc.SaveBytes(ctx, append(pngPayload(), 0x00), 7, "page-2.png", false)
require.NoError(t, err)
require.NotEqual(t, first, second)
require.Equal(t, 2, inner.saveBytesCalls)
require.Len(t, catalog.registered, 2)
}
func TestResourceCatalogFileServiceDoesNotReuseTemporaryBytes(t *testing.T) {
ctx := context.Background()
inner := &countingFileStub{}
catalog := newContentCatalogStub()
svc := NewResourceCatalogFileService(inner, catalog)
first, err := svc.SaveBytes(ctx, pngPayload(), 7, "scratch-1.png", true)
require.NoError(t, err)
second, err := svc.SaveBytes(ctx, pngPayload(), 7, "scratch-2.png", true)
require.NoError(t, err)
require.NotEqual(t, first, second)
require.Equal(t, 2, inner.saveBytesCalls)
require.Zero(t, catalog.reuseCalls, "temporary writes must not consult the content index")
}
// Non-image payloads keep their own registered object even when their bytes are
// equal: for an upload or an artifact the original name is part of the result,
// and sharing would make the second file answer to the first one's name.
func TestResourceCatalogFileServiceDoesNotReuseNonImageBytes(t *testing.T) {
ctx := context.Background()
inner := &countingFileStub{}
catalog := newContentCatalogStub()
svc := NewResourceCatalogFileService(inner, catalog)
notes := []byte("quarterly notes\n")
first, err := svc.SaveBytes(ctx, notes, 7, "notes-a.txt", false)
require.NoError(t, err)
second, err := svc.SaveBytes(ctx, notes, 7, "notes-b.txt", false)
require.NoError(t, err)
require.NotEqual(t, first, second)
require.Equal(t, 2, inner.saveBytesCalls)
require.Zero(t, catalog.reuseCalls, "non-image payloads must not consult the content index")
}
// The lookup is an optimisation, not a gate: if it fails, the bytes still have
// to be stored.
func TestResourceCatalogFileServiceStoresWhenContentLookupFails(t *testing.T) {
ctx := context.Background()
inner := &countingFileStub{}
catalog := newContentCatalogStub()
catalog.reuseErr = errors.New("content index unavailable")
svc := NewResourceCatalogFileService(inner, catalog)
first, err := svc.SaveBytes(ctx, pngPayload(), 7, "page-1.png", false)
require.NoError(t, err)
require.NotEmpty(t, first)
require.Equal(t, 1, inner.saveBytesCalls)
require.Equal(t, 1, catalog.reuseCalls)
require.Len(t, catalog.registered, 1, "a failed lookup must fall back to the write path")
}
// The image/non-image boundary is what keeps payload sharing from leaking into
// uploads and artifacts, so pin it down directly.
func TestIsImagePayloadKeepsNameBoundary(t *testing.T) {
cases := []struct {
label string
name string
data []byte
want bool
}{
{"sniffed png under an image name", "page-1.png", pngPayload(), true},
{"sniffed png with no extension", "no-extension", pngPayload(), true},
{"svg relies on its extension", "logo.svg", []byte("<svg/>"), true},
{"plain text", "notes.txt", []byte("hello"), false},
{"markdown artifact", "web-1.md", []byte("# title\n"), false},
{"unrecognised binary", "blob.bin", []byte{0x00, 0x01, 0x02, 0x03}, false},
}
for _, tc := range cases {
require.Equalf(t, tc.want, isImagePayload(tc.name, tc.data), "case %s", tc.label)
}
}

View File

@ -38,6 +38,12 @@ func (c *resolvingCatalog) Register(
return "", errors.New("unused")
}
// ReuseByContentHash stays a miss so the catalog under test is only consulted
// through the resolution paths these tests cover.
func (c *resolvingCatalog) ReuseByContentHash(context.Context, uint64, string) (string, bool, error) {
return "", false, nil
}
func (c *resolvingCatalog) ResolvePath(
_ context.Context, value string,
) (string, *types.StoredResource, error) {

View File

@ -109,6 +109,41 @@ func (s *resourceCatalog) Register(
return "", fmt.Errorf("failed to allocate unique resource handle")
}
// ReuseByContentHash implements interfaces.ResourceCatalog. It is the
// content-addressed counterpart of Register's location lookup: two extractions
// of one image from different pages land on different physical paths, so only
// the bytes can tell that they are the same stored object.
//
// A blank hash, a zero tenant or an unknown payload all report "no reusable
// resource" rather than an error, so the caller can fall through to its normal
// write path. A missing tenant guard here would let one tenant's bytes satisfy
// another tenant's lookup, which is why the tenant is part of the query.
func (s *resourceCatalog) ReuseByContentHash(
ctx context.Context,
tenantID uint64,
contentHash string,
) (string, bool, error) {
contentHash = strings.TrimSpace(contentHash)
if tenantID == 0 || contentHash == "" {
return "", false, nil
}
existing, err := s.repo.GetActiveByContentHash(ctx, tenantID, contentHash)
if err != nil {
return "", false, err
}
if existing == nil {
return "", false, nil
}
// A temporary row is scratch storage: nothing keeps its bytes alive once
// its owner finishes, so aliasing a long-lived reference onto it would let
// that cleanup delete a payload the reusable caller still serves. Only
// persistent resources are reusable.
if existing.Lifecycle != types.ResourceLifecyclePersistent {
return "", false, nil
}
return types.BuildResourcePath(existing.Handle), true, nil
}
func (s *resourceCatalog) Resolve(ctx context.Context, reference string) (*types.StoredResource, error) {
handle, ok := types.ParseResourcePath(reference)
if !ok {

View File

@ -246,3 +246,50 @@ func TestResourceCatalogRejectsUnsupportedPhysicalPath(t *testing.T) {
_, err := catalog.Register(context.Background(), 7, "https://example.com/a.png", interfaces.ResourceRegistration{})
require.ErrorContains(t, err, "unsupported provider")
}
// Register deduplicates by physical location only. Content is a second identity
// the extractor needs: the same image pulled from two pages is written to two
// paths, and only the payload hash can tell that it is one stored object.
func TestResourceCatalogReuseByContentHashIsScopedToTenant(t *testing.T) {
catalog, _ := newResourceCatalogForTest(t)
ctx := context.Background()
ref, err := catalog.Register(ctx, 7, "local://7/exports/a.png", interfaces.ResourceRegistration{
Kind: "image",
ContentHash: "hash-a",
})
require.NoError(t, err)
reused, ok, err := catalog.ReuseByContentHash(ctx, 7, "hash-a")
require.NoError(t, err)
require.True(t, ok)
require.Equal(t, ref, reused)
for label, tenantID := range map[string]uint64{"other tenant": 8, "zero tenant": 0} {
reused, ok, err = catalog.ReuseByContentHash(ctx, tenantID, "hash-a")
require.NoError(t, err, label)
require.Falsef(t, ok, "case %s", label)
require.Emptyf(t, reused, "case %s", label)
}
_, ok, err = catalog.ReuseByContentHash(ctx, 7, "hash-missing")
require.NoError(t, err)
require.False(t, ok)
}
// A temporary resource is scratch storage that its owner may delete at any
// time; aliasing a long-lived reference onto it would let that cleanup remove
// bytes the reusable caller still serves.
func TestResourceCatalogReuseByContentHashSkipsTemporaryResources(t *testing.T) {
catalog, _ := newResourceCatalogForTest(t)
ctx := context.Background()
_, err := catalog.Register(ctx, 7, "local://7/tmp/a.png", interfaces.ResourceRegistration{
Kind: "image",
ContentHash: "hash-temp",
Temporary: true,
})
require.NoError(t, err)
_, ok, err := catalog.ReuseByContentHash(ctx, 7, "hash-temp")
require.NoError(t, err)
require.False(t, ok)
}

View File

@ -136,19 +136,20 @@ func (s *temporaryDocumentService) Create(
}
optionsJSON, _ := json.Marshal(options)
document := &types.TemporaryDocument{
ID: uuid.NewString(),
TenantID: tenantID, SessionID: sessionID, ResourceRef: resourceRef,
FileName: baseName, FileType: ext, MimeType: strings.TrimSpace(mimeType), FileSize: fileSize,
Status: types.TemporaryDocumentStatusUploaded, ExpiresAt: time.Now().Add(temporaryDocumentTTL()),
ProcessingOptions: types.JSON(optionsJSON),
}
if err := s.repo.Create(ctx, document); err != nil {
_ = s.fileService.DeleteFile(ctx, resourceRef)
_ = s.releaseResource(ctx, document.ID, resourceRef)
return nil, fmt.Errorf("create attachment record: %w", err)
}
if s.resourceCatalog != nil {
if err := s.resourceCatalog.Bind(ctx, resourceRef, types.ResourceOwnerTemporaryDocument, document.ID, types.ResourceRelationSourceFile); err != nil {
_ = s.repo.DeleteScoped(ctx, tenantID, sessionID, document.ID)
_ = s.fileService.DeleteFile(ctx, resourceRef)
_ = s.releaseResource(ctx, document.ID, resourceRef)
return nil, fmt.Errorf("bind attachment resource: %w", err)
}
}
@ -272,13 +273,38 @@ func (s *temporaryDocumentService) Delete(ctx context.Context, tenantID uint64,
if err != nil || document == nil {
return err
}
refs := map[string]struct{}{document.ResourceRef: {}}
for _, ref := range temporaryDocumentImageRefs(document.ImageRefs) {
_ = s.fileService.DeleteFile(ctx, ref.URL)
refs[ref.URL] = struct{}{}
}
for ref := range refs {
if err := s.releaseResource(ctx, document.ID, ref); err != nil {
logger.Warnf(ctx, "keeping attachment resource after cleanup failure: document_id=%s err=%v",
document.ID, err)
}
}
_ = s.fileService.DeleteFile(ctx, document.ResourceRef)
return s.repo.DeleteScoped(ctx, tenantID, sessionID, documentID)
}
// A content-deduplicated image can also belong to another attachment or a
// knowledge entry. Drop only this document's claim, including on rollback;
// an unreadable binding count must never authorize deleting shared bytes.
func (s *temporaryDocumentService) releaseResource(ctx context.Context, documentID, ref string) error {
if ref == "" {
return nil
}
if s.resourceCatalog != nil {
remaining, err := s.resourceCatalog.Release(ctx, ref, types.ResourceOwnerTemporaryDocument, documentID)
if err != nil {
return fmt.Errorf("release attachment resource: %w", err)
}
if remaining > 0 {
return nil
}
}
return s.fileService.DeleteFile(ctx, ref)
}
func temporaryDocumentImageRefs(raw types.JSON) []types.TemporaryDocumentImage {
var images []types.TemporaryDocumentImage
_ = json.Unmarshal(raw, &images)

View File

@ -0,0 +1,164 @@
package service
import (
"bytes"
"context"
"encoding/json"
"errors"
"testing"
"time"
files "github.com/Tencent/WeKnora/internal/application/service/file"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/stretchr/testify/require"
)
type attachmentLifecycleRepo struct {
interfaces.TemporaryDocumentRepository
docs map[string]*types.TemporaryDocument
expiredID string
createErr error
}
func (r *attachmentLifecycleRepo) GetScoped(
_ context.Context, _ uint64, _, id string,
) (*types.TemporaryDocument, error) {
return r.docs[id], nil
}
func (r *attachmentLifecycleRepo) DeleteScoped(_ context.Context, _ uint64, _, id string) error {
delete(r.docs, id)
return nil
}
func (r *attachmentLifecycleRepo) ListExpired(context.Context, time.Time, int) ([]*types.TemporaryDocument, error) {
if d := r.docs[r.expiredID]; d != nil {
return []*types.TemporaryDocument{d}, nil
}
return nil, nil
}
func (r *attachmentLifecycleRepo) Create(_ context.Context, d *types.TemporaryDocument) error {
if r.createErr != nil {
return r.createErr
}
r.docs[d.ID] = d
return nil
}
type failingAttachmentBinding struct {
interfaces.ResourceCatalog
releaseErr error
}
func (c *failingAttachmentBinding) Bind(context.Context, string, string, string, string) error {
return errors.New("binding failed")
}
func (c *failingAttachmentBinding) Release(ctx context.Context, ref, owner, id string) (int64, error) {
if c.releaseErr != nil {
return -1, c.releaseErr
}
return c.ResourceCatalog.Release(ctx, ref, owner, id)
}
func TestTemporaryDocumentReleaseDeduplicatedImages(t *testing.T) {
for _, expired := range []bool{false, true} {
name := "delete"
if expired {
name = "expiry"
}
t.Run(name, func(t *testing.T) {
ctx := context.Background()
catalog, _ := newResourceCatalogForTest(t)
fs := files.NewResourceCatalogFileService(files.NewLocalFileService(t.TempDir(), ""), catalog)
payload := []byte("identical image content")
a, err := fs.SaveBytes(ctx, payload, 7, "first.png", false)
require.NoError(t, err)
b, err := fs.SaveBytes(ctx, payload, 7, "second.png", false)
require.NoError(t, err)
require.Equal(t, a, b)
require.NoError(t, catalog.Bind(
ctx, a, types.ResourceOwnerTemporaryDocument, "first", types.ResourceRelationSourceFile,
))
require.NoError(t, catalog.Bind(
ctx, b, types.ResourceOwnerTemporaryDocument, "second", types.ResourceRelationSourceFile,
))
images, _ := json.Marshal([]types.TemporaryDocumentImage{{URL: a}, {URL: a}})
repo := &attachmentLifecycleRepo{expiredID: "first", docs: map[string]*types.TemporaryDocument{
"first": {ID: "first", TenantID: 7, SessionID: "session", ResourceRef: a, ImageRefs: images},
"second": {ID: "second", TenantID: 7, SessionID: "session", ResourceRef: b},
}}
svc := &temporaryDocumentService{fileService: fs, resourceCatalog: catalog, repo: repo}
if expired {
require.NoError(t, svc.CleanupExpired(ctx))
} else {
require.NoError(t, svc.Delete(ctx, 7, "session", "first"))
}
file, err := fs.GetFile(ctx, b)
require.NoError(t, err)
require.NoError(t, file.Close())
require.NoError(t, svc.Delete(ctx, 7, "session", "second"))
_, err = fs.GetFile(ctx, b)
require.Error(t, err, "last owner must reclaim the image")
})
}
}
func TestTemporaryDocumentRollbackKeepsSharedKnowledgeImage(t *testing.T) {
for _, failBind := range []bool{false, true} {
name := "create failure"
if failBind {
name = "bind failure"
}
t.Run(name, func(t *testing.T) {
ctx := context.Background()
catalog, _ := newResourceCatalogForTest(t)
fs := files.NewResourceCatalogFileService(files.NewLocalFileService(t.TempDir(), ""), catalog)
payload := []byte("shared image")
ref, err := fs.SaveBytes(ctx, payload, 7, "knowledge.png", false)
require.NoError(t, err)
require.NoError(t, catalog.Bind(
ctx, ref, types.ResourceOwnerKnowledge, "knowledge", types.ResourceRelationExtractedImage,
))
repo := &attachmentLifecycleRepo{docs: map[string]*types.TemporaryDocument{}}
activeCatalog := catalog
if failBind {
activeCatalog = &failingAttachmentBinding{ResourceCatalog: catalog}
} else {
repo.createErr = errors.New("create failed")
}
svc := &temporaryDocumentService{fileService: fs, resourceCatalog: activeCatalog, repo: repo}
_, err = svc.Create(
ctx, 7, "session", "upload.png", "image/png", int64(len(payload)),
bytes.NewReader(payload), types.TemporaryDocumentCreateOptions{},
)
require.Error(t, err)
file, err := fs.GetFile(ctx, ref)
require.NoError(t, err)
require.NoError(t, file.Close())
resource, err := catalog.Resolve(ctx, ref)
require.NoError(t, err)
require.Equal(t, types.ResourceStateActive, resource.State)
})
}
}
func TestTemporaryDocumentKeepsResourceWhenReleaseFails(t *testing.T) {
ctx := context.Background()
catalog, _ := newResourceCatalogForTest(t)
fs := files.NewResourceCatalogFileService(files.NewLocalFileService(t.TempDir(), ""), catalog)
ref, err := fs.SaveBytes(ctx, []byte("image"), 7, "image.png", false)
require.NoError(t, err)
svc := &temporaryDocumentService{
fileService: fs,
resourceCatalog: &failingAttachmentBinding{
ResourceCatalog: catalog, releaseErr: errors.New("database unavailable"),
},
}
require.Error(t, svc.releaseResource(ctx, "document", ref))
file, err := fs.GetFile(ctx, ref)
require.NoError(t, err)
require.NoError(t, file.Close())
}

View File

@ -80,6 +80,12 @@ func (s *stubResourceCatalog) Register(
panic("unexpected Register")
}
// ReuseByContentHash stays a miss: these handlers serve existing references and
// never reach the payload-sharing path.
func (s *stubResourceCatalog) ReuseByContentHash(context.Context, uint64, string) (string, bool, error) {
return "", false, nil
}
func (s *stubResourceCatalog) Resolve(context.Context, string) (*types.StoredResource, error) {
return s.resource, nil
}

View File

@ -25,6 +25,11 @@ type ResourceRepository interface {
GetByID(ctx context.Context, id string) (*types.StoredResource, error)
GetByHandle(ctx context.Context, handle string) (*types.StoredResource, error)
GetByTenantLocation(ctx context.Context, tenantID uint64, locationHash string) (*types.StoredResource, error)
// GetActiveByContentHash finds a live resource holding the exact same
// bytes. Unlike location, content is not unique: several rows may carry
// the same hash (duplicates registered before this lookup existed), so
// the oldest live row wins and the result is stable across calls.
GetActiveByContentHash(ctx context.Context, tenantID uint64, contentHash string) (*types.StoredResource, error)
MarkDeleted(ctx context.Context, id string) error
CreateBinding(ctx context.Context, binding *types.ResourceBinding) error
DeleteBinding(ctx context.Context, resourceID, ownerType, ownerID string) error
@ -59,6 +64,14 @@ type ResourceRegistration struct {
// locations and manages their access capabilities.
type ResourceCatalog interface {
Register(ctx context.Context, tenantID uint64, physicalPath string, meta ResourceRegistration) (string, error)
// ReuseByContentHash returns the reference of a live resource whose bytes
// hash to contentHash, letting a caller holding the same payload skip
// storing it again. ok is false when the tenant holds no such resource.
//
// Register only deduplicates by physical location, so bytes that arrive on
// a new path — one image extracted from several pages — would otherwise
// mint a second handle for a payload the tenant already has.
ReuseByContentHash(ctx context.Context, tenantID uint64, contentHash string) (ref string, ok bool, err error)
Resolve(ctx context.Context, reference string) (*types.StoredResource, error)
ResolvePath(ctx context.Context, value string) (string, *types.StoredResource, error)
Bind(ctx context.Context, reference, ownerType, ownerID, relation string) error

View File

@ -0,0 +1 @@
DROP INDEX IF EXISTS idx_resources_tenant_content_hash;

View File

@ -0,0 +1,16 @@
-- Migration 000123: make the resource content hash a usable identity.
--
-- resources.content_hash has been written since the catalog was introduced but
-- nothing ever queried it, so it could not answer "do I already store these
-- exact bytes?". Register() only deduplicates by physical location
-- (location_hash), and identical bytes extracted onto new paths — the same
-- logo pulled out of several pages — therefore mint one handle per occurrence.
--
-- The index satisfies the lookup with the tenant scope and the live-row
-- predicate in one pass. It is deliberately NOT unique: existing rows already
-- hold duplicate payloads, and a unique index would refuse to build. The
-- partial predicate also keeps deleted rows and rows without a hash (legacy
-- registrations, temporary or non-hashed writes) out of the index.
CREATE INDEX IF NOT EXISTS idx_resources_tenant_content_hash
ON resources(tenant_id, content_hash)
WHERE deleted_at IS NULL AND content_hash <> '';