Class: BugBunny::Session Private

Inherits:
Object
  • Object
show all
Includes:
Observability
Defined in:
lib/bug_bunny/session.rb

Overview

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

Clase interna que encapsula una unidad de trabajo sobre una conexión RabbitMQ.

Implementa la lógica de “Configuración en Cascada” para Exchanges y Colas, gestionando el ciclo de vida de un ‘Bunny::Channel` con resiliencia y carga perezosa.

Opciones por Defecto (Nivel 1: Gema) collapse

DEFAULT_EXCHANGE_OPTIONS =

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

Opciones predeterminadas de la gema para Exchanges.

{ durable: false, auto_delete: false }.freeze
DEFAULT_QUEUE_OPTIONS =

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

Opciones predeterminadas de la gema para Colas.

{ exclusive: false, durable: false, auto_delete: true }.freeze

Constants included from Observability

Observability::SENSITIVE_KEYS

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Observability

sensitive_key?

Constructor Details

#initialize(connection, publisher_confirms: true) ⇒ Session

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.

Inicializa una nueva sesión sin abrir canales todavía.

Parameters:

  • connection (Bunny::Session)

    Una conexión (puede estar abierta o cerrada temporalmente).

  • publisher_confirms (Boolean) (defaults to: true)

    Si es ‘true`, el canal se abre en modo Publisher Confirms. Activar solo en sesiones de Producer. En sesiones de Consumer genera overhead innecesario ya que los replies RPC son fire-and-forget desde la perspectiva del servidor.



32
33
34
35
36
37
38
39
# File 'lib/bug_bunny/session.rb', line 32

def initialize(connection, publisher_confirms: true)
  @connection = connection
  @publisher_confirms = publisher_confirms
  @channel = nil
  @channel_mutex = Mutex.new
  @logger = BugBunny.configuration.logger
  @configured_returns = {}
end

Instance Attribute Details

#connectionBunny::Session (readonly)

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.

Returns La conexión TCP subyacente.

Returns:

  • (Bunny::Session)

    La conexión TCP subyacente.



24
25
26
# File 'lib/bug_bunny/session.rb', line 24

def connection
  @connection
end

Instance Method Details

#channelBunny::Channel

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.

Obtiene el canal actual o crea uno nuevo si es necesario.

Este método es el punto central de la robustez. Verifica la salud de la conexión y del canal antes de devolverlo.

Returns:

  • (Bunny::Channel)

    Un canal abierto y configurado.

Raises:



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/bug_bunny/session.rb', line 48

def channel
  # Fast path: canal abierto, sin adquirir el mutex.
  return @channel if @channel&.open?

  # Slow path: adquirimos el mutex y verificamos de nuevo (double-checked locking).
  # Evita que múltiples threads creen canales simultáneamente cuando el canal cae.
  @channel_mutex.synchronize do
    return @channel if @channel&.open?

    ensure_connection!
    create_channel!
  end

  @channel
end

#closevoid

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.

This method returns an undefined value.

Cierra el canal asociado a esta sesión de forma segura.



110
111
112
113
114
115
116
# File 'lib/bug_bunny/session.rb', line 110

def close
  @channel_mutex.synchronize do
    @channel&.close if @channel&.open?
    @channel = nil
    @configured_returns.clear
  end
end

#exchange(name: nil, type: 'direct', opts: {}) ⇒ Bunny::Exchange

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.

Factory method para declarar o recuperar un Exchange aplicando la cascada de configuración.

Jerarquía de fusión:

  1. Defaults de la gema (‘DEFAULT_EXCHANGE_OPTIONS`)

  2. Configuración global (‘BugBunny.configuration.exchange_options`)

  3. Opciones específicas pasadas como argumento (‘opts`)

Parameters:

  • name (String, nil) (defaults to: nil)

    Nombre del exchange.

  • type (String, Symbol) (defaults to: 'direct')

    Tipo de exchange (‘direct’, ‘topic’, ‘fanout’).

  • opts (Hash) (defaults to: {})

    Opciones específicas de infraestructura para este intercambio.

Returns:

  • (Bunny::Exchange)

    El objeto exchange de Bunny configurado.



75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/bug_bunny/session.rb', line 75

def exchange(name: nil, type: 'direct', opts: {})
  return channel.default_exchange if name.nil? || name.empty?

  # Aplicación de la lógica de fusión en cascada
  merged_opts = DEFAULT_EXCHANGE_OPTIONS
                .merge(BugBunny.configuration.exchange_options || {})
                .merge(opts)

  # public_send permite llamar a :topic, :direct, etc. dinámicamente según el tipo
  x = channel.public_send(type.to_s, name.to_s, merged_opts)
  register_on_return!(x) if @publisher_confirms
  x
end

#queue(name, opts = {}) ⇒ Bunny::Queue

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.

Factory method para declarar o recuperar una Cola aplicando la cascada de configuración.

Jerarquía de fusión:

  1. Defaults de la gema (‘DEFAULT_QUEUE_OPTIONS`)

  2. Configuración global (‘BugBunny.configuration.queue_options`)

  3. Opciones específicas pasadas como argumento (‘opts`)

Parameters:

  • name (String)

    Nombre de la cola.

  • opts (Hash) (defaults to: {})

    Opciones específicas de infraestructura para esta cola.

Returns:

  • (Bunny::Queue)

    El objeto cola de Bunny configurado.



99
100
101
102
103
104
105
106
# File 'lib/bug_bunny/session.rb', line 99

def queue(name, opts = {})
  # Aplicación de la lógica de fusión en cascada
  merged_opts = DEFAULT_QUEUE_OPTIONS
                .merge(BugBunny.configuration.queue_options || {})
                .merge(opts)

  channel.queue(name.to_s, merged_opts)
end