Module: Legion::Data::Rls

Extended by:
Logging::Helper
Defined in:
lib/legion/data/rls.rb

Constant Summary collapse

RLS_TABLES =
%i[
  tasks digital_workers audit_log memory_traces extensions
  functions runners nodes settings value_metrics
].freeze

Class Method Summary collapse

Methods included from Logging::Helper

handle_exception

Class Method Details

.assign_tenant(tenant_id) ⇒ Object



26
27
28
29
30
31
32
# File 'lib/legion/data/rls.rb', line 26

def assign_tenant(tenant_id)
  return unless rls_enabled?

  Legion::Data.connection.run(
    Sequel.lit('SET app.current_tenant = ?', tenant_id.to_s)
  )
end

.current_tenantObject



34
35
36
37
38
39
40
41
# File 'lib/legion/data/rls.rb', line 34

def current_tenant
  return nil unless rls_enabled?

  Legion::Data.connection.fetch('SHOW app.current_tenant').first&.values&.first
rescue Sequel::DatabaseError => e
  handle_exception(e, level: :warn, handled: true, operation: :current_tenant)
  nil
end

.reset_tenantObject



43
44
45
46
47
# File 'lib/legion/data/rls.rb', line 43

def reset_tenant
  return unless rls_enabled?

  Legion::Data.connection.run('RESET app.current_tenant')
end

.rls_enabled?Boolean

Returns:

  • (Boolean)


17
18
19
20
21
22
23
24
# File 'lib/legion/data/rls.rb', line 17

def rls_enabled?
  return false unless Legion::Settings[:data][:connected]

  Legion::Data.connection.adapter_scheme == :postgres
rescue StandardError => e
  handle_exception(e, level: :warn, handled: true, operation: :rls_enabled)
  false
end

.with_tenant(tenant_id) ⇒ Object



49
50
51
52
53
54
55
# File 'lib/legion/data/rls.rb', line 49

def with_tenant(tenant_id)
  previous = current_tenant
  assign_tenant(tenant_id)
  yield
ensure
  previous ? assign_tenant(previous) : reset_tenant
end