exis_ray 0.11.1 → 1.0.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.
@@ -123,22 +123,13 @@ module ExisRay
123
123
  end
124
124
 
125
125
  # Construye los campos KV de excepción para el log de `task_finished` failed.
126
- # Siempre incluye `exception.type` / `exception.message` / `exception.stacktrace` (OTel v1.0).
127
- # Incluye además `error_class` / `error_message` cuando
128
- # `ExisRay.configuration.emit_legacy_exception_keys` es `true` (default durante la ventana
129
- # de transición).
126
+ # Incluye `exception.type` / `exception.message` / `exception.stacktrace` (OTel v1.0).
130
127
  #
131
128
  # @param error [Exception]
132
129
  # @return [String]
133
130
  def self.format_exception_fields(error)
134
- message_quoted = error.message.inspect
135
- stack = format_stacktrace(error.backtrace)
136
-
137
- parts = []
138
- parts << "error_class=#{error.class} error_message=#{message_quoted}" if ExisRay.configuration.emit_legacy_exception_keys
139
- parts << "exception.type=#{error.class} exception.message=#{message_quoted} " \
140
- "exception.stacktrace=#{stack}"
141
- parts.join(" ")
131
+ "exception.type=#{error.class} exception.message=#{error.message.inspect} " \
132
+ "exception.stacktrace=#{format_stacktrace(error.backtrace)}"
142
133
  end
143
134
 
144
135
  private_class_method :pod_identifier, :setup_tracer, :execute_with_optional_tags,
@@ -2,5 +2,5 @@
2
2
 
3
3
  module ExisRay
4
4
  # Versión actual de la gema.
5
- VERSION = "0.11.1"
5
+ VERSION = "1.0.0"
6
6
  end
data/lib/exis_ray.rb CHANGED
@@ -17,7 +17,9 @@ require "exis_ray/task_monitor"
17
17
  require "exis_ray/http_middleware"
18
18
  require "exis_ray/current"
19
19
  require "exis_ray/reporter"
20
+ require "exis_ray/log_sanitizer"
20
21
  require "exis_ray/json_formatter"
22
+ require "exis_ray/sanitizing_formatter"
21
23
 
22
24
  # Integraciones Opcionales
23
25
  # Solo cargamos el middleware de Faraday si la gema está presente en el sistema.
@@ -61,6 +63,22 @@ module ExisRay
61
63
  yield(configuration)
62
64
  end
63
65
 
66
+ # Pone el formatter de logs que corresponde a {Configuration#log_format}: {JsonFormatter} en JSON, o el que
67
+ # el logger ya tenía, envuelto en {SanitizingFormatter}, en texto (ADR-131). Lo usa el Railtie para el
68
+ # logger de Rails y el de Sidekiq.
69
+ #
70
+ # @param logger [Logger, nil]
71
+ # @return [void]
72
+ def install_log_formatter(logger)
73
+ return if logger.nil?
74
+
75
+ if configuration.json_logs?
76
+ logger.formatter = JsonFormatter.new
77
+ else
78
+ SanitizingFormatter.install(logger)
79
+ end
80
+ end
81
+
64
82
  # --- Helpers Centralizados de Resolución de Clases ---
65
83
 
66
84
  # Resuelve y retorna la clase configurada para manejar el contexto de negocio (Current).
