From 8d629480584da8fa807a09816987084af349242f Mon Sep 17 00:00:00 2001 From: Benjamin Fleischer Date: Thu, 24 Sep 2020 10:40:54 -0500 Subject: [PATCH] Add opt-in sidekiq extension for annotating delayed classes Even if no one wants to use the extension as is, it makes a good example of how one may do it. Usage: in config/initializers/sidekiq.rb ```ruby Marginalia::SidekiqInstrumentation.enable!(annotate_delayed_class_extension: true) ``` optionally customize the `marginalia_annotate_perform` method, for example ```ruby Sidekiq::Extensions::DelayedClass.class_eval do def marginalia_annotate_perform(target, method_name, args) Rollbar.scope!(target, method_name, *args) "#{target}.#{method_name}" end end ``` --- lib/marginalia/sidekiq_instrumentation.rb | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/lib/marginalia/sidekiq_instrumentation.rb b/lib/marginalia/sidekiq_instrumentation.rb index 3f000ca..f703068 100644 --- a/lib/marginalia/sidekiq_instrumentation.rb +++ b/lib/marginalia/sidekiq_instrumentation.rb @@ -13,7 +13,28 @@ def call(worker, msg, queue) end end - def self.enable! + def self.enable!(annotate_delayed_class_extension: false) + if annotate_delayed_class_extension + Sidekiq::Extensions::DelayedClass.class_eval do + # NOTE: Prefer redefining perform so that YAML is only parsed once. + # Adding a Marginalia::Comment.components would incur an extra parsing on every query + # in a delayed class + def perform(yml) + (target, method_name, args) = YAML.load(yml) + annotation_context = marginalia_annotate_perform(target, method_name, args) + Marginalia.with_annotation(annotation_context) do + target.__send__(method_name, *args) + end + end + + # NOTE: Hook is called before perform is executed and may have + # other side-effects + # @return [String] annotation_context + def marginalia_annotate_perform(target, method_name, args) + "#{target}.#{method_name}" + end + end + end Sidekiq.configure_server do |config| config.server_middleware do |chain| chain.add Marginalia::SidekiqInstrumentation::Middleware