π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Fix trash operations to be app-aware
Neeraj Guptaafebd54d5ca4
diff --git a/server/pkg/api/trash.go b/server/pkg/api/trash.goindex f193100bf0..831d578688 100644--- a/server/pkg/api/trash.go+++ b/server/pkg/api/trash.go@@ -71,16 +71,17 @@ func (t *TrashHandler) Delete(c *gin.Context) {// Empty deletes eligible files from the trashfunc (t *TrashHandler) Empty(c *gin.Context) {- userID := auth.GetUserID(c.Request.Header)- var request ente.EmptyTrashRequest- if err := c.ShouldBindJSON(&request); err != nil {- handler.Error(c, stacktrace.Propagate(err, ""))- return- }- err := t.Controller.EmptyTrash(c, userID, request)- if err != nil {- handler.Error(c, stacktrace.Propagate(err, ""))- return- }- c.Status(http.StatusOK)+ userID := auth.GetUserID(c.Request.Header)+ enteApp := auth.GetApp(c)+ var request ente.EmptyTrashRequest+ if err := c.ShouldBindJSON(&request); err != nil {+ handler.Error(c, stacktrace.Propagate(err, ""))+ return+ }+ err := t.Controller.EmptyTrash(c, userID, request, enteApp)+ if err != nil {+ handler.Error(c, stacktrace.Propagate(err, ""))+ return+ }+ c.Status(http.StatusOK)}diff --git a/server/pkg/controller/data_cleanup/controller.go b/server/pkg/controller/data_cleanup/controller.goindex c6f2a1f814..ca749e90c3 100644--- a/server/pkg/controller/data_cleanup/controller.go+++ b/server/pkg/controller/data_cleanup/controller.go@@ -139,12 +139,17 @@ func (c *DeleteUserCleanupController) deleteCollections(ctx context.Context, ite}func (c *DeleteUserCleanupController) emptyTrash(ctx context.Context, item *entity.DataCleanup) error {- err := c.TrashRepo.EmptyTrash(ctx, item.UserID, time.Microseconds())- if err != nil {- return stacktrace.Propagate(err, "")- }- // schedule storage consumed check for the user after 60min. Trash should ideally get emptied after 60 min- return c.Repo.MoveToNextStage(ctx, item.UserID, entity.Storage, time.MicrosecondsAfterMinutes(60))+ // Enqueue empty-trash for both apps+ err := c.TrashRepo.EmptyTrash(ctx, item.UserID, time.Microseconds(), ente.Photos)+ if err != nil {+ return stacktrace.Propagate(err, "")+ }+ err = c.TrashRepo.EmptyTrash(ctx, item.UserID, time.Microseconds(), ente.Locker)+ if err != nil {+ return stacktrace.Propagate(err, "")+ }+ // schedule storage consumed check for the user after 60min. Trash should ideally get emptied after 60 min+ return c.Repo.MoveToNextStage(ctx, item.UserID, entity.Storage, time.MicrosecondsAfterMinutes(60))}func (c *DeleteUserCleanupController) completeCleanup(ctx context.Context, item *entity.DataCleanup) error {@@ -170,21 +175,26 @@ func (c *DeleteUserCleanupController) storageCheck(ctx context.Context, item *enreturn stacktrace.Propagate(err2, "failed to fetch timestamp")}// no entry in trash- if timeStamp != nil {- log.WithFields(log.Fields{- "user_id": item.UserID,- "flow": "delete_user_data",- "timeStamp": timeStamp,- }).Info("trash is not empty")- err = c.TrashRepo.EmptyTrash(ctx, item.UserID, *timeStamp)- if err != nil {- return stacktrace.Propagate(err, "")- }- } else if item.StageAttemptCount >= maxStorageCheckAttempt {- // Note: if storage is still not zero after maxStorageCheckAttempt attempts and trash is empty, mark the clean-up as done- return c.completeCleanup(ctx, item)- }- return fmt.Errorf("storage consumed is not zero: %d", usage)+ if timeStamp != nil {+ log.WithFields(log.Fields{+ "user_id": item.UserID,+ "flow": "delete_user_data",+ "timeStamp": timeStamp,+ }).Info("trash is not empty")+ // Enqueue empty-trash for both apps+ err = c.TrashRepo.EmptyTrash(ctx, item.UserID, *timeStamp, ente.Photos)+ if err != nil {+ return stacktrace.Propagate(err, "")+ }+ err = c.TrashRepo.EmptyTrash(ctx, item.UserID, *timeStamp, ente.Locker)+ if err != nil {+ return stacktrace.Propagate(err, "")+ }+ } else if item.StageAttemptCount >= maxStorageCheckAttempt {+ // Note: if storage is still not zero after maxStorageCheckAttempt attempts and trash is empty, mark the clean-up as done+ return c.completeCleanup(ctx, item)+ }+ return fmt.Errorf("storage consumed is not zero: %d", usage)}return c.completeCleanup(ctx, item)}diff --git a/server/pkg/controller/trash.go b/server/pkg/controller/trash.goindex 7fde973e49..6501d47ec2 100644--- a/server/pkg/controller/trash.go+++ b/server/pkg/controller/trash.go@@ -1,12 +1,12 @@package controllerimport (- "context"- "fmt"- "strconv"- "strings"+ "context"+ "fmt"+ "strconv"+ "strings"- "github.com/ente-io/museum/ente"+ "github.com/ente-io/museum/ente""github.com/ente-io/museum/pkg/repo""github.com/ente-io/museum/pkg/utils/time""github.com/ente-io/stacktrace"@@ -80,7 +80,7 @@ func (t *TrashController) getDiff(userID int64, sinceTime int64, limit int, appreturn filteredDiffs, true, nil}// case 2- diff, err := t.TrashRepo.GetFilesWithVersion(userID, lastFileVersion)+ diff, err := t.TrashRepo.GetFilesWithVersion(userID, lastFileVersion, app)if err != nil {return nil, false, stacktrace.Propagate(err, "")}@@ -96,13 +96,13 @@ func (t *TrashController) Delete(ctx context.Context, request ente.DeleteTrashFireturn nil}-func (t *TrashController) EmptyTrash(ctx context.Context, userID int64, req ente.EmptyTrashRequest) error {- err := t.TrashRepo.EmptyTrash(ctx, userID, req.LastUpdatedAt)- if err != nil {- return stacktrace.Propagate(err, "")- }- defer t.ProcessEmptyTrashRequests()- return nil+func (t *TrashController) EmptyTrash(ctx context.Context, userID int64, req ente.EmptyTrashRequest, app ente.App) error {+ err := t.TrashRepo.EmptyTrash(ctx, userID, req.LastUpdatedAt, app)+ if err != nil {+ return stacktrace.Propagate(err, "")+ }+ defer t.ProcessEmptyTrashRequests()+ return nil}func (t *TrashController) CleanupTrashedCollections() {@@ -134,22 +134,33 @@ func (t *TrashController) CleanupTrashedCollections() {}func (t *TrashController) ProcessEmptyTrashRequests() {- if t.emptyTrashRunning {- log.Info("Already processing empty trash requests, skipping cron")- return- }- t.emptyTrashRunning = true+ if t.emptyTrashRunning {+ log.Info("Already processing empty trash requests, skipping cron")+ return+ }+ t.emptyTrashRunning = truedefer func() {t.emptyTrashRunning = false}()- items, err := t.QueueRepo.GetItemsReadyForDeletion(repo.TrashEmptyQueue, 100)- if err != nil {- log.Error("Could not fetch from emptyTrashQueue queue", err)- return- }- for _, item := range items {- t.emptyTrash(item)- }+ // Process photos queue+ items, err := t.QueueRepo.GetItemsReadyForDeletion(repo.TrashEmptyQueue, 100)+ if err != nil {+ log.Error("Could not fetch from emptyTrashQueue queue", err)+ } else {+ for _, item := range items {+ t.emptyTrash(item, ente.Photos, repo.TrashEmptyQueue)+ }+ }++ // Process locker queue+ itemsLocker, err2 := t.QueueRepo.GetItemsReadyForDeletion(repo.TrashEmptyLockerQueue, 100)+ if err2 != nil {+ log.Error("Could not fetch from emptyTrashLockerQueue queue", err2)+ return+ }+ for _, item := range itemsLocker {+ t.emptyTrash(item, ente.Locker, repo.TrashEmptyLockerQueue)+ }}// DeleteAgedTrashedFiles delete trashed files which are in trash since repo.TrashDurationInDays@@ -253,17 +264,18 @@ func (t *TrashController) trashCollection(item repo.QueueItem, queueName string,}}-func (t *TrashController) emptyTrash(item repo.QueueItem) {- lockName := fmt.Sprintf("EmptyTrash:%s", item.Item)- lockStatus, err := t.TaskLockRepo.AcquireLock(lockName, time.MicrosecondsAfterHours(1), t.HostName)- split := strings.Split(item.Item, repo.EmptyTrashQueueItemSeparator)- userID, _ := strconv.ParseInt(split[0], 10, 64)- lastUpdateAt, _ := strconv.ParseInt(split[1], 10, 64)- ctxLogger := log.WithFields(log.Fields{- "user_id": userID,- "lastUpdatedAt": lastUpdateAt,- "flow": "empty_trash",- })+func (t *TrashController) emptyTrash(item repo.QueueItem, app ente.App, queueName string) {+ lockName := fmt.Sprintf("EmptyTrash:%s", item.Item)+ lockStatus, err := t.TaskLockRepo.AcquireLock(lockName, time.MicrosecondsAfterHours(1), t.HostName)+ split := strings.Split(item.Item, repo.EmptyTrashQueueItemSeparator)+ userID, _ := strconv.ParseInt(split[0], 10, 64)+ lastUpdateAt, _ := strconv.ParseInt(split[1], 10, 64)+ ctxLogger := log.WithFields(log.Fields{+ "user_id": userID,+ "lastUpdatedAt": lastUpdateAt,+ "flow": "empty_trash",+ "app": app,+ })if err != nil || !lockStatus {if err == nil {@@ -281,12 +293,12 @@ func (t *TrashController) emptyTrash(item repo.QueueItem) {}}()- ctxLogger.Info("Start emptying trash")- fileIDs, err := t.TrashRepo.GetFilesIDsForDeletion(userID, lastUpdateAt)- if err != nil {- ctxLogger.WithError(err).Error("Failed to fetch fileIDs")- return- }+ ctxLogger.Info("Start emptying trash")+ fileIDs, err := t.TrashRepo.GetFilesIDsForDeletion(userID, lastUpdateAt, app)+ if err != nil {+ ctxLogger.WithError(err).Error("Failed to fetch fileIDs")+ return+ }ctx := context.Background()size := len(fileIDs)limit := repo.TrashBatchSize@@ -302,10 +314,10 @@ func (t *TrashController) emptyTrash(item repo.QueueItem) {return}}- err = t.QueueRepo.DeleteItem(repo.TrashEmptyQueue, item.Item)- if err != nil {- log.Error("Error while removing item from queue "+item.Item, err)- return- }- ctxLogger.Info("Finished emptying trash")+ err = t.QueueRepo.DeleteItem(queueName, item.Item)+ if err != nil {+ log.Error("Error while removing item from queue "+item.Item, err)+ return+ }+ ctxLogger.Info("Finished emptying trash")}diff --git a/server/pkg/repo/queue.go b/server/pkg/repo/queue.goindex 49544dbc8c..cd082885b9 100644--- a/server/pkg/repo/queue.go+++ b/server/pkg/repo/queue.go@@ -24,7 +24,8 @@ var itemDeletionDelayInMinMap = map[string]int64{DeleteObjectQueue: 45 * 24 * 60, // 45 days in minutesDeleteEmbeddingsQueue: -1 * 24 * 60, // -ve value to ensure embeddings are immediately removedTrashCollectionQueueV3: -1 * 24 * 60, // -ve value to ensure collections are immediately marked as trashed- TrashEmptyQueue: -1 * 24 * 60, // -ve value to ensure empty trash request are processed in next cron run+ TrashEmptyQueue: -1 * 24 * 60, // -ve value to ensure empty trash request are processed in next cron run+ TrashEmptyLockerQueue: -1 * 24 * 60, // -ve value to ensure empty trash request for locker are processed in next cron runRemoveComplianceHoldQueue: -1 * 24 * 60, // -ve value to ensure compliance hold is removed in next cron run}@@ -36,7 +37,8 @@ const (// Deprecated: Keeping it till we clean up items from the queue DB.TrashCollectionQueue string = "trashCollection"TrashCollectionQueueV3 string = "trashCollectionV3"- TrashEmptyQueue string = "trashEmpty"+ TrashEmptyQueue string = "trashEmpty"+ TrashEmptyLockerQueue string = "trashEmptyLocker"RemoveComplianceHoldQueue string = "removeComplianceHold"BatchSize int = 30000)diff --git a/server/pkg/repo/trash.go b/server/pkg/repo/trash.goindex 826ee554cd..5f1e9bea85 100644--- a/server/pkg/repo/trash.go+++ b/server/pkg/repo/trash.go@@ -33,11 +33,11 @@ type FileWithUpdatedAt struct {}type TrashRepository struct {- DB *sql.DB- ObjectRepo *ObjectRepository- FileRepo *FileRepository- QueueRepo *QueueRepository- FileLinkRepo *public.FileLinkRepository+ DB *sql.DB+ ObjectRepo *ObjectRepository+ FileRepo *FileRepository+ QueueRepo *QueueRepository+ FileLinkRepo *public.FileLinkRepository}func (t *TrashRepository) InsertItems(ctx context.Context, tx *sql.Tx, userID int64, items []ente.TrashItemRequest) error {@@ -100,18 +100,20 @@ func (t *TrashRepository) GetDiff(userID int64, sinceTime int64, limit int, appreturn convertRowsToTrash(rows)}-func (t *TrashRepository) GetFilesWithVersion(userID int64, updateAtTime int64) ([]ente.Trash, error) {+func (t *TrashRepository) GetFilesWithVersion(userID int64, updateAtTime int64, app ente.App) ([]ente.Trash, error) {rows, err := t.DB.Query(`- SELECT t.file_id, t.user_id, t.collection_id, cf.encrypted_key, cf.key_decryption_nonce,- f.file_decryption_header, f.thumbnail_decryption_header, f.metadata_decryption_header,+ SELECT t.file_id, t.user_id, t.collection_id, cf.encrypted_key, cf.key_decryption_nonce,+ f.file_decryption_header, f.thumbnail_decryption_header, f.metadata_decryption_header,f.encrypted_metadata, f.magic_metadata, f.pub_magic_metadata, f.updation_time, f.info,t.is_deleted, t.is_restored, t.created_at, t.updated_at, t.delete_by- FROM trash t+ FROM trash tJOIN collection_files cf ON t.file_id = cf.file_id AND t.collection_id = cf.collection_idJOIN files f ON f.file_id = t.file_idAND t.user_id = $1- AND t.updated_at = $2`,- userID, updateAtTime)+ AND t.updated_at = $2+ JOIN collections c ON c.collection_id = t.collection_id+ WHERE c.app = $3`,+ userID, updateAtTime, app)if err != nil {return nil, stacktrace.Propagate(err, "")}@@ -320,17 +322,18 @@ func (t *TrashRepository) verifyFilesAreDeleted(ctx context.Context, userID int6// GetFilesIDsForDeletion for given userID and lastUpdateAt timestamp, returns the fileIDs which are in trash and// where last updated_at before lastUpdateAt timestamp.-func (t *TrashRepository) GetFilesIDsForDeletion(userID int64, lastUpdatedAt int64) ([]int64, error) {- rows, err := t.DB.Query(`SELECT file_id FROM trash- WHERE user_id = $1 AND updated_at <= $2 AND is_deleted = FALSE AND is_restored = FALSE`, userID, lastUpdatedAt)- if err != nil {- return nil, stacktrace.Propagate(err, "")- }- fileIDs, err := convertRowsToFileId(rows)- if err != nil {- return nil, stacktrace.Propagate(err, "")- }- return fileIDs, nil+func (t *TrashRepository) GetFilesIDsForDeletion(userID int64, lastUpdatedAt int64, app ente.App) ([]int64, error) {+ rows, err := t.DB.Query(`SELECT t.file_id FROM trash t+ JOIN collections c ON c.collection_id = t.collection_id+ WHERE t.user_id = $1 AND t.updated_at <= $2 AND t.is_deleted = FALSE AND t.is_restored = FALSE AND c.app = $3`, userID, lastUpdatedAt, app)+ if err != nil {+ return nil, stacktrace.Propagate(err, "")+ }+ fileIDs, err := convertRowsToFileId(rows)+ if err != nil {+ return nil, stacktrace.Propagate(err, "")+ }+ return fileIDs, nil}// GetTimeStampForLatestNonDeletedEntry returns the updated at timestamp for the latest,non-deleted entry in the trash@@ -441,9 +444,13 @@ order by updated_at ASC limit $2return fileWithUpdatedAt[0 : i+1], nil}-func (t *TrashRepository) EmptyTrash(ctx context.Context, userID int64, lastUpdatedAt int64) error {- itemID := fmt.Sprintf("%d%s%d", userID, EmptyTrashQueueItemSeparator, lastUpdatedAt)- return t.QueueRepo.InsertItem(ctx, TrashEmptyQueue, itemID)+func (t *TrashRepository) EmptyTrash(ctx context.Context, userID int64, lastUpdatedAt int64, app ente.App) error {+ itemID := fmt.Sprintf("%d%s%d", userID, EmptyTrashQueueItemSeparator, lastUpdatedAt)+ queueName := TrashEmptyQueue+ if app == ente.Locker {+ queueName = TrashEmptyLockerQueue+ }+ return t.QueueRepo.InsertItem(ctx, queueName, itemID)}func (t *TrashRepository) GetTrashUpdatedAt(userID int64) (int64, error) {