Module: CMDx::Middlewares::Correlate
Overview
Middleware for correlating task executions with unique identifiers.
The Correlate middleware provides thread-safe correlation ID management for tracking task execution flows across different operations. It automatically generates correlation IDs when none are provided and stores them in task result metadata for traceability.
Constant Summary collapse
- THREAD_KEY =
:cmdx_correlate
Instance Method Summary collapse
-
#call(task, **options) { ... } ⇒ Object
Middleware entry point that applies correlation ID logic to task execution.
-
#clear ⇒ nil
Clears the current correlation ID from thread-local storage.
-
#id ⇒ String?
Retrieves the current correlation ID from thread-local storage.
-
#id=(id) ⇒ String
Sets the correlation ID in thread-local storage.
-
#use(new_id) { ... } ⇒ Object
Temporarily uses a new correlation ID for the duration of a block.
Instance Method Details
#call(task, **options) { ... } ⇒ Object
Middleware entry point that applies correlation ID logic to task execution.
Evaluates the condition from options and applies correlation ID handling if enabled. Generates or retrieves correlation IDs based on the :id option and stores them in task result metadata.
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 |
# File 'lib/cmdx/middlewares/correlate.rb', line 106 def call(task, **, &) return yield unless Utils::Condition.evaluate(task, ) correlation_id = task.result.[:correlation_id] ||= id || case callable = [:id] when Symbol then task.send(callable) when Proc then task.instance_eval(&callable) else if callable.respond_to?(:call) callable.call(task) else callable || id || Identifier.generate end end use(correlation_id, &) end |
#clear ⇒ nil
Clears the current correlation ID from thread-local storage.
51 52 53 |
# File 'lib/cmdx/middlewares/correlate.rb', line 51 def clear Thread.current[THREAD_KEY] = nil end |
#id ⇒ String?
Retrieves the current correlation ID from thread-local storage.
26 27 28 |
# File 'lib/cmdx/middlewares/correlate.rb', line 26 def id Thread.current[THREAD_KEY] end |
#id=(id) ⇒ String
Sets the correlation ID in thread-local storage.
39 40 41 |
# File 'lib/cmdx/middlewares/correlate.rb', line 39 def id=(id) Thread.current[THREAD_KEY] = id end |
#use(new_id) { ... } ⇒ Object
Temporarily uses a new correlation ID for the duration of a block. Restores the previous ID after the block completes, even if an error occurs.
70 71 72 73 74 75 76 |
# File 'lib/cmdx/middlewares/correlate.rb', line 70 def use(new_id) old_id = id self.id = new_id yield ensure self.id = old_id end |