puma-log_stats-codeur 0.1.1

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: 2449156394b5c86c2bee695565450e4c49a0b2bb87b15d3e7cb03e21ac47b322
4
+ data.tar.gz: 91887bd1d2f23c594889504063268d5dfeadcebd2a1539bbd4300aec14625eb4
5
+ SHA512:
6
+ metadata.gz: 3084f6e89321b110e7bec943ff66435dbc3446a84257929e937a073bc80e8ca21209661050dbc9c4b2bf7a6d3f14dd291b31221eeafe937b8e737974c1bda630
7
+ data.tar.gz: 6b6f9f8f4fe2925f4dccdd89b503516d350932e0875fb3d50e42eb2c21f4b8f5ad10c53108564fe8ec721a47a9d1add5bc464076ac4affc8a873f08692002b59
data/.standard.yml ADDED
@@ -0,0 +1,3 @@
1
+ # For available configuration options, see:
2
+ # https://github.com/standardrb/standard
3
+ ruby_version: 3.0
@@ -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 Brice TEXIER
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,40 @@
1
+ # PumaLogStats
2
+
3
+ Puma plugin to log server stats whenever the number of concurrent requests exceeds a configured threshold.
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'puma-log_stats'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle install
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install puma-log_stats
20
+
21
+ ## Usage
22
+
23
+ This plugin is loaded using Puma's plugin API. To enable, add a `plugin :log_stats` directive to your Puma config DSL, then configure the `LogStats` object with any additional configuration:
24
+
25
+ ```ruby
26
+ # config/puma.rb
27
+
28
+ plugin :log_stats
29
+ LogStats.threshold = 2
30
+ ```
31
+
32
+ ## Development
33
+
34
+ After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
35
+
36
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
37
+
38
+ ## Contributing
39
+
40
+ Bug reports and pull requests are welcome on GitHub at https://github.com/codeur/puma-log_stats.
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "minitest/test_task"
5
+
6
+ Minitest::TestTask.create
7
+
8
+ require "standard/rake"
9
+
10
+ task default: %i[test standard]
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Puma
4
+ module LogStats
5
+ VERSION = "0.1.1"
6
+ end
7
+ end
@@ -0,0 +1,3 @@
1
+ # frozen_string_literal: true
2
+
3
+ # require "puma/log_stats/version"
@@ -0,0 +1,238 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "puma/plugin"
4
+
5
+ module LogStats
6
+ class << self
7
+ # Interval between logging attempts in seconds.
8
+ attr_accessor :interval
9
+ LogStats.interval = 10
10
+
11
+ attr_accessor :alarm_on_sentry
12
+ LogStats.alarm_on_sentry = true
13
+
14
+ attr_accessor :alarm_notification_interval
15
+ LogStats.alarm_notification_interval = 60
16
+
17
+ attr_accessor :warning_threshold
18
+ LogStats.warning_threshold = 0.7
19
+
20
+ attr_accessor :critical_threshold
21
+ LogStats.critical_threshold = 0.85
22
+ end
23
+
24
+ def start(launcher)
25
+ @launcher = launcher
26
+ launcher.events.register(:state) do |state|
27
+ if %i[halt restart stop].include?(state)
28
+ @running = false
29
+ end
30
+ end
31
+
32
+ in_background do
33
+ @running = true
34
+ @load_level = :normal
35
+ while @running
36
+ sleep LogStats.interval
37
+ @stats = Puma.stats_hash
38
+ log(status)
39
+ check_alarms
40
+ end
41
+ end
42
+ end
43
+
44
+ def check_alarms
45
+ threshold_reached(:critical, LogStats.critical_threshold) ||
46
+ threshold_reached(:warning, LogStats.warning_threshold) ||
47
+ normal_load
48
+ end
49
+
50
+ def threshold_reached(level, threshold)
51
+ return false if threads_load < threshold
52
+
53
+ notify_alarm("#{level.to_s.upcase}: Puma threads load is more than #{threshold * 100}% (#{max_threads - pool_capacity}/#{max_threads})")
54
+ @load_level = level if @load_level != level
55
+ true
56
+ end
57
+
58
+ def normal_load
59
+ return if @load_level == :normal
60
+
61
+ log("INFO: Puma threads load is back to normal values")
62
+ @load_level = :normal
63
+ end
64
+
65
+ def notify_alarm(message)
66
+ if @notified_at.nil? || (Time.now - @notified_at) < LogStats.alarm_notification_interval
67
+ log(message)
68
+ Sentry.capture_message(message) if LogStats.alarm_on_sentry && defined?(Sentry)
69
+ @notified_at = Time.now
70
+ end
71
+ end
72
+
73
+ def status
74
+ if clustered?
75
+ "cluster: #{booted_workers}/#{workers} workers: #{running}/#{max_threads} threads, #{pool_capacity} available, #{backlog} backlog"
76
+ else
77
+ "single: #{running}/#{max_threads} threads, #{pool_capacity} available, #{backlog} backlog"
78
+ end
79
+ end
80
+
81
+ def log(str)
82
+ @launcher.log_writer.log("[#{Time.now}][puma #{Puma::Const::VERSION}] #{str}")
83
+ end
84
+
85
+ def threads_load
86
+ 1.0 - pool_capacity.to_f / max_threads.to_f
87
+ end
88
+
89
+ def clustered?
90
+ @stats.key?(:workers)
91
+ end
92
+
93
+ def workers
94
+ @stats.fetch(:workers, 1)
95
+ end
96
+
97
+ def booted_workers
98
+ @stats.fetch(:booted_workers, 1)
99
+ end
100
+
101
+ def running
102
+ if clustered?
103
+ @stats[:worker_status].sum { |s| s[:last_status].fetch(:running, 0) }
104
+ else
105
+ @stats.fetch(:running, 0)
106
+ end
107
+ end
108
+
109
+ def backlog
110
+ if clustered?
111
+ @stats[:worker_status].sum { |s| s[:last_status].fetch(:backlog, 0) }
112
+ else
113
+ @stats.fetch(:backlog, 0)
114
+ end
115
+ end
116
+
117
+ def pool_capacity
118
+ if clustered?
119
+ @stats[:worker_status].sum { |s| s[:last_status].fetch(:pool_capacity, 0) }
120
+ else
121
+ @stats.fetch(:pool_capacity, 0)
122
+ end
123
+ end
124
+
125
+ def max_threads
126
+ if clustered?
127
+ @stats[:worker_status].sum { |s| s[:last_status].fetch(:max_threads, 0) }
128
+ else
129
+ @stats.fetch(:max_threads, 0)
130
+ end
131
+ end
132
+ end
133
+
134
+ Puma::Plugin.create do
135
+ include LogStats
136
+ end
137
+
138
+ # require "puma"
139
+ # require "puma/plugin"
140
+ # require "json"
141
+
142
+ # # Puma plugin to log server stats whenever the number of
143
+ # # concurrent requests exceeds a configured threshold.
144
+ # module LogStats
145
+ # STAT_METHODS = %i[backlog running pool_capacity max_threads requests_count].freeze
146
+
147
+ # class << self
148
+ # # Minimum concurrent requests per process that will trigger logging server
149
+ # # stats, or nil to disable logging.
150
+ # # Default is the max number of threads in the server's thread pool.
151
+ # # If this attribute is a Proc, it will be re-evaluated each interval.
152
+ # attr_accessor :threshold
153
+ # LogStats.threshold = :max
154
+
155
+ # # Interval between logging attempts in seconds.
156
+ # attr_accessor :interval
157
+ # LogStats.interval = 1
158
+
159
+ # # Proc to filter backtraces.
160
+ # attr_accessor :backtrace_filter
161
+ # LogStats.backtrace_filter = ->(bt) { bt }
162
+ # end
163
+
164
+ # Puma::Plugin.create do
165
+ # attr_reader :launcher
166
+
167
+ # def start(launcher)
168
+ # @launcher = launcher
169
+ # launcher.events.register(:state) do |state|
170
+ # @state = state
171
+ # stats_logger_thread if state == :running
172
+ # end
173
+
174
+ # in_background { start }
175
+ # end
176
+
177
+ # private
178
+
179
+ # def stats_logger_thread
180
+ # Thread.new do
181
+ # if Thread.current.respond_to?(:name=)
182
+ # Thread.current.name = "puma stats logger"
183
+ # end
184
+ # start while @state == :running
185
+ # end
186
+ # end
187
+
188
+ # def start
189
+ # sleep LogStats.interval
190
+ # return unless server
191
+
192
+ # if should_log?
193
+ # stats = server_stats
194
+ # stats[:threads] = thread_backtraces
195
+ # stats[:gc] = GC.stat
196
+ # log stats.to_json
197
+ # end
198
+ # rescue => e
199
+ # log "LogStats failed: #{e}\n #{e.backtrace.join("\n ")}"
200
+ # end
201
+
202
+ # def log(str)
203
+ # launcher.log_writer.log str
204
+ # end
205
+
206
+ # # Save reference to Server object from the thread-local key.
207
+ # def server
208
+ # @server ||= Thread.list.map { |t| t[Puma::Server::ThreadLocalKey] }.compact.first
209
+ # end
210
+
211
+ # def server_stats
212
+ # STAT_METHODS.select(&server.method(:respond_to?))
213
+ # .map { |name| [name, server.send(name) || 0] }.to_h
214
+ # end
215
+
216
+ # # True if current server load meets configured threshold.
217
+ # def should_log?
218
+ # threshold = LogStats.threshold
219
+ # threshold = threshold.call if threshold.is_a?(Proc)
220
+ # threshold = server.max_threads if threshold == :max
221
+ # threshold && (server.max_threads - server.pool_capacity) >= threshold
222
+ # end
223
+
224
+ # def thread_backtraces
225
+ # worker_threads.map do |t|
226
+ # name = t.respond_to?(:name) ? t.name : thread.object_id.to_s(36)
227
+ # [name, LogStats.backtrace_filter.call(t.backtrace)]
228
+ # end.sort.to_h
229
+ # end
230
+
231
+ # # List all non-idle worker threads in the thread pool.
232
+ # def worker_threads
233
+ # server.instance_variable_get(:@thread_pool)
234
+ # .instance_variable_get(:@workers)
235
+ # .reject { |t| t.backtrace.first.match?(/thread_pool\.rb.*sleep/) }
236
+ # end
237
+ # end
238
+ # end
metadata ADDED
@@ -0,0 +1,72 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: puma-log_stats-codeur
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.1
5
+ platform: ruby
6
+ authors:
7
+ - Will Jordan
8
+ - Codeur SAS
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2025-01-24 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: puma
16
+ requirement: !ruby/object:Gem::Requirement
17
+ requirements:
18
+ - - "~>"
19
+ - !ruby/object:Gem::Version
20
+ version: '6.0'
21
+ type: :runtime
22
+ prerelease: false
23
+ version_requirements: !ruby/object:Gem::Requirement
24
+ requirements:
25
+ - - "~>"
26
+ - !ruby/object:Gem::Version
27
+ version: '6.0'
28
+ description: Puma plugin to log server stats whenever the number of concurrent requests
29
+ exceeds a configured threshold.
30
+ email:
31
+ - will@code.org
32
+ - dev@codeur.com
33
+ executables: []
34
+ extensions: []
35
+ extra_rdoc_files: []
36
+ files:
37
+ - ".standard.yml"
38
+ - CODE_OF_CONDUCT.md
39
+ - LICENSE.txt
40
+ - README.md
41
+ - Rakefile
42
+ - lib/puma/log_stats.rb
43
+ - lib/puma/log_stats/version.rb
44
+ - lib/puma/plugin/log_stats.rb
45
+ homepage: https://github.com/codeur/puma-log_stats
46
+ licenses:
47
+ - MIT
48
+ metadata:
49
+ allowed_push_host: https://rubygems.org
50
+ homepage_uri: https://github.com/codeur/puma-log_stats
51
+ source_code_uri: https://github.com/codeur/puma-log_stats
52
+ changelog_uri: https://github.com/codeur/puma-log_stats/blob/main/CHANGELOG.md
53
+ post_install_message:
54
+ rdoc_options: []
55
+ require_paths:
56
+ - lib
57
+ required_ruby_version: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: 3.0.0
62
+ required_rubygems_version: !ruby/object:Gem::Requirement
63
+ requirements:
64
+ - - ">="
65
+ - !ruby/object:Gem::Version
66
+ version: '0'
67
+ requirements: []
68
+ rubygems_version: 3.5.22
69
+ signing_key:
70
+ specification_version: 4
71
+ summary: Logs Puma stats when concurrent requests are high.
72
+ test_files: []