file_copy.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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 := req.FileIDs()
  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. }
  68. s3ObjectsToCopy, err := fc.ObjectRepo.GetObjectsForFileIDs(fileIDs)
  69. if err != nil {
  70. return nil, err
  71. }
  72. // note: this assumes that preview existingFilesToCopy for videos are not tracked inside the object_keys table
  73. if len(s3ObjectsToCopy) != 2*len(fileIDs) {
  74. return nil, ente.NewInternalError(fmt.Sprintf("expected %d objects, got %d", 2*len(fileIDs), len(s3ObjectsToCopy)))
  75. }
  76. // todo:(neeraj) if the total size is greater than 1GB, do an early check if the user can upload the existingFilesToCopy
  77. var totalSize int64
  78. for _, obj := range s3ObjectsToCopy {
  79. totalSize += obj.FileSize
  80. }
  81. logger.WithField("totalSize", totalSize).Info("total size of existingFilesToCopy to copy")
  82. // request the uploadUrls using existing method. This is to ensure that orphan objects are automatically cleaned up
  83. // todo:(neeraj) optimize this method by removing the need for getting a signed url for each object
  84. uploadUrls, err := fc.FileController.GetUploadURLs(c, userID, len(s3ObjectsToCopy), app)
  85. if err != nil {
  86. return nil, err
  87. }
  88. existingFilesToCopy, err := fc.FileRepo.GetFileAttributesForCopy(fileIDs)
  89. if err != nil {
  90. return nil, err
  91. }
  92. if len(existingFilesToCopy) != len(fileIDs) {
  93. return nil, ente.NewInternalError(fmt.Sprintf("expected %d existingFilesToCopy, got %d", len(fileIDs), len(existingFilesToCopy)))
  94. }
  95. fileOGS3Object := make(map[int64]*copyS3ObjectReq)
  96. fileThumbS3Object := make(map[int64]*copyS3ObjectReq)
  97. for i, s3Obj := range s3ObjectsToCopy {
  98. if s3Obj.Type == ente.FILE {
  99. fileOGS3Object[s3Obj.FileID] = &copyS3ObjectReq{
  100. SourceS3Object: s3Obj,
  101. DestObjectKey: uploadUrls[i].ObjectKey,
  102. }
  103. } else if s3Obj.Type == ente.THUMBNAIL {
  104. fileThumbS3Object[s3Obj.FileID] = &copyS3ObjectReq{
  105. SourceS3Object: s3Obj,
  106. DestObjectKey: uploadUrls[i].ObjectKey,
  107. }
  108. } else {
  109. return nil, ente.NewInternalError(fmt.Sprintf("unexpected object type %s", s3Obj.Type))
  110. }
  111. }
  112. fileCopyList := make([]fileCopyInternal, 0, len(existingFilesToCopy))
  113. for i := range existingFilesToCopy {
  114. file := existingFilesToCopy[i]
  115. collectionItem := fileToCollectionFileMap[file.ID]
  116. if collectionItem.ID != file.ID {
  117. return nil, ente.NewInternalError(fmt.Sprintf("expected collectionItem.ID %d, got %d", file.ID, collectionItem.ID))
  118. }
  119. fileCopy := fileCopyInternal{
  120. SourceFile: file,
  121. DestCollectionID: req.DstCollection,
  122. EncryptedFileKey: fileToCollectionFileMap[file.ID].EncryptedKey,
  123. EncryptedFileKeyNonce: fileToCollectionFileMap[file.ID].KeyDecryptionNonce,
  124. FileCopyReq: fileOGS3Object[file.ID],
  125. ThumbCopyReq: fileThumbS3Object[file.ID],
  126. }
  127. fileCopyList = append(fileCopyList, fileCopy)
  128. }
  129. oldToNewFileIDMap := make(map[int64]int64)
  130. var wg sync.WaitGroup
  131. errChan := make(chan error, len(fileCopyList))
  132. for _, fileCopy := range fileCopyList {
  133. wg.Add(1)
  134. go func(fileCopy fileCopyInternal) {
  135. defer wg.Done()
  136. newFile, err := fc.createCopy(c, fileCopy, userID, app)
  137. if err != nil {
  138. errChan <- err
  139. return
  140. }
  141. oldToNewFileIDMap[fileCopy.SourceFile.ID] = newFile.ID
  142. }(fileCopy)
  143. }
  144. // Wait for all goroutines to finish
  145. wg.Wait()
  146. // Close the error channel and check if there were any errors
  147. close(errChan)
  148. if err, ok := <-errChan; ok {
  149. return nil, err
  150. }
  151. return &ente.CopyResponse{OldToNewFileIDMap: oldToNewFileIDMap}, nil
  152. }
  153. func (fc *FileCopyController) createCopy(c *gin.Context, fcInternal fileCopyInternal, userID int64, app ente.App) (*ente.File, error) {
  154. // using HotS3Client copy the File and Thumbnail
  155. s3Client := fc.S3Config.GetHotS3Client()
  156. hotBucket := fc.S3Config.GetHotBucket()
  157. err := copyS3Object(s3Client, hotBucket, fcInternal.FileCopyReq)
  158. if err != nil {
  159. return nil, err
  160. }
  161. err = copyS3Object(s3Client, hotBucket, fcInternal.ThumbCopyReq)
  162. if err != nil {
  163. return nil, err
  164. }
  165. file := fcInternal.newFile(userID)
  166. newFile, err := fc.FileController.Create(c, userID, file, "", app)
  167. if err != nil {
  168. return nil, err
  169. }
  170. return &newFile, nil
  171. }
  172. // Helper function for S3 object copying.
  173. func copyS3Object(s3Client *s3.S3, bucket *string, req *copyS3ObjectReq) error {
  174. copySource := fmt.Sprintf("%s/%s", *bucket, req.SourceS3Object.ObjectKey)
  175. copyInput := &s3.CopyObjectInput{
  176. Bucket: bucket,
  177. CopySource: &copySource,
  178. Key: &req.DestObjectKey,
  179. }
  180. start := time.Now()
  181. _, err := s3Client.CopyObject(copyInput)
  182. elapsed := time.Since(start)
  183. if err != nil {
  184. return fmt.Errorf("failed to copy (%s) from %s to %s: %w", req.SourceS3Object.Type, copySource, req.DestObjectKey, err)
  185. }
  186. logrus.WithField("duration", elapsed).WithField("size", req.SourceS3Object.FileSize).Infof("copied (%s) from %s to %s", req.SourceS3Object.Type, copySource, req.DestObjectKey)
  187. return nil
  188. }