Class: Apartment::PoolManager

Inherits:
Object
  • Object
show all
Defined in:
lib/apartment/pool_manager.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializePoolManager

Returns a new instance of PoolManager.



11
12
13
14
15
16
# File 'lib/apartment/pool_manager.rb', line 11

def initialize
  @pools = Concurrent::Map.new
  @timestamps = Concurrent::Map.new
  @create_mutex = Mutex.new
  @admission_controller = nil
end

Instance Attribute Details

#admission_controllerObject

Set by Apartment.configure to the PoolReaper when max_total_connections is configured. nil (no cap) keeps the lock-free compute_if_absent fast path.



9
10
11
# File 'lib/apartment/pool_manager.rb', line 9

def admission_controller
  @admission_controller
end

Instance Method Details

#clearObject

Disconnect all pools before clearing to prevent connection leaks. Each pool's disconnect! is individually rescued so one broken pool doesn't prevent cleanup of others.



147
148
149
150
151
152
153
154
155
# File 'lib/apartment/pool_manager.rb', line 147

def clear
  @pools.each_pair do |key, pool|
    pool.disconnect! if pool.respond_to?(:disconnect!)
  rescue StandardError => e
    warn "[Apartment::PoolManager] Failed to disconnect pool '#{key}': #{e.class}: #{e.message}"
  end
  @pools.clear
  @timestamps.clear
end

#each_pairObject

Yields each tracked pool as [tenant_key, pool]. Snapshot semantics follow Concurrent::Map#each_pair: keys observed during iteration are those present at the time the iterator visits them. Read-only; do not mutate the manager from inside the block.



140
141
142
# File 'lib/apartment/pool_manager.rb', line 140

def each_pair(&)
  @pools.each_pair(&)
end

#evict_by_role(role) ⇒ Object



90
91
92
93
94
95
96
97
98
99
100
# File 'lib/apartment/pool_manager.rb', line 90

def evict_by_role(role)
  suffix = ":#{role}"
  removed = []
  @pools.each_key do |key|
    next unless key.end_with?(suffix)

    pool = remove(key)
    removed << [key, pool] if pool
  end
  removed
end

#fetch_or_create(tenant_key) ⇒ Object

Fetch an existing pool or create one via the block. Timestamp is updated after pool creation to avoid orphaned timestamps if the block raises. When an admission controller is wired (a cap is configured), cold creates go through the bounded path so the pool count cannot exceed max_total.



22
23
24
25
26
# File 'lib/apartment/pool_manager.rb', line 22

def fetch_or_create(tenant_key, &)
  return fetch_or_admit(tenant_key, &) if @admission_controller

  touch_and_return(tenant_key, @pools.compute_if_absent(tenant_key, &))
end

#get(tenant_key) ⇒ Object



28
29
30
31
32
# File 'lib/apartment/pool_manager.rb', line 28

def get(tenant_key)
  pool = @pools[tenant_key]
  touch(tenant_key) if pool
  pool
end

#idle_tenants(timeout:) ⇒ Object



115
116
117
118
# File 'lib/apartment/pool_manager.rb', line 115

def idle_tenants(timeout:)
  cutoff = monotonic_now - timeout
  @timestamps.each_pair.filter_map { |key, ts| key if ts < cutoff }
end

#lru_tenants(count:) ⇒ Object



120
121
122
123
124
125
# File 'lib/apartment/pool_manager.rb', line 120

def lru_tenants(count:)
  @timestamps.each_pair
    .sort_by { |_, ts| ts }
    .first(count)
    .map(&:first)
end

#peek(tenant_key) ⇒ Object

Read a pool without updating its idle timestamp. PoolReaper uses this to inspect an eviction candidate; get would reset the very idleness the reaper is measuring.



37
38
39
# File 'lib/apartment/pool_manager.rb', line 37

def peek(tenant_key)
  @pools[tenant_key]
end

#remove(tenant_key) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Delete pool first, then timestamp. This ordering prevents a concurrent #get from orphaning a timestamp (get checks @pools, skips touch if absent).

Forgetting a pool here is only HALF of discarding it — the pool stays registered in AR's ConnectionHandler, leaking the registration and a live backend if the tenant is never re-accessed. Callers outside the gem want Apartment.deregister_shard (one pool) or Apartment.reset_tenant_pools! (all). These mutators also bypass PoolReaper's in-use guard: they will drop a pool with a checked-out connection or an open transaction. See docs/designs/out-of-band-tenant-ddl.md.

ACCEPTED LIMITATION, the check-then-act race. A caller that guards a discard with Apartment.pool_in_use? — AbstractAdapter#discard_ddl_role_pool is the one in the gem — reads "not in use" and then calls Apartment.deregister_shard, and another thread can lease a connection from that pool in between. The guard narrows the window; it does not close it.

It cannot be closed here. Leasing does not go through this map: a thread that already holds the pool object leases from the object directly, so no lock this class could take would serialize the two. Closing it would need a lock inside ActiveRecord's pool, which is not ours to add.

Two things bound the exposure. Migrator leases eagerly rather than lazily, which its own comment explains as closing a capture->lease window — so the pool a migration will use is already in use by the time a concurrent discard could look at it. And #evict_by_role, which Migrator calls at the end of a run, has no in-use check at all: the race class is pre-existing and strictly wider there, so a guarded discard is an improvement on the surrounding code rather than a new hazard.



70
71
72
73
74
# File 'lib/apartment/pool_manager.rb', line 70

def remove(tenant_key)
  pool = @pools.delete(tenant_key)
  @timestamps.delete(tenant_key)
  pool
end

#remove_tenant(tenant) ⇒ Object



77
78
79
80
81
82
83
84
85
86
87
# File 'lib/apartment/pool_manager.rb', line 77

def remove_tenant(tenant)
  prefix = "#{tenant}:"
  removed = []
  @pools.each_key do |key|
    next unless key.start_with?(prefix)

    pool = remove(key)
    removed << [key, pool] if pool
  end
  removed
end

#statsObject

Basic stats. Full observability (per-tenant breakdown, connection counts, eviction counters) deferred to Phase 3.



129
130
131
132
133
134
# File 'lib/apartment/pool_manager.rb', line 129

def stats
  {
    total_pools: @pools.size,
    tenants: @pools.keys,
  }
end

#stats_for(tenant_key) ⇒ Object

Returns stats for a tenant pool. Follows ActiveRecord's convention of exposing computed durations (seconds_idle) rather than raw monotonic timestamps, which are meaningless outside the process.



109
110
111
112
113
# File 'lib/apartment/pool_manager.rb', line 109

def stats_for(tenant_key)
  return nil unless tracked?(tenant_key)

  { seconds_idle: monotonic_now - @timestamps[tenant_key] }
end

#tracked?(tenant_key) ⇒ Boolean

Returns:

  • (Boolean)


102
103
104
# File 'lib/apartment/pool_manager.rb', line 102

def tracked?(tenant_key)
  @pools.key?(tenant_key)
end