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