gvl_metrics_middleware 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: e3ed6765b65e47dc4b7b194c206994881750a0029d07ab40125c4300b93bcba2
4
+ data.tar.gz: 66ce9746ef0ec48e258f34c5bf34c79325addc2393d29b19cc142c697d64edff
5
+ SHA512:
6
+ metadata.gz: f091d8530abd00c5aef08300d33ee3e50323d6e62cfb3a117fa478817af00d81a6a30cf33c98eba87a37731d01afda3a82751ea81f3bafaa37aba96af3891a88
7
+ data.tar.gz: f92832fddb6530a4ea8699c609b36f0fd283918740c2938a22dfe16e5a67059c21cf78b96e01b24b823fb64a76d193105a6174083d381c365713e670f5225125
data/.rubocop.yml ADDED
@@ -0,0 +1,16 @@
1
+ AllCops:
2
+ DisabledByDefault: true
3
+
4
+ Style/FrozenStringLiteralComment:
5
+ Enabled: true
6
+ EnforcedStyle: always_true
7
+
8
+ Style/StringLiterals:
9
+ Enabled: true
10
+ EnforcedStyle: double_quotes
11
+
12
+ Layout/EmptyLineAfterMagicComment:
13
+ Enabled: true
14
+
15
+ Layout/TrailingEmptyLines:
16
+ Enabled: true
data/Appraisals ADDED
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ appraise "rails_edge" do
4
+ git "https://github.com/rails/rails.git" do
5
+ gem "rails"
6
+ gem "railties"
7
+ gem "activesupport"
8
+ gem "activemodel"
9
+ end
10
+ end
11
+
12
+ appraise "rails_80" do
13
+ gem "rails", "~> 8.0.0"
14
+ gem "railties", "~> 8.0.0"
15
+ gem "activesupport", "~> 8.0.0"
16
+ gem "activemodel", "~> 8.0.0"
17
+ end
18
+
19
+ appraise "rails_72" do
20
+ gem "rails", "~> 7.2.0"
21
+ gem "railties", "~> 7.2.0"
22
+ gem "activesupport", "~> 7.2.0"
23
+ gem "activemodel", "~> 7.2.0"
24
+ end
25
+
26
+ appraise "rails_71" do
27
+ gem "rails", "~> 7.1.0"
28
+ gem "railties", "~> 7.1.0"
29
+ gem "activesupport", "~> 7.1.0"
30
+ gem "activemodel", "~> 7.1.0"
31
+ end
data/CHANGELOG.md ADDED
@@ -0,0 +1,10 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.2.0] - 2025-10-30
4
+
5
+ - Add sampling support ([#7](https://github.com/speedshop/gvl_metrics_middleware/pull/7)). Set `config.sampling_rate = 0.1` to sample 10% of requests/jobs (defaults to 1%).
6
+ - Allow middleware configuration in initializers ([#8](https://github.com/speedshop/gvl_metrics_middleware/pull/8)). Configure the middleware in `config/initializers/gvl_metrics_middleware.rb` before Rails loads it.
7
+
8
+ ## [0.1.0] - 2025-01-09
9
+
10
+ - Initial release
@@ -0,0 +1,132 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, caste, color, religion, or sexual
10
+ identity and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the overall
26
+ community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or advances of
31
+ any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email address,
35
+ without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official email address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ [INSERT CONTACT METHOD].
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series of
86
+ actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or permanent
93
+ ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within the
113
+ community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.1, available at
119
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120
+
121
+ Community Impact Guidelines were inspired by
122
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123
+
124
+ For answers to common questions about this code of conduct, see the FAQ at
125
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
126
+ [https://www.contributor-covenant.org/translations][translations].
127
+
128
+ [homepage]: https://www.contributor-covenant.org
129
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130
+ [Mozilla CoC]: https://github.com/mozilla/diversity
131
+ [FAQ]: https://www.contributor-covenant.org/faq
132
+ [translations]: https://www.contributor-covenant.org/translations
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Yuki Nishijima
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,143 @@
1
+ # GVL Metrics Middleware
2
+
3
+ `gvl_metrics_middleware` is a Ruby gem that provides middleware for monitoring and gathering metrics on Global VM Lock (
4
+ GVL) in multi-threaded Ruby applications. This gem leverages
5
+ [the `gvl_timing` gem](https://github.com/jhawthorn/gvl_timing) to measure time spent in the GVL and invokes a provided
6
+ callback with the collected metrics data.
7
+
8
+ ## Installation
9
+
10
+ Add the gem to your application’s Gemfile, and run `bundle install` to install the gem:
11
+
12
+ ```bash
13
+ gem 'gvl_metrics_middleware', git: "https://github.com/speedshop/gvl_metrics_middleware.git"
14
+ ```
15
+
16
+ ## Usage
17
+
18
+ The `gvl_metrics_middleware` automatically inserts the nessecary middleware into your application’s stack. To get
19
+ started, configure a callback to handle the GVL metrics. Place the following configuration in your
20
+ application’s `config/initializers`directory:
21
+
22
+ ```ruby
23
+ # config/initializers/gvl_metrics_middleware.rb
24
+ GvlMetricsMiddleware.configure do |config|
25
+ # Optional: Set sampling rate (0.0 to 1.0, defaults to 0.01 for 1% sampling)
26
+ config.sampling_rate = 0.1 # Sample 10% of requests/jobs
27
+
28
+ config.rack do |total, running, io_wait, gvl_wait|
29
+ # Your code here...
30
+ end
31
+
32
+ config.sidekiq do |total, running, io_wait, gvl_wait|
33
+ # Your code here...
34
+ end
35
+ end
36
+ ```
37
+
38
+ For example, if you would like to record the GVL metrics in New Relic, you can use the following configuration.
39
+
40
+ ```ruby
41
+ # config/initializers/gvl_metrics_middleware.rb
42
+ GvlMetricsMiddleware.configure do |config|
43
+ # Increase sampling from default 1% to 10% for more data
44
+ config.sampling_rate = 0.1
45
+
46
+ config.rack do |total, running, io_wait, gvl_wait|
47
+ NewRelic::Agent.record_metric("Custom/Rack/GVL/total", total)
48
+ NewRelic::Agent.record_metric("Custom/Rack/GVL/running", running)
49
+ NewRelic::Agent.record_metric("Custom/Rack/GVL/io_wait", io_wait)
50
+ NewRelic::Agent.record_metric("Custom/Rack/GVL/gvl_wait", gvl_wait)
51
+ end
52
+
53
+ config.sidekiq do |total, running, io_wait, gvl_wait, options|
54
+ NewRelic::Agent.record_metric("Custom/Sidekiq/GVL/total", total)
55
+ NewRelic::Agent.record_metric("Custom/Sidekiq/GVL/running", running)
56
+ NewRelic::Agent.record_metric("Custom/Sidekiq/GVL/io_wait", io_wait)
57
+ NewRelic::Agent.record_metric("Custom/Sidekiq/GVL/gvl_wait", gvl_wait)
58
+
59
+ # If you want to record metrics for specific queues and job classes, you can do so like this:
60
+ queue = options[:queue]
61
+ job_class = options[:job_class]
62
+ NewRelic::Agent.record_metric("Custom/Sidekiq/GVL/#{queue}/#{job_class}/total", total)
63
+ NewRelic::Agent.record_metric("Custom/Sidekiq/GVL/#{queue}/#{job_class}/running", running)
64
+ NewRelic::Agent.record_metric("Custom/Sidekiq/GVL/#{queue}/#{job_class}/io_wait", io_wait)
65
+ NewRelic::Agent.record_metric("Custom/Sidekiq/GVL/#{queue}/#{job_class}/gvl_wait", gvl_wait)
66
+ end
67
+ end
68
+ ```
69
+
70
+ After configuring, you should be able to set up custom charts in New Relic to visualize the GVL metrics. Here is an
71
+ example chart:
72
+
73
+ ![Screenshot of the GVL metrics chart on New Relic](gvl-metrics.png)
74
+
75
+ ## Available Metrics
76
+
77
+ The `gvl_metrics_middleware` reports the following metrics. The metrics are all reported in nanoseconds.
78
+
79
+ - **`total`**: The total duration of the request processing time, which is the sum of `running`, `io_wait`,
80
+ and `gvl_wait`. This corresponds to the returned value from the value returned by the `GVLTiming::Timer#duration`
81
+ method in `gvl_timing`.
82
+ - **`running`**: The time a thread held the GVL and performed work (a.k.a CPU time). This corresponds to the
83
+ value returned by the `GVLTiming::Timer#cpu_duration` method.
84
+ - **`io_wait`**: The time spent waiting for I/O operations after releasing the GVL. This corresponds to the
85
+ value returned by the `GVLTiming::Timer#idle_duration` method.
86
+ - **`gvl_wait`**: The time spent waiting to acquire the GVL. This corresponds to the value returned by
87
+ the `GVLTiming::Timer#stalled_duration` method.
88
+
89
+ ## Sampling
90
+
91
+ By default, the middleware samples 1% of requests and jobs to minimize overhead. You can adjust this sampling rate:
92
+ ```ruby
93
+ GvlMetricsMiddleware.configure do |config|
94
+ # Sample 25% of requests/jobs
95
+ config.sampling_rate = 0.25
96
+
97
+ # Your reporters here...
98
+ end
99
+ ```
100
+
101
+ The `sampling_rate` option accepts a value between `0.0` (no sampling) and `1.0` (100% sampling). The default is `0.01` (1%).
102
+
103
+ The middleware will randomly decide whether to instrument each request or job based on the configured rate. The default 1% sampling provides meaningful metrics while maintaining minimal performance overhead.
104
+
105
+ **Important**: Your metrics will only represent the sampled portion of traffic. You may need to adjust your alerting and analysis accordingly.
106
+
107
+ ## Performance Overhead
108
+
109
+ The overhead introduced by `gvl_metrics_middleware` is minimal. Benchmarking has shown only a 1% difference in response
110
+ times between scenarios with and without GVL metrics collection. This result has been validated through an A/A test,
111
+ where both the control and experiment groups ran identical code, and the difference remained at 1%. This 1% overhead is
112
+ consistent with those reported in [Shopify's `gvltools`](https://github.com/Shopify/gvltools?tab=readme-ov-file#usage),
113
+ where the overhead was measured at 1-5% in a production environment.
114
+
115
+ As stated in [the README of `gvltools`](https://github.com/Shopify/gvltools?tab=readme-ov-file#usage)`, the exact
116
+ overhead is not yet known. However, unless you observe an immediate, significant jump in response times after
117
+ deployment, the overhead is negligible and should not impact application performance. This makes the middleware a
118
+ reliable choice for tracking GVL metrics in production environments.
119
+
120
+ ## Development
121
+
122
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can
123
+ also run `bin/console` for an interactive prompt that will allow you to experiment.
124
+
125
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the
126
+ version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version,
127
+ push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
128
+
129
+ ## Contributing
130
+
131
+ Bug reports and pull requests are welcome on GitHub at https://github.com/speedshop/gvl_metrics_middleware. This
132
+ project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to
133
+ the [code of conduct](https://github.com/speedshop/gvl_metrics_middleware/blob/main/CODE_OF_CONDUCT.md).
134
+
135
+ ## License
136
+
137
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
138
+
139
+ ## Code of Conduct
140
+
141
+ Everyone interacting in the GvlMetricsMiddleware project's codebases, issue trackers, chat rooms and mailing lists is
142
+ expected to follow
143
+ the [code of conduct](https://github.com/speedshop/gvl_metrics_middleware/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rake/testtask"
5
+
6
+ Rake::TestTask.new("test") do |task|
7
+ task.libs << "test"
8
+
9
+ task.test_files = Dir["test/gvl_metrics_middleware/**/*_test.rb"]
10
+ task.verbose = true
11
+ task.warning = true
12
+ end
13
+
14
+ Rake::TestTask.new("test:isolated") do |task|
15
+ task.libs << "test"
16
+
17
+ task.test_files = ["test/isolated/**/*_test.rb"]
18
+ task.verbose = true
19
+ task.warning = true
20
+ end
21
+
22
+ task default: [:test, "test:isolated"]
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ # This file was generated by Appraisal
4
+
5
+ source "https://rubygems.org"
6
+
7
+ gem "minitest", "~> 5.16"
8
+ gem "rake", "~> 13.0"
9
+ gem "rubocop", require: false
10
+ gem "rails", "~> 7.1.0"
11
+ gem "railties", "~> 7.1.0"
12
+ gem "activesupport", "~> 7.1.0"
13
+ gem "rackup"
14
+
15
+ gemspec path: "../"
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ # This file was generated by Appraisal
4
+
5
+ source "https://rubygems.org"
6
+
7
+ gem "minitest", "~> 5.16"
8
+ gem "rake", "~> 13.0"
9
+ gem "rubocop", require: false
10
+ gem "rails", "~> 7.2.0"
11
+ gem "railties", "~> 7.2.0"
12
+ gem "activesupport", "~> 7.2.0"
13
+ gem "rackup"
14
+
15
+ gemspec path: "../"
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ # This file was generated by Appraisal
4
+
5
+ source "https://rubygems.org"
6
+
7
+ gem "minitest", "~> 5.16"
8
+ gem "rake", "~> 13.0"
9
+ gem "rubocop", require: false
10
+ gem "rails", "~> 8.0.0"
11
+ gem "railties", "~> 8.0.0"
12
+ gem "activesupport", "~> 8.0.0"
13
+ gem "rackup"
14
+
15
+ gemspec path: "../"
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ # This file was generated by Appraisal
4
+
5
+ source "https://rubygems.org"
6
+
7
+ git "https://github.com/rails/rails.git" do
8
+ gem "rails"
9
+ gem "railties"
10
+ gem "activesupport"
11
+ end
12
+
13
+ gem "minitest", "~> 5.16"
14
+ gem "rake", "~> 13.0"
15
+ gem "rubocop", require: false
16
+ gem "rackup"
17
+
18
+ gemspec path: "../"
data/gvl-metrics.png ADDED
Binary file
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "gvl_timing"
4
+
5
+ module GvlMetricsMiddleware
6
+ class Rack
7
+ @@reporter = nil
8
+
9
+ class << self
10
+ def reporter = @@reporter
11
+
12
+ def reporter=(reporter)
13
+ @@reporter = reporter
14
+ end
15
+ end
16
+
17
+ def initialize(app)
18
+ @app = app
19
+ end
20
+
21
+ def call(env)
22
+ return @app.call(env) unless GvlMetricsMiddleware.should_sample?
23
+
24
+ response = nil
25
+
26
+ gvl_times = GVLTiming.measure do
27
+ response = @app.call(env)
28
+ end
29
+
30
+ begin
31
+ self.class.reporter&.call(gvl_times.duration_ns, gvl_times.running_duration_ns, gvl_times.idle_duration_ns, gvl_times.stalled_duration_ns)
32
+ rescue => exception
33
+ GvlMetricsMiddleware.on_report_failure&.call("Rack", exception)
34
+
35
+ raise(exception) unless GvlMetricsMiddleware.safe_guard?
36
+ end
37
+
38
+ response
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails/railtie"
4
+
5
+ module GvlMetricsMiddleware
6
+ class Railtie < Rails::Railtie
7
+ config.gvl_metrics_middleware = ActiveSupport::OrderedOptions.new
8
+ config.gvl_metrics_middleware.enabled = !Rails.env.test?
9
+ config.gvl_metrics_middleware.safe_guard = Rails.env.production?
10
+
11
+ initializer "gvl_metrics_middleware", after: :load_config_initializers do |app|
12
+ if app.config.gvl_metrics_middleware.enabled && app.config.gvl_metrics_middleware.safe_guard
13
+ GvlMetricsMiddleware.on_report_failure.nil? && GvlMetricsMiddleware.on_report_failure do |source, exception|
14
+ Rails.logger.error("GVL Metrics Middleware failed to report metrics from #{source}: #{exception.class} (#{exception.message})")
15
+ end
16
+
17
+ GvlMetricsMiddleware.safe_guard = app.config.gvl_metrics_middleware.safe_guard
18
+ end
19
+ end
20
+
21
+ initializer "gvl_metrics_middleware.rack", after: :load_config_initializers do |app|
22
+ app.config.middleware.insert(0, GvlMetricsMiddleware::Rack) if app.config.gvl_metrics_middleware.enabled
23
+ end
24
+
25
+ initializer "gvl_metrics_middleware.sidekiq", after: :load_config_initializers do |app|
26
+ if defined?(::Sidekiq) && app.config.gvl_metrics_middleware.enabled
27
+ require "gvl_metrics_middleware/sidekiq"
28
+ ::Sidekiq.configure_server do |config|
29
+ config.server_middleware do |chain|
30
+ chain.prepend(GvlMetricsMiddleware::Sidekiq)
31
+ end
32
+ end
33
+ end
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "gvl_timing"
4
+ require "sidekiq/middleware/modules"
5
+
6
+ module GvlMetricsMiddleware
7
+ class Sidekiq
8
+ @@reporter = nil
9
+
10
+ class << self
11
+ def reporter = @@reporter
12
+
13
+ def reporter=(reporter)
14
+ @@reporter = reporter
15
+ end
16
+ end
17
+
18
+ include ::Sidekiq::ServerMiddleware
19
+
20
+ def call(job_instance, _job_payload, queue)
21
+ return yield unless GvlMetricsMiddleware.should_sample?
22
+
23
+ gvl_times = GVLTiming.measure { yield }
24
+
25
+ begin
26
+ self.class.reporter&.call(gvl_times.duration_ns, gvl_times.running_duration_ns, gvl_times.idle_duration_ns, gvl_times.stalled_duration_ns, job_class: job_instance.class.to_s, queue: queue)
27
+ rescue => exception
28
+ GvlMetricsMiddleware.on_report_failure&.call("Sidekiq", exception)
29
+
30
+ raise(exception) unless GvlMetricsMiddleware.safe_guard?
31
+ end
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GvlMetricsMiddleware
4
+ VERSION = "0.2.0"
5
+ end
@@ -0,0 +1,67 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "gvl_metrics_middleware/version"
4
+ require "gvl_metrics_middleware/rack"
5
+ require "gvl_metrics_middleware/railtie" if defined?(::Rails)
6
+
7
+ module GvlMetricsMiddleware
8
+ def self.configure = yield(self)
9
+
10
+ def self.rack(&block)
11
+ if block_given?
12
+ GvlMetricsMiddleware::Rack.reporter = block
13
+ else
14
+ GvlMetricsMiddleware::Rack.reporter
15
+ end
16
+ end
17
+
18
+ def self.sidekiq(&block)
19
+ require "gvl_metrics_middleware/sidekiq"
20
+
21
+ if block_given?
22
+ GvlMetricsMiddleware::Sidekiq.reporter = block
23
+ else
24
+ GvlMetricsMiddleware::Sidekiq.reporter
25
+ end
26
+ end
27
+
28
+ @@on_report_failure = nil
29
+
30
+ def self.on_report_failure(&block)
31
+ if block_given?
32
+ @@on_report_failure = block
33
+ else
34
+ @@on_report_failure
35
+ end
36
+ end
37
+
38
+ @@safe_guard = nil
39
+
40
+ def self.safe_guard? = @@safe_guard
41
+
42
+ def self.safe_guard=(value)
43
+ @@safe_guard = value
44
+ end
45
+
46
+ @@sampling_rate = 0.01
47
+
48
+ def self.sampling_rate
49
+ @@sampling_rate
50
+ end
51
+
52
+ def self.sampling_rate=(rate)
53
+ rate = rate.to_f
54
+ if rate < 0.0 || rate > 1.0
55
+ raise ArgumentError, "sampling_rate must be between 0.0 and 1.0, got #{rate}"
56
+ end
57
+
58
+ @@sampling_rate = rate
59
+ end
60
+
61
+ def self.should_sample?
62
+ return true if @@sampling_rate == 1.0
63
+ return false if @@sampling_rate == 0.0
64
+
65
+ rand < @@sampling_rate
66
+ end
67
+ end
@@ -0,0 +1,4 @@
1
+ module GvlMetricsMiddleware
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,120 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: gvl_metrics_middleware
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.2.0
5
+ platform: ruby
6
+ authors:
7
+ - Nate Berkopec
8
+ - Yuki Nishijima
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 1980-01-02 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: gvl_timing
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: appraisal
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '2.2'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '2.2'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rack
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: sidekiq
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ description: gvl_metrics_middlewareprovides Rack and Sidekiq middlewares for GVL metrics
70
+ email:
71
+ - nate.berkopec@speedshop.co
72
+ - yuki.nishijima@speedshop.co
73
+ executables: []
74
+ extensions: []
75
+ extra_rdoc_files: []
76
+ files:
77
+ - ".rubocop.yml"
78
+ - Appraisals
79
+ - CHANGELOG.md
80
+ - CODE_OF_CONDUCT.md
81
+ - LICENSE.txt
82
+ - README.md
83
+ - Rakefile
84
+ - gemfiles/rails_71.gemfile
85
+ - gemfiles/rails_72.gemfile
86
+ - gemfiles/rails_80.gemfile
87
+ - gemfiles/rails_edge.gemfile
88
+ - gvl-metrics.png
89
+ - lib/gvl_metrics_middleware.rb
90
+ - lib/gvl_metrics_middleware/rack.rb
91
+ - lib/gvl_metrics_middleware/railtie.rb
92
+ - lib/gvl_metrics_middleware/sidekiq.rb
93
+ - lib/gvl_metrics_middleware/version.rb
94
+ - sig/gvl_metrics_middleware.rbs
95
+ homepage: https://github.com/speedshop/gvl_metrics_middleware
96
+ licenses:
97
+ - MIT
98
+ metadata:
99
+ allowed_push_host: https://rubygems.org
100
+ homepage_uri: https://github.com/speedshop/gvl_metrics_middleware
101
+ source_code_uri: https://github.com/speedshop/gvl_metrics_middleware
102
+ changelog_uri: https://github.com/speedshop/gvl_metrics_middleware/releases
103
+ rdoc_options: []
104
+ require_paths:
105
+ - lib
106
+ required_ruby_version: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - ">="
109
+ - !ruby/object:Gem::Version
110
+ version: 3.2.0
111
+ required_rubygems_version: !ruby/object:Gem::Requirement
112
+ requirements:
113
+ - - ">="
114
+ - !ruby/object:Gem::Version
115
+ version: '0'
116
+ requirements: []
117
+ rubygems_version: 3.6.9
118
+ specification_version: 4
119
+ summary: Rack and Sidekiq middlewares for GVL metrics
120
+ test_files: []