dataDownloadAdminService.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package services
  2. import (
  3. "context"
  4. "fmt"
  5. "time"
  6. "fwh-toolbox-server/cache"
  7. minioRepo "fwh-toolbox-server/repositories/minio"
  8. mongoRepo "fwh-toolbox-server/repositories/mongo"
  9. pgsqlRepo "fwh-toolbox-server/repositories/pgsql"
  10. )
  11. func DeleteDataDownloadDocument(ctx context.Context, documentID string, force bool) error {
  12. references, err := mongoRepo.CountDataDownloadDocumentReferences(ctx, documentID)
  13. if err != nil {
  14. return err
  15. }
  16. if references > 0 && !force {
  17. return fmt.Errorf("document is referenced by %d task(s); use force=true to delete", references)
  18. }
  19. requestLock, ok, err := cache.TryLock(ctx, dataDownloadRequestKey(documentID), 5*time.Minute)
  20. if err != nil {
  21. return err
  22. }
  23. if !ok {
  24. return fmt.Errorf("document has an active file request")
  25. }
  26. defer requestLock.SafeRelease(context.Background())
  27. lock, err := cache.Lock(ctx, "data-download:content:"+documentID, 5*time.Minute, 250*time.Millisecond, 5*time.Second)
  28. if err != nil {
  29. return fmt.Errorf("document has an active reader or writer: %w", err)
  30. }
  31. defer lock.SafeRelease(context.Background())
  32. document, err := mongoRepo.GetDataDownloadDocument(ctx, documentID)
  33. if err != nil {
  34. return err
  35. }
  36. artifacts, err := mongoRepo.ListDataDownloadArtifacts(ctx, documentID)
  37. if err != nil {
  38. return err
  39. }
  40. entries, err := mongoRepo.ListDataDownloadFaultRecordEntries(ctx, documentID)
  41. if err != nil {
  42. return err
  43. }
  44. if document.BinaryObjectKey != "" {
  45. if err := minioRepo.Delete(ctx, document.BinaryObjectKey); err != nil {
  46. return err
  47. }
  48. }
  49. for i := range artifacts {
  50. if err := minioRepo.Delete(ctx, artifacts[i].ObjectKey); err != nil {
  51. return err
  52. }
  53. }
  54. for i := range entries {
  55. if err := minioRepo.Delete(ctx, entries[i].ObjectKey); err != nil {
  56. return err
  57. }
  58. }
  59. if err := pgsqlRepo.DeleteDataDownloadContent(documentID); err != nil {
  60. return err
  61. }
  62. return mongoRepo.DeleteDataDownloadDocumentMetadata(ctx, documentID)
  63. }