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
167 168 169 |
# File 'lib/rails_otel_context/activerecord_context.rb', line 167 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.
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 |
# File 'lib/rails_otel_context/activerecord_context.rb', line 193 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.
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 322 323 324 325 326 |
# File 'lib/rails_otel_context/activerecord_context.rb', line 297 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
175 176 177 178 |
# File 'lib/rails_otel_context/activerecord_context.rb', line 175 def clear! Thread.current[THREAD_KEY] = nil Thread.current[SCOPE_THREAD_KEY] = nil end |
.current ⇒ Object
171 172 173 |
# File 'lib/rails_otel_context/activerecord_context.rb', line 171 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.
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 |
# File 'lib/rails_otel_context/activerecord_context.rb', line 278 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
155 156 157 158 159 160 161 162 163 164 165 |
# File 'lib/rails_otel_context/activerecord_context.rb', line 155 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+.
227 228 229 230 231 232 233 234 235 236 237 238 239 240 |
# File 'lib/rails_otel_context/activerecord_context.rb', line 227 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.
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 |
# File 'lib/rails_otel_context/activerecord_context.rb', line 248 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
328 329 330 |
# File 'lib/rails_otel_context/activerecord_context.rb', line 328 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.
181 182 183 |
# File 'lib/rails_otel_context/activerecord_context.rb', line 181 def stub_context(context) Thread.current[THREAD_KEY] = context end |
.stub_scope(scope_name) ⇒ Object
185 186 187 |
# File 'lib/rails_otel_context/activerecord_context.rb', line 185 def stub_scope(scope_name) Thread.current[SCOPE_THREAD_KEY] = scope_name end |