bug_bunny 3.1.1 → 3.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: fc4ecbe75edaf8811acfe2929b74fb4aa98cb65c61d74aca4f5a1320b40a94b8
4
- data.tar.gz: c3ed5b1e5a773ab8d80fbecc1b96d4a04a62dd1f0b1b5414a2275f497fcde9ee
3
+ metadata.gz: 297dacbda238ba5789ff56e5869302a851d15011cd43cb873b9eb3ece129c797
4
+ data.tar.gz: 0cc109f779f574e29f6dd96d0b41e3b956397db4eca2e0476d39ab6d5e96e877
5
5
  SHA512:
6
- metadata.gz: ee79317a849f3b62e25791f8c3e2bc73e55e6531c697f04ef7896ff438bfac817c5efef15f170769fc3c441a212776f6cec90d0a02b7a52764208512862df1af
7
- data.tar.gz: a4e7c0a8a5661e285978376b12c13977fcb9c522a4a19b8c15177d81917084dde7b595baa30c8ef142547d2e35a5983abec7ccaf2a8b6a52e044e51b8196889f
6
+ metadata.gz: 8b7850f2ca72f08f76823a0cf8a1b8845ab9ec831b5e26ba994bffcf88e41d5163351679690a0fd993aea81f9dbdc5344c2558ac28a0daffe98ae5f8e83acdf6
7
+ data.tar.gz: 834d477e56ccf027eea1009813b8e38536d1ea0f49fd40f95070f9db314a3b29550613b2fa4bdda3fc4562d994d404f7123ca6d526ac3b886e2f509d046506ec
data/CHANGELOG.md CHANGED
@@ -1,4 +1,18 @@
1
1
  # Changelog
2
+ ## [3.1.2] - 2026-02-19
3
+
4
+ ### 🐛 Bug Fixes
5
+ * **Controller Callback Inheritance:** Fixed a critical issue where `before_action`, `around_action`, and `rescue_from` definitions in a parent class (like `ApplicationController`) were not being inherited by child controllers. Migrated internal storage to `class_attribute` with deep duplication to ensure isolated, thread-safe inheritance without mutating the parent class.
6
+ * **Gemspec Hygiene:** Updated the `spec.description` to resolve RubyGems identity warnings and added explicit minimum version boundaries for standard dependencies (e.g., `json >= 2.0`).
7
+
8
+ ### 🌟 Observability & DX (Developer Experience)
9
+ * **Structured Remote Errors:** `BugBunny::Resource` now intelligently formats the body of remote errors. When raising a `ClientError` (4xx) or `InternalServerError` (500), it extracts the specific error message (e.g., `"Internal Server Error - undefined method 'foo'"`) or falls back to a readable JSON string. This drastically improves the legibility of remote stack traces in monitoring tools like Sentry or Datadog.
10
+ * **Infrastructure Logging:** The `Consumer` and `Producer` now calculate the final resolved cascade options (`exchange_opts`, `queue_opts`) and explicitly log them during worker startup and message publishing. This provides absolute transparency into what configurations are actually reaching RabbitMQ.
11
+ * **Consumer Cascade Options:** Added the `exchange_opts:` parameter to `Consumer.subscribe` to fully support Level 3 (On-the-fly) infrastructure configuration for manual worker instantiations.
12
+
13
+ ### 📖 Documentation
14
+ * **Built-in Middlewares:** Added comprehensive documentation to the README explaining how to inject and utilize the provided `RaiseError` and `JsonResponse` middlewares when using the manual `BugBunny::Client`.
15
+
2
16
  ## [3.1.1] - 2026-02-19
3
17
 
4
18
  ### 🚀 Features
