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
STALE_SECONDS =
300

Class Method Summary collapse

Class Method Details

.check_publish(tenant_id, message_size: 0) ⇒ Object



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
52
53
54
55
56
57
58
# File 'lib/legion/transport/tenant_quota.rb', line 22

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

  tenant_mutex(tenant_id).synchronize do
    @counters[tenant_id] ||= { window: now, count: 0, bytes: 0, updated_at: now }
    entry = @counters[tenant_id]
    if entry[:window] != now
      entry[:window]     = now
      entry[:count]      = 0
      entry[:bytes]      = 0
      entry[:updated_at] = now
    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
    entry[:updated_at]  = now
  end

  sweep_stale!
  true
end

.enabled?Boolean

Returns:

  • (Boolean)


60
61
62
# File 'lib/legion/transport/tenant_quota.rb', line 60

def enabled?
  TenantTopology.enabled?
end

.reset!Object



64
65
66
67
68
69
# File 'lib/legion/transport/tenant_quota.rb', line 64

def reset!
  @registry_mutex.synchronize do
    @counters.clear
    @mutexes.clear
  end
end