15061: Add missing file
[arvados.git] / services / api / lib / refresh_permission_view.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 PERMISSION_VIEW = "materialized_permission_view"
6
7 def do_refresh_permission_view
8   ActiveRecord::Base.transaction do
9     ActiveRecord::Base.connection.execute("LOCK TABLE permission_refresh_lock")
10     ActiveRecord::Base.connection.execute("REFRESH MATERIALIZED VIEW #{PERMISSION_VIEW}")
11   end
12 end
13
14 def refresh_permission_view(async=false)
15   if async and Rails.configuration.API.AsyncPermissionsUpdateInterval > 0
16     exp = Rails.configuration.API.AsyncPermissionsUpdateInterval.seconds
17     need = false
18     Rails.cache.fetch('AsyncRefreshPermissionView', expires_in: exp) do
19       need = true
20     end
21     if need
22       # Schedule a new permission update and return immediately
23       Thread.new do
24         Thread.current.abort_on_exception = false
25         begin
26           sleep(exp)
27           Rails.cache.delete('AsyncRefreshPermissionView')
28           do_refresh_permission_view
29         rescue => e
30           Rails.logger.error "Updating permission view: #{e}\n#{e.backtrace.join("\n\t")}"
31         ensure
32           ActiveRecord::Base.connection.close
33         end
34       end
35       true
36     end
37   else
38     do_refresh_permission_view
39   end
40 end