data/README.md CHANGED
@@ -185,7 +185,27 @@ Manager::Service.with(
185
185
  ```
186
186
 
187
187
  ### 4. Client Middleware (Interceptores)
188
- Intercepta peticiones antes de salir hacia RabbitMQ. Ideal para inyectar Auth o Headers.
188
+ Intercepta peticiones de ida y respuestas de vuelta en la arquitectura del cliente.
189
+
190
+ **Middlewares Incluidos (Built-ins)**
191
+ Si usas `BugBunny::Resource` el manejo de JSON y errores ya está integrado. Pero si utilizas el cliente manual (`BugBunny::Client`), puedes inyectar los middlewares incluidos para no tener que parsear respuestas manualmente:
192
+
193
+ * `BugBunny::Middleware::JsonResponse`: Parsea automáticamente el cuerpo de la respuesta de JSON a un Hash de Ruby.
194
+ * `BugBunny::Middleware::RaiseError`: Evalúa el código de estado (`status`) de la respuesta y lanza excepciones nativas (`BugBunny::NotFound`, `BugBunny::UnprocessableEntity`, `BugBunny::InternalServerError`, etc.).
195
+
196
+ ```ruby
197
+ # Uso con el cliente manual
198
+ client = BugBunny::Client.new(pool: BUG_BUNNY_POOL) do |stack|
199
+ stack.use BugBunny::Middleware::RaiseError
200
+ stack.use BugBunny::Middleware::JsonResponse
201
+ end
202
+
203
+ # Ahora el cliente devolverá Hashes y lanzará errores si el worker falla
204
+ response = client.request('users/1', method: :get)
205
+ ```
206
+
207
+ **Middlewares Personalizados**
208
+ Ideales para inyectar Auth o Headers de trazabilidad en todos los requests de un Recurso.
189
209
 
190
210
  ```ruby
191
211
  class Manager::Service < BugBunny::Resource
@@ -53,15 +53,27 @@ module BugBunny
53
53
  # @param exchange_name [String] Nombre del exchange al cual enlazar la cola.
54
54
  # @param routing_key [String] Patrón de enrutamiento (ej: 'users.*').
55
55
  # @param exchange_type [String] Tipo de exchange ('direct', 'topic', 'fanout').
56
+ # @param exchange_opts [Hash] Opciones adicionales para el exchange (durable, auto_delete).
56
57
  # @param queue_opts [Hash] Opciones adicionales para la cola (durable, auto_delete).
57
58
  # @param block [Boolean] Si es `true`, bloquea el hilo actual (loop infinito).
58
59
  # @return [void]
59
- def subscribe(queue_name:, exchange_name:, routing_key:, exchange_type: 'direct', queue_opts: {}, block: true)
60
- x = session.exchange(name: exchange_name, type: exchange_type)
60
+ def subscribe(queue_name:, exchange_name:, routing_key:, exchange_type: 'direct', exchange_opts: {}, queue_opts: {}, block: true)
61
+ # Declaración de Infraestructura
62
+ x = session.exchange(name: exchange_name, type: exchange_type, opts: exchange_opts)
61
63
  q = session.queue(queue_name, queue_opts)
62
64
  q.bind(x, routing_key: routing_key)
63
65
 
64
- BugBunny.configuration.logger.info("[BugBunny::Consumer] 🎧 Listening on '#{queue_name}' | Exchange: '#{exchange_name}' | Routing Key: '#{routing_key}'")
66
+ # 📊 LOGGING DE OBSERVABILIDAD: Calculamos las opciones finales para mostrarlas en consola
67
+ final_x_opts = BugBunny::Session::DEFAULT_EXCHANGE_OPTIONS
68
+ .merge(BugBunny.configuration.exchange_options || {})
69
+ .merge(exchange_opts || {})
70
+ final_q_opts = BugBunny::Session::DEFAULT_QUEUE_OPTIONS
71
+ .merge(BugBunny.configuration.queue_options || {})
72
+ .merge(queue_opts || {})
73
+
74
+ BugBunny.configuration.logger.info("[BugBunny::Consumer] 🎧 Listening on '#{queue_name}' (Opts: #{final_q_opts})")
75
+ BugBunny.configuration.logger.info("[BugBunny::Consumer] 🔀 Bounded to Exchange '#{exchange_name}' (#{exchange_type}) | Opts: #{final_x_opts} | RK: '#{routing_key}'")
76
+
65
77
  start_health_check(queue_name)
66
78
 
67
79
  q.subscribe(manual_ack: true, block: block) do |delivery_info, properties, body|
@@ -7,99 +7,146 @@ require 'active_support/core_ext/class/attribute'
7
7
  module BugBunny
8
8
  # Clase base para todos los Controladores de Mensajes en BugBunny.
9
9
  #
10
+ # Actúa como el receptor final de los mensajes enrutados desde el consumidor.
11
+ # Implementa un ciclo de vida similar a ActionController en Rails, soportando:
12
+ # - Filtros (`before_action`, `around_action`).
13
+ # - Manejo declarativo de errores (`rescue_from`).
14
+ # - Parsing de parámetros unificados (`params`).
15
+ # - Respuestas estructuradas (`render`).
16
+ #
10
17
  # @author Gabriel
11
18
  # @since 3.0.6
12
19
  class Controller
13
20
  include ActiveModel::Model
14
21
  include ActiveModel::Attributes
15
22
 
16
- # @return [Hash] Metadatos del mensaje entrante.
23
+ # @!group Atributos de Instancia
24
+
25
+ # @return [Hash] Metadatos del mensaje entrante (ej. HTTP method, routing_key, id).
17
26
  attribute :headers
18
27
 
19
- # @return [ActiveSupport::HashWithIndifferentAccess] Parámetros unificados.
28
+ # @return [ActiveSupport::HashWithIndifferentAccess] Parámetros unificados (Body JSON + Query String).
20
29
  attribute :params
21
30
 
22
- # @return [String] Cuerpo crudo.
31
+ # @return [String] Cuerpo crudo original en caso de no ser JSON.
23
32
  attribute :raw_string
24
33
 
25
- # @return [Hash] Headers de respuesta.
34
+ # @return [Hash] Headers de respuesta que serán enviados de vuelta en RPC.
26
35
  attr_reader :response_headers
27
36
 
28
- # @return [Hash, nil] Respuesta renderizada.
37
+ # @return [Hash, nil] Respuesta final renderizada.
29
38
  attr_reader :rendered_response
30
39
 
31
- # --- INFRAESTRUCTURA DE FILTROS (DEFINICIÓN) ---
32
- # Deben definirse ANTES de ser usados por la configuración de logs.
40
+ # @!endgroup
33
41
 
34
- # @api private
35
- def self.before_actions
36
- @before_actions ||= Hash.new { |h, k| h[k] = [] }
37
- end
38
42
 
39
- # @api private
40
- def self.around_actions
41
- @around_actions ||= Hash.new { |h, k| h[k] = [] }
42
- end
43
+ # ==========================================
44
+ # INFRAESTRUCTURA DE FILTROS Y LOGS (HEREDABLES)
45
+ # ==========================================
46
+
47
+ # Usamos `class_attribute` con `default` para garantizar la herencia correcta
48
+ # hacia las subclases (ej. de ApplicationController a ServicesController).
49
+ class_attribute :before_actions, default: {}
50
+ class_attribute :around_actions, default: {}
51
+ class_attribute :log_tags, default: []
52
+ class_attribute :rescue_handlers, default: []
43
53
 
44
54
  # Registra un filtro que se ejecutará **antes** de la acción.
55
+ # Si el filtro invoca `render`, la cadena se interrumpe y la acción no se ejecuta.
56
+ #
57
+ # @param method_name [Symbol] Nombre del método privado a ejecutar.
58
+ # @param options [Hash] Opciones como `only: [:show, :update]`.
59
+ # @return [void]
45
60
  def self.before_action(method_name, **options)
46
- register_callback(before_actions, method_name, options)
61
+ register_callback(:before_actions, method_name, options)
47
62
  end
48
63
 
49
64
  # Registra un filtro que **envuelve** la ejecución de la acción.
65
+ # El método registrado debe invocar `yield` para continuar la ejecución.
66
+ #
67
+ # @param method_name [Symbol] Nombre del método privado a ejecutar.
68
+ # @param options [Hash] Opciones como `only: [:index]`.
69
+ # @return [void]
50
70
  def self.around_action(method_name, **options)
51
- register_callback(around_actions, method_name, options)
71
+ register_callback(:around_actions, method_name, options)
52
72
  end
53
73
 
54
- # Helper interno para registrar callbacks.
55
- def self.register_callback(collection, method_name, options)
56
- only = Array(options[:only]).map(&:to_sym)
57
- target_actions = only.empty? ? [:_all_actions] : only
58
- target_actions.each { |action| collection[action] << method_name }
74
+ # Manejo declarativo de excepciones.
75
+ # Atrapa errores específicos que ocurran durante la ejecución de la acción.
76
+ #
77
+ # @example
78
+ # rescue_from Api::Error::NotFound, with: :render_not_found
79
+ # rescue_from StandardError do |e|
80
+ # render status: 500, json: { error: e.message }
81
+ # end
82
+ #
83
+ # @param klasses [Array<Class, String>] Clases de excepciones a atrapar.
84
+ # @param with [Symbol, nil] Nombre del método manejador.
85
+ # @yield [Exception] Bloque opcional para manejar el error inline.
86
+ # @raise [ArgumentError] Si no se provee un manejador (with o block).
87
+ def self.rescue_from(*klasses, with: nil, &block)
88
+ handler = with || block
89
+ raise ArgumentError, "Need a handler. Supply 'with: :method' or a block." unless handler
90
+
91
+ # Duplicamos el array del padre para no mutarlo al registrar reglas en el hijo
92
+ new_handlers = self.rescue_handlers.dup
93
+
94
+ klasses.each do |klass|
95
+ new_handlers.unshift([klass, handler])
96
+ end
97
+
98
+ self.rescue_handlers = new_handlers
59
99
  end
60
100
 
61
- # --- CONFIGURACIÓN DE LOGGING ---
101
+ # Helper interno para registrar callbacks garantizando Thread-Safety e Inmutabilidad del padre.
102
+ # @api private
103
+ def self.register_callback(collection_name, method_name, options)
104
+ current_hash = send(collection_name)
62
105
 
63
- # Define los tags que se antepondrán a cada línea de log.
64
- class_attribute :log_tags
65
- self.log_tags = []
106
+ # Deep dup: Clonamos el hash y sus arrays internos para no modificar la clase padre
107
+ new_hash = current_hash.transform_values(&:dup)
66
108
 
67
- # AHORA SÍ: Podemos llamar a around_action porque ya fue definido arriba.
68
- around_action :apply_log_tags
109
+ only = Array(options[:only]).map(&:to_sym)
110
+ target_actions = only.empty? ? [:_all_actions] : only
69
111
 
70
- # --- INICIALIZACIÓN ---
112
+ target_actions.each do |action|
113
+ new_hash[action] ||= []
114
+ new_hash[action] << method_name
115
+ end
71
116
 
72
- def initialize(attributes = {})
73
- super
74
- @response_headers = {}
117
+ send("#{collection_name}=", new_hash)
75
118
  end
76
119
 
77
- # --- MANEJO DE ERRORES ---
120
+ # Aplicamos automáticamente las etiquetas de logs a todas las acciones.
121
+ around_action :apply_log_tags
78
122
 
79
- # @api private
80
- def self.rescue_handlers
81
- @rescue_handlers ||= []
82
- end
83
123
 
84
- def self.rescue_from(*klasses, with: nil, &block)
85
- handler = with || block
86
- raise ArgumentError, "Need a handler. Supply 'with: :method' or a block." unless handler
124
+ # ==========================================
125
+ # INICIALIZACIÓN Y CICLO DE VIDA
126
+ # ==========================================
87
127
 
88
- klasses.each do |klass|
89
- rescue_handlers.unshift([klass, handler])
90
- end
128
+ def initialize(attributes = {})
129
+ super
130
+ @response_headers = {}
91
131
  end
92
132
 
93
- # --- PIPELINE DE EJECUCIÓN ---
94
-
133
+ # Punto de entrada principal estático llamado por el Router (`BugBunny::Consumer`).
134
+ #
135
+ # @param headers [Hash] Metadatos y variables de enrutamiento.
136
+ # @param body [String, Hash] El payload del mensaje AMQP.
137
+ # @return [Hash] Respuesta final estructurada.
95
138
  def self.call(headers:, body: {})
96
139
  new(headers: headers).process(body)
97
140
  end
98
141
 
142
+ # Ejecuta el ciclo de vida completo de la petición: Params -> Before -> Action -> Rescue.
143
+ #
144
+ # @param body [String, Hash] El cuerpo del mensaje.
145
+ # @return [Hash] La respuesta lista para ser enviada vía RabbitMQ RPC.
99
146
  def process(body)
100
147
  prepare_params(body)
101
148
 
102
- # Inyección de configuración global de logs si no hay específica
149
+ # Inyección de configuración global de logs si el controlador no define propios
103
150
  if self.class.log_tags.empty? && BugBunny.configuration.log_tags.any?
104
151
  self.class.log_tags = BugBunny.configuration.log_tags
105
152
  end
@@ -118,15 +165,14 @@ module BugBunny
118
165
  end
119
166
  end
120
167
 
121
- # Construir la cadena de responsabilidad
168
+ # Construir e invocar la cadena de responsabilidad (Middlewares/Around Actions)
122
169
  execution_chain = current_arounds.reverse.inject(core_execution) do |next_step, method_name|
123
170
  lambda { send(method_name, &next_step) }
124
171
  end
125
172
 
126
- # Ejecutar la cadena
127
173
  execution_chain.call
128
174
 
129
- # Respuesta final
175
+ # Si no hubo renderización explícita, devuelve 204 No Content
130
176
  rendered_response || { status: 204, headers: response_headers, body: nil }
131
177
 
132
178
  rescue StandardError => e
@@ -135,21 +181,14 @@ module BugBunny
135
181
 
136
182
  private
137
183
 
138
- # --- HELPERS INTERNOS ---
139
-
140
- def resolve_callbacks(collection, action_name)
141
- (collection[:_all_actions] || []) + (collection[action_name] || [])
142
- end
143
-
144
- def run_before_actions(action_name)
145
- current_befores = resolve_callbacks(self.class.before_actions, action_name)
146
- current_befores.uniq.each do |method_name|
147
- send(method_name)
148
- return false if rendered_response
149
- end
150
- true
151
- end
184
+ # ==========================================
185
+ # HELPERS INTERNOS
186
+ # ==========================================
152
187
 
188
+ # Evalúa la excepción lanzada y busca el manejador más adecuado definido en `rescue_from`.
189
+ #
190
+ # @param exception [StandardError] La excepción atrapada.
191
+ # @return [Hash] Respuesta de error renderizada.
153
192
  def handle_exception(exception)
154
193
  handler_entry = self.class.rescue_handlers.find do |klass, _|
155
194
  if klass.is_a?(String)
@@ -161,24 +200,34 @@ module BugBunny
161
200
 
162
201
  if handler_entry
163
202
  _, handler = handler_entry
164
- if handler.is_a?(Symbol); send(handler, exception)
165
- elsif handler.respond_to?(:call); instance_exec(exception, &handler)
203
+ if handler.is_a?(Symbol)
204
+ send(handler, exception)
205
+ elsif handler.respond_to?(:call)
206
+ instance_exec(exception, &handler)
166
207
  end
167
208
  return rendered_response if rendered_response
168
209
  end
169
210
 
211
+ # Fallback genérico si la excepción no fue mapeada
170
212
  BugBunny.configuration.logger.error("[BugBunny::Controller] 💥 Unhandled Exception (#{exception.class}): #{exception.message}")
171
- BugBunny.configuration.logger.error(exception.backtrace.first(5).join("\n")) # Limitamos a 5 líneas para no ensuciar
213
+ BugBunny.configuration.logger.error(exception.backtrace.first(5).join("\n"))
172
214
 
173
215
  {
174
216
  status: 500,
175
217
  headers: response_headers,
176
- body: { error: exception.message, type: exception.class.name }
218
+ body: { error: "Internal Server Error", detail: exception.message, type: exception.class.name }
177
219
  }
178
220
  end
179
221
 
222
+ # Renderiza una respuesta que será enviada de vuelta por la cola reply-to.
223
+ #
224
+ # @param status [Symbol, Integer] Código HTTP (ej. :ok, :not_found, 201).
225
+ # @param json [Object] El payload a serializar como JSON.
226
+ # @return [Hash] La estructura renderizada interna.
180
227
  def render(status:, json: nil)
181
- code = Rack::Utils::SYMBOL_TO_STATUS_CODE[status] || 200
228
+ code = Rack::Utils::SYMBOL_TO_STATUS_CODE[status] || status.to_i
229
+ code = 200 if code.zero? # Fallback de seguridad
230
+
182
231
  @rendered_response = {
183
232
  status: code,
184
233
  headers: response_headers,
@@ -186,21 +235,43 @@ module BugBunny
186
235
  }
187
236
  end
188
237
 
238
+ # Unifica el query string, parámetros de ruta y el body JSON en un solo objeto `params`.
189
239
  def prepare_params(body)
190
240
  self.params = {}.with_indifferent_access
241
+
191
242
  params.merge!(headers[:query_params]) if headers[:query_params].present?
192
243
  params[:id] = headers[:id] if headers[:id].present?
193
244
 
194
245
  if body.is_a?(Hash)
195
246
  params.merge!(body)
196
247
  elsif body.is_a?(String) && headers[:content_type].to_s.include?('json')
197
- parsed = JSON.parse(body) rescue nil
248
+ parsed = begin
249
+ JSON.parse(body)
250
+ rescue JSON::ParserError
251
+ nil
252
+ end
198
253
  params.merge!(parsed) if parsed
199
254
  else
200
255
  self.raw_string = body
201
256
  end
202
257
  end
203
258
 
259
+ # Obtiene la lista combinada de callbacks globales y específicos para una acción.
260
+ def resolve_callbacks(collection, action_name)
261
+ (collection[:_all_actions] || []) + (collection[action_name] || [])
262
+ end
263
+
264
+ # Ejecuta secuencialmente todos los before_actions.
265
+ # Si alguno invoca render(), detiene el flujo devolviendo `false`.
266
+ def run_before_actions(action_name)
267
+ current_befores = resolve_callbacks(self.class.before_actions, action_name)
268
+ current_befores.uniq.each do |method_name|
269
+ send(method_name)
270
+ return false if rendered_response
271
+ end
272
+ true
273
+ end
274
+
204
275
  # --- LÓGICA DE LOGGING ENCAPSULADA ---
205
276
 
206
277
  def apply_log_tags
@@ -225,6 +296,7 @@ module BugBunny
225
296
  end.compact
226
297
  end
227
298
 
299
+ # @return [String] Identificador único de trazabilidad de la petición.
228
300
  def uuid
229
301
  headers[:correlation_id] || headers['X-Request-Id']
230
302
  end
@@ -91,16 +91,26 @@ module BugBunny
91
91
 
92
92
  private
93
93
 
94
+ # Registra la petición en el log calculando las opciones de infraestructura.
95
+ #
96
+ # @param request [BugBunny::Request] Objeto Request que se está enviando.
97
+ # @param payload [String] El cuerpo del mensaje serializado.
94
98
  def log_request(request, payload)
95
99
  verb = request.method.to_s.upcase
96
100
  target = request.path
97
101
  rk = request.final_routing_key
98
102
  id = request.correlation_id
99
103
 
104
+ # 📊 LOGGING DE OBSERVABILIDAD: Calculamos las opciones finales para mostrarlas en consola
105
+ final_x_opts = BugBunny::Session::DEFAULT_EXCHANGE_OPTIONS
106
+ .merge(BugBunny.configuration.exchange_options || {})
107
+ .merge(request.exchange_options || {})
108
+
100
109
  # INFO: Resumen de una línea (Traffic)
101
110
  BugBunny.configuration.logger.info("[BugBunny::Producer] 📤 #{verb} /#{target} | RK: '#{rk}' | ID: #{id}")
102
111
 
103
- # DEBUG: Detalle completo (Payload)
112
+ # DEBUG: Detalle completo de Infraestructura y Payload
113
+ BugBunny.configuration.logger.debug("[BugBunny::Producer] ⚙️ Exchange Opts: #{final_x_opts}")
104
114
  BugBunny.configuration.logger.debug("[BugBunny::Producer] 📦 Payload: #{payload.truncate(300)}") if payload.is_a?(String)
105
115
  end
106
116
 
@@ -414,9 +414,9 @@ module BugBunny
414
414
  if response['status'] == 422
415
415
  raise BugBunny::UnprocessableEntity.new(response['body']['errors'] || response['body'])
416
416
  elsif response['status'] >= 500
417
- raise BugBunny::InternalServerError
417
+ raise BugBunny::InternalServerError, format_error_message(response['body'])
418
418
  elsif response['status'] >= 400
419
- raise BugBunny::ClientError
419
+ raise BugBunny::ClientError, format_error_message(response['body'])
420
420
  end
421
421
 
422
422
  assign_attributes(response['body'])
@@ -425,6 +425,21 @@ module BugBunny
425
425
  true
426
426
  end
427
427
 
428
+ # Formatea el cuerpo de la respuesta de error para que sea legible en las excepciones
429
+ def format_error_message(body)
430
+ return "Unknown Error" if body.nil?
431
+ return body if body.is_a?(String)
432
+
433
+ # Si el worker devolvió un JSON con una key 'error' (nuestra convención en Controller), la priorizamos
434
+ if body.is_a?(Hash) && body['error']
435
+ detail = body['detail'] ? " - #{body['detail']}" : ""
436
+ "#{body['error']}#{detail}"
437
+ else
438
+ # Fallback: Convertir todo el Hash a JSON string para que se vea claro en Sentry/Logs
439
+ body.to_json
440
+ end
441
+ end
442
+
428
443
  # Carga errores remotos en el objeto local.
429
444
  def load_remote_rabbit_errors(errors_hash)
430
445
  return if errors_hash.nil?
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module BugBunny
4
- VERSION = "3.1.1"
4
+ VERSION = "3.1.2"
5
5
  end
data/test/test_helper.rb CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  require 'bundler/setup'
4
4
  require 'minitest/autorun'
5
- # require 'minitest/reporters'
5
+ # require 'minitest/reporters'
6
6
  require 'bug_bunny'
7
7
  require 'connection_pool'
8
8
  require 'securerandom'
@@ -14,7 +14,7 @@ BugBunny.configure do |config|
14
14
  config.password = ENV.fetch('RABBITMQ_PASS', 'guest')
15
15
  config.vhost = '/'
16
16
  config.logger = Logger.new($stdout)
17
- config.logger.level = Logger::WARN
17
+ config.logger.level = Logger::WARN
18
18
 
19
19
  # ========================================================
20
20
  # LA MAGIA DE LA CASCADA (Nivel 2: Configuración Global)
@@ -38,10 +38,10 @@ module IntegrationHelper
38
38
 
39
39
  def with_running_worker(queue:, exchange:, exchange_type: 'topic', routing_key: '#')
40
40
  conn = BugBunny.create_connection
41
-
41
+
42
42
  worker_thread = Thread.new do
43
43
  ch = conn.create_channel
44
-
44
+
45
45
  x_opts = BugBunny.configuration.exchange_options || {}
46
46
  q_opts = BugBunny.configuration.queue_options || {}
47
47
 
@@ -63,7 +63,7 @@ module IntegrationHelper
63
63
  puts e.backtrace.join("\n")
64
64
  end
65
65
 
66
- sleep 0.5
66
+ sleep 0.5
67
67
  yield
68
68
  ensure
69
69
  conn&.close
@@ -74,26 +74,26 @@ module IntegrationHelper
74
74
  def with_spy_worker(queue:, exchange:, exchange_type: 'topic', routing_key: '#')
75
75
  captured_messages = Thread::Queue.new
76
76
  conn = BugBunny.create_connection
77
-
77
+
78
78
  worker_thread = Thread.new do
79
79
  ch = conn.create_channel
80
-
80
+
81
81
  x_opts = BugBunny.configuration.exchange_options || {}
82
82
  q_opts = BugBunny.configuration.queue_options || {}
83
-
83
+
84
84
  # FIX DEFINITIVO: Ahora 'x' es un hermoso objeto Bunny::Exchange
85
85
  # que la función .bind() entiende perfectamente.
86
86
  x = ch.public_send(exchange_type, exchange, x_opts)
87
87
  q = ch.queue(queue, q_opts)
88
-
88
+
89
89
  # Bindeamos el objeto al queue
90
90
  q.bind(x, routing_key: routing_key)
91
91
 
92
92
  q.subscribe(block: true) do |delivery, props, body|
93
- captured_messages << {
94
- body: body,
93
+ captured_messages << {
94
+ body: body,
95
95
  routing_key: delivery.routing_key,
96
- headers: props.headers
96
+ headers: props.headers
97
97
  }
98
98
  end
99
99
  rescue => e
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: bug_bunny
3
3
  version: !ruby/object:Gem::Version
4
- version: 3.1.1
4
+ version: 3.1.2
5
5
  platform: ruby
6
6
  authors:
7
7
  - gabix