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
-
.retroactively_apply_to_span(span, ctx) ⇒ Object
Retroactively applies AR context to a finished span (e.g. PREPARE spans that finished before sql.active_record fired).
-
.stash_prepare_span(span) ⇒ Object
Called from CallContextProcessor#on_finish when a PREPARE span finishes before its sql.active_record notification.
-
.stub_context(context) ⇒ Object
Test helpers: set AR context directly for unit tests.
- .stub_scope(scope_name) ⇒ Object
Class Method Details
.app_root ⇒ Object
179 180 181 |
# File 'lib/rails_otel_context/activerecord_context.rb', line 179 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.
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 |
# File 'lib/rails_otel_context/activerecord_context.rb', line 241 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 return unless span.respond_to?(:attributes) && span.attributes&.key?('db.system') # 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.
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 |
# File 'lib/rails_otel_context/activerecord_context.rb', line 346 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
187 188 189 190 191 |
# File 'lib/rails_otel_context/activerecord_context.rb', line 187 def clear! Thread.current[THREAD_KEY] = nil Thread.current[SCOPE_THREAD_KEY] = nil Thread.current[PENDING_PREPARE_KEY] = nil end |
.current ⇒ Object
183 184 185 |
# File 'lib/rails_otel_context/activerecord_context.rb', line 183 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.
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 |
# File 'lib/rails_otel_context/activerecord_context.rb', line 327 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
167 168 169 170 171 172 173 174 175 176 177 |
# File 'lib/rails_otel_context/activerecord_context.rb', line 167 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+.
276 277 278 279 280 281 282 283 284 285 286 287 288 289 |
# File 'lib/rails_otel_context/activerecord_context.rb', line 276 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.
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 |
# File 'lib/rails_otel_context/activerecord_context.rb', line 297 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) model_name = table ? ar_table_model_map[table] : nil # Fall back to the virtual "SQL" model when the table cannot be resolved # (e.g. SELECT SLEEP(0.2), SELECT 1, raw DDL). This lets the span-name # formatter produce "SQL.Select" / "SQL.Update" for tab-group purposes # instead of leaving the span unnamed. model_name ||= 'SQL' { model_name: model_name, method_name: verb, query_key: "#{model_name}.#{verb}".freeze } end |
.reset_ar_table_model_map! ⇒ Object
377 378 379 |
# File 'lib/rails_otel_context/activerecord_context.rb', line 377 def reset_ar_table_model_map! @ar_table_model_map = nil end |
.retroactively_apply_to_span(span, ctx) ⇒ Object
Retroactively applies AR context to a finished span (e.g. PREPARE spans that finished before sql.active_record fired). Uses direct @attributes mutation because span.recording? is false — set_attribute would be a no-op.
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 |
# File 'lib/rails_otel_context/activerecord_context.rb', line 212 def retroactively_apply_to_span(span, ctx) attrs = span.instance_variable_get(:@attributes) return unless attrs.respond_to?(:store) attrs.store(AR_MODEL_ATTR, ctx[:model_name]) if ctx[:model_name] attrs.store(AR_METHOD_ATTR, ctx[:method_name]) if ctx[:method_name] attrs.store(AR_SCOPE_ATTR, ctx[:scope_name]) if ctx[:scope_name] formatter = RailsOtelContext.configuration.span_name_formatter return unless formatter && span.respond_to?(:name) && attrs.key?('db.system') ar_ctx = ctx.dup ar_ctx[:code_namespace] = attrs['code.namespace'] ar_ctx[:code_function] = attrs['code.function'] original_name = span.name new_name = formatter.call(original_name, ar_ctx) return unless new_name && new_name != original_name attrs.store(ORIG_NAME_ATTR, original_name) span.instance_variable_set(:@name, new_name) rescue StandardError nil end |
.stash_prepare_span(span) ⇒ Object
Called from CallContextProcessor#on_finish when a PREPARE span finishes before its sql.active_record notification. Stashed spans are flushed by Subscriber#start when the notification fires.
196 197 198 |
# File 'lib/rails_otel_context/activerecord_context.rb', line 196 def stash_prepare_span(span) (Thread.current[PENDING_PREPARE_KEY] ||= []) << span end |
.stub_context(context) ⇒ Object
Test helpers: set AR context directly for unit tests.
201 202 203 |
# File 'lib/rails_otel_context/activerecord_context.rb', line 201 def stub_context(context) Thread.current[THREAD_KEY] = context end |
.stub_scope(scope_name) ⇒ Object
205 206 207 |
# File 'lib/rails_otel_context/activerecord_context.rb', line 205 def stub_scope(scope_name) Thread.current[SCOPE_THREAD_KEY] = scope_name end |