bug_bunny 5.1.1 → 5.3.0
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 +4 -4
- data/.rspec +2 -0
- data/AGENTS.md +3 -2
- data/CHANGELOG.md +32 -0
- data/CLAUDE.md +2 -2
- data/README.md +69 -3
- data/Rakefile +9 -1
- data/docs/behavior/behavior.md +60 -10
- data/docs/config/configuracion.md +67 -52
- data/docs/consumed/rabbitmq.md +4 -4
- data/docs/errors/errors.md +7 -5
- data/docs/release/release.md +13 -8
- data/docs/test/testing.md +28 -9
- data/lib/bug_bunny/configuration.rb +33 -2
- data/lib/bug_bunny/consumer.rb +184 -31
- data/lib/bug_bunny/consumer_middleware/rails_executor.rb +33 -0
- data/lib/bug_bunny/consumer_middleware.rb +13 -0
- data/lib/bug_bunny/drain_tracker.rb +54 -0
- data/lib/bug_bunny/railtie.rb +18 -2
- data/lib/bug_bunny/version.rb +1 -1
- data/lib/bug_bunny.rb +1 -0
- data/skill/SKILL.md +21 -8
- data/skill/references/consumer.md +36 -1
- data/skill/references/errores.md +1 -1
- data/skill/references/routing.md +1 -1
- data/skill/references/testing.md +4 -1
- data/spec/integration/drain_spec.rb +177 -0
- data/spec/rails/app.rb +70 -0
- data/spec/rails/consumer_rails_executor_spec.rb +165 -0
- data/spec/rails/rails_helper.rb +6 -0
- data/spec/unit/configuration_spec.rb +33 -1
- data/spec/unit/consumer_middleware_spec.rb +13 -0
- data/spec/unit/consumer_rails_executor_outside_rails_spec.rb +19 -0
- data/spec/unit/drain_tracker_spec.rb +37 -0
- metadata +54 -3
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 6a28c7b99a99dc128e597b0dd3c6d128ab0abcf634410603f1dbeee78321ff33
|
|
4
|
+
data.tar.gz: 176ef53af6d5b7de0d6d10426aad13dbce548c2e894fd06db43550146791c216
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: ed8f25adc078770d9009b145cae463a772d0bae7234dcbae31e398f65896c7a055f230952c626becab97f235cbf23c66cd590938189ef4176c4bcecd94db092e
|
|
7
|
+
data.tar.gz: 0e5a151b21aee8a2647c41a8407df889d36582eb45026c4ca8a6a1d04b3bd0109a0e371e1a1f00d7625247e8be9ed6baf9b14c8a7ef28c9b50b5f6a0262207f2
|
data/.rspec
ADDED
data/AGENTS.md
CHANGED
|
@@ -12,7 +12,7 @@ proyecto y convenciones de equipo, ver `CLAUDE.md`. Para la entrada humana, ver
|
|
|
12
12
|
|
|
13
13
|
| capa | artefacto | estado | qué responde |
|
|
14
14
|
|---|---|---|---|
|
|
15
|
-
| Comportamiento | `docs/behavior/behavior.md` | completo (
|
|
15
|
+
| Comportamiento | `docs/behavior/behavior.md` | completo (8 flujos) | secuencias de publish/RPC/consume/confirms, contrato de error-wrapping |
|
|
16
16
|
| Glosario | `docs/glossary/glossary.md` | parcial (acreta por PR) | término de negocio → binding físico en `lib/` |
|
|
17
17
|
| Errores | `docs/errors/errors.md` | completo (§a/b/d estructura + §c política inferida) | jerarquía de excepciones públicas, mapeo `status→excepción`, shape del payload, política retry |
|
|
18
18
|
| Configuración | `docs/config/configuracion.md` | completo (estructura + enrich §f/g/h) | opciones de `Configuration`, defaults, failure-mode/threading, inyecciones del `Railtie`, ENV sugeridas |
|
|
@@ -38,6 +38,7 @@ a YARD/specs/CHANGELOG. Pendiente de **verificación humana** (inferencias):
|
|
|
38
38
|
|
|
39
39
|
- Ruby: `.ruby-version` · gemas: `Gemfile.lock` · manager: chruby + Bundler.
|
|
40
40
|
- Antes de commitear: `bundle exec rubocop -a` (base `rubocop-rails-omakase`),
|
|
41
|
-
`bundle exec
|
|
41
|
+
`bundle exec rake` (las dos suites: `spec/` y `spec/rails/`, cada una en su proceso; `bundle exec rspec` solo
|
|
42
|
+
corre `spec/`, sin Rails), YARD incremental (`bundle exec yard stats --list-undoc`).
|
|
42
43
|
- Releases: `/gem-release` (el GitHub Action publica a RubyGems al pushear tag `v*`).
|
|
43
44
|
- Doc por-PR: si tocás una capa, mové su artefacto en el mismo PR (régimen RFC-001).
|
data/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,37 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [5.3.0] - 2026-10-16
|
|
4
|
+
|
|
5
|
+
### Nuevas funcionalidades
|
|
6
|
+
- **Dentro de Rails, cada mensaje del Consumer corre dentro del executor de Rails (#70):** el railtie registra `BugBunny::ConsumerMiddleware::RailsExecutor`, que envuelve cada mensaje con `Rails.application.executor.wrap`, como Sidekiq con cada job. El Consumer procesa en el hilo de trabajo de Bunny, que Rails no conoce, así que hasta ahora lo que Rails guarda por hilo pasaba de un mensaje al siguiente: los `CurrentAttributes` (tags de Sentry, contexto de traza, métricas por ejecución) y la conexión de ActiveRecord (el hilo la retenía en vez de devolverla al pool). Fuera de Rails no se registra nada y la gema se comporta como antes. (#70, #71) — @Pslp
|
|
7
|
+
- **`config.consumer_rails_executor`** (default `true`): con `false`, el railtie no registra el middleware. Se lee al terminar de inicializar la app, así que se apaga desde `config/initializers`. Si la app no llamó a `BugBunny.configure` antes de ese momento, el railtie usa la configuración por default en vez de caerse al bootear. — @Pslp
|
|
8
|
+
- **`ConsumerMiddleware::Stack#prepend`:** registra un middleware al principio de la cadena. El del executor va primero así, para envolver también a los middlewares que cargan estado por hilo (el de tracing de ExisRay se registra en su propio `after_initialize`, en un orden que no controlamos). — @Pslp
|
|
9
|
+
|
|
10
|
+
### ⚠️ Cambio de conducta (dentro de Rails)
|
|
11
|
+
- **Rails ≥ 7.0 — un error que escapa del procesamiento de un mensaje ahora además se reporta a `Rails.error`** con `handled: false`, porque es lo que hace `executor.wrap` antes de relanzar. El camino del mensaje no cambia: se rechaza sin requeue, como desde 5.2.0. Los errores dentro de las acciones del controller los sigue rescatando el Consumer y no se ven afectados. **A mirar si consumís:** si tenés un subscriber de `Rails.error` (el de Sentry, por ejemplo), esos errores ahora aparecen ahí. Para volver a la conducta anterior: `config.consumer_rails_executor = false`. — @Pslp
|
|
12
|
+
- **La caché de queries de ActiveRecord queda prendida durante cada mensaje** y se limpia al terminarlo: es lo que hace el executor (`ActiveRecord::QueryCache::ExecutorHooks`). En el hilo de Bunny estaba apagada. **A mirar si consumís:** un handler que relee la misma fila dentro de un mensaje esperando que otro proceso la cambie (un poll) ahora recibe el valor cacheado; usá `ActiveRecord::Base.uncached { … }` ahí. Se vuelve a la conducta anterior con `config.consumer_rails_executor = false`. — @Pslp
|
|
13
|
+
|
|
14
|
+
### Tests
|
|
15
|
+
- `spec/rails/`: una app Rails mínima (ActiveRecord sobre SQLite en memoria) prueba el railtie con Rails de verdad. Corre en su propio proceso (`rake spec:rails`), para que el resto de la suite siga probando la gema fuera de Rails; `rake` sin argumentos corre las dos, y `rspec` pelado corre `spec/` (un `.rspec` excluye `spec/rails/` salvo que se lo pida: `rspec spec/rails` la corre). Suma `railties`, `activerecord` y `sqlite3` como dependencias de desarrollo. — @Pslp
|
|
16
|
+
|
|
17
|
+
### Documentación
|
|
18
|
+
- README, `skill/` y los artefactos de `docs/` (configuración, comportamiento, tests, errores) describen el executor, la opción y los dos cambios de conducta; las metas que tocó #70 se re-anclaron a `67cca83`. — @Pslp
|
|
19
|
+
|
|
20
|
+
## [5.2.0] - 2026-09-29
|
|
21
|
+
|
|
22
|
+
### Nuevas funcionalidades
|
|
23
|
+
- **`Consumer.drain` / `Consumer#drain` — consumir hasta vaciar la cola y retornar (#65):** el modo para correr un consumidor **como job** (Sidekiq, un Job de k8s) en vez de como proceso eterno. Se suscribe respetando `channel_prefetch` y retorna cuando pasan `drain_idle_timeout` segundos sin entregas y sin nada en proceso; con la cola vacía retorna `0` al instante. Devuelve cuántos mensajes procesó (incluye los rechazados: también salieron de la cola). Un mensaje que llega dentro de la ventana se procesa en esa vuelta; los posteriores, en la próxima. No tiene loop de reconexión ni health check (el reintento es del framework del job). **La conexión es del llamador:** `drain` cierra su canal, no la conexión — si la creás por corrida, cerrala (`ensure connection.close`), o cada corrida deja una abierta. **Con un flujo sostenido más rápido que `drain_idle_timeout`, no retorna:** acotalo desde el job. — @gedera
|
|
24
|
+
- **`drain_idle_timeout` (default `5`) y `drain_poll_interval` (default `0.1`) en `Configuration`**, validados en `validate!`. — @gedera
|
|
25
|
+
|
|
26
|
+
### ⚠️ Cambio de conducta — `subscribe` y `drain`
|
|
27
|
+
- **Una entrega cuyo middleware —o `handle_fatal_error`— levanta antes del ack ahora se rechaza sin requeue** y se loguea `consumer.delivery_failed` (#65). Antes quedaba **sin ack ni reject**: con `channel_prefetch = 1` ocupaba el único lugar de prefetch y el consumidor dejaba de recibir, sin error. Es lo mismo que `process_message` ya hacía con sus propios errores. Si el error llega **después** del ack, sólo se loguea (rechazar un tag ya confirmado cierra el canal). **A mirar si consumís:** si un middleware tuyo levantaba a propósito para que el mensaje se reintentara, ahora el mensaje **se pierde** — el reintento tiene que ser tuyo. — @gedera
|
|
28
|
+
|
|
29
|
+
### Documentación
|
|
30
|
+
- `subscribe(block: false)` **no** es un modo "drenar": retorna al instante y el `ensure shutdown` cierra el canal, así que no consume nada (medido en #65). Queda documentado en el README; no se cambia en este release. — @gedera
|
|
31
|
+
|
|
32
|
+
### Tests
|
|
33
|
+
- `configuration_spec` restaura la configuración original en vez de dejar una con defaults: los specs de integración que corrían después se conectaban como `guest` y quedaban *pending* como "RabbitMQ no disponible" aun con broker, según el seed (#65). — @gedera
|
|
34
|
+
|
|
3
35
|
## [5.1.1] - 2026-07-31
|
|
4
36
|
|
|
5
37
|
### Correcciones
|
data/CLAUDE.md
CHANGED
|
@@ -15,7 +15,7 @@ BugBunny es una gema Ruby que implementa una capa de enrutamiento RESTful sobre
|
|
|
15
15
|
`dev-compose`. Verificación humana antes de commitear.
|
|
16
16
|
- **Estado actual:**
|
|
17
17
|
- `docs/data` = n/a (gema sin DB, declarado solo en índice).
|
|
18
|
-
- `docs/behavior` completo (
|
|
18
|
+
- `docs/behavior` completo (7 flujos, backfill on-demand).
|
|
19
19
|
- `docs/glossary` parcial (acreta por PR).
|
|
20
20
|
- `docs/errors` (RFC-020) completo: §a/§b/§d (estructura) + §c política
|
|
21
21
|
(enrich, **inferida** de HTTP/AMQP, verificación humana pendiente).
|
|
@@ -61,7 +61,7 @@ BugBunny es una gema Ruby que implementa una capa de enrutamiento RESTful sobre
|
|
|
61
61
|
|
|
62
62
|
### Testing
|
|
63
63
|
- Framework: RSpec
|
|
64
|
-
- Correr: `bundle exec rspec`
|
|
64
|
+
- Correr: `bundle exec rake` (las dos suites: `spec/` y `spec/rails/`, cada una en su proceso; `bundle exec rspec` solo corre `spec/`, sin Rails)
|
|
65
65
|
- Todo código nuevo debe tener tests.
|
|
66
66
|
|
|
67
67
|
### Releases o Nuevas versiones
|
data/README.md
CHANGED
|
@@ -66,6 +66,28 @@ BugBunny::Consumer.subscribe(
|
|
|
66
66
|
)
|
|
67
67
|
```
|
|
68
68
|
|
|
69
|
+
To run a consumer **as a job** (Sidekiq, a k8s Job) instead of a long-lived process, use `drain`: it consumes until the queue goes quiet and returns how many messages it processed. With an empty queue it returns `0` right away.
|
|
70
|
+
|
|
71
|
+
```ruby
|
|
72
|
+
connection = BugBunny.create_connection
|
|
73
|
+
begin
|
|
74
|
+
processed_count = BugBunny::Consumer.drain(
|
|
75
|
+
connection: connection,
|
|
76
|
+
queue_name: 'inventory_queue',
|
|
77
|
+
exchange_name: 'inventory',
|
|
78
|
+
routing_key: 'nodes'
|
|
79
|
+
)
|
|
80
|
+
ensure
|
|
81
|
+
connection.close # drain closes its channel, not the connection: the connection is yours
|
|
82
|
+
end
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
- **The connection belongs to the caller.** `drain` closes its channel when it returns, not the connection, because it may be shared (a pool, the publisher's). If you create one per job run, close it — otherwise every run leaks a connection. Reusing the process connection works too.
|
|
86
|
+
- **A delivery that fails leaves the queue.** If a middleware raises before the ack, the message is rejected without requeue (same as `process_message` errors), so it does not block the prefetch.
|
|
87
|
+
- **With a sustained flow, `drain` does not return.** If messages arrive faster than `drain_idle_timeout`, the idle window never closes. Bound it from outside (the Sidekiq job timeout, `activeDeadlineSeconds` in k8s).
|
|
88
|
+
|
|
89
|
+
> `subscribe(block: false)` is **not** this mode: it returns immediately and closes the channel, so it consumes nothing.
|
|
90
|
+
|
|
69
91
|
### Service A — Producer
|
|
70
92
|
|
|
71
93
|
```ruby
|
|
@@ -146,6 +168,15 @@ BugBunny.configure do |config|
|
|
|
146
168
|
# Health check file for Kubernetes / Docker Swarm liveness probes
|
|
147
169
|
config.health_check_file = '/tmp/bug_bunny_health'
|
|
148
170
|
|
|
171
|
+
# Consumer.drain — seconds without deliveries before the queue counts as empty (default: 5),
|
|
172
|
+
# and how often that is checked (default: 0.1)
|
|
173
|
+
config.drain_idle_timeout = 5
|
|
174
|
+
config.drain_poll_interval = 0.1
|
|
175
|
+
|
|
176
|
+
# Rails only — wrap every consumed message in Rails.application.executor (default: true).
|
|
177
|
+
# See "Rails executor around each message" below. Set it from config/initializers.
|
|
178
|
+
config.consumer_rails_executor = true
|
|
179
|
+
|
|
149
180
|
# Publisher Confirms — fail-loud defaults (both flags default to true).
|
|
150
181
|
# Set to false to restore legacy log-only behavior.
|
|
151
182
|
config.nack_raise = true # broker NACK → raise BugBunny::PublishNacked
|
|
@@ -335,6 +366,41 @@ end
|
|
|
335
366
|
BugBunny.consumer_middlewares.use TracingMiddleware
|
|
336
367
|
```
|
|
337
368
|
|
|
369
|
+
`use` appends to the chain; `prepend` puts a middleware first, wrapping every other one.
|
|
370
|
+
|
|
371
|
+
### Rails executor around each message
|
|
372
|
+
|
|
373
|
+
Inside Rails, the railtie registers `BugBunny::ConsumerMiddleware::RailsExecutor` **first** in the chain. It wraps every
|
|
374
|
+
message in `Rails.application.executor.wrap`, the same way Sidekiq wraps each job. The consumer processes messages on
|
|
375
|
+
Bunny's worker thread, which Rails does not know about; without the executor, what Rails keeps per thread survives from
|
|
376
|
+
one message to the next:
|
|
377
|
+
|
|
378
|
+
- `ActiveSupport::CurrentAttributes` (and whatever lives in them: Sentry tags, trace context, per-run metrics);
|
|
379
|
+
- the ActiveRecord connection, which the thread keeps until it dies instead of returning it to the pool.
|
|
380
|
+
|
|
381
|
+
It goes first (`prepend`, not `use`) so that it also wraps the middlewares that load per-thread state, like ExisRay's
|
|
382
|
+
tracing middleware. Outside Rails nothing is registered and the consumer behaves as before.
|
|
383
|
+
|
|
384
|
+
#### ⚠️ Behavior change
|
|
385
|
+
|
|
386
|
+
**Errors that escape a message (Rails ≥ 7.0).**
|
|
387
|
+
An error that escapes the processing of a message (from a middleware, or from `handle_fatal_error`) still ends the same
|
|
388
|
+
way: the delivery is rejected without requeue. **It is now also reported to `Rails.error`** with `handled: false`, because that is what `executor.wrap` does before re-raising. If you have a `Rails.error` subscriber
|
|
389
|
+
(e.g. Sentry's), that error shows up there. Errors inside your controller actions are rescued by the consumer as
|
|
390
|
+
before and are not affected.
|
|
391
|
+
|
|
392
|
+
**The ActiveRecord query cache is on during each message**, and cleared when it ends: that is what the executor does
|
|
393
|
+
(`ActiveRecord::QueryCache::ExecutorHooks`). On Bunny's thread it used to be off. A handler that re-reads the same row
|
|
394
|
+
within one message, waiting for another process to change it (a poll), now gets the cached value; wrap that read in
|
|
395
|
+
`ActiveRecord::Base.uncached { … }`.
|
|
396
|
+
|
|
397
|
+
To turn it off (for example, if your consumer already wraps each message itself):
|
|
398
|
+
|
|
399
|
+
```ruby
|
|
400
|
+
# config/initializers/bug_bunny.rb
|
|
401
|
+
BugBunny.configure { |config| config.consumer_rails_executor = false }
|
|
402
|
+
```
|
|
403
|
+
|
|
338
404
|
---
|
|
339
405
|
|
|
340
406
|
## Observability
|
|
@@ -432,16 +498,16 @@ end
|
|
|
432
498
|
|
|
433
499
|
Artefactos de detalle (modelo `dev-*`, RFC-001). El README indexa; no duplica.
|
|
434
500
|
|
|
435
|
-
Anclado a `v5.
|
|
501
|
+
Anclado a `v5.3.0`.
|
|
436
502
|
|
|
437
503
|
| Capa | Artefacto | Estado |
|
|
438
504
|
|---|---|---|
|
|
439
505
|
| Glosario | [docs/glossary/glossary.md](docs/glossary/glossary.md) | parcial, acreta por PR |
|
|
440
|
-
| Comportamiento | [docs/behavior/behavior.md](docs/behavior/behavior.md) | completa —
|
|
506
|
+
| Comportamiento | [docs/behavior/behavior.md](docs/behavior/behavior.md) | completa — 8 flujos (backfill on-demand) |
|
|
441
507
|
| Configuración | [docs/config/configuracion.md](docs/config/configuracion.md) | §a-§e/§i estructura + §f/§g/§h enrich — completa |
|
|
442
508
|
| Dependencias consumidas | [docs/consumed/rabbitmq.md](docs/consumed/rabbitmq.md) | §a/§b/§d estructura + §c/§e enrich |
|
|
443
509
|
| Errores | [docs/errors/errors.md](docs/errors/errors.md) | §a/§b/§d completas; §c política inferida (verificación humana pendiente) |
|
|
444
|
-
| Test | [docs/test/testing.md](docs/test/testing.md) | §a-§h —
|
|
510
|
+
| Test | [docs/test/testing.md](docs/test/testing.md) | §a-§h — 18 unit / 8 integration / 1 rails (`spec/rails/`, en su propio proceso) |
|
|
445
511
|
| Release | [docs/release/release.md](docs/release/release.md) | completa (régimen gema: build→publish; §e/f/g n/a) |
|
|
446
512
|
| Datos | — | n/a — gema sin DB (sin schema/models) |
|
|
447
513
|
| Eventos | — | n/a — la gema **es** el transporte; no declara catálogo de eventos de dominio propio |
|
data/Rakefile
CHANGED
|
@@ -4,6 +4,7 @@ require 'rspec/core/rake_task'
|
|
|
4
4
|
|
|
5
5
|
RSpec::Core::RakeTask.new(:spec) do |t|
|
|
6
6
|
t.rspec_opts = '--require spec_helper'
|
|
7
|
+
t.exclude_pattern = 'spec/rails/**/*_spec.rb'
|
|
7
8
|
end
|
|
8
9
|
|
|
9
10
|
RSpec::Core::RakeTask.new('spec:unit') do |t|
|
|
@@ -16,6 +17,12 @@ RSpec::Core::RakeTask.new('spec:integration') do |t|
|
|
|
16
17
|
t.rspec_opts = '--require spec_helper'
|
|
17
18
|
end
|
|
18
19
|
|
|
20
|
+
# Los specs que necesitan Rails (el Railtie) bootean una app propia, y Rails se inicializa una vez por
|
|
21
|
+
# proceso: corren aparte, para que el resto de la suite siga probando la gema fuera de Rails.
|
|
22
|
+
RSpec::Core::RakeTask.new('spec:rails') do |t|
|
|
23
|
+
t.pattern = 'spec/rails/**/*_spec.rb'
|
|
24
|
+
end
|
|
25
|
+
|
|
19
26
|
# Mantiene la tarea :test apuntando a los tests de integración legacy de Minitest
|
|
20
27
|
Rake::TestTask.new(:test) do |t|
|
|
21
28
|
t.libs << 'test'
|
|
@@ -25,4 +32,5 @@ Rake::TestTask.new(:test) do |t|
|
|
|
25
32
|
t.warning = false
|
|
26
33
|
end
|
|
27
34
|
|
|
28
|
-
|
|
35
|
+
# Las dos suites, cada una en su proceso: es lo que corren `quality-code` y `gem-release`.
|
|
36
|
+
task default: [:spec, 'spec:rails']
|
data/docs/behavior/behavior.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Comportamiento — bug_bunny
|
|
2
2
|
|
|
3
|
-
> meta: artefacto `comportamiento` · RFC-007 (cadencia incremental default / completo on-demand) · generado dev-enrich 1.3.0 (backfill on-demand) · anclado a `
|
|
3
|
+
> meta: artefacto `comportamiento` · RFC-007 (cadencia incremental default / completo on-demand) · generado dev-enrich 1.3.0 (backfill on-demand) · anclado a `67cca83` (squash de #71 en `main`; antes `35b075a`) · cobertura: completa (8 flujos) · verificado por humano 2026-05-18 (base) · 2026-05-26 (refresco scoped: contrato de error wrapping post-#49) — incremento 2026-09-28 (#64, flujo `drain` + re-mapeo de `file:line`): escrito por el agente, **sin verificación humana todavía** — incremento 2026-10-16 (#70, flujo «Executor de Rails alrededor de cada mensaje»; re-anclado a `67cca83` en el release 5.3.0): escrito por el agente, **sin verificación humana todavía**
|
|
4
4
|
|
|
5
5
|
## 1. Resumen
|
|
6
6
|
|
|
@@ -10,14 +10,16 @@ Flujos de ejecución de la gema. Generado en **modo completo on-demand** (RFC-00
|
|
|
10
10
|
|
|
11
11
|
| Flujo | Estado | Anclaje principal |
|
|
12
12
|
|---|---|---|
|
|
13
|
-
| RPC síncrono | **documentado** | `producer.rb:103-134`, `consumer.rb:
|
|
13
|
+
| RPC síncrono | **documentado** | `producer.rb:103-134`, `consumer.rb:305-446` |
|
|
14
14
|
| Fire-and-forget | **documentado** | `producer.rb:47-51,146-161` |
|
|
15
15
|
| Confirmed + basic.return bridge | **documentado** | `producer.rb:72-93,299-333`, `session.rb:204-250` |
|
|
16
|
-
| Consumer subscribe loop + reconnect + health | **documentado** | `consumer.rb:
|
|
17
|
-
|
|
|
16
|
+
| Consumer subscribe loop + reconnect + health | **documentado** | `consumer.rb:76-111,493-514` |
|
|
17
|
+
| Consumer drain (drenar y salir) | **documentado** | `consumer.rb:158-176,271-290`, `drain_tracker.rb:28-47` |
|
|
18
|
+
| Error handling / RemoteError | **documentado** | `consumer.rb:473-482`, `remote_error.rb`, `raise_error.rb:32-65` |
|
|
18
19
|
| Client middleware stack (onion) | **documentado** | `middleware/stack.rb:43-47`, `base.rb:35-43` |
|
|
20
|
+
| Executor de Rails alrededor de cada mensaje | **documentado** | `railtie.rb:44-51`, `consumer_middleware/rails_executor.rb:28-30`, `consumer.rb:227-238` |
|
|
19
21
|
|
|
20
|
-
Cobertura completa a `
|
|
22
|
+
Cobertura completa a `67cca83`. Acreta incremental en cada PR que toque un flujo (default RFC-007). Ausencia futura ≠ inexistencia.
|
|
21
23
|
|
|
22
24
|
## 2. Cuerpo
|
|
23
25
|
|
|
@@ -50,7 +52,7 @@ sequenceDiagram
|
|
|
50
52
|
P-->>CL: response hidratada
|
|
51
53
|
Note over P: bloqueo L122 · timeout → RequestTimeout L124
|
|
52
54
|
```
|
|
53
|
-
Contexto: `client.rb:97-101` → `producer.rb:103-134` (bloqueo L122) → reply listener `producer.rb:405-424` → `consumer.rb:
|
|
55
|
+
Contexto: `client.rb:97-101` → `producer.rb:103-134` (bloqueo L122) → reply listener `producer.rb:405-424` → `consumer.rb:400,425-446`.
|
|
54
56
|
|
|
55
57
|
### Flujo: Fire-and-forget
|
|
56
58
|
Publica y retorna `{ 'status' => 202 }` sin esperar broker ni consumer.
|
|
@@ -109,14 +111,62 @@ sequenceDiagram
|
|
|
109
111
|
C->>H: start_health_check (touch file)
|
|
110
112
|
C->>BR: q.subscribe(manual_ack, block:true) — LOOP
|
|
111
113
|
loop por mensaje
|
|
112
|
-
BR->>C: deliver → consumer_middlewares → process_message
|
|
114
|
+
BR->>C: deliver → consumer_middlewares (en Rails: RailsExecutor primero) → process_message
|
|
113
115
|
end
|
|
114
116
|
H-->>S: cada interval: queue_declare(passive:true)
|
|
115
117
|
H-->>S: falla → cierra session (fuerza reconnect)
|
|
116
118
|
Note over C: rescue StandardError → attempt++ · backoff min(nri*2^(n-1), max) · sleep · retry (redeclara)
|
|
117
119
|
Note over C: max_reconnect_attempts alcanzado → raise (fatal) · ensure → shutdown
|
|
118
120
|
```
|
|
119
|
-
Contexto: `consumer.rb:
|
|
121
|
+
Contexto: `consumer.rb:76-111` (retry L90-108), `consumer.rb:493-514` (health). **Honestidad:** health check es thread aparte (TimerTask); no es parte del manejo de error del loop — se acoplan sólo vía cierre de session. Marcado, no fingido como un único flujo.
|
|
122
|
+
|
|
123
|
+
### Flujo: Consumer drain (drenar y salir)
|
|
124
|
+
Consume hasta que la cola queda quieta y retorna la cantidad procesada: el modo para correr un consumidor **como job** (#64). A diferencia del loop de `subscribe`, **no** tiene loop de reconexión ni health check (Bunny sí recupera la conexión por su cuenta con `automatically_recover`).
|
|
125
|
+
|
|
126
|
+
```mermaid
|
|
127
|
+
sequenceDiagram
|
|
128
|
+
participant J as Job (llamador)
|
|
129
|
+
participant C as Consumer
|
|
130
|
+
participant T as DrainTracker
|
|
131
|
+
participant BR as RabbitMQ
|
|
132
|
+
J->>C: Consumer.drain(connection:, queue_name:, …)
|
|
133
|
+
C->>BR: exchange/queue declare · bind · message_count
|
|
134
|
+
alt message_count == 0
|
|
135
|
+
C-->>J: 0 (sin esperar) · ensure → shutdown
|
|
136
|
+
else hay mensajes
|
|
137
|
+
C->>BR: subscribe(manual_ack, block:false) — respeta channel_prefetch
|
|
138
|
+
loop por entrega (work pool de Bunny)
|
|
139
|
+
BR->>C: deliver → T.track { middlewares → process_message → ack/reject }
|
|
140
|
+
end
|
|
141
|
+
loop cada drain_poll_interval
|
|
142
|
+
C->>T: idle?(drain_idle_timeout) — nada en proceso y sin actividad en la ventana
|
|
143
|
+
end
|
|
144
|
+
C->>BR: cancel · espera a que T no esté busy
|
|
145
|
+
C-->>J: T.processed · ensure → shutdown
|
|
146
|
+
end
|
|
147
|
+
```
|
|
148
|
+
Contexto: `consumer.rb:158-176` (`drain`), `consumer.rb:271-290` (`consume_until_idle`), `drain_tracker.rb:28-47`. **Mensajes que llegan mientras drena:** entran en esta vuelta si llegan antes de que venza la ventana; los posteriores quedan para la próxima corrida. Una entrega ya recibida al cancelar se procesa antes de volver (Bunny drena su work pool al cancelar — leído de la fuente de Bunny 2.24.0, no medido); si igual no se ack-eara, **vuelve a la cola** (at-least-once). El conteo devuelto incluye los rechazados. **Una entrega que falla fuera del rescue de `process_message`** (un middleware, `handle_fatal_error`) se rechaza sin requeue en `handle_delivery` y se loguea `consumer.delivery_failed`; antes quedaba sin ack, trababa el prefetch y `drain` volvía "con éxito" con la cola llena (medido en el review de #65). **Con un flujo sostenido no retorna:** si los mensajes llegan más seguido que `drain_idle_timeout` la ventana no vence — la duración la decide el productor; se acota desde afuera (timeout del job). **La conexión es del llamador:** `drain` cierra el canal, no la conexión. **Distinto de `subscribe(block: false)`:** ese modo retorna al instante y el `ensure shutdown` cierra el canal, así que no consume nada (medido en #64).
|
|
149
|
+
|
|
150
|
+
### Flujo: Executor de Rails alrededor de cada mensaje
|
|
151
|
+
Dentro de Rails, cada entrega corre dentro de `Rails.application.executor.wrap`, como un job de Sidekiq. El Consumer procesa en el hilo de trabajo de Bunny, que Rails no conoce: sin esto, el estado por hilo pasa de un mensaje al siguiente (#70).
|
|
152
|
+
|
|
153
|
+
```mermaid
|
|
154
|
+
sequenceDiagram
|
|
155
|
+
participant BR as RabbitMQ
|
|
156
|
+
participant C as Consumer#handle_delivery
|
|
157
|
+
participant X as RailsExecutor
|
|
158
|
+
participant M as otros middlewares (p. ej. tracing de ExisRay)
|
|
159
|
+
participant P as process_message
|
|
160
|
+
BR->>C: deliver (hilo de Bunny)
|
|
161
|
+
C->>X: consumer_middlewares.call
|
|
162
|
+
X->>X: executor.wrap — al entrar: reset de CurrentAttributes · prende la caché de queries de AR
|
|
163
|
+
X->>M: @app.call
|
|
164
|
+
M->>P: core: rutea, llama al controller, ack/reject, reply RPC
|
|
165
|
+
P-->>X: vuelve
|
|
166
|
+
X->>X: al salir: reset de CurrentAttributes · la conexión de AR vuelve al pool · se apaga y limpia la caché de queries
|
|
167
|
+
Note over C: un error que escapa: wrap lo relanza (en Rails ≥ 7.0, antes lo reporta a Rails.error) → rescue de handle_delivery → reject sin requeue
|
|
168
|
+
```
|
|
169
|
+
Contexto: `railtie.rb:44-51` (registro en `after_initialize`, sólo si `config.consumer_rails_executor`), `consumer_middleware.rb:72-75` (`Stack#prepend`), `consumer_middleware/rails_executor.rb:28-30` (`wrap`), `consumer.rb:227-238` (`handle_delivery`: la cadena y su `rescue`). **Va primero** (`prepend`) porque el reset al entrar borraría el estado que un middleware anterior ya cargó: el de tracing de ExisRay carga `ExisRay::Tracer` (un `CurrentAttributes`) y se registra en su propio `after_initialize`, en un orden que no controlamos. El ack/reject queda adentro del wrap (vive en `process_message`); el `rescue` de `handle_delivery`, afuera. Si el hilo ya está dentro del executor, `wrap` no abre otro. **Fuera de Rails** el Railtie no se carga y la cadena no cambia. Probado con Rails de verdad en `spec/rails/consumer_rails_executor_spec.rb` (Rails 8.1.4, la versión que corre la suite). **Cambio de conducta:** la caché de queries, que en el hilo de Bunny estaba apagada, queda prendida durante cada mensaje (`ActiveRecord::QueryCache::ExecutorHooks`).
|
|
120
170
|
|
|
121
171
|
### Flujo: Error handling / RemoteError
|
|
122
172
|
Excepción no manejada en controller → serializada (clase/mensaje/backtrace[0..25]) → reply 500 → reconstruida client-side por `Middleware::RaiseError`.
|
|
@@ -137,7 +187,7 @@ sequenceDiagram
|
|
|
137
187
|
RE->>RE: status 500..599 + bug_bunny_exception
|
|
138
188
|
RE-->>CL: raise BugBunny::RemoteError(class,message,backtrace)
|
|
139
189
|
```
|
|
140
|
-
Contexto: `controller.rb:200-234`, `consumer.rb:
|
|
190
|
+
Contexto: `controller.rb:200-234`, `consumer.rb:473-482`, `remote_error.rb:29-48`, `raise_error.rb:32-65`. **Honestidad:** backtrace truncado a 25 líneas en serialize; si el controller nunca llega a responder, el cliente expira por timeout en vez de recibir el error (no hay path de error garantizado).
|
|
141
191
|
|
|
142
192
|
### Flujo: Client middleware stack (onion)
|
|
143
193
|
`Stack#build` hace `@middlewares.reverse.inject(final_action)` → el **primer `use` queda como el más externo** (corre `on_request` primero, `on_complete` último). Documentado en `stack.rb:37-39`; sigue la convención Rack/Faraday (primer registrado = capa externa).
|
|
@@ -167,7 +217,7 @@ Contexto: `middleware/stack.rb:31-47` (build L43-47, `reverse.inject`), `base.rb
|
|
|
167
217
|
|---|---|---|
|
|
168
218
|
| Secuencias y `file:line` extraídos por el LLM del código a `a5cdb10`; 2ª pasada LLM corrigió 3 discrepancias (flujo middleware invertido, timeout RPC `producer.rb:124`, timeout confirmed `producer.rb:214-215`) | confirmed | **verificado por humano 2026-05-18** (invariante RFC-001 §3.3 satisfecho) |
|
|
169
219
|
| Orden wire `basic.return → basic.ack` garantizado por AMQP; `RETURN_RACE_WINDOW_S` cubre GVL | declared (código) / inferred (garantía AMQP) | confirmar lectura de `producer.rb:299-308` + spec AMQP |
|
|
170
|
-
| Health check acoplado flojo al loop vía cierre de session | inferred | confirmar `consumer.rb:
|
|
220
|
+
| Health check acoplado flojo al loop vía cierre de session | inferred | confirmar `consumer.rb:493-514` vs `90-108` |
|
|
171
221
|
| Frontera de error del Client: cualquier `Bunny::Exception` durante `@pool.with` (try_create o in-flight) → `BugBunny::CommunicationError` con `.cause` preservada (`client.rb:155-167`). `Producer#confirmed` rescate estrechado a `Bunny::Exception` (`producer.rb:87-90`) — no traga bugs Ruby. `BugBunny.create_connection` también envuelve (`bug_bunny.rb:96-99`). | declared (código post-#49) | confirmar lectura de `client.rb:155-167`, `producer.rb:87-90`, `bug_bunny.rb:96-99` + specs `communication_error_wrapping_spec.rb` |
|
|
172
222
|
|
|
173
223
|
## 4. Cobertura y fronteras
|
|
@@ -1,12 +1,19 @@
|
|
|
1
1
|
# Configuración — bug_bunny
|
|
2
2
|
|
|
3
3
|
> meta: artefacto configuración · RFC-012 · generado `arch-structure` (inventario
|
|
4
|
-
> §a-§e/§i) + `arch-enrich` (§f/§g/§h/§j) · anclado a `
|
|
4
|
+
> §a-§e/§i) + `arch-enrich` (§f/§g/§h/§j) · anclado a `67cca83` (squash de #71 en `main`),
|
|
5
5
|
> `lib/bug_bunny/configuration.rb`, `lib/bug_bunny.rb`, `lib/bug_bunny/railtie.rb`,
|
|
6
6
|
> `lib/bug_bunny/consumer.rb`,
|
|
7
7
|
> `lib/generators/bug_bunny/install/templates/initializer.rb` · fecha 2026-06-30
|
|
8
8
|
> · cobertura: §a-§e/§i (estructura) + §f/§g/§h (enrich, anclado a YARD) completas;
|
|
9
|
-
> §j n/a.
|
|
9
|
+
> §j n/a. Incremento 2026-09-28 (#64): `drain_idle_timeout`/`drain_poll_interval`,
|
|
10
|
+
> anclados a `configuration.rb:37-38,99-105,273-275` y `consumer.rb:271-290`; todas las
|
|
11
|
+
> citas `file:line` re-mapeadas al árbol de `35b075a` (el refactor de #64 las corrió).
|
|
12
|
+
> Incremento 2026-10-16 (#70): `consumer_rails_executor` (`configuration.rb:196,277`,
|
|
13
|
+
> `railtie.rb:44-51`); las citas de `configuration.rb` re-mapeadas por contenido (el atributo
|
|
14
|
+
> nuevo corrió +10/+11 todo lo que viene después) y las de `railtie.rb` (§i). Re-anclado a
|
|
15
|
+
> `67cca83` en el release 5.3.0: entre `35b075a` y `67cca83` sólo cambiaron los archivos de #70
|
|
16
|
+
> (re-mapeados) y `version.rb` (no citado). Escrito por el agente, sin verificación humana todavía.
|
|
10
17
|
|
|
11
18
|
## 1. Resumen
|
|
12
19
|
|
|
@@ -20,13 +27,15 @@ en `lib/`**; el `ENV.fetch` vive en el **template** que sugiere al consumidor
|
|
|
20
27
|
|
|
21
28
|
### a. Hecho verificable
|
|
22
29
|
|
|
23
|
-
- **Total opciones (`Configuration`):**
|
|
24
|
-
-
|
|
30
|
+
- **Total opciones (`Configuration`):** 33 (32 `attr_accessor` + 1 `attr_reader`; medido
|
|
31
|
+
2026-10-16, con `consumer_rails_executor` de #70 — el `29` anterior ya estaba desfasado del código antes de #64).
|
|
32
|
+
- **Validadas requeridas (`VALIDATIONS`, `configuration.rb:25-39`):** 5 (`host`,
|
|
25
33
|
`port`, `username`, `password`, `vhost` — `required: true`; igual tienen
|
|
26
34
|
default, `validate!` exige no-vacío).
|
|
27
|
-
- **Con default:**
|
|
28
|
-
- **Con rango validado:**
|
|
29
|
-
`read_timeout`, `write_timeout`, `rpc_timeout`, `channel_prefetch
|
|
35
|
+
- **Con default:** 33 (todas; defaults en `initialize`/`init_callback_defaults`/`init_drain_defaults`).
|
|
36
|
+
- **Con rango validado:** 9 (`port`, `heartbeat`, `connection_timeout`,
|
|
37
|
+
`read_timeout`, `write_timeout`, `rpc_timeout`, `channel_prefetch`,
|
|
38
|
+
`drain_idle_timeout`, `drain_poll_interval`).
|
|
30
39
|
- **Secretas (por nombre):** 1 (`password`).
|
|
31
40
|
- **ENV leídas por la gema en `lib/`:** 0 (config 100% por code-default + bloque).
|
|
32
41
|
|
|
@@ -37,36 +46,39 @@ Origen `code-default` salvo nota. Consumidor = `configuration.rb` (default en
|
|
|
37
46
|
|
|
38
47
|
| nombre | tipo | requerida | default | origen | consumidor | secret? |
|
|
39
48
|
|---|---|---|---|---|---|---|
|
|
40
|
-
| `host` | String | sí (validate!) | `'127.0.0.1'` | code-default | `configuration.rb:
|
|
41
|
-
| `port` | Integer | sí (validate!, 1..65535) | `5672` | code-default | `:
|
|
42
|
-
| `username` | String | sí (validate!) | `'guest'` | code-default | `:
|
|
43
|
-
| `password` | String | sí (validate!) | `'guest'` | code-default | `:
|
|
44
|
-
| `vhost` | String | sí (validate!) | `'/'` | code-default | `:
|
|
45
|
-
| `logger` | Logger | no | `Logger.new($stdout)` INFO | code-default | `:
|
|
46
|
-
| `bunny_logger` | Logger | no | `Logger.new($stdout)` WARN | code-default | `:
|
|
47
|
-
| `automatically_recover` | Boolean | no | `true` | code-default | `:
|
|
48
|
-
| `network_recovery_interval` | Integer | no | `5` | code-default | `:
|
|
49
|
-
| `max_reconnect_attempts` | Integer/nil | no | `nil` (reintenta ∞) | code-default | `:
|
|
50
|
-
| `max_reconnect_interval` | Integer | no | `60` | code-default | `:
|
|
51
|
-
| `connection_timeout` | Integer | no (1..300) | `10` | code-default | `:
|
|
52
|
-
| `read_timeout` | Integer | no (1..300) | `30` | code-default | `:
|
|
53
|
-
| `write_timeout` | Integer | no (1..300) | `30` | code-default | `:
|
|
54
|
-
| `heartbeat` | Integer | no (0..3600) | `15` | code-default | `:
|
|
55
|
-
| `continuation_timeout` | Integer (ms) | no | `15000` | code-default | `:
|
|
56
|
-
| `channel_prefetch` | Integer | no (1..10000) | `1` | code-default | `:
|
|
57
|
-
| `rpc_timeout` | Integer | no (1..3600) | `10` | code-default | `:
|
|
58
|
-
| `health_check_interval` | Integer | no | `60` | code-default | `:
|
|
59
|
-
| `health_check_file` | String/nil | no | `nil` (desactivado) | code-default | `:
|
|
60
|
-
| `
|
|
61
|
-
| `
|
|
62
|
-
| `
|
|
63
|
-
| `
|
|
64
|
-
| `
|
|
65
|
-
| `
|
|
66
|
-
| `
|
|
67
|
-
| `
|
|
68
|
-
| `
|
|
69
|
-
| `
|
|
49
|
+
| `host` | String | sí (validate!) | `'127.0.0.1'` | code-default | `configuration.rb:202` | no |
|
|
50
|
+
| `port` | Integer | sí (validate!, 1..65535) | `5672` | code-default | `:203` | no |
|
|
51
|
+
| `username` | String | sí (validate!) | `'guest'` | code-default | `:204` | no |
|
|
52
|
+
| `password` | String | sí (validate!) | `'guest'` | code-default | `:205` | **sí** |
|
|
53
|
+
| `vhost` | String | sí (validate!) | `'/'` | code-default | `:206` | no |
|
|
54
|
+
| `logger` | Logger | no | `Logger.new($stdout)` INFO | code-default | `:208` | no |
|
|
55
|
+
| `bunny_logger` | Logger | no | `Logger.new($stdout)` WARN | code-default | `:211` | no |
|
|
56
|
+
| `automatically_recover` | Boolean | no | `true` | code-default | `:213` | no |
|
|
57
|
+
| `network_recovery_interval` | Integer | no | `5` | code-default | `:214` | no |
|
|
58
|
+
| `max_reconnect_attempts` | Integer/nil | no | `nil` (reintenta ∞) | code-default | `:215` | no |
|
|
59
|
+
| `max_reconnect_interval` | Integer | no | `60` | code-default | `:216` | no |
|
|
60
|
+
| `connection_timeout` | Integer | no (1..300) | `10` | code-default | `:217` | no |
|
|
61
|
+
| `read_timeout` | Integer | no (1..300) | `30` | code-default | `:218` | no |
|
|
62
|
+
| `write_timeout` | Integer | no (1..300) | `30` | code-default | `:219` | no |
|
|
63
|
+
| `heartbeat` | Integer | no (0..3600) | `15` | code-default | `:220` | no |
|
|
64
|
+
| `continuation_timeout` | Integer (ms) | no | `15000` | code-default | `:221` | no |
|
|
65
|
+
| `channel_prefetch` | Integer | no (1..10000) | `1` | code-default | `:222` | no |
|
|
66
|
+
| `rpc_timeout` | Integer | no (1..3600) | `10` | code-default | `:223` | no |
|
|
67
|
+
| `health_check_interval` | Integer | no | `60` | code-default | `:224` | no |
|
|
68
|
+
| `health_check_file` | String/nil | no | `nil` (desactivado) | code-default | `:227` | no |
|
|
69
|
+
| `drain_idle_timeout` | Integer (s) | no (1..3600) | `5` | code-default | `:285` | no |
|
|
70
|
+
| `drain_poll_interval` | Numeric (s) | no (0.01..10) | `0.1` | code-default | `:286` | no |
|
|
71
|
+
| `controller_namespace` | String | no | `'BugBunny::Controllers'` | code-default | `:230` | no |
|
|
72
|
+
| `log_tags` | Array | no | `[:uuid]` | code-default | `:232` | no |
|
|
73
|
+
| `exchange_options` | Hash | no | `{}` | code-default | `:235` | no |
|
|
74
|
+
| `queue_options` | Hash | no | `{}` | code-default | `:236` | no |
|
|
75
|
+
| `consumer_middlewares` | Stack (attr_reader) | no | `Stack.new` | code-default | `:238` | no |
|
|
76
|
+
| `rpc_reply_headers` | Proc/nil | no | `nil` | code-default | `:272` | no |
|
|
77
|
+
| `on_rpc_reply` | Proc/nil | no | `nil` | code-default | `:273` | no |
|
|
78
|
+
| `on_return` | Proc/nil | no | `nil` | code-default | `:274` | no |
|
|
79
|
+
| `nack_raise` | Boolean | no | `true` | code-default | `:275` | no |
|
|
80
|
+
| `return_raise` | Boolean | no | `true` | code-default | `:276` | no |
|
|
81
|
+
| `consumer_rails_executor` | Boolean | no | `true` | code-default | `:277` | no |
|
|
70
82
|
|
|
71
83
|
> **Override por request:** `nack_raise` y `return_raise` se sobreescriben por
|
|
72
84
|
> llamada con `nack_raise:` / `return_raise:` en `Client#publish` (scope-override
|
|
@@ -87,7 +99,7 @@ El install template (`initializer.rb`) **sugiere al consumidor** wirear 4 ENV
|
|
|
87
99
|
### d. Derivaciones simples
|
|
88
100
|
|
|
89
101
|
- `url` ← `"amqp://#{username}:#{password}@#{host}:#{port}/#{vhost}"`
|
|
90
|
-
(`configuration.rb:
|
|
102
|
+
(`configuration.rb:246`).
|
|
91
103
|
- `create_connection(**options)` ← `merge_connection_options(options)` sobre la
|
|
92
104
|
config global; las options explícitas pisan los defaults (`bug_bunny.rb:88`).
|
|
93
105
|
|
|
@@ -100,11 +112,12 @@ El install template (`initializer.rb`) **sugiere al consumidor** wirear 4 ENV
|
|
|
100
112
|
|
|
101
113
|
| inyección | qué hace | ancla |
|
|
102
114
|
|---|---|---|
|
|
103
|
-
| `initializer 'bug_bunny.add_autoload_paths'` | registra `app/rabbit` en el autoloader (Zeitwerk, `eager_load: true`) si existe | `:
|
|
104
|
-
| `config.after_initialize` → `ForkTracker.after_fork` | cierra la conexión heredada en cada fork (Rails 7.1+) | `:
|
|
105
|
-
| `config.after_initialize` → `Puma.events.on_worker_boot` | mismo cierre, hook legacy Puma <5 | `:
|
|
106
|
-
| `
|
|
107
|
-
| `
|
|
115
|
+
| `initializer 'bug_bunny.add_autoload_paths'` | registra `app/rabbit` en el autoloader (Zeitwerk, `eager_load: true`) si existe | `:16-19` |
|
|
116
|
+
| `config.after_initialize` → `ForkTracker.after_fork` | cierra la conexión heredada en cada fork (Rails 7.1+) | `:25-27` |
|
|
117
|
+
| `config.after_initialize` → `Puma.events.on_worker_boot` | mismo cierre, hook legacy Puma <5 | `:31-35` |
|
|
118
|
+
| `config.after_initialize` → `consumer_middlewares.prepend(RailsExecutor)` | si `consumer_rails_executor` (default `true`), pone `ConsumerMiddleware::RailsExecutor` **primero** en la cadena del Consumer: cada mensaje corre dentro de `Rails.application.executor.wrap` (#70) | `:44-51` |
|
|
119
|
+
| `rake_tasks` | carga `tasks/bug_bunny.rake` (`bug_bunny:sync`) | `:54-56` |
|
|
120
|
+
| `Spring.after_fork` | cierra conexión en preloader Spring | `:59-63` |
|
|
108
121
|
|
|
109
122
|
### f. Enriquecimiento semántico
|
|
110
123
|
|
|
@@ -116,21 +129,23 @@ del código.
|
|
|
116
129
|
| Conexión (`host`/`port`/`username`/`password`/`vhost`) | conectividad | valor inválido/vacío → `ConfigurationError` en `validate!`; credencial/host errados → `CommunicationError` al conectar (`bug_bunny.rb:95`) | abre socket TCP al broker | identidad y destino del broker; `vhost` aísla ambientes |
|
|
117
130
|
| Timeouts (`connection_timeout`/`read_timeout`/`write_timeout`/`heartbeat`/`continuation_timeout`) | resiliencia/latencia | muy bajo → cortes espurios bajo carga; muy alto → detección de fallo lenta | — | tuning de la conexión Bunny; `heartbeat` detecta conexiones zombi |
|
|
118
131
|
| `rpc_timeout` | latencia | el worker remoto no responde a tiempo → `RequestTimeout` (`producer.rb:124,214`) | bloquea el hilo llamante hasta el timeout | techo de espera de un RPC síncrono |
|
|
119
|
-
| Resiliencia (`automatically_recover`/`network_recovery_interval`/`max_reconnect_attempts`/`max_reconnect_interval`) | resiliencia | `max_reconnect_attempts` agotado → el Consumer re-levanta y muere (`consumer.rb:
|
|
132
|
+
| Resiliencia (`automatically_recover`/`network_recovery_interval`/`max_reconnect_attempts`/`max_reconnect_interval`) | resiliencia | `max_reconnect_attempts` agotado → el Consumer re-levanta y muere (`consumer.rb:94-96`) | reintentos con **backoff exponencial** `network_recovery_interval * 2^(n-1)` cap `max_reconnect_interval` (`consumer.rb:99-102`) | sobrevivir caídas transitorias del broker sin perder el worker |
|
|
120
133
|
| QoS (`channel_prefetch`) | rendimiento | alto → un worker lento acapara mensajes; `1` → menor throughput | controla unacked in-flight (backpressure) | balancea fairness vs throughput (default `1` = fair round-robin) |
|
|
121
134
|
| Health (`health_check_interval`/`health_check_file`) | observabilidad | `health_check_file` no escribible → el touch falla (degradación de visibilidad, no del flujo) | **escribe (touch) un archivo** en cada health check OK; `nil` desactiva | probe para orquestadores (K8s/Swarm) |
|
|
122
|
-
|
|
|
135
|
+
| Drain (`drain_idle_timeout`/`drain_poll_interval`) | latencia | `drain_idle_timeout` muy bajo → un productor lento deja mensajes para la próxima corrida (no se pierden); muy alto → el job tarda más en terminar tras vaciar la cola | ninguno: sólo acota cuánto espera `Consumer#drain` (`consumer.rb:285`) | correr un consumidor como job que termina (#64) |
|
|
136
|
+
| Callbacks (`on_return`/`on_rpc_reply`/`rpc_reply_headers`) | extensibilidad | una excepción en `on_return` se captura pero **degrada visibilidad** (YARD `configuration.rb:157`) | corren en hilos sensibles (ver §h) | propagar trace-context / alertar unroutable |
|
|
123
137
|
| Confirms (`nack_raise`/`return_raise`) | integridad de entrega | `false` → NACK/return solo se logea, la llamada retorna `202` (modo legacy, posible pérdida silenciosa) | habilitan el raise de `PublishNacked`/`PublishUnroutable` | elegir entre fail-fast vs best-effort en publish confirmado |
|
|
124
|
-
|
|
|
138
|
+
| Executor de Rails (`consumer_rails_executor`) | aislamiento entre mensajes | `false` dentro de Rails → el estado por hilo (`CurrentAttributes`, conexión de ActiveRecord) pasa de un mensaje al siguiente, salvo que el consumidor envuelva cada mensaje por su cuenta; fuera de Rails no tiene efecto | `true` → el Railtie registra `ConsumerMiddleware::RailsExecutor` **primero** en la cadena (`railtie.rb:44-51`); en Rails ≥ 7.0, un error que escapa del mensaje además se reporta a `Rails.error` (`handled: false`), y la caché de queries de AR queda prendida durante cada mensaje | que cada mensaje empiece limpio, como un job de Sidekiq (#70) |
|
|
139
|
+
| Routing (`controller_namespace`) | seguridad | clase resuelta no subclase de `BugBunny::Controller` → el worker responde **403** + reject (guard anti-RCE, `consumer.rb:375-381`) | acota qué clases son enrutables | superficie de control de RCE |
|
|
125
140
|
| Logging (`logger`/`bunny_logger`/`log_tags`) | observabilidad | — | salida a `$stdout` por default | trazabilidad estructurada |
|
|
126
141
|
| Infra (`exchange_options`/`queue_options`) | infraestructura | options incompatibles con el broker → `PreconditionFailed` (vía `CommunicationError`) | defaults globales mergeados por recurso | declaración AMQP por default |
|
|
127
142
|
|
|
128
143
|
### g. Ramificadores intra-config
|
|
129
144
|
|
|
130
145
|
- `health_check_file = nil` (default) **desactiva** el touchfile aunque
|
|
131
|
-
`health_check_interval` siga corriendo (`configuration.rb:
|
|
146
|
+
`health_check_interval` siga corriendo (`configuration.rb:109-111,227`).
|
|
132
147
|
- `return_raise` es **inerte cuando `mandatory: false`** — sin `mandatory` el
|
|
133
|
-
broker nunca retorna, así que el flag no tiene efecto (`configuration.rb:
|
|
148
|
+
broker nunca retorna, así que el flag no tiene efecto (`configuration.rb:181`).
|
|
134
149
|
- `nack_raise`/`return_raise` se sobreescriben **por request** (`Client#publish`),
|
|
135
150
|
ganando sobre el valor global (scope-override).
|
|
136
151
|
|
|
@@ -138,10 +153,10 @@ del código.
|
|
|
138
153
|
|
|
139
154
|
| opción | hilo de ejecución | restricción |
|
|
140
155
|
|---|---|---|
|
|
141
|
-
| `on_return` | **hilo interno del consumidor de Bunny** (`configuration.rb:
|
|
142
|
-
| `on_rpc_reply` | **hilo llamante** tras recibir el reply RPC (`configuration.rb:
|
|
143
|
-
| `rpc_reply_headers` | hilo del consumer, justo antes del `basic_publish` del reply (`configuration.rb:
|
|
144
|
-
| reconexión del Consumer | hilo del `subscribe` loop (`consumer.rb:
|
|
156
|
+
| `on_return` | **hilo interno del consumidor de Bunny** (`configuration.rb:157`) | debe ser rápido y no lanzar; BugBunny captura, pero degrada visibilidad |
|
|
157
|
+
| `on_rpc_reply` | **hilo llamante** tras recibir el reply RPC (`configuration.rb:142`) | hidrata trace-context en el publisher |
|
|
158
|
+
| `rpc_reply_headers` | hilo del consumer, justo antes del `basic_publish` del reply (`configuration.rb:135`) | debe retornar un Hash de headers |
|
|
159
|
+
| reconexión del Consumer | hilo del `subscribe` loop (`consumer.rb:87,106`) | `sleep wait` bloquea ese hilo durante el backoff |
|
|
145
160
|
|
|
146
161
|
### j. Inyección a gemas configuradas
|
|
147
162
|
|
data/docs/consumed/rabbitmq.md
CHANGED
|
@@ -69,16 +69,16 @@ catálogo `docs/errors/errors.md` (RFC-020), no lo redefine.
|
|
|
69
69
|
|
|
70
70
|
| aspecto | comportamiento (anclado) |
|
|
71
71
|
|---|---|
|
|
72
|
-
| recuperación de conexión | `automatically_recover = true` (default): Bunny recupera canales/suscripciones tras corte TCP (`configuration.rb:
|
|
73
|
-
| retry del Consumer | `Consumer#subscribe` reintenta en cualquier `StandardError` con **backoff exponencial** `network_recovery_interval * 2^(n-1)` cap `max_reconnect_interval`, hasta `max_reconnect_attempts` (`nil` = ∞) (`consumer.rb:
|
|
74
|
-
| ack | `manual_ack: true` (`consumer.rb:
|
|
72
|
+
| recuperación de conexión | `automatically_recover = true` (default): Bunny recupera canales/suscripciones tras corte TCP (`configuration.rb:62-63`). |
|
|
73
|
+
| retry del Consumer | `Consumer#subscribe` reintenta en cualquier `StandardError` con **backoff exponencial** `network_recovery_interval * 2^(n-1)` cap `max_reconnect_interval`, hasta `max_reconnect_attempts` (`nil` = ∞) (`consumer.rb:90-108`). |
|
|
74
|
+
| ack | `manual_ack: true` (`consumer.rb:87`) → entrega **at-least-once**: si el worker cae tras procesar pero antes del ack, el mensaje se re-entrega. **El handler debe ser idempotente.** |
|
|
75
75
|
| retry de publish | **no automático** — un publish fallido levanta `CommunicationError`/`PublishNacked`; reintentarlo puede **duplicar** salvo dedup aguas abajo. |
|
|
76
76
|
| RPC | `request` espera reply hasta `rpc_timeout`; el retry de un RPC mutante requiere idempotencia (correlación por `correlation_id`). |
|
|
77
77
|
|
|
78
78
|
### e. Degradación (si RabbitMQ cae)
|
|
79
79
|
|
|
80
80
|
- **Al conectar:** `create_connection` levanta `CommunicationError` (`bug_bunny.rb:95`); no hay fallback ni cola local — el caller decide (circuit-break/alertar).
|
|
81
|
-
- **Consumer:** entra al loop de reconexión con backoff; por default (`max_reconnect_attempts = nil`) **reintenta indefinidamente**, logueando `consumer.connection_error` con `retry_in_s` (`consumer.rb:
|
|
81
|
+
- **Consumer:** entra al loop de reconexión con backoff; por default (`max_reconnect_attempts = nil`) **reintenta indefinidamente**, logueando `consumer.connection_error` con `retry_in_s` (`consumer.rb:104-106`). Si se fija un máximo y se agota → `consumer.reconnect_exhausted` y re-raise (el worker muere).
|
|
82
82
|
- **Publisher:** cada publish/RPC sobre conexión caída levanta `CommunicationError` (envuelto en `client.rb:168`); **sin buffering** — el mensaje no sale.
|
|
83
83
|
- **Sin circuit-breaker propio:** la gema no trae breaker ni outbox; la resiliencia aguas arriba (reintentar el comando, encolar, alertar) es responsabilidad del consumidor.
|
|
84
84
|
|