file_copy.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. package file_copy
  2. import (
  3. "fmt"
  4. "github.com/aws/aws-sdk-go/service/s3"
  5. "github.com/ente-io/museum/ente"
  6. "github.com/ente-io/museum/pkg/controller"
  7. "github.com/ente-io/museum/pkg/repo"
  8. "github.com/ente-io/museum/pkg/utils/auth"
  9. "github.com/ente-io/museum/pkg/utils/s3config"
  10. enteTime "github.com/ente-io/museum/pkg/utils/time"
  11. "github.com/gin-contrib/requestid"
  12. "github.com/gin-gonic/gin"
  13. "github.com/sirupsen/logrus"
  14. "golang.org/x/sync/errgroup"
  15. "sync"
  16. "time"
  17. )
  18. type FileCopyController struct {
  19. S3Config *s3config.S3Config
  20. FileController *controller.FileController
  21. FileRepo *repo.FileRepository
  22. CollectionCtrl *controller.CollectionController
  23. ObjectRepo *repo.ObjectRepository
  24. }
  25. type copyS3ObjectReq struct {
  26. SourceS3Object ente.S3ObjectKey
  27. DestObjectKey string
  28. }
  29. type fileCopyInternal struct {
  30. SourceFile ente.File
  31. DestCollectionID int64
  32. // The FileKey is encrypted with the destination collection's key
  33. EncryptedFileKey string
  34. EncryptedFileKeyNonce string
  35. FileCopyReq *copyS3ObjectReq
  36. ThumbCopyReq *copyS3ObjectReq
  37. }
  38. func (fci fileCopyInternal) newFile(ownedID int64) ente.File {
  39. newFileAttributes := fci.SourceFile.File
  40. newFileAttributes.ObjectKey = fci.FileCopyReq.DestObjectKey
  41. newThumbAttributes := fci.SourceFile.Thumbnail
  42. newThumbAttributes.ObjectKey = fci.ThumbCopyReq.DestObjectKey
  43. return ente.File{
  44. OwnerID: ownedID,
  45. CollectionID: fci.DestCollectionID,
  46. EncryptedKey: fci.EncryptedFileKey,
  47. KeyDecryptionNonce: fci.EncryptedFileKeyNonce,
  48. File: newFileAttributes,
  49. Thumbnail: newThumbAttributes,
  50. Metadata: fci.SourceFile.Metadata,
  51. UpdationTime: enteTime.Microseconds(),
  52. IsDeleted: false,
  53. }
  54. }
  55. func (fc *FileCopyController) CopyFiles(c *gin.Context, req ente.CopyFileSyncRequest) (*ente.CopyResponse, error) {
  56. userID := auth.GetUserID(c.Request.Header)
  57. app := auth.GetApp(c)
  58. logger := logrus.WithFields(logrus.Fields{"req_id": requestid.Get(c), "user_id": userID})
  59. err := fc.CollectionCtrl.IsCopyAllowed(c, userID, req)
  60. if err != nil {
  61. return nil, err
  62. }
  63. fileIDs := make([]int64, 0, len(req.CollectionFileItems))
  64. fileToCollectionFileMap := make(map[int64]*ente.CollectionFileItem, len(req.CollectionFileItems))
  65. for i := range req.CollectionFileItems {
  66. item := &req.CollectionFileItems[i]
  67. fileToCollectionFileMap[item.ID] = item
  68. fileIDs = append(fileIDs, item.ID)
  69. }
  70. s3ObjectsToCopy, err := fc.ObjectRepo.GetObjectsForFileIDs(fileIDs)
  71. if err != nil {
  72. return nil, err
  73. }
  74. // note: this assumes that preview existingFilesToCopy for videos are not tracked inside the object_keys table
  75. if len(s3ObjectsToCopy) != 2*len(fileIDs) {
  76. return nil, ente.NewInternalError(fmt.Sprintf("expected %d objects, got %d", 2*len(fileIDs), len(s3ObjectsToCopy)))
  77. }
  78. // todo:(neeraj) if the total size is greater than 1GB, do an early check if the user can upload the existingFilesToCopy
  79. var totalSize int64
  80. for _, obj := range s3ObjectsToCopy {
  81. totalSize += obj.FileSize
  82. }
  83. logger.WithField("totalSize", totalSize).Info("total size of existingFilesToCopy to copy")
  84. // request the uploadUrls using existing method. This is to ensure that orphan objects are automatically cleaned up
  85. // todo:(neeraj) optimize this method by removing the need for getting a signed url for each object
  86. uploadUrls, err := fc.FileController.GetUploadURLs(c, userID, len(s3ObjectsToCopy), app)
  87. if err != nil {
  88. return nil, err
  89. }
  90. existingFilesToCopy, err := fc.FileRepo.GetFileAttributesForCopy(fileIDs)
  91. if err != nil {
  92. return nil, err
  93. }
  94. if len(existingFilesToCopy) != len(fileIDs) {
  95. return nil, ente.NewInternalError(fmt.Sprintf("expected %d existingFilesToCopy, got %d", len(fileIDs), len(existingFilesToCopy)))
  96. }
  97. fileOGS3Object := make(map[int64]*copyS3ObjectReq)
  98. fileThumbS3Object := make(map[int64]*copyS3ObjectReq)
  99. for i, s3Obj := range s3ObjectsToCopy {
  100. if s3Obj.Type == ente.FILE {
  101. fileOGS3Object[s3Obj.FileID] = &copyS3ObjectReq{
  102. SourceS3Object: s3Obj,
  103. DestObjectKey: uploadUrls[i].ObjectKey,
  104. }
  105. } else if s3Obj.Type == ente.THUMBNAIL {
  106. fileThumbS3Object[s3Obj.FileID] = &copyS3ObjectReq{
  107. SourceS3Object: s3Obj,
  108. DestObjectKey: uploadUrls[i].ObjectKey,
  109. }
  110. } else {
  111. return nil, ente.NewInternalError(fmt.Sprintf("unexpected object type %s", s3Obj.Type))
  112. }
  113. }
  114. fileCopyList := make([]fileCopyInternal, 0, len(existingFilesToCopy))
  115. for i := range existingFilesToCopy {
  116. file := existingFilesToCopy[i]
  117. collectionItem := fileToCollectionFileMap[file.ID]
  118. if collectionItem.ID != file.ID {
  119. return nil, ente.NewInternalError(fmt.Sprintf("expected collectionItem.ID %d, got %d", file.ID, collectionItem.ID))
  120. }
  121. fileCopy := fileCopyInternal{
  122. SourceFile: file,
  123. DestCollectionID: req.DstCollection,
  124. EncryptedFileKey: fileToCollectionFileMap[file.ID].EncryptedKey,
  125. EncryptedFileKeyNonce: fileToCollectionFileMap[file.ID].KeyDecryptionNonce,
  126. FileCopyReq: fileOGS3Object[file.ID],
  127. ThumbCopyReq: fileThumbS3Object[file.ID],
  128. }
  129. fileCopyList = append(fileCopyList, fileCopy)
  130. }
  131. oldToNewFileIDMap := make(map[int64]int64)
  132. var wg sync.WaitGroup
  133. errChan := make(chan error, len(fileCopyList))
  134. for _, fileCopy := range fileCopyList {
  135. wg.Add(1)
  136. go func(fileCopy fileCopyInternal) {
  137. defer wg.Done()
  138. newFile, err := fc.createCopy(c, fileCopy, userID, app)
  139. if err != nil {
  140. errChan <- err
  141. return
  142. }
  143. oldToNewFileIDMap[fileCopy.SourceFile.ID] = newFile.ID
  144. }(fileCopy)
  145. }
  146. // Wait for all goroutines to finish
  147. wg.Wait()
  148. // Close the error channel and check if there were any errors
  149. close(errChan)
  150. if err, ok := <-errChan; ok {
  151. return nil, err
  152. }
  153. return &ente.CopyResponse{OldToNewFileIDMap: oldToNewFileIDMap}, nil
  154. }
  155. func (fc *FileCopyController) createCopy(c *gin.Context, fcInternal fileCopyInternal, userID int64, app ente.App) (*ente.File, error) {
  156. // using HotS3Client copy the File and Thumbnail
  157. s3Client := fc.S3Config.GetHotS3Client()
  158. hotBucket := fc.S3Config.GetHotBucket()
  159. g := new(errgroup.Group)
  160. g.Go(func() error {
  161. return copyS3Object(s3Client, hotBucket, fcInternal.FileCopyReq)
  162. })
  163. g.Go(func() error {
  164. return copyS3Object(s3Client, hotBucket, fcInternal.ThumbCopyReq)
  165. })
  166. if err := g.Wait(); err != nil {
  167. return nil, err
  168. }
  169. file := fcInternal.newFile(userID)
  170. newFile, err := fc.FileController.Create(c, userID, file, "", app)
  171. if err != nil {
  172. return nil, err
  173. }
  174. return &newFile, nil
  175. }
  176. // Helper function for S3 object copying.
  177. func copyS3Object(s3Client *s3.S3, bucket *string, req *copyS3ObjectReq) error {
  178. copySource := fmt.Sprintf("%s/%s", *bucket, req.SourceS3Object.ObjectKey)
  179. copyInput := &s3.CopyObjectInput{
  180. Bucket: bucket,
  181. CopySource: &copySource,
  182. Key: &req.DestObjectKey,
  183. }
  184. start := time.Now()
  185. _, err := s3Client.CopyObject(copyInput)
  186. elapsed := time.Since(start)
  187. if err != nil {
  188. return fmt.Errorf("failed to copy (%s) from %s to %s: %w", req.SourceS3Object.Type, copySource, req.DestObjectKey, err)
  189. }
  190. logrus.WithField("duration", elapsed).WithField("size", req.SourceS3Object.FileSize).Infof("copied (%s) from %s to %s", req.SourceS3Object.Type, copySource, req.DestObjectKey)
  191. return nil
  192. }