closes #9587
[arvados.git] / services / api / lib / sweep_trashed_collections.rb
1 require 'current_api_client'
2
3 module SweepTrashedCollections
4   extend CurrentApiClient
5
6   def self.sweep_now
7     act_as_system_user do
8       Collection.unscoped.
9         where('delete_at is not null and delete_at < statement_timestamp()').
10         destroy_all
11       Collection.unscoped.
12         where('is_trashed = false and trash_at < statement_timestamp()').
13         update_all('is_trashed = true')
14     end
15   end
16
17   def self.sweep_if_stale
18     return if Rails.configuration.trash_sweep_interval <= 0
19     exp = Rails.configuration.trash_sweep_interval.seconds
20     need = false
21     Rails.cache.fetch('SweepTrashedCollections', expires_in: exp) do
22       need = true
23     end
24     if need
25       Thread.new do
26         Thread.current.abort_on_exception = false
27         begin
28           sweep_now
29         rescue => e
30           Rails.logger.error "#{e.class}: #{e}\n#{e.backtrace.join("\n\t")}"
31         ensure
32           ActiveRecord::Base.connection.close
33         end
34       end
35     end
36   end
37 end