Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

[server] add contact attachment replication lifecycle

Neeraj Guptacf00ea84d2bb
diff --git a/server/cmd/museum/main.go b/server/cmd/museum/main.go
index be7bbb1f9f..4709334968 100644
--- a/server/cmd/museum/main.go
+++ b/server/cmd/museum/main.go
@@ -1004,7 +1004,7 @@ func main() {
adminAPI.POST("/discount/add-coupons", discountCouponHandler.AddCoupons)
setKnownAPIs(server.Routes())
- setupAndStartBackgroundJobs(objectCleanupController, replicationController3, fileDataCtrl)
+ setupAndStartBackgroundJobs(objectCleanupController, replicationController3, fileDataCtrl, contactController)
setupAndStartCrons(
userAuthRepo, collectionLinkRepo, fileLinkRepo, pasteRepo, twoFactorRepo, passkeysRepo, fileController, taskLockingRepo, emailNotificationCtrl,
trashController, pushController, objectController, dataCleanupController, storageBonusCtrl, emergencyCtrl,
@@ -1125,6 +1125,7 @@ func setupAndStartBackgroundJobs(
objectCleanupController *controller.ObjectCleanupController,
replicationController3 *controller.ReplicationController3,
fileDataCtrl *filedata.Controller,
+ contactController *contactCtrl.Controller,
) {
isReplicationEnabled := viper.GetBool("replication.enabled")
if isReplicationEnabled {
@@ -1136,11 +1137,16 @@ func setupAndStartBackgroundJobs(
if err != nil {
log.Warnf("Could not start fileData replication: %s", err)
}
+ err = contactController.StartReplication()
+ if err != nil {
+ log.Warnf("Could not start contact attachment replication: %s", err)
+ }
} else {
log.Info("Skipping Replication as replication is disabled")
}
fileDataCtrl.StartDataDeletion() // Start data deletion for file data;
+ contactController.StartDataDeletion()
objectCleanupController.StartRemovingUnreportedObjects()
objectCleanupController.StartClearingOrphanObjects()
}
diff --git a/server/ente/contact/contact.go b/server/ente/contact/contact.go
index df4fd9023a..ebbe0c1400 100644
--- a/server/ente/contact/contact.go
+++ b/server/ente/contact/contact.go
@@ -136,6 +136,10 @@ type Attachment struct {
UpdatedAt int64 `json:"updatedAt" binding:"required"`
}
+func (a Attachment) ObjectKey() string {
+ return AttachmentObjectKey(a.UserID, a.AttachmentType, a.AttachmentID)
+}
+
func (at AttachmentType) IsValid() error {
switch at {
case ProfilePicture:
diff --git a/server/pkg/controller/contact/controller.go b/server/pkg/controller/contact/controller.go
index a1734f879f..504d727d3e 100644
--- a/server/pkg/controller/contact/controller.go
+++ b/server/pkg/controller/contact/controller.go
@@ -1,22 +1,36 @@
package contact
import (
+ "context"
+ "io"
+ "os"
+ "time"
+
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/s3"
+ "github.com/aws/aws-sdk-go/service/s3/s3manager"
"github.com/ente-io/museum/ente"
contactmodel "github.com/ente-io/museum/ente/contact"
basecontroller "github.com/ente-io/museum/pkg/controller"
contactrepo "github.com/ente-io/museum/pkg/repo/contact"
"github.com/ente-io/museum/pkg/utils/auth"
+ fileutil "github.com/ente-io/museum/pkg/utils/file"
"github.com/ente-io/museum/pkg/utils/s3config"
+ enteTime "github.com/ente-io/museum/pkg/utils/time"
"github.com/ente-io/stacktrace"
"github.com/gin-gonic/gin"
+ log "github.com/sirupsen/logrus"
+ "github.com/spf13/viper"
)
type Controller struct {
Repo *contactrepo.Repository
ObjectCleanupController *basecontroller.ObjectCleanupController
S3Config *s3config.S3Config
+ downloadManagerCache map[string]*s3manager.Downloader
+ tempStorage string
+ replicateAttachmentFn func(context.Context, contactmodel.Attachment, string) error
+ deleteAttachmentFn func(contactmodel.Attachment, string) error
}
func New(
@@ -24,11 +38,30 @@ func New(
objectCleanupController *basecontroller.ObjectCleanupController,
s3Config *s3config.S3Config,
) *Controller {
- return &Controller{
+ attachmentDcs := []string{
+ s3Config.GetHotBackblazeDC(),
+ s3Config.GetHotWasabiDC(),
+ s3Config.GetWasabiDerivedDC(),
+ s3Config.GetDerivedStorageDataCenter(),
+ "scw-eu-fr",
+ "scw-eu-fr-v3",
+ "b5",
+ "b6",
+ }
+ cache := make(map[string]*s3manager.Downloader, len(attachmentDcs))
+ for _, dc := range attachmentDcs {
+ s3Client := s3Config.GetS3Client(dc)
+ cache[dc] = s3manager.NewDownloaderWithClient(&s3Client)
+ }
+ ctrl := &Controller{
Repo: repo,
ObjectCleanupController: objectCleanupController,
S3Config: s3Config,
+ downloadManagerCache: cache,
}
+ ctrl.replicateAttachmentFn = ctrl.replicateAttachmentObject
+ ctrl.deleteAttachmentFn = ctrl.deleteAttachmentObject
+ return ctrl
}
func (c *Controller) Create(ctx *gin.Context, req contactmodel.CreateRequest) (*contactmodel.Entity, error) {
@@ -206,3 +239,223 @@ func (c *Controller) DeleteProfilePicture(ctx *gin.Context, contactID string) (*
userID := auth.GetUserID(ctx.Request.Header)
return c.Repo.DeleteProfilePicture(ctx, userID, contactID)
}
+
+func (c *Controller) StartReplication() error {
+ workerCount := viper.GetInt("replication.contact-attachments.worker-count")
+ if workerCount == 0 {
+ workerCount = 2
+ }
+ if err := c.createTemporaryStorage(); err != nil {
+ return stacktrace.Propagate(err, "failed to create temporary storage")
+ }
+ go c.startReplicationWorkers(workerCount)
+ return nil
+}
+
+func (c *Controller) StartDataDeletion() {
+ go c.startDeleteWorkers(1)
+}
+
+func (c *Controller) createTemporaryStorage() error {
+ tempStorage := viper.GetString("replication.contact-attachments.tmp-storage")
+ if tempStorage == "" {
+ tempStorage = "tmp/replication-contact-attachments"
+ }
+ if err := fileutil.DeleteAllFilesInDirectory(tempStorage); err != nil {
+ return stacktrace.Propagate(err, "failed deleting old files from %s", tempStorage)
+ }
+ if err := fileutil.MakeDirectoryIfNotExists(tempStorage); err != nil {
+ return stacktrace.Propagate(err, "failed to create temporary storage %s", tempStorage)
+ }
+ c.tempStorage = tempStorage
+ return nil
+}
+
+func (c *Controller) startReplicationWorkers(n int) {
+ log.Infof("Starting %d workers for contact attachment replication", n)
+ for i := 0; i < n; i++ {
+ go c.replicate(i)
+ time.Sleep(time.Duration(2*i+1) * time.Second)
+ }
+}
+
+func (c *Controller) replicate(i int) {
+ for {
+ if err := c.tryReplicate(); err != nil {
+ time.Sleep(time.Duration(i+1) * time.Minute)
+ }
+ }
+}
+
+func (c *Controller) tryReplicate() error {
+ newLockTime := enteTime.MicrosecondsAfterMinutes(240)
+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Minute)
+ defer cancel()
+
+ row, err := c.Repo.GetPendingSyncAttachmentAndExtendLock(ctx, newLockTime, false)
+ if err != nil {
+ return err
+ }
+ if err := c.replicateAttachmentRow(ctx, *row); err != nil {
+ return err
+ }
+ return c.Repo.ResetAttachmentSyncLock(ctx, *row, newLockTime)
+}
+
+func (c *Controller) replicateAttachmentRow(ctx context.Context, row contactmodel.Attachment) error {
+ wantInBucketIDs := map[string]bool{}
+ wantInBucketIDs[c.S3Config.GetAttachmentBucketID(string(row.AttachmentType))] = true
+ for _, bucket := range c.S3Config.GetReplicatedAttachmentBuckets(string(row.AttachmentType)) {
+ wantInBucketIDs[bucket] = true
+ }
+ delete(wantInBucketIDs, row.LatestBucket)
+ for _, bucket := range row.ReplicatedBuckets {
+ delete(wantInBucketIDs, bucket)
+ }
+ if len(wantInBucketIDs) == 0 {
+ return c.Repo.MarkAttachmentReplicationAsDone(ctx, row)
+ }
+ for bucketID := range wantInBucketIDs {
+ if err := c.Repo.RegisterReplicationAttempt(ctx, row, bucketID); err != nil {
+ return stacktrace.Propagate(err, "could not register attachment replication attempt")
+ }
+ if err := c.replicateAttachmentFn(ctx, row, bucketID); err != nil {
+ return stacktrace.Propagate(err, "failed to replicate attachment")
+ }
+ if err := c.Repo.MoveBetweenBuckets(row, bucketID, contactrepo.InflightRepColumn, contactrepo.ReplicationColumn); err != nil {
+ return err
+ }
+ }
+ return c.Repo.MarkAttachmentReplicationAsDone(ctx, row)
+}
+
+func (c *Controller) startDeleteWorkers(n int) {
+ log.Infof("Starting %d delete workers for contact attachments", n)
+ for i := 0; i < n; i++ {
+ go c.delete(i)
+ time.Sleep(time.Duration(2*i+1) * time.Minute)
+ }
+}
+
+func (c *Controller) delete(i int) {
+ for {
+ if err := c.tryDelete(); err != nil {
+ time.Sleep(time.Duration(i+5) * time.Minute)
+ }
+ }
+}
+
+func (c *Controller) tryDelete() error {
+ newLockTime := enteTime.MicrosecondsAfterMinutes(10)
+ row, err := c.Repo.GetPendingSyncAttachmentAndExtendLock(context.Background(), newLockTime, true)
+ if err != nil {
+ return err
+ }
+ return c.deleteAttachmentRow(*row)
+}
+
+func (c *Controller) deleteAttachmentRow(row contactmodel.Attachment) error {
+ if !row.IsDeleted {
+ return stacktrace.NewError("attachment is not marked as deleted")
+ }
+ bucketColumnMap, err := getAttachmentBucketColumnMap(row)
+ if err != nil {
+ return err
+ }
+ for bucketID, columnName := range bucketColumnMap {
+ if err := c.deleteAttachmentFn(row, bucketID); err != nil {
+ return stacktrace.Propagate(err, "failed to delete attachment from bucket")
+ }
+ if err := c.Repo.RemoveBucket(row, bucketID, columnName); err != nil {
+ return stacktrace.Propagate(err, "failed to remove attachment bucket from db")
+ }
+ }
+ if err := c.deleteAttachmentFn(row, row.LatestBucket); err != nil {
+ return stacktrace.Propagate(err, "failed to delete latest attachment object")
+ }
+ return c.Repo.DeleteAttachment(context.Background(), row)
+}
+
+func getAttachmentBucketColumnMap(row contactmodel.Attachment) (map[string]string, error) {
+ bucketColumnMap := make(map[string]string)
+ for _, bucketID := range row.DeleteFromBuckets {
+ if existingColumn, exists := bucketColumnMap[bucketID]; exists {
+ return nil, stacktrace.NewError("duplicate delete bucket " + bucketID + " in " + existingColumn)
+ }
+ bucketColumnMap[bucketID] = contactrepo.DeletionColumn
+ }
+ for _, bucketID := range row.ReplicatedBuckets {
+ if existingColumn, exists := bucketColumnMap[bucketID]; exists {
+ return nil, stacktrace.NewError("duplicate replicated bucket " + bucketID + " in " + existingColumn)
+ }
+ bucketColumnMap[bucketID] = contactrepo.ReplicationColumn
+ }
+ for _, bucketID := range row.InflightRepBuckets {
+ if existingColumn, exists := bucketColumnMap[bucketID]; exists {
+ return nil, stacktrace.NewError("duplicate inflight bucket " + bucketID + " in " + existingColumn)
+ }
+ bucketColumnMap[bucketID] = contactrepo.InflightRepColumn
+ }
+ return bucketColumnMap, nil
+}
+
+func (c *Controller) replicateAttachmentObject(ctx context.Context, row contactmodel.Attachment, dstBucketID string) error {
+ if err := fileutil.EnsureSufficientSpace(row.Size); err != nil {
+ return stacktrace.Propagate(err, "")
+ }
+ filePath, file, err := fileutil.CreateTemporaryFile(c.tempStorage, row.AttachmentID)
+ if err != nil {
+ return stacktrace.Propagate(err, "failed to create temporary file")
+ }
+ defer os.Remove(filePath)
+ defer file.Close()
+
+ downloader := c.downloadManagerCache[row.LatestBucket]
+ if downloader == nil {
+ s3Client := c.S3Config.GetS3Client(row.LatestBucket)
+ downloader = s3manager.NewDownloaderWithClient(&s3Client)
+ c.downloadManagerCache[row.LatestBucket] = downloader
+ }
+ _, err = downloader.DownloadWithContext(ctx, file, &s3.GetObjectInput{
+ Bucket: c.S3Config.GetBucket(row.LatestBucket),
+ Key: aws.String(row.ObjectKey()),
+ })
+ if err != nil {
+ return stacktrace.Propagate(err, "failed to download attachment from bucket %s", row.LatestBucket)
+ }
+ if err := c.verifyAttachmentSize(row.LatestBucket, row.ObjectKey(), row.Size); err != nil {
+ return err
+ }
+ dstClient := c.S3Config.GetS3Client(dstBucketID)
+ uploader := s3manager.NewUploaderWithClient(&dstClient)
+ if _, err := file.Seek(0, io.SeekStart); err != nil {
+ return stacktrace.Propagate(err, "failed to seek temporary attachment file")
+ }
+ if _, err := uploader.Upload(&s3manager.UploadInput{
+ Bucket: c.S3Config.GetBucket(dstBucketID),
+ Key: aws.String(row.ObjectKey()),
+ Body: file,
+ }); err != nil {
+ return stacktrace.Propagate(err, "failed to upload attachment to bucket %s", dstBucketID)
+ }
+ return c.verifyAttachmentSize(dstBucketID, row.ObjectKey(), row.Size)
+}
+
+func (c *Controller) verifyAttachmentSize(bucketID string, objectKey string, expectedSize int64) error {
+ s3Client := c.S3Config.GetS3Client(bucketID)
+ res, err := s3Client.HeadObject(&s3.HeadObjectInput{
+ Bucket: c.S3Config.GetBucket(bucketID),
+ Key: aws.String(objectKey),
+ })
+ if err != nil {
+ return stacktrace.Propagate(err, "failed to fetch attachment info from bucket %s", bucketID)
+ }
+ if *res.ContentLength != expectedSize {
+ return stacktrace.NewError("attachment size does not match expected size")
+ }
+ return nil
+}
+
+func (c *Controller) deleteAttachmentObject(row contactmodel.Attachment, bucketID string) error {
+ return c.ObjectCleanupController.DeleteObjectFromDataCenter(row.ObjectKey(), bucketID)
+}
diff --git a/server/pkg/controller/contact/controller_test.go b/server/pkg/controller/contact/controller_test.go
index c114056b7c..650a86bf1a 100644
--- a/server/pkg/controller/contact/controller_test.go
+++ b/server/pkg/controller/contact/controller_test.go
@@ -1,10 +1,13 @@
package contact
import (
+ "context"
"database/sql"
"errors"
"fmt"
"net/http/httptest"
+ "reflect"
+ "sort"
"strings"
"testing"
@@ -18,6 +21,7 @@ import (
"github.com/ente-io/museum/pkg/utils/crypto"
"github.com/ente-io/museum/pkg/utils/s3config"
"github.com/gin-gonic/gin"
+ "github.com/lib/pq"
"github.com/spf13/viper"
)
@@ -734,6 +738,114 @@ func TestDeleteContactMarksCurrentProfilePictureDeleted(t *testing.T) {
}
}
+func TestAttachmentReplicationLifecycle(t *testing.T) {
+ ctrl, db, _, _ := setupContactControllerTest(t)
+ mustInsertTestUser(t, db, 1)
+ viper.Set("s3.attachment-config.profile_picture.primaryBucket", "b2-eu-cen")
+ viper.Set("s3.attachment-config.profile_picture.replicaBuckets", []string{"scw-eu-fr"})
+ ctrl.S3Config = s3config.NewS3Config()
+
+ mustInsertAttachmentRow(t, db, "ua_replication", 1, false, "b2-eu-cen", nil, nil, nil)
+
+ replicatedTo := make([]string, 0)
+ ctrl.replicateAttachmentFn = func(_ context.Context, row contactmodel.Attachment, dstBucketID string) error {
+ replicatedTo = append(replicatedTo, dstBucketID)
+ if row.AttachmentID != "ua_replication" {
+ t.Fatalf("unexpected attachment id %q", row.AttachmentID)
+ }
+ return nil
+ }
+
+ if err := ctrl.tryReplicate(); err != nil {
+ t.Fatalf("tryReplicate() first pass error = %v", err)
+ }
+ if !reflect.DeepEqual(replicatedTo, []string{"scw-eu-fr"}) {
+ t.Fatalf("replicated buckets = %v, want [scw-eu-fr]", replicatedTo)
+ }
+
+ attachment, err := ctrl.Repo.GetAttachment(context.Background(), 1, "ua_replication")
+ if err != nil {
+ t.Fatalf("GetAttachment() error = %v", err)
+ }
+ if !reflect.DeepEqual(attachment.ReplicatedBuckets, []string{"scw-eu-fr"}) {
+ t.Fatalf("replicated buckets after first pass = %v", attachment.ReplicatedBuckets)
+ }
+ if attachment.PendingSync {
+ t.Fatal("attachment should not be pending after replication is complete")
+ }
+}
+
+func TestAttachmentDeletionLifecycle(t *testing.T) {
+ ctrl, db, _, _ := setupContactControllerTest(t)
+ mustInsertTestUser(t, db, 1)
+
+ mustInsertAttachmentRow(t, db, "ua_delete", 1, true, "b2-eu-cen", nil, []string{"scw-eu-fr"}, nil)
+
+ deletedFrom := make([]string, 0)
+ ctrl.deleteAttachmentFn = func(row contactmodel.Attachment, bucketID string) error {
+ deletedFrom = append(deletedFrom, bucketID)
+ if row.AttachmentID != "ua_delete" {
+ t.Fatalf("unexpected attachment id %q", row.AttachmentID)
+ }
+ return nil
+ }
+
+ if err := ctrl.tryDelete(); err != nil {
+ t.Fatalf("tryDelete() error = %v", err)
+ }
+
+ if _, err := ctrl.Repo.GetAttachment(context.Background(), 1, "ua_delete"); err == nil {
+ t.Fatal("attachment row should be removed after deletion")
+ } else if !errors.Is(err, &ente.ErrNotFoundError) {
+ t.Fatalf("unexpected GetAttachment error = %v", err)
+ }
+
+ sort.Strings(deletedFrom)
+ if !reflect.DeepEqual(deletedFrom, []string{"b2-eu-cen", "scw-eu-fr"}) {
+ t.Fatalf("deleted buckets = %v", deletedFrom)
+ }
+}
+
func ptrInt64(v int64) *int64 {
return &v
}
+
+func mustInsertAttachmentRow(
+ t *testing.T,
+ db *sql.DB,
+ attachmentID string,
+ userID int64,
+ isDeleted bool,
+ latestBucket string,
+ replicatedBuckets []string,
+ deleteFromBuckets []string,
+ inflightBuckets []string,
+) {
+ t.Helper()
+ if replicatedBuckets == nil {
+ replicatedBuckets = []string{}
+ }
+ if deleteFromBuckets == nil {
+ deleteFromBuckets = []string{}
+ }
+ if inflightBuckets == nil {
+ inflightBuckets = []string{}
+ }
+ if _, err := db.Exec(
+ `INSERT INTO user_attachments(
+ attachment_id, user_id, attachment_type, size, latest_bucket, replicated_buckets,
+ delete_from_buckets, inflight_rep_buckets, pending_sync, is_deleted
+ ) VALUES($1, $2, $3, $4, $5, $6::s3region[], $7::s3region[], $8::s3region[], TRUE, $9)`,
+ attachmentID,
+ userID,
+ "profile_picture",
+ 128,
+ latestBucket,
+ pq.Array(replicatedBuckets),
+ pq.Array(deleteFromBuckets),
+ pq.Array(inflightBuckets),
+ isDeleted,
+ ); err != nil {
+ t.Fatalf("failed to insert attachment row: %v", err)
+ }
+}
diff --git a/server/pkg/repo/contact/contact.go b/server/pkg/repo/contact/contact.go
index 630a6a0cb4..6ba0275a58 100644
--- a/server/pkg/repo/contact/contact.go
+++ b/server/pkg/repo/contact/contact.go
@@ -4,9 +4,12 @@ import (
"context"
"database/sql"
"errors"
+ "fmt"
+ "time"
"github.com/ente-io/museum/ente"
contactmodel "github.com/ente-io/museum/ente/contact"
+ "github.com/ente-io/museum/pkg/utils/array"
"github.com/ente-io/museum/pkg/utils/crypto"
"github.com/ente-io/stacktrace"
"github.com/lib/pq"
@@ -421,6 +424,222 @@ func (r *Repository) GetAttachment(ctx context.Context, userID int64, attachment
return attachment, nil
}
+func (r *Repository) AddBucket(row contactmodel.Attachment, bucketID string, columnName string) error {
+ query := fmt.Sprintf(`
+ UPDATE user_attachments
+ SET %s = array(
+ SELECT DISTINCT elem FROM unnest(
+ array_append(user_attachments.%s, $1)
+ ) AS elem
+ WHERE elem IS NOT NULL
+ )
+ WHERE attachment_id = $2 AND user_id = $3 AND attachment_type = $4`, columnName, columnName)
+ result, err := r.DB.Exec(query, bucketID, row.AttachmentID, row.UserID, string(row.AttachmentType))
+ if err != nil {
+ return stacktrace.Propagate(err, "failed to add bucket to "+columnName)
+ }
+ rowsAffected, err := result.RowsAffected()
+ if err != nil {
+ return stacktrace.Propagate(err, "")
+ }
+ if rowsAffected == 0 {
+ return stacktrace.NewError("bucket not added to " + columnName)
+ }
+ return nil
+}
+
+func (r *Repository) RemoveBucket(row contactmodel.Attachment, bucketID string, columnName string) error {
+ query := fmt.Sprintf(`
+ UPDATE user_attachments
+ SET %s = array(
+ SELECT DISTINCT elem FROM unnest(
+ array_remove(user_attachments.%s, $1)
+ ) AS elem
+ WHERE elem IS NOT NULL
+ )
+ WHERE attachment_id = $2 AND user_id = $3 AND attachment_type = $4`, columnName, columnName)
+ result, err := r.DB.Exec(query, bucketID, row.AttachmentID, row.UserID, string(row.AttachmentType))
+ if err != nil {
+ return stacktrace.Propagate(err, "failed to remove bucket from "+columnName)
+ }
+ rowsAffected, err := result.RowsAffected()
+ if err != nil {
+ return stacktrace.Propagate(err, "")
+ }
+ if rowsAffected == 0 {
+ return stacktrace.NewError("bucket not removed from " + columnName)
+ }
+ return nil
+}
+
+func (r *Repository) MoveBetweenBuckets(row contactmodel.Attachment, bucketID string, sourceColumn string, destColumn string) error {
+ query := fmt.Sprintf(`
+ UPDATE user_attachments
+ SET %s = array(
+ SELECT DISTINCT elem FROM unnest(
+ array_append(user_attachments.%s, $1)
+ ) AS elem
+ WHERE elem IS NOT NULL
+ ),
+ %s = array(
+ SELECT DISTINCT elem FROM unnest(
+ array_remove(user_attachments.%s, $1)
+ ) AS elem
+ WHERE elem IS NOT NULL
+ )
+ WHERE attachment_id = $2 AND user_id = $3 AND attachment_type = $4`, destColumn, destColumn, sourceColumn, sourceColumn)
+ result, err := r.DB.Exec(query, bucketID, row.AttachmentID, row.UserID, string(row.AttachmentType))
+ if err != nil {
+ return stacktrace.Propagate(err, "failed to move bucket from "+sourceColumn+" to "+destColumn)
+ }
+ rowsAffected, err := result.RowsAffected()
+ if err != nil {
+ return stacktrace.Propagate(err, "")
+ }
+ if rowsAffected == 0 {
+ return stacktrace.NewError("bucket not moved from " + sourceColumn + " to " + destColumn)
+ }
+ return nil
+}
+
+func (r *Repository) GetPendingSyncAttachmentAndExtendLock(
+ ctx context.Context,
+ newSyncLockTime int64,
+ forDeletion bool,
+) (*contactmodel.Attachment, error) {
+ if newSyncLockTime < time.Now().Add(5*time.Minute).UnixMicro() {
+ return nil, stacktrace.NewError("newSyncLockTime should be at least 5min in the future")
+ }
+ tx, err := r.DB.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ defer tx.Rollback()
+
+ row := tx.QueryRowContext(
+ ctx,
+ `SELECT attachment_id, user_id, attachment_type, size, latest_bucket, replicated_buckets,
+ delete_from_buckets, inflight_rep_buckets, pending_sync, is_deleted, sync_locked_till,
+ created_at, updated_at
+ FROM user_attachments
+ WHERE pending_sync = TRUE
+ AND is_deleted = $1
+ AND sync_locked_till < now_utc_micro_seconds()
+ LIMIT 1
+ FOR UPDATE SKIP LOCKED`,
+ forDeletion,
+ )
+ attachment, err := scanAttachment(row)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ if attachment.SyncLockedTill > newSyncLockTime {
+ return nil, stacktrace.NewError(
+ fmt.Sprintf(
+ "newSyncLockTime (%d) is less than existing SyncLockedTill(%d)",
+ newSyncLockTime,
+ attachment.SyncLockedTill,
+ ),
+ )
+ }
+ if _, err := tx.ExecContext(
+ ctx,
+ `UPDATE user_attachments
+ SET sync_locked_till = $1
+ WHERE attachment_id = $2 AND user_id = $3 AND attachment_type = $4`,
+ newSyncLockTime,
+ attachment.AttachmentID,
+ attachment.UserID,
+ string(attachment.AttachmentType),
+ ); err != nil {
+ return nil, stacktrace.Propagate(err, "failed to extend attachment sync lock")
+ }
+ if err := tx.Commit(); err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ return attachment, nil
+}
+
+func (r *Repository) MarkAttachmentReplicationAsDone(ctx context.Context, row contactmodel.Attachment) error {
+ _, err := r.DB.ExecContext(
+ ctx,
+ `UPDATE user_attachments
+ SET pending_sync = FALSE
+ WHERE is_deleted = FALSE
+ AND attachment_id = $1
+ AND user_id = $2
+ AND attachment_type = $3`,
+ row.AttachmentID,
+ row.UserID,
+ string(row.AttachmentType),
+ )
+ if err != nil {
+ return stacktrace.Propagate(err, "")
+ }
+ return nil
+}
+
+func (r *Repository) RegisterReplicationAttempt(ctx context.Context, row contactmodel.Attachment, dstBucketID string) error {
+ if array.StringInList(dstBucketID, row.DeleteFromBuckets) {
+ return r.MoveBetweenBuckets(row, dstBucketID, DeletionColumn, InflightRepColumn)
+ }
+ if !array.StringInList(dstBucketID, row.InflightRepBuckets) {
+ return r.AddBucket(row, dstBucketID, InflightRepColumn)
+ }
+ return nil
+}
+
+func (r *Repository) ResetAttachmentSyncLock(ctx context.Context, row contactmodel.Attachment, syncLockedTill int64) error {
+ _, err := r.DB.ExecContext(
+ ctx,
+ `UPDATE user_attachments
+ SET sync_locked_till = now_utc_micro_seconds()
+ WHERE pending_sync = FALSE
+ AND attachment_id = $1
+ AND user_id = $2
+ AND attachment_type = $3
+ AND sync_locked_till = $4`,
+ row.AttachmentID,
+ row.UserID,
+ string(row.AttachmentType),
+ syncLockedTill,
+ )
+ if err != nil {
+ return stacktrace.Propagate(err, "")
+ }
+ return nil
+}
+
+func (r *Repository) DeleteAttachment(ctx context.Context, row contactmodel.Attachment) error {
+ res, err := r.DB.ExecContext(
+ ctx,
+ `DELETE FROM user_attachments
+ WHERE attachment_id = $1
+ AND attachment_type = $2
+ AND latest_bucket = $3
+ AND user_id = $4
+ AND replicated_buckets = ARRAY[]::s3region[]
+ AND delete_from_buckets = ARRAY[]::s3region[]
+ AND inflight_rep_buckets = ARRAY[]::s3region[]
+ AND is_deleted = TRUE`,
+ row.AttachmentID,
+ string(row.AttachmentType),
+ row.LatestBucket,
+ row.UserID,
+ )
+ if err != nil {
+ return stacktrace.Propagate(err, "")
+ }
+ rowsAffected, err := res.RowsAffected()
+ if err != nil {
+ return stacktrace.Propagate(err, "")
+ }
+ if rowsAffected == 0 {
+ return stacktrace.NewError("attachment not deleted")
+ }
+ return nil
+}
+
func (r *Repository) getForUpdate(ctx context.Context, tx *sql.Tx, userID int64, id string) (*contactmodel.Entity, error) {
row := tx.QueryRowContext(
ctx,
diff --git a/server/pkg/repo/contact/repository.go b/server/pkg/repo/contact/repository.go
index 3f4cebec57..52782bde02 100644
--- a/server/pkg/repo/contact/repository.go
+++ b/server/pkg/repo/contact/repository.go
@@ -6,6 +6,12 @@ import (
"github.com/ente-io/museum/pkg/repo"
)
+const (
+ ReplicationColumn = "replicated_buckets"
+ DeletionColumn = "delete_from_buckets"
+ InflightRepColumn = "inflight_rep_buckets"
+)
+
type Repository struct {
DB *sql.DB
ObjectCleanupRepo *repo.ObjectCleanupRepository
diff --git a/server/pkg/repo/datacleanup/repository.go b/server/pkg/repo/datacleanup/repository.go
index 7d080c2f0f..94a3857494 100644
--- a/server/pkg/repo/datacleanup/repository.go
+++ b/server/pkg/repo/datacleanup/repository.go
@@ -88,9 +88,21 @@ func (r *Repository) DeleteTableData(ctx context.Context, userID int64) error {
if err != nil {
return stacktrace.Propagate(err, "failed to delete entity data")
}
- _, err = r.DB.ExecContext(ctx, `DELETE FROM user_attachments WHERE user_id = $1`, userID)
- if err != nil {
- return stacktrace.Propagate(err, "failed to delete contact attachment data")
+ _, err = r.DB.ExecContext(ctx, `UPDATE user_attachments
+ SET is_deleted = TRUE,
+ pending_sync = TRUE,
+ sync_locked_till = 0,
+ delete_from_buckets = array(
+ SELECT DISTINCT elem
+ FROM unnest(array_cat(array_cat(replicated_buckets, delete_from_buckets), inflight_rep_buckets)) AS elem
+ WHERE elem IS NOT NULL
+ ),
+ replicated_buckets = ARRAY[]::s3region[],
+ inflight_rep_buckets = ARRAY[]::s3region[]
+ WHERE user_id = $1
+ AND is_deleted = FALSE`, userID)
+ if err != nil {
+ return stacktrace.Propagate(err, "failed to mark contact attachment data deleted")
}
_, err = r.DB.ExecContext(ctx, `DELETE FROM contact_entity WHERE user_id = $1`, userID)
if err != nil {
diff --git a/server/pkg/repo/datacleanup/repository_test.go b/server/pkg/repo/datacleanup/repository_test.go
index 5d475bac04..0320f6ea12 100644
--- a/server/pkg/repo/datacleanup/repository_test.go
+++ b/server/pkg/repo/datacleanup/repository_test.go
@@ -71,9 +71,20 @@ func TestDeleteTableDataDeletesContactsAndAttachmentsForUser(t *testing.T) {
}
assertCleanupRowCount(t, db, `SELECT COUNT(*) FROM contact_entity WHERE user_id = $1`, targetUserID, 0)
- assertCleanupRowCount(t, db, `SELECT COUNT(*) FROM user_attachments WHERE user_id = $1`, targetUserID, 0)
+ assertCleanupRowCount(t, db, `SELECT COUNT(*) FROM user_attachments WHERE user_id = $1`, targetUserID, 1)
assertCleanupRowCount(t, db, `SELECT COUNT(*) FROM contact_entity WHERE user_id = $1`, otherUserID, 1)
assertCleanupRowCount(t, db, `SELECT COUNT(*) FROM user_attachments WHERE user_id = $1`, otherUserID, 1)
+
+ var isDeleted, pendingSync bool
+ if err := db.QueryRow(
+ `SELECT is_deleted, pending_sync FROM user_attachments WHERE attachment_id = $1`,
+ "ua_target",
+ ).Scan(&isDeleted, &pendingSync); err != nil {
+ t.Fatalf("failed to query target attachment row: %v", err)
+ }
+ if !isDeleted || !pendingSync {
+ t.Fatalf("target attachment row = {is_deleted:%v pending_sync:%v}, want both true", isDeleted, pendingSync)
+ }
}
func mustExecCleanupTest(t *testing.T, db *sql.DB, query string, args ...any) {