π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Keep collection trash batches atomic
Neeraj Gupta548919216218
diff --git a/server/pkg/controller/file.go b/server/pkg/controller/file.goindex 2a89218510..c8d750b41e 100644--- a/server/pkg/controller/file.go+++ b/server/pkg/controller/file.go@@ -600,7 +600,7 @@ func (c *FileController) Trash(ctx *gin.Context, userID int64, request ente.Trasreturn stacktrace.Propagate(ente.ErrPermissionDenied, "user doesn't own collection")}}- return c.TrashRepository.TrashFiles(fileIDs, userID, request)+ return c.TrashRepository.TrashFiles(ctx.Request.Context(), userID, request)}func (c *FileController) GetSize(userID int64, fileIDs []int64) (int64, error) {diff --git a/server/pkg/repo/collection.go b/server/pkg/repo/collection.goindex 3d9198156a..2261356ddb 100644--- a/server/pkg/repo/collection.go+++ b/server/pkg/repo/collection.go@@ -1035,7 +1035,7 @@ func (repo *CollectionRepository) TrashV3(ctx context.Context, collectionID int6CollectionID: collectionID,})}- err = repo.TrashRepo.TrashFiles(fileIDs, ownerID, ente.TrashRequest{OwnerID: ownerID, TrashItems: items})+ err = repo.TrashRepo.TrashFiles(ctx, ownerID, ente.TrashRequest{OwnerID: ownerID, TrashItems: items})if err != nil {log.WithError(err).Error("failed to trash file")return stacktrace.Propagate(err, "")diff --git a/server/pkg/repo/public/file_link.go b/server/pkg/repo/public/file_link.goindex a55c6401b4..30e00cb481 100644--- a/server/pkg/repo/public/file_link.go+++ b/server/pkg/repo/public/file_link.go@@ -19,6 +19,10 @@ type FileLinkRepository struct {lockerHost string}+type fileLinkUpdater interface {+ ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)+}+func NewFileLinkRepo(db *sql.DB) *FileLinkRepository {albumHost := viper.GetString("apps.public-albums")if albumHost == "" {@@ -173,11 +177,19 @@ func (pcr *FileLinkRepository) GetFileUrls(ctx context.Context, userID int64, si}func (pcr *FileLinkRepository) DisableLinkForFiles(ctx context.Context, fileIDs []int64) error {+ return disableLinkForFiles(ctx, pcr.DB, fileIDs)+}++func (pcr *FileLinkRepository) DisableLinkForFilesTx(ctx context.Context, tx *sql.Tx, fileIDs []int64) error {+ return disableLinkForFiles(ctx, tx, fileIDs)+}++func disableLinkForFiles(ctx context.Context, updater fileLinkUpdater, fileIDs []int64) error {if len(fileIDs) == 0 {return nil}- query := `UPDATE public_file_tokens SET is_disabled = TRUE WHERE file_id = ANY($1)`- _, err := pcr.DB.ExecContext(ctx, query, pq.Array(fileIDs))+ query := `UPDATE public_file_tokens SET is_disabled = TRUE WHERE file_id = ANY($1) AND is_disabled IS FALSE`+ _, err := updater.ExecContext(ctx, query, pq.Array(fileIDs))if err != nil {return stacktrace.Propagate(err, "failed to disable public file links")}diff --git a/server/pkg/repo/trash.go b/server/pkg/repo/trash.goindex 1dfe4842c9..8c8db3cd72 100644--- a/server/pkg/repo/trash.go+++ b/server/pkg/repo/trash.go@@ -114,15 +114,19 @@ func (t *TrashRepository) GetFilesWithVersion(userID int64, updateAtTime int64,return convertRowsToTrash(rows)}-func (t *TrashRepository) TrashFiles(fileIDs []int64, userID int64, trash ente.TrashRequest) error {+func (t *TrashRepository) TrashFiles(ctx context.Context, userID int64, trash ente.TrashRequest) error {+ fileIDs := make([]int64, 0, len(trash.TrashItems))+ for _, item := range trash.TrashItems {+ fileIDs = append(fileIDs, item.FileID)+ }updationTime := time.Microseconds()- ctx := context.Background()tx, err := t.DB.BeginTx(ctx, nil)if err != nil {return stacktrace.Propagate(err, "")}+ defer tx.Rollback()rows, err := tx.QueryContext(ctx, `SELECT DISTINCT collection_id FROM- collection_files WHERE file_id = ANY($1) AND is_deleted = $2`, pq.Array(fileIDs), false)+ collection_files WHERE file_id = ANY($1) AND is_deleted = $2`, pq.Array(fileIDs), false)if err != nil {return stacktrace.Propagate(err, "")}@@ -136,32 +140,24 @@ func (t *TrashRepository) TrashFiles(fileIDs []int64, userID int64, trash ente.TcIDs = append(cIDs, cID)}_, err = tx.ExecContext(ctx, `UPDATE collection_files- SET is_deleted = $1, updation_time = $2 WHERE file_id = ANY($3)`,+ SET is_deleted = $1, updation_time = $2 WHERE file_id = ANY($3)`,true, updationTime, pq.Array(fileIDs))if err != nil {- tx.Rollback()return stacktrace.Propagate(err, "")}_, err = tx.ExecContext(ctx, `UPDATE collections SET updation_time = $1- WHERE collection_id = ANY ($2)`, updationTime, pq.Array(cIDs))+ WHERE collection_id = ANY ($2)`, updationTime, pq.Array(cIDs))if err != nil {- tx.Rollback()return stacktrace.Propagate(err, "")}err = t.InsertItems(ctx, tx, userID, trash.TrashItems)if err != nil {- tx.Rollback()return stacktrace.Propagate(err, "")}- err = tx.Commit()-- if err == nil {- removeLinkErr := t.FileLinkRepo.DisableLinkForFiles(ctx, fileIDs)- if removeLinkErr != nil {- return stacktrace.Propagate(removeLinkErr, "failed to disable file links for files being trashed")- }+ if err = t.FileLinkRepo.DisableLinkForFilesTx(ctx, tx, fileIDs); err != nil {+ return stacktrace.Propagate(err, "failed to disable file links for files being trashed")}- return stacktrace.Propagate(err, "")+ return stacktrace.Propagate(tx.Commit(), "")}func (t *TrashRepository) CleanUpDeletedFilesFromCollection(ctx context.Context, fileIDs []int64, userID int64) error {diff --git a/server/pkg/repo/trash_test.go b/server/pkg/repo/trash_test.gonew file mode 100644index 0000000000..05c8a319db--- /dev/null+++ b/server/pkg/repo/trash_test.go@@ -0,0 +1,179 @@+package repo++import (+ "database/sql"+ "testing"++ "github.com/ente/museum/ente"+ "github.com/ente/museum/internal/testutil"+ "github.com/ente/museum/pkg/repo/public"+)++func TestTrashFilesUsesRequestItemsAsItsScope(t *testing.T) {+ repository, db := setupTrashTest(t)+ ownerID := testutil.InsertUser(t, db, testutil.UserFixture{+ UserID: 1,+ Email: "[email protected]",+ CreationTime: 1,+ })+ collectionID := insertObjectTestCollection(t, db, ownerID)+ requestedFileID := insertObjectTestFile(t, db, ownerID)+ untouchedFileID := insertObjectTestFile(t, db, ownerID)+ linkObjectTestFileToCollection(t, db, collectionID, requestedFileID, ownerID)+ linkObjectTestFileToCollection(t, db, collectionID, untouchedFileID, ownerID)+ insertTrashTestFileLink(t, db, "pft_requested", "requested-token", requestedFileID, ownerID)+ insertTrashTestFileLink(t, db, "pft_untouched", "untouched-token", untouchedFileID, ownerID)++ err := repository.TrashFiles(t.Context(), ownerID, ente.TrashRequest{+ OwnerID: ownerID,+ TrashItems: []ente.TrashItemRequest{{+ FileID: requestedFileID,+ CollectionID: collectionID,+ }},+ })+ if err != nil {+ t.Fatalf("TrashFiles() error = %v", err)+ }++ var requestedDeleted, untouchedDeleted bool+ err = db.QueryRow(+ `SELECT requested.is_deleted, untouched.is_deleted+ FROM collection_files AS requested+ JOIN collection_files AS untouched ON untouched.collection_id = requested.collection_id+ WHERE requested.collection_id = $1+ AND requested.file_id = $2+ AND untouched.file_id = $3`,+ collectionID,+ requestedFileID,+ untouchedFileID,+ ).Scan(&requestedDeleted, &untouchedDeleted)+ if err != nil {+ t.Fatalf("failed to read collection file states: %v", err)+ }+ if !requestedDeleted || untouchedDeleted {+ t.Fatalf("unexpected collection file states: requested deleted=%t, untouched deleted=%t", requestedDeleted, untouchedDeleted)+ }++ var trashCount, trashedFileID int64+ if err := db.QueryRow(`SELECT COUNT(*), COALESCE(MAX(file_id), 0) FROM trash`).Scan(&trashCount, &trashedFileID); err != nil {+ t.Fatalf("failed to read trash state: %v", err)+ }+ if trashCount != 1 || trashedFileID != requestedFileID {+ t.Fatalf("unexpected trash state: count=%d file=%d, want count=1 file=%d", trashCount, trashedFileID, requestedFileID)+ }++ var requestedLinkDisabled, untouchedLinkDisabled bool+ err = db.QueryRow(+ `SELECT requested.is_disabled, untouched.is_disabled+ FROM public_file_tokens AS requested+ JOIN public_file_tokens AS untouched ON untouched.id = $2+ WHERE requested.id = $1`,+ "pft_requested",+ "pft_untouched",+ ).Scan(&requestedLinkDisabled, &untouchedLinkDisabled)+ if err != nil {+ t.Fatalf("failed to read public file link states: %v", err)+ }+ if !requestedLinkDisabled || untouchedLinkDisabled {+ t.Fatalf("unexpected public file link states: requested disabled=%t, untouched disabled=%t", requestedLinkDisabled, untouchedLinkDisabled)+ }+}++func TestTrashFilesRollsBackWhenFileLinkCleanupFails(t *testing.T) {+ repository, db := setupTrashTest(t)+ ownerID := testutil.InsertUser(t, db, testutil.UserFixture{+ UserID: 1,+ Email: "[email protected]",+ CreationTime: 1,+ })+ collectionID := insertObjectTestCollection(t, db, ownerID)+ fileID := insertObjectTestFile(t, db, ownerID)+ linkObjectTestFileToCollection(t, db, collectionID, fileID, ownerID)+ insertTrashTestFileLink(t, db, "pft_failure", "failure-token", fileID, ownerID)++ if _, err := db.Exec(`ALTER TABLE public_file_tokens+ ADD CONSTRAINT test_public_file_tokens_disable_failure CHECK (is_disabled = FALSE)`); err != nil {+ t.Fatalf("failed to install public file link failure constraint: %v", err)+ }+ t.Cleanup(func() {+ if _, err := db.Exec(`ALTER TABLE public_file_tokens+ DROP CONSTRAINT IF EXISTS test_public_file_tokens_disable_failure`); err != nil {+ t.Errorf("failed to remove public file link failure constraint: %v", err)+ }+ })++ err := repository.TrashFiles(t.Context(), ownerID, ente.TrashRequest{+ OwnerID: ownerID,+ TrashItems: []ente.TrashItemRequest{{+ FileID: fileID,+ CollectionID: collectionID,+ }},+ })+ if err == nil {+ t.Fatal("TrashFiles() succeeded despite public file link cleanup failure")+ }++ var membershipDeleted bool+ if err := db.QueryRow(+ `SELECT is_deleted FROM collection_files WHERE collection_id = $1 AND file_id = $2`,+ collectionID,+ fileID,+ ).Scan(&membershipDeleted); err != nil {+ t.Fatalf("failed to read collection file state: %v", err)+ }+ if membershipDeleted {+ t.Fatal("collection membership remained deleted after transaction rollback")+ }++ var trashCount int64+ if err := db.QueryRow(`SELECT COUNT(*) FROM trash WHERE file_id = $1`, fileID).Scan(&trashCount); err != nil {+ t.Fatalf("failed to read trash state: %v", err)+ }+ if trashCount != 0 {+ t.Fatalf("trash row remained after transaction rollback: count=%d", trashCount)+ }++ var linkDisabled bool+ if err := db.QueryRow(`SELECT is_disabled FROM public_file_tokens WHERE id = $1`, "pft_failure").Scan(&linkDisabled); err != nil {+ t.Fatalf("failed to read public file link state: %v", err)+ }+ if linkDisabled {+ t.Fatal("public file link changed despite transaction rollback")+ }+}++func setupTrashTest(t *testing.T) (*TrashRepository, *sql.DB) {+ t.Helper()++ _, db := setupAccessibleObjectTest(t)+ if _, err := db.Exec(`TRUNCATE TABLE public_file_tokens_access_history, public_file_tokens RESTART IDENTITY CASCADE`); err != nil {+ t.Fatalf("failed to reset public file link tables: %v", err)+ }+ t.Cleanup(func() {+ if _, err := db.Exec(`TRUNCATE TABLE public_file_tokens_access_history, public_file_tokens RESTART IDENTITY CASCADE`); err != nil {+ t.Errorf("failed to reset public file link tables: %v", err)+ }+ })++ return &TrashRepository{+ DB: db,+ FileLinkRepo: public.NewFileLinkRepo(db),+ }, db+}++func insertTrashTestFileLink(t *testing.T, db *sql.DB, id string, token string, fileID int64, ownerID int64) {+ t.Helper()++ _, err := db.Exec(+ `INSERT INTO public_file_tokens(id, file_id, owner_id, app, access_token)+ VALUES($1, $2, $3, $4, $5)`,+ id,+ fileID,+ ownerID,+ string(ente.Photos),+ token,+ )+ if err != nil {+ t.Fatalf("failed to insert public file link %q: %v", id, err)+ }+}