file_copy.go 7.0 KB

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