Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rails reload fails when instrumenting class methods in config/initializers #301

Open
dmitri-minkin opened this issue Apr 18, 2022 · 1 comment

Comments

@dmitri-minkin
Copy link

dmitri-minkin commented Apr 18, 2022

Environment

Ruby interpreter version: ruby 2.7.5
statsd-instrument version: 3.1.2
StatsD backend: Datadog
Rails: 7.0.2.3
Machine: Mac M1
OS: Mac OS Monterey 12.3.1

Description

Anything that triggers reloading will throw error from statsd-instrument when instrumenting class methods from config/initializer.

How to reproduce

Given this code in Rails:

# app/services/pin/manager.rb

module Pin
  module Manager
        class << self
           def consume_and_grant
           end
        end
  end
end
# config/initializers/statsd.rb

Rails.application.reloader.to_prepare do
  Pin::Manager.singleton_class.extend(StatsD::Instrument)
  Pin::Manager.singleton_class.statsd_count_success(:consume_and_grant, "Pin.Manager.consume_and_grant")
end

Reload fails in console:

  1. Run in terminal: bin/rails console
  2. Reload in rails console: reload!

Observe this error:

Reloading...
ArgumentError: Already instrumented consume_and_grant for
from /Users/<user>/.gem/ruby/2.7.5/gems/statsd-instrument-3.1.2/lib/statsd/instrument.rb:263:in `add_to_method'

Possible cause

StatsD::Instrument having a cache that is likely not being reset on reload

Workaround

You can instrument inside the file that has the module being instrumented:

# app/services/pin/manager.rb

module Pin
  module Manager
        class << self
            def consume_and_grant
            end
        end
  end
end

Pin::Manager.singleton_class.extend(StatsD::Instrument)
Pin::Manager.singleton_class.statsd_count_success(:consume_and_grant, "Pin.Manager.consume_and_grant")
@swh-tropic
Copy link

Another workaround that also keeps the logic in an initializer is to use the after_initialize config hook:

Rails.application.config.after_initialize do
  # StatsD config here
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants