Module: Legion::Transport::TenantQuota

Extended by:
Logging::Helper
Defined in:
lib/legion/transport/tenant_quota.rb

Defined Under Namespace

Classes: QuotaExceededError

Constant Summary collapse

WINDOW_SECONDS =
1

Class Method Summary collapse

Class Method Details

.check_publish(tenant_id, message_size: 0) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/legion/transport/tenant_quota.rb', line 20

def check_publish(tenant_id, message_size: 0)
  return true unless enabled?

  msg_limit  = rate_limit(tenant_id)
  size_limit = byte_limit(tenant_id)
  return true if msg_limit.nil? && size_limit.nil?

  now = current_window
  @mutex.synchronize do
    @counters[tenant_id] ||= { window: now, count: 0, bytes: 0 }
    entry = @counters[tenant_id]
    if entry[:window] != now
      entry[:window] = now
      entry[:count] = 0
      entry[:bytes] = 0
    end

    if msg_limit && entry[:count] >= msg_limit
      log.warn "Tenant #{tenant_id} exceeded message rate quota (#{msg_limit} msg/s)"
      raise QuotaExceededError, "Tenant #{tenant_id} exceeded message rate quota (#{msg_limit} msg/s)"
    end

    if size_limit && (entry[:bytes] + message_size) > size_limit
      log.warn "Tenant #{tenant_id} exceeded byte rate quota (#{size_limit} bytes/s)"
      raise QuotaExceededError, "Tenant #{tenant_id} exceeded byte rate quota (#{size_limit} bytes/s)"
    end

    entry[:count] += 1
    entry[:bytes] += message_size
  end
  true
end

.enabled?Boolean

Returns:

  • (Boolean)


53
54
55
# File 'lib/legion/transport/tenant_quota.rb', line 53

def enabled?
  TenantTopology.enabled?
end

.reset!Object



57
58
59
# File 'lib/legion/transport/tenant_quota.rb', line 57

def reset!
  @mutex.synchronize { @counters.clear }
end