data/skill/SKILL.md CHANGED
@@ -11,13 +11,14 @@ Para el complemento del estándar de logging Wispro (regla Data First, mapeo Ope
11
11
 
12
12
  ### Artefactos de detalle (RFC-008)
13
13
 
14
- Este SKILL.md **resume e indexa**; el contrato y el significado de detalle viven en `docs/<capa>/`. **Version-lock por construcción:** `gemspec.files` empaqueta `docs/**` en el mismo tag que este `SKILL.md`; los links son rutas relativas dentro del paquete del release (nunca rama/`HEAD`/URL flotante). Contrato resumido anclado a **v0.11.1** (capas de doc config/interface + Mapa de conocimiento; sin cambios de código desde v0.11.0):
14
+ Este SKILL.md **resume e indexa**; el contrato y el significado de detalle viven en `docs/<capa>/`. **Version-lock por construcción:** `gemspec.files` empaqueta `docs/**` en el mismo tag que este `SKILL.md`; los links son rutas relativas dentro del paquete del release (nunca rama/`HEAD`/URL flotante). Contrato resumido anclado a **v1.0.0** (filtro con la lista del servicio, topes y sólo nombres OpenTelemetry, sequre/exis_ray#24; la capa de release nace en esta versión):
15
15
 
16
16
  - [`docs/behavior/behavior.md`](../docs/behavior/behavior.md) — secuencias de hidratación de trace por entrypoint + emisión en logs (parcial, incremental).
17
17
  - [`docs/glossary/glossary.md`](../docs/glossary/glossary.md) — lenguaje ubicuo del bounded context (`root_id`, `trace_id`, `source`, `request_id`, `entrypoint`, ...).
18
18
  - [`docs/config/configuracion.md`](../docs/config/configuracion.md) — inventario de las 10 opciones de `ExisRay.configure` + `HOSTNAME` + inyecciones del Railtie al host (enriquecimiento semántico §f pendiente).
19
19
  - [`docs/test/testing.md`](../docs/test/testing.md) — mapa de suites RSpec + fixtures + coverage.
20
20
  - [`docs/interface/interface.md`](../docs/interface/interface.md) — superficie Ruby pública (símbolo · tipo · firma · nota); el detalle de uso de cada símbolo permanece abajo.
21
+ - [`docs/release/release.md`](../docs/release/release.md) — cómo se publica la gema (tag `v*` → RubyGems).
21
22
  - Datos · Operaciones · Eventos · Consumidas = `n/a` (gema sin DB, no expone superficie propia ni consume servicios). Topología/Release/Errores = **pendiente**. Ver mapa de cobertura completo en `AGENTS.md`.
22
23
 
23
24
  ---
@@ -83,7 +84,7 @@ ExisRay unifica trazabilidad distribuida, logging estructurado JSON, contexto de
83
84
  3. `ExisRay.sync_correlation_id` asigna `Tracer.correlation_id` a `Current.correlation_id`
84
85
  4. Controller ejecuta `before_action` para setear `Current.user_id`, `Current.isp_id`
85
86
  5. `JsonFormatter` intercepta cada `Rails.logger.*` e inyecta el contexto de ejecucion en cada linea. **No es incondicional:** cada campo tiene un guard especifico (ver tabla "Condiciones de emision" mas abajo). En particular `inject_tracer_context` corta el bloque `root_id`/`trace_id`/`source`/`task`/`sidekiq_job` con `return unless Tracer.root_id` — la invariante "todo entrypoint garantiza `root_id`" es lo que hace que `source` (mandatorio) nunca falte. `request_id` se emite **fuera** de ese guard (distinto ciclo de vida que `root_id`). El developer aporta `component` (modulo de negocio) y `event` (que paso); estos NO son auto-inyectados porque dependen del call site, no del contexto de ejecucion.
86
- 6. `LogSubscriber` emite un unico Hash al finalizar el request con campos default (`component`, `event`, `method`, `url.path` siempre + `path` si `config.emit_legacy_path_key`, `http_route`, `format`, `controller`, `action`, `http_status`, `duration_s`, `duration_human`, `view_runtime_s`, `db_runtime_s`, `user_agent_original`, `server_address`, y en error `exception.type`/`exception.message`/`exception.stacktrace` siempre + `error_class`/`error_message` si `config.emit_legacy_exception_keys`).
87
+ 6. `LogSubscriber` emite un unico Hash al finalizar el request con campos default (`component`, `event`, `method`, `url.path`, `http_route`, `format`, `controller`, `action`, `http_status`, `duration_s`, `duration_human`, `view_runtime_s`, `db_runtime_s`, `user_agent_original`, `server_address`, y en error `exception.type`/`exception.message`/`exception.stacktrace`).
87
88
  7. En llamadas salientes, `FaradayMiddleware`/`ActiveResourceInstrumentation` inyectan `propagation_trace_header` con `Tracer.generate_trace_header`
88
89
  8. Al finalizar, `ActiveSupport::CurrentAttributes` hace reset automatico
89
90
 
@@ -103,8 +104,6 @@ ExisRay.configure do |config|
103
104
  config.log_subscriber_class = "MyLogSubscriber" # String|nil, default nil
104
105
  config.service_version = "1.2.3" # String|nil, default: Rails config.version o config.x.version
105
106
  config.deployment_environment = "production" # String|nil, default: Rails.env
106
- config.emit_legacy_exception_keys = true # Boolean, default true (ventana transicion OTel v1.0)
107
- config.emit_legacy_path_key = true # Boolean, default true (ventana transicion `path` -> `url.path` OTel v1.0)
108
107
  end
109
108
 
110
109
  ExisRay.configuration.json_logs? # => true si log_format == :json
@@ -193,7 +192,7 @@ end
193
192
 
194
193
  Reglas:
195
194
 
196
- - `JsonFormatter` filtra claves sensibles del hash retornado (mismo regex que el resto del formatter).
195
+ - Lo que devuelve pasa por el mismo filtro que el mensaje (`README.md` §*Filtrado y topes de los logs*).
197
196
  - Si el override revienta, el formatter rescata silenciosamente (logging no afecta flujo principal).
198
197
  - Precedencia: campos canónicos del Tracer y keys del mensaje del developer pisan `log_fields` en colisión. Solo sirve para agregar fields nuevos, no para overrideear los canónicos.
199
198
 
@@ -239,8 +238,7 @@ ExisRay::TaskMonitor.run("billing:generate_invoices") do
239
238
  end
240
239
  # Genera root_id propio, loguea task_started/task_finished con outcome y duration_s.
241
240
  # En caso de error emite: exception.type, exception.message, exception.stacktrace
242
- # (OTel, limitado a 20 lineas) + error_class/error_message si
243
- # config.emit_legacy_exception_keys es true (default durante ventana de transicion).
241
+ # (OTel, limitado a 20 lineas).
244
242
  # Re-lanza excepciones despues de loguearlas.
245
243
  # Hace reset de Tracer, Current y Reporter en ensure.
246
244
  ```
@@ -257,7 +255,6 @@ Reemplaza Lograge. Se suscribe a `process_action.action_controller` y emite un H
257
255
  | `event` | String | Siempre `"http_request"` |
258
256
  | `method` | String | Verbo HTTP |
259
257
  | `url.path` | String | URL concreta del request (OTel v1.0). Siempre presente |
260
- | `path` | String | Alias legacy de `url.path`. Solo si `config.emit_legacy_path_key` (default `true`, deprecado) |
261
258
  | `http_route` | String | Template (ej: `/users/:id`). Baja cardinalidad para dashboards. En endpoints sin params coincide en valor con `url.path` — dupe semanticamente esperada (concrete vs template) |
262
259
  | `format` | Symbol/String | `html`, `json`, etc. |
263
260
  | `controller` | String | Class name del controller |
@@ -269,7 +266,6 @@ Reemplaza Lograge. Se suscribe a `process_action.action_controller` y emite un H
269
266
  | `db_runtime_s` | Float\|nil | Solo si ActiveRecord lo reporta |
270
267
  | `user_agent_original` | String | Header `User-Agent` |
271
268
  | `server_address` | String | Hostname sin puerto (de `Host` header) |
272
- | `error_class`, `error_message` | String | Solo en fallo y si `config.emit_legacy_exception_keys` (default `true`, deprecadas) |
273
269
  | `exception.type`, `exception.message`, `exception.stacktrace` | String | Solo en fallo (OTel; stack limitado a 20 lineas) |
274
270
 
275
271
  Para inyectar campos extra, sobreescribir `extra_fields`:
@@ -293,7 +289,7 @@ Se asigna automaticamente a `Rails.logger.formatter` cuando `log_format: :json`.
293
289
  - **String KV** (`"event=foo bar=baz"`): parsea pares y los eleva al root del JSON. Util para one-liners rapidos.
294
290
  - **String libre**: asigna al campo `body` (OTel log body).
295
291
 
296
- Casteo automatico: integers, floats, objetos JSON (`{...}`, `[...]`). Filtra claves sensibles (`password|secret|token|api_key|auth`) a `[FILTERED]`. Fallback a JSON minimo si el formateo falla.
292
+ Casteo automatico: integers, floats, objetos JSON (`{...}`, `[...]`). Tapa lo sensible y limita valores y línea con `ExisRay::LogSanitizer` (default + `filtered_keys` − `unfiltered_keys`, ADR-131; `README.md` §*Filtrado y topes de los logs*). Si tapar o escribir falla: contexto + `filter_error`, nunca el mensaje.
297
293
 
298
294
  #### Criterio auto-inyectado vs manual
299
295
 
@@ -121,7 +121,7 @@ Todo proceso aislado debe reportar inicio y finalización con estructura consist
121
121
  - `event`: identificador de estado (`task_started`, `task_finished`, `job_started`, `job_finished`).
122
122
  - `outcome`: resultado final como **string semántico**, nunca un código numérico: `success`, `failed`, `aborted`.
123
123
  - `duration_s`: tiempo total de ejecución (reloj monotónico).
124
- - `error_class` y `error_message`: **obligatorios solo en caso de fallo**.
124
+ - `exception.type` y `exception.message` (nombres de OpenTelemetry): **obligatorios solo en caso de fallo**.
125
125
 
126
126
  ```ruby
127
127
  start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
@@ -131,7 +131,7 @@ begin
131
131
  Rails.logger.info("component=billing event=task_finished outcome=success duration_s=#{duration_s} record_count=500")
132
132
  rescue => e
133
133
  duration_s = Process.clock_gettime(Process::CLOCK_MONOTONIC) - start
134
- Rails.logger.error("component=billing event=task_finished outcome=failed duration_s=#{duration_s} error_class=#{e.class} error_message=\"#{e.message}\"")
134
+ Rails.logger.error("component=billing event=task_finished outcome=failed duration_s=#{duration_s} exception.type=#{e.class} exception.message=#{e.message.inspect}")
135
135
  raise
136
136
  end
137
137
  ```
@@ -38,12 +38,10 @@ RSpec.describe ExisRay::Configuration do
38
38
  expect(config.deployment_environment).to be_nil
39
39
  end
40
40
 
41
- it "emit_legacy_exception_keys por defecto es true (ventana de transición OTel)" do
42
- expect(config.emit_legacy_exception_keys).to be true
43
- end
44
-
45
- it "emit_legacy_path_key por defecto es true (ventana de transición OTel url.path)" do
46
- expect(config.emit_legacy_path_key).to be true
41
+ it "filtrado y topes por defecto: sin listas propias, 500 caracteres, 100 elementos, 8 KB y 64 KB" do
42
+ expect([config.filtered_keys, config.unfiltered_keys]).to eq([nil, nil])
43
+ expect([config.max_value_chars, config.max_array_items, config.max_line_bytes, config.max_traverse_bytes])
44
+ .to eq([500, 100, 8192, 65_536])
47
45
  end
48
46
  end
49
47
 
@@ -167,18 +165,8 @@ RSpec.describe ExisRay::Configuration do
167
165
  expect(config.log_subscriber_class).to eq("MyLogSubscriber")
168
166
  end
169
167
 
170
- it "permite cambiar emit_legacy_exception_keys" do
171
- config = described_class.new
172
- config.emit_legacy_exception_keys = false
173
-
174
- expect(config.emit_legacy_exception_keys).to be false
175
- end
176
-
177
- it "permite cambiar emit_legacy_path_key" do
178
- config = described_class.new
179
- config.emit_legacy_path_key = false
180
-
181
- expect(config.emit_legacy_path_key).to be false
168
+ it "ya no tiene los flags de las claves viejas (se borraron en 0.12)" do
169
+ expect(described_class.new).not_to respond_to(:emit_legacy_exception_keys, :emit_legacy_path_key)
182
170
  end
183
171
  end
184
172
  end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "spec_helper"
4
+ require "stringio"
5
+
6
+ RSpec.describe "ExisRay.install_log_formatter" do
7
+ let(:config) { ExisRay::Configuration.new }
8
+ let(:io) { StringIO.new }
9
+ let(:logger) { Logger.new(io) }
10
+
11
+ before { allow(ExisRay).to receive(:configuration).and_return(config) }
12
+
13
+ it "en modo texto envuelve el formatter y tapa lo que escribe la app" do
14
+ config.log_format = :text
15
+
16
+ ExisRay.install_log_formatter(logger)
17
+ logger.info("token=SECRET")
18
+
19
+ expect(logger.formatter).to be_a(ExisRay::SanitizingFormatter)
20
+ expect(io.string).to include("token=[FILTERED]")
21
+ expect(io.string).not_to include("SECRET")
22
+ end
23
+
24
+ it "en modo JSON pone el JsonFormatter, sin envolverlo" do
25
+ config.log_format = :json
26
+
27
+ ExisRay.install_log_formatter(logger)
28
+
29
+ expect(logger.formatter).to be_an_instance_of(ExisRay::JsonFormatter)
30
+ end
31
+
32
+ it "no hace nada sin logger (Sidekiq sin logger)" do
33
+ expect { ExisRay.install_log_formatter(nil) }.not_to raise_error
34
+ end
35
+ end
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "spec_helper"
4
+ require "timeout"
4
5
 
5
6
  RSpec.describe ExisRay::JsonFormatter do
6
7
  subject(:formatter) { described_class.new }
@@ -291,7 +292,7 @@ RSpec.describe ExisRay::JsonFormatter do
291
292
 
292
293
  result = call("event=boot")
293
294
 
294
- # tenant_id="42" se castea a Integer por filter_sensitive_hash (igual que cualquier otro KV)
295
+ # tenant_id="42" se castea a Integer por cast_deep (igual que cualquier otro KV)
295
296
  expect(result).to include("tenant_id" => 42, "region" => "us-east-1", "event" => "boot")
296
297
  end
297
298
 
@@ -529,43 +530,155 @@ RSpec.describe ExisRay::JsonFormatter do
529
530
  end
530
531
  end
531
532
 
532
- describe "#filter_sensitive_hash (privado)" do
533
- it "filtra claves sensibles en el nivel raíz" do
534
- result = formatter.send(:filter_sensitive_hash, { user: "gabriel", password: "secret" })
533
+ describe "tapado y topes (ADR-131)" do
534
+ let(:config) { ExisRay::Configuration.new }
535
535
 
536
- expect(result[:user]).to eq("gabriel")
537
- expect(result[:password]).to eq("[FILTERED]")
536
+ before { allow(ExisRay).to receive(:configuration).and_return(config) }
537
+
538
+ def line_for(msg)
539
+ formatter.call(severity, timestamp, progname, msg)
538
540
  end
539
541
 
540
- it "filtra claves sensibles en hashes anidados" do
541
- result = formatter.send(:filter_sensitive_hash, {
542
- db: { host: "localhost", token: "abc123" }
543
- })
542
+ context "cuando se tapa" do
543
+ it "tapa un secreto en un string clave=valor" do
544
+ line = line_for("event=login password=SECRET")
544
545
 
545
- expect(result[:db][:host]).to eq("localhost")
546
- expect(result[:db][:token]).to eq("[FILTERED]")
547
- end
546
+ expect(JSON.parse(line)).to include("event" => "login", "password" => "[FILTERED]")
547
+ expect(line).not_to include("SECRET")
548
+ end
549
+
550
+ it "tapa las claves de la lista del servicio" do
551
+ config.filtered_keys = %w[data]
552
+
553
+ line = line_for({ event: "x", data: { a: "SECRET" } })
554
+
555
+ expect(JSON.parse(line)).to include("data" => "[FILTERED]")
556
+ expect(line).not_to include("SECRET")
557
+ end
558
+
559
+ it "tapa el JSON que viene adentro de un valor clave=valor" do
560
+ result = call('event=x queue_opts={"password":"SECRET","n":1}')
561
+
562
+ expect(result["queue_opts"]).to eq({ "password" => "[FILTERED]", "n" => 1 })
563
+ end
548
564
 
549
- it "filtra claves sensibles dentro de arrays de hashes" do
550
- result = formatter.send(:filter_sensitive_hash, {
551
- users: [{ name: "gabriel", password: "secret" }, { name: "ana", password: "other" }]
552
- })
565
+ it "tapa el body libre y no lo recorta por caracteres" do
566
+ result = call("login failed password=SECRET #{"x" * 600}")
553
567
 
554
- expect(result[:users][0][:name]).to eq("gabriel")
555
- expect(result[:users][0][:password]).to eq("[FILTERED]")
556
- expect(result[:users][1][:password]).to eq("[FILTERED]")
568
+ expect(result["body"]).to eq("login failed password=[FILTERED] #{"x" * 600}")
569
+ end
557
570
  end
558
571
 
559
- it "filtra claves sensibles en arrays primitivos cuando la clave padre es sensible" do
560
- result = formatter.send(:filter_sensitive_hash, { tokens: %w[abc def] })
572
+ context "con el tope de línea (max_line_bytes)" do
573
+ it "achica el message antes que el event" do
574
+ line = line_for({ event: "job_failed", message: "m" * 20_000 })
575
+ result = JSON.parse(line)
576
+
577
+ expect(result["event"]).to eq("job_failed")
578
+ expect(result["message"]).to end_with("…[TRUNCATED size=20000]")
579
+ expect(line.bytesize).to be <= 8192
580
+ end
581
+
582
+ it "recorta exception.message conservando el principio, en vez de reemplazarlo entero" do
583
+ message = "AFIP rechazó: #{"detalle " * 1_200}"
584
+ line = line_for({ event: "job_failed", "exception.type" => "Savon::SOAPFault", "exception.message" => message })
585
+ result = JSON.parse(line)
586
+
587
+ expect(result["exception.message"]).to start_with("AFIP rechazó: detalle")
588
+ expect(result["exception.message"]).to end_with("…[TRUNCATED size=#{message.bytesize}]")
589
+ expect(line.bytesize).to be <= 8192
590
+ end
591
+
592
+ it "con mensaje y stacktrace juntos, recorta el mensaje y conserva los frames" do
593
+ stack = Array.new(20) { |i| "/app/app/services/billing/afip/invoice_issuer_#{i}.rb:#{i}:in `issue`" }.join("\n")
594
+ line = line_for({ event: "job_failed", "exception.message" => "AFIP rechazó: #{"detalle " * 1_000}",
595
+ "exception.stacktrace" => stack })
596
+ result = JSON.parse(line)
597
+
598
+ expect(result["exception.stacktrace"]).to eq(stack)
599
+ expect(result["exception.message"]).to start_with("AFIP rechazó: detalle")
600
+ expect(line.bytesize).to be <= 8192
601
+ end
602
+
603
+ it "no se pasa del tope aunque el contexto solo no entre (F4)" do
604
+ allow(formatter).to receive(:current_tags).and_return(["x" * 9000])
605
+
606
+ line = line_for("hola")
607
+
608
+ expect(line.bytesize).to be <= 8192
609
+ expect(JSON.parse(line)).to include("service" => "test-service", "truncated" => true)
610
+ end
561
611
 
562
- expect(result[:tokens]).to eq(["[FILTERED]", "[FILTERED]"])
612
+ it "no toca una línea que entra" do
613
+ line = line_for({ event: "e", note: "n" })
614
+
615
+ expect(line).not_to include("TRUNCATED")
616
+ expect(JSON.parse(line)).not_to have_key("truncated")
617
+ end
618
+
619
+ it "reemplaza primero el campo más grande que no es de diagnóstico" do
620
+ result = JSON.parse(line_for({ event: "e", a: Array.new(100) { "x" * 500 } }))
621
+
622
+ expect(result).to include("event" => "e", "a" => "[TRUNCATED size=50301]")
623
+ end
624
+
625
+ it "siempre escribe JSON válido, en UTF-8 y dentro del tope (propiedad, semilla fija)" do
626
+ random = Random.new(20_261_201)
627
+ pieces = ["a", "ñ", "😀", '"', "\n", "\\", "token=x ", " "]
628
+ text = ->(max) { Array.new(random.rand(0..max)) { pieces.sample(random: random) }.join }
629
+
630
+ 200.times do |i|
631
+ msg = case i % 3
632
+ when 0 then text.call(40_000)
633
+ when 1 then { event: text.call(50), message: text.call(30_000), body: text.call(30_000), x: text.call(20_000) }
634
+ else { event: { nested: text.call(20_000) }, list: Array.new(random.rand(0..150)) { text.call(200) } }
635
+ end
636
+ line = line_for(msg)
637
+
638
+ expect(line).to be_valid_encoding
639
+ expect(line.bytesize).to be <= 8192
640
+ expect(JSON.parse(line)).to include("service" => "test-service", "level" => "INFO")
641
+ end
642
+ end
563
643
  end
564
644
 
565
- it "no altera valores no sensibles en arrays" do
566
- result = formatter.send(:filter_sensitive_hash, { tags: %w[admin active] })
645
+ context "cuando tapar o escribir falla" do
646
+ it "escribe el contexto y filter_error, nunca el mensaje" do
647
+ allow(ExisRay::LogSanitizer).to receive(:new).and_raise(ArgumentError)
648
+
649
+ line = line_for("password=SECRET plain text")
567
650
 
568
- expect(result[:tags]).to eq(%w[admin active])
651
+ expect(JSON.parse(line)).to include("filter_error" => "ArgumentError")
652
+ expect(JSON.parse(line)).not_to have_key("body")
653
+ expect(line).not_to include("SECRET")
654
+ end
655
+
656
+ it "conserva la traza y el negocio en el fallback" do
657
+ allow(ExisRay::LogSanitizer).to receive(:new).and_raise(ArgumentError)
658
+ allow(ExisRay::Tracer).to receive(:request_id).and_return("r-1")
659
+ allow(ExisRay).to receive(:current_class).and_return(Class.new { def self.user_id = 7 })
660
+
661
+ expect(call("x")).to include("request_id" => "r-1", "user_id" => 7, "service" => "test-service")
662
+ end
663
+
664
+ it "no levanta con un SystemStackError" do
665
+ sanitizer = instance_double(ExisRay::LogSanitizer)
666
+ allow(sanitizer).to receive(:call).and_raise(SystemStackError)
667
+ allow(ExisRay::LogSanitizer).to receive(:new).and_return(sanitizer)
668
+
669
+ expect(call({ a: 1 })).to include("filter_error" => "SystemStackError")
670
+ end
671
+
672
+ it "no se cuelga con un Hash que se referencia a sí mismo" do
673
+ cyclic = {}
674
+ cyclic[:a] = cyclic
675
+ cyclic[:b] = cyclic
676
+ cyclic[:c] = cyclic
677
+
678
+ line = Timeout.timeout(2) { line_for(cyclic) }
679
+
680
+ expect { JSON.parse(line) }.not_to raise_error
681
+ end
569
682
  end
570
683
  end
571
684
  end