Skip to content

Commit

Permalink
Instrument Reflex processing in development and log summary
Browse files Browse the repository at this point in the history
  • Loading branch information
Matt-Yorkley committed Mar 9, 2024
1 parent 078db30 commit 0120ae6
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
3 changes: 2 additions & 1 deletion lib/stimulus_reflex/configuration.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ def configuration
end

class Configuration
attr_accessor :on_failed_sanity_checks, :on_missing_default_urls, :parent_channel, :logging, :logger, :middleware, :morph_operation, :replace_operation, :precompile_assets
attr_accessor :on_failed_sanity_checks, :on_missing_default_urls, :parent_channel, :logging, :logger, :middleware, :morph_operation, :replace_operation, :precompile_assets, :instrument_reflexes

DEFAULT_LOGGING = proc { "[#{session_id}] #{operation_counter.magenta} #{reflex_info.green} -> #{selector.cyan} via #{mode} Morph (#{operation.yellow})" }

Expand All @@ -36,6 +36,7 @@ def initialize
@morph_operation = :morph
@replace_operation = :inner_html
@precompile_assets = true
@instrument_reflexes = Rails.env.development?
end
end
end
24 changes: 24 additions & 0 deletions lib/stimulus_reflex/instrumentation.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# frozen_string_literal: true

module StimulusReflex
class Instrumentation
def self.track(reflex)
return yield unless reflex.logger && StimulusReflex.config.instrument_reflexes

events = []

time = Benchmark.realtime do
ActiveSupport::Notifications.subscribed(lambda { |event| events << event }, /^sql.active_record|^render/) do
yield
end
end

sql, views = events.partition { |e| e.name.match?(/^sql/) }

reflex.logger.info "Processed #{reflex.class.name}##{reflex.method_name} in #{(time * 1000).round(1)}ms " +
"(Views: #{views.sum(&:duration).round(1)}ms | " +
"ActiveRecord: #{sql.sum(&:duration).round(1)}ms | " +
"Allocations: #{events.sum(&:allocations)}) \n"
end
end
end
5 changes: 4 additions & 1 deletion lib/stimulus_reflex/reflex.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

require "stimulus_reflex/cable_readiness"
require "stimulus_reflex/version_checker"
require "stimulus_reflex/instrumentation"

class StimulusReflex::Reflex
prepend StimulusReflex::CableReadiness
Expand Down Expand Up @@ -122,7 +123,9 @@ def render(*args)

# Invoke the reflex action specified by `name` and run all callbacks
def process(name, *args)
run_callbacks(:process) { public_send(name, *args) }
StimulusReflex::Instrumentation.track(self) do
run_callbacks(:process) { public_send(name, *args) }
end
end

# Indicates if the callback chain was halted via a throw(:abort) in a before_reflex callback.
Expand Down

0 comments on commit 0120ae6

Please sign in to comment.