Class: Familia::Connection::Scope

Inherits:
Object
  • Object
show all
Defined in:
lib/familia/connection/scope.rb

Overview

A fiber-owned set of database connections held open for the duration of a #with_connection_scope block.

Without a connection provider, every dbclient lookup that reaches CreateConnectionHandler returns a new Redis client that nobody closes. A scope gives those lookups an owner: while the block runs, ScopedConnectionHandler resolves each lookup to the one client the scope holds for that connection configuration, creating it on first use, and #release! closes every client the scope created when the block exits, on a normal return and on an exception alike.

Ownership

A scope belongs to the fiber that opened it. A new fiber starts with a copy of the opener's fiber storage (Ruby's documentation for Fiber.new: "If the storage is unspecified, the default is to inherit a copy of the storage from the current fiber."), and a new thread's root fiber does the same on Ruby 3.3 (observed; the Thread documentation does not state it). A thread or fiber spawned inside the block therefore sees the same Fiber[FIBER_KEY] value, but Scope.current and #active? compare the owner with Fiber.current, so those children never share the owner's clients and resolve connections as if no scope were open. They open their own scope when they need one.

Identity of a connection

Clients are keyed by the connection parameters the URI resolves to (URI#conf: host, port, database, TLS, credentials, timeout). Two lookups that differ only in how the URI is spelled, such as redis://host:6379 and redis://host:6379/0, share one client; a different logical database or server gets its own.

Nesting and operation modes

Opening a scope inside an active scope of the same fiber joins it: nothing new is acquired and nothing is released until the outer block exits. An explicit #release! from anywhere inside the block, a joined inner block included, releases the scope for the rest of the outer block: plain lookups after it resolve as if no scope were open, and a with_connection_scope opened after it opens a new scope of its own, closed when that inner block exits. Transactions and pipelines opened inside a scope run on the scope's client for their URI, because the fiber-local transaction and pipeline handlers take precedence while a block is open and then hand back to the scope.

Reset

Familia.reconnect! and the other calls that bump Familia.middleware_version do not reach into other fibers. A scope notices the new version on its next lookup and retires the clients it created under the old version: new lookups get fresh clients, while the retired ones stay open, so a handle the block already holds and a WATCH or MULTI in flight on it keep their connection. Retired clients are closed with the rest when the scope is released. Closing them at once would let the Redis object reconnect silently on its next command, dropping the WATCH.

Limits

  • A client reference kept past the block reconnects on its next command, as an unowned connection that nothing closes.
  • Enumerator#next and #peek run the enumerator in a fiber of their own, so lookups made there are not the owner's and resolve as if no scope were open.
  • The scope's client for a URI is shared by every lookup for that URI in the block, so per-connection state set on it (SELECT, CLIENT SETNAME, SUBSCRIBE) is visible to the next lookup.

WATCH windows

EXEC, DISCARD and UNWATCH on a connection clear every key that connection watches. While a WATCH-guarded transaction holds a scope client between its WATCH and its EXEC (Scope.watching marks it), the scope does not hand that client to other lookups: they get another client for the same URI, which the scope also holds and closes. So a transaction run from an atomic_write +pre_check+ cannot clear the outer WATCH by committing on the same connection. The watched MULTI itself runs on the connection it was given, not through a lookup.

Constant Summary collapse

FIBER_KEY =

Fiber storage key that holds the scope a fiber opened.

:familia_connection_scope

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize ⇒ Scope

Returns a new instance of Scope.



149
150
151
152
153
154
155
156
# File 'lib/familia/connection/scope.rb', line 149

def initialize
  @owner = Fiber.current
  @middleware_version = Familia.middleware_version
  @clients = {}
  @retired = []
  @watching = {}.compare_by_identity
  @released = false
end

Instance Attribute Details

#middleware_version ⇒ Integer (readonly)

Returns the Familia.middleware_version the held clients were created under.

Returns:

  • (Integer) —

    the Familia.middleware_version the held clients were created under



147
148
149
# File 'lib/familia/connection/scope.rb', line 147

def middleware_version
  @middleware_version
end

#owner ⇒ Fiber (readonly)

Returns the fiber that opened this scope.

Returns:

  • (Fiber) —

    the fiber that opened this scope



144
145
146
# File 'lib/familia/connection/scope.rb', line 144

def owner
  @owner
end

Class Method Details

.current ⇒ Scope?

The scope the current fiber opened and has not released yet.

Returns nil outside a scope, after #release!, and in a thread or fiber that inherited another fiber's scope through fiber storage.

Returns:



99
100
101
102
# File 'lib/familia/connection/scope.rb', line 99

def current
  scope = Fiber[FIBER_KEY]
  scope if scope&.active?
end

.open { ... } ⇒ Object

Runs the block inside a scope owned by the current fiber.

Joins the active scope when one is open (reentrant). Otherwise opens a new scope, restores the previous fiber storage value and releases the scope when the block exits, whether it returns or raises.

Yields:

  • []

Returns:

  • (Object) —

    the block's return value



113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/familia/connection/scope.rb', line 113

def open
  return yield if current

  scope = new
  previous = Fiber[FIBER_KEY]
  Fiber[FIBER_KEY] = scope
  begin
    yield
  ensure
    Fiber[FIBER_KEY] = previous
    scope.release!
  end
end

.watching(conn) { ... } ⇒ Object

Runs the block with +conn+ marked as holding a WATCH in the current fiber's scope, so lookups made in the block do not get +conn+ (see "WATCH windows" above). Without an open scope it only yields.

Parameters:

  • conn (Redis) —

    the connection the WATCH was or will be sent on

Yields:

  • []

Returns:

  • (Object) —

    the block's return value



135
136
137
138
139
140
# File 'lib/familia/connection/scope.rb', line 135

def watching(conn, &)
  scope = current
  return yield unless scope

  scope.hold_for_watch(conn, &)
end

Instance Method Details

#active? ⇒ Boolean

Returns true while the owning fiber can use this scope.

Returns:

  • (Boolean) —

    true while the owning fiber can use this scope



169
170
171
# File 'lib/familia/connection/scope.rb', line 169

def active?
  !@released && owned_by_current_fiber?
end

#client(uri) ⇒ Redis

Returns the client this scope holds for uri, creating it on first use with Familia.create_dbclient. While that client holds a WATCH (see watching), returns another client for the same URI, held and reused the same way.

Parameters:

  • uri (URI) —

    a normalized URI (see Familia.normalize_uri)

Returns:

  • (Redis)

Raises:

  • (Familia::Problem) —

    when the scope has been released or belongs to another fiber



182
183
184
185
186
187
188
189
# File 'lib/familia/connection/scope.rb', line 182

def client(uri)
  raise Familia::Problem, 'Connection scope has been released' if @released
  raise Familia::Problem, 'Connection scope belongs to another fiber' unless owned_by_current_fiber?

  retire_stale_clients!
  pool = (@clients[uri.conf] ||= [])
  pool.find { |held| !@watching.key?(held) } || (pool << acquire(uri)).last
end

#clients ⇒ Array<Redis>

Returns every client the scope holds open, retired ones first, then the current ones grouped by connection configuration (URI#conf) in the order each was first used, each group in acquisition order.

Returns:

  • (Array<Redis>) —

    every client the scope holds open, retired ones first, then the current ones grouped by connection configuration (URI#conf) in the order each was first used, each group in acquisition order



211
212
213
# File 'lib/familia/connection/scope.rb', line 211

def clients
  (@retired + pooled_clients).freeze
end

#hold_for_watch(conn) { ... } ⇒ Object

Marks +conn+ as holding a WATCH for the duration of the block. Called through watching.

Parameters:

  • conn (Redis)

Yields:

  • []

Returns:

  • (Object) —

    the block's return value



197
198
199
200
201
202
203
204
205
# File 'lib/familia/connection/scope.rb', line 197

def hold_for_watch(conn)
  @watching[conn] = @watching.fetch(conn, 0) + 1
  begin
    yield
  ensure
    remaining = @watching[conn] - 1
    remaining.zero? ? @watching.delete(conn) : @watching[conn] = remaining
  end
end

#inspect ⇒ String

Omits the held clients' connection parameters, which can carry a password.

Returns:

  • (String)


238
239
240
# File 'lib/familia/connection/scope.rb', line 238

def inspect
  "#<#{self.class.name} clients=#{size} released=#{@released}>"
end

#owned_by_current_fiber? ⇒ Boolean

Returns whether the current fiber is the one that opened this scope.

Returns:

  • (Boolean) —

    whether the current fiber is the one that opened this scope



159
160
161
# File 'lib/familia/connection/scope.rb', line 159

def owned_by_current_fiber?
  @owner.equal?(Fiber.current)
end

#release! ⇒ nil

Closes every client the scope holds and marks the scope released. Further #client calls raise. Safe to call more than once; only the owning fiber may call it.

Returns:

  • (nil)

Raises:



226
227
228
229
230
231
232
# File 'lib/familia/connection/scope.rb', line 226

def release!
  raise Familia::Problem, 'Connection scope belongs to another fiber' unless owned_by_current_fiber?

  @released = true
  close_all!
  nil
end

#released? ⇒ Boolean

Returns whether #release! has run.

Returns:



164
165
166
# File 'lib/familia/connection/scope.rb', line 164

def released?
  @released
end

#size ⇒ Integer

Returns number of clients the scope holds open.

Returns:

  • (Integer) —

    number of clients the scope holds open



216
217
218
# File 'lib/familia/connection/scope.rb', line 216

def size
  @retired.size + @clients.each_value.sum(&:size)
end