From b1d3c645255db900de0a7ed3b1bd1e033c21cae8 Mon Sep 17 00:00:00 2001
From: Hugo Gameiro <email@hugogameiro.com>
Date: Mon, 28 Oct 2024 13:32:56 +0000
Subject: [PATCH] Fix and improve batch attachment deletion handling when using
 OpenStack Swift (#32637)

---
 app/lib/attachment_batch.rb | 16 ++++++++++++++--
 1 file changed, 14 insertions(+), 2 deletions(-)

diff --git a/app/lib/attachment_batch.rb b/app/lib/attachment_batch.rb
index 32ccb0b13..374abfac4 100644
--- a/app/lib/attachment_batch.rb
+++ b/app/lib/attachment_batch.rb
@@ -77,10 +77,22 @@ class AttachmentBatch
           when :fog
             logger.debug { "Deleting #{attachment.path(style)}" }
 
+            retries = 0
             begin
               attachment.send(:directory).files.new(key: attachment.path(style)).destroy
-            rescue Fog::Storage::OpenStack::NotFound
-              # Ignore failure to delete a file that has already been deleted
+            rescue Fog::OpenStack::Storage::NotFound
+              logger.debug "Will ignore because file is not found #{attachment.path(style)}"
+            rescue => e
+              retries += 1
+
+              if retries < MAX_RETRY
+                logger.debug "Retry #{retries}/#{MAX_RETRY} after #{e.message}"
+                sleep 2**retries
+                retry
+              else
+                logger.error "Batch deletion from fog failed after #{e.message}"
+                raise e
+              end
             end
           when :azure
             logger.debug { "Deleting #{attachment.path(style)}" }