Module: RailsOtelContext::ActiveRecordContext
- Defined in:
- lib/rails_otel_context/activerecord_context.rb
Overview
Extracts ActiveRecord model name, method, and scope from sql.active_record notifications and scope instrumentation.
Two mechanisms work together:
-
sql.active_record subscriber — captures model name + AR operation type (e.g., “Transaction Load”) at query time via payload.
-
Scope tracking — wraps scope-generated methods to store the scope name on the Relation object, then captures it at materialization time via Relation#exec_queries. This handles lazy scopes like Transaction.recent_completed.to_a where the scope method returns before SQL fires.
Defined Under Namespace
Modules: ClassMethodScopeTracking, RelationScopeCapture, ScopeNameTracking Classes: Subscriber
Constant Summary collapse
- DB_SLOW_ATTR =
'db.slow'
Class Method Summary collapse
- .app_root ⇒ Object
-
.apply_to_span(span, ctx) ⇒ Object
Applies AR context directly to a span.
-
.ar_table_model_map ⇒ Object
Lazy table_name → model_name index.
- .clear! ⇒ Object
- .current ⇒ Object
-
.extract_table_after(sql, keyword) ⇒ Object
Extracts a table name from
sqlstarting afterkeyword. - .install!(app_root: nil) ⇒ Object
-
.parse_ar_name(name) ⇒ Object
Parses “Transaction Load” → { model_name: “Transaction”, method_name: “Load” } Uses index+byteslice instead of split to avoid allocating the intermediate Array and two String copies — saves 1 alloc (Array) vs split which returns Array+Strings but with frozen_string_literal the slice shares storage on MRI 3.2+.
-
.parse_sql_context(sql) ⇒ Object
Parses raw SQL (payload == “SQL”) to extract model context.
- .reset_ar_table_model_map! ⇒ Object
-
.stub_context(context) ⇒ Object
Test helpers: set AR context directly for unit tests.
- .stub_scope(scope_name) ⇒ Object
Class Method Details
.app_root ⇒ Object
187 188 189 |
# File 'lib/rails_otel_context/activerecord_context.rb', line 187 def app_root @app_root end |
.apply_to_span(span, ctx) ⇒ Object
Applies AR context directly to a span. Used by Subscriber#start to enrich spans created by driver-level OTel instrumentation (Trilogy, PG) before our notification subscriber runs. Also reads code.namespace/code.function already set by CallContextProcessor#on_start so the span_name_formatter has full context.
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 |
# File 'lib/rails_otel_context/activerecord_context.rb', line 215 def apply_to_span(span, ctx) return unless span.context.valid? span.set_attribute('code.activerecord.model', ctx[:model_name]) if ctx[:model_name] span.set_attribute('code.activerecord.method', ctx[:method_name]) if ctx[:method_name] span.set_attribute('code.activerecord.scope', ctx[:scope_name]) if ctx[:scope_name] span.set_attribute('db.query_count', ctx[:query_count]) if ctx[:query_count] span.set_attribute('db.async', true) if ctx[:async] formatter = RailsOtelContext.configuration.span_name_formatter return unless formatter # Dup deferred to here: set_attribute calls above need only the original ctx keys. # The formatter may inspect code.namespace/code.function already on the span. ar_ctx = ctx.dup if span.respond_to?(:attributes) ar_ctx[:code_namespace] = span.attributes['code.namespace'] ar_ctx[:code_function] = span.attributes['code.function'] end original_name = span.name new_name = formatter.call(original_name, ar_ctx) return unless new_name && new_name != original_name && span.respond_to?(:name=) span.set_attribute('l9.orig.name', original_name) span.name = new_name rescue StandardError nil end |
.ar_table_model_map ⇒ Object
Lazy table_name → model_name index. Built on first use after all models are loaded (eager_load! in production). In development, call reset_ar_table_model_map! after a code reload to get a fresh index.
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 |
# File 'lib/rails_otel_context/activerecord_context.rb', line 316 def ar_table_model_map @ar_table_model_map ||= begin next_map = {} if defined?(::ActiveRecord::Base) ::ActiveRecord::Base.descendants.each do |m| model_name = begin m.name rescue StandardError next end next unless model_name # Skip STI subclasses — they share the parent's table_name. # Without this guard, AdminUser < User would overwrite users → User # with users → AdminUser in the map, giving wrong model names on # SQL-named spans (counter caches, update_all). next unless m.base_class == m table = begin m.table_name rescue StandardError next end next unless table next_map[table] = model_name end end next_map end end |
.clear! ⇒ Object
195 196 197 198 199 200 |
# File 'lib/rails_otel_context/activerecord_context.rb', line 195 def clear! Thread.current[THREAD_KEY] = nil Thread.current[SCOPE_THREAD_KEY] = nil Thread.current[TIMING_ID_KEY] = nil Thread.current[TIMING_START_KEY] = nil end |
.current ⇒ Object
191 192 193 |
# File 'lib/rails_otel_context/activerecord_context.rb', line 191 def current Thread.current[THREAD_KEY] end |
.extract_table_after(sql, keyword) ⇒ Object
Extracts a table name from sql starting after keyword. Skips one optional leading quote character (‘ “ ’), reads word chars until the next delimiter (space, quote, comma). Returns nil when keyword not found. Saves 1 alloc vs regex: index()+slice allocates only the result String.
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 |
# File 'lib/rails_otel_context/activerecord_context.rb', line 297 def extract_table_after(sql, keyword) idx = sql.index(keyword) return nil unless idx start = idx + keyword.length first = sql.getbyte(start) start += 1 if first == BYTE_BACKTICK || first == BYTE_DQUOTE || first == BYTE_SQUOTE # rubocop:disable Style/MultipleComparison stop = start stop += 1 while stop < sql.length && (b = sql.getbyte(stop)) != BYTE_SPACE && b != BYTE_BACKTICK && b != BYTE_DQUOTE && b != BYTE_SQUOTE && b != BYTE_COMMA stop > start ? sql[start, stop - start] : nil end |
.install!(app_root: nil) ⇒ Object
175 176 177 178 179 180 181 182 183 184 185 |
# File 'lib/rails_otel_context/activerecord_context.rb', line 175 def install!(app_root: nil) @app_root = File.(app_root.to_s) if app_root return unless defined?(::ActiveSupport::Notifications) return unless defined?(::ActiveRecord::Base) ActiveSupport::Notifications.subscribe('sql.active_record', Subscriber.new) ::ActiveRecord::Base.extend(ScopeNameTracking) ::ActiveRecord::Base.extend(ClassMethodScopeTracking) ::ActiveRecord::Relation.prepend(RelationScopeCapture) end |
.parse_ar_name(name) ⇒ Object
Parses “Transaction Load” → { model_name: “Transaction”, method_name: “Load” } Uses index+byteslice instead of split to avoid allocating the intermediate Array and two String copies — saves 1 alloc (Array) vs split which returns Array+Strings but with frozen_string_literal the slice shares storage on MRI 3.2+.
249 250 251 252 253 254 255 256 257 258 259 260 261 262 |
# File 'lib/rails_otel_context/activerecord_context.rb', line 249 def parse_ar_name(name) return nil unless name idx = name.index(' ') return nil unless idx model_name = name[0, idx] method_name = name[idx + 1, name.length] return nil if model_name == 'ActiveRecord' { model_name: model_name, method_name: method_name, query_key: "#{model_name}.#{method_name}".freeze } end |
.parse_sql_context(sql) ⇒ Object
Parses raw SQL (payload == “SQL”) to extract model context. Used for counter cache updates, touch_later, and connection.execute calls that fire sql.active_record with name=“SQL” rather than “Model Method”.
Returns nil when the table cannot be mapped to a known AR model, so callers fall through to the existing skip path.
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 |
# File 'lib/rails_otel_context/activerecord_context.rb', line 270 def parse_sql_context(sql) return nil unless sql verb = sql[SQL_VERB_RE, 1]&.capitalize return nil unless verb keyword = case verb when 'Update' then KW_UPDATE when 'Insert' then KW_INTO when 'Delete', 'Select' then KW_FROM end return nil unless keyword table = extract_table_after(sql, keyword) return nil unless table model_name = ar_table_model_map[table] return nil unless model_name { model_name: model_name, method_name: verb, query_key: "#{model_name}.#{verb}".freeze } end |
.reset_ar_table_model_map! ⇒ Object
347 348 349 |
# File 'lib/rails_otel_context/activerecord_context.rb', line 347 def reset_ar_table_model_map! @ar_table_model_map = nil end |
.stub_context(context) ⇒ Object
Test helpers: set AR context directly for unit tests.
203 204 205 |
# File 'lib/rails_otel_context/activerecord_context.rb', line 203 def stub_context(context) Thread.current[THREAD_KEY] = context end |
.stub_scope(scope_name) ⇒ Object
207 208 209 |
# File 'lib/rails_otel_context/activerecord_context.rb', line 207 def stub_scope(scope_name) Thread.current[SCOPE_THREAD_KEY] = scope_name end |