rails_api_profiler 0.1.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: 1831414415a44ee2a8ca9ae9d1861109ae80a33e7c6b222d9640e2a714f4941e
4
+ data.tar.gz: b034f5465418ed54d86c0b815d7280e4a8c6ffc77ee770ccc4e8c3723e0d501d
5
+ SHA512:
6
+ metadata.gz: fe96e39fd05795345a5ba22d1ab3789edc73fae42dfdd3b2649f0fb72ed52586f2f1a160309048fad70b495199112b872580f1494994cc740aee3f7fbbd8e9c7
7
+ data.tar.gz: 8304743d25e615ba6bd7a04782468d57f12a5f29a3f1db698277d03759b82ad83282217fa28c277342cb8ed5e7a2d968b8d41a67f6b8d40bc9000c34a4c18fc5
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2026-01-13
4
+
5
+ - 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) 2026 Sparsh Garg
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,169 @@
1
+ Perfect 👍
2
+ Here’s a **clean, professional, RubyGems-ready README** that fits the quality of the gem you’re building.
3
+ You can copy-paste this directly into `README.md`.
4
+
5
+ ---
6
+
7
+ # Rails API Profiler
8
+
9
+ **Rails API Profiler** is a lightweight, middleware-based performance profiling tool for **Rails API applications**.
10
+ It provides request-level insights such as **response time**, **database query count**, and **database execution time** — with **zero changes** to your controllers or business logic.
11
+
12
+ Designed to be **simple, fast, and production-safe**, it supports **Rails 5 and above**.
13
+
14
+ ---
15
+
16
+ ## ✨ Features
17
+
18
+ * 🚀 Measures **API request duration**
19
+ * 🗄️ Tracks **ActiveRecord query count**
20
+ * ⏱️ Tracks **total database execution time**
21
+ * ⚙️ Middleware-based (no controller code required)
22
+ * 🔕 Can be enabled/disabled via configuration
23
+ * 🧪 Safe for development, staging, and debugging
24
+ * 🧩 Works with **Rails 5+**
25
+
26
+ ---
27
+
28
+ ## 📦 Installation
29
+
30
+ Add the gem to your Gemfile:
31
+
32
+ ```ruby
33
+ gem "rails_api_profiler", group: [:development, :staging]
34
+ ```
35
+
36
+ Then install:
37
+
38
+ ```bash
39
+ bundle install
40
+ ```
41
+
42
+ That’s it — no further setup required.
43
+
44
+ ---
45
+
46
+ ## ⚙️ Configuration
47
+
48
+ You can optionally configure the profiler in an initializer:
49
+
50
+ ```ruby
51
+ # config/initializers/rails_api_profiler.rb
52
+
53
+ RailsApiProfiler.configure do |config|
54
+ config.enabled = true
55
+ config.slow_request_threshold = 500 # milliseconds
56
+ end
57
+ ```
58
+
59
+ ### Available Options
60
+
61
+ | Option | Description | Default |
62
+ | ------------------------ | ---------------------------------------- | -------------- |
63
+ | `enabled` | Enable or disable profiling | `true` |
64
+ | `slow_request_threshold` | Threshold for slow request warnings (ms) | `500` |
65
+ | `logger` | Custom logger instance | `Rails.logger` |
66
+
67
+ ---
68
+
69
+ ## 📊 Example Log Output
70
+
71
+ ```text
72
+ [RailsApiProfiler] {:method=>"GET",
73
+ :path=>"/api/v1/users",
74
+ :status=>200,
75
+ :duration_ms=>183.21,
76
+ :db_queries=>7,
77
+ :db_time_ms=>41.8}
78
+ ```
79
+
80
+ For slow requests:
81
+
82
+ ```text
83
+ [RailsApiProfiler] SLOW REQUEST {:method=>"POST",
84
+ :path=>"/api/v1/orders",
85
+ :status=>201,
86
+ :duration_ms=>812.44,
87
+ :db_queries=>18,
88
+ :db_time_ms=>220.3}
89
+ ```
90
+
91
+ ---
92
+
93
+ ## 🧠 How It Works
94
+
95
+ * Uses a **Rack middleware** to measure request duration
96
+ * Hooks into **ActiveSupport::Notifications** to track SQL queries
97
+ * Stores per-request stats using **thread-local storage**
98
+ * Automatically attaches via a **Rails Railtie**
99
+
100
+ No monkey-patching. No controller hooks. No overhead outside requests.
101
+
102
+ ---
103
+
104
+ ## 🧪 Supported Versions
105
+
106
+ * **Rails:** 5.0+
107
+ * **Ruby:** 2.4+
108
+
109
+ ---
110
+
111
+ ## 🚧 When Should I Use This?
112
+
113
+ This gem is ideal when you want to:
114
+
115
+ * Identify slow API endpoints
116
+ * Detect excessive database queries
117
+ * Debug performance regressions
118
+ * Profile APIs in development or staging
119
+ * Keep instrumentation lightweight
120
+
121
+ ---
122
+
123
+ ## 🛑 When NOT to Use This
124
+
125
+ * As a full APM replacement (Datadog, New Relic, etc.)
126
+ * For deep flamegraph analysis
127
+ * For long-running background jobs
128
+
129
+ This gem focuses on **request-level clarity**, not heavy analytics.
130
+
131
+ ---
132
+
133
+ ## 🛣️ Roadmap
134
+
135
+ Planned improvements:
136
+
137
+ * JSON / structured log formatter
138
+ * N+1 query detection
139
+ * Prometheus exporter
140
+ * Memory usage tracking
141
+ * Optional endpoint filtering
142
+
143
+ ---
144
+
145
+ ## 🤝 Contributing
146
+
147
+ Contributions are welcome!
148
+
149
+ 1. Fork the repository
150
+ 2. Create a feature branch
151
+ 3. Add tests
152
+ 4. Submit a pull request
153
+
154
+ Please ensure all specs pass before submitting.
155
+
156
+ ---
157
+
158
+ ## 📄 License
159
+
160
+ This project is licensed under the **MIT License**.
161
+
162
+ ---
163
+
164
+ ## 👤 Author
165
+
166
+ **Sparsh Garg**
167
+ GitHub: [https://github.com/sparsh9](https://github.com/sparsh9)
168
+
169
+ ---
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ task default: :spec
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RailsApiProfiler
4
+ class Configuration
5
+ attr_accessor :enabled,
6
+ :slow_request_threshold,
7
+ :logger
8
+
9
+ def initialize
10
+ @enabled = true
11
+ @slow_request_threshold = 500
12
+ @logger =
13
+ if defined?(Rails) && Rails.respond_to?(:logger) && Rails.logger
14
+ Rails.logger
15
+ else
16
+ Logger.new($stdout)
17
+ end
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,46 @@
1
+ module RailsApiProfiler
2
+ class Middleware
3
+ def initialize(app)
4
+ @app = app
5
+ end
6
+
7
+ def call(env)
8
+ config = RailsApiProfiler.configuration
9
+ return @app.call(env) unless config.enabled
10
+
11
+ Subscribers::ActiveRecord.reset!
12
+
13
+ start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
14
+
15
+ status, headers, response = @app.call(env)
16
+
17
+ finish = Process.clock_gettime(Process::CLOCK_MONOTONIC)
18
+ duration = ((finish - start) * 1000).round(2)
19
+
20
+ db_stats = Subscribers::ActiveRecord.stats
21
+
22
+ log(env, status, duration, db_stats, config)
23
+
24
+ [status, headers, response]
25
+ end
26
+
27
+ private
28
+
29
+ def log(env, status, duration, db, config)
30
+ payload = {
31
+ method: env["REQUEST_METHOD"],
32
+ path: env["PATH_INFO"],
33
+ status: status,
34
+ duration_ms: duration,
35
+ db_queries: db[:queries],
36
+ db_time_ms: db[:time_ms]
37
+ }
38
+
39
+ if duration >= config.slow_request_threshold
40
+ config.logger.warn("[RailsApiProfiler] SLOW REQUEST #{payload}")
41
+ else
42
+ config.logger.info("[RailsApiProfiler] #{payload}")
43
+ end
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ if defined?(Rails)
4
+ module RailsApiProfiler
5
+ class Railtie < ::Rails::Railtie
6
+ initializer "rails_api_profiler.configure" do |app|
7
+ app.middleware.use RailsApiProfiler::Middleware
8
+ end
9
+
10
+ initializer "rails_api_profiler.active_record" do
11
+ Subscribers::ActiveRecord.subscribe!
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,34 @@
1
+ module RailsApiProfiler
2
+ module Subscribers
3
+ class ActiveRecord
4
+ def self.subscribe!
5
+ return unless defined?(::ActiveRecord)
6
+
7
+ ::ActiveSupport::Notifications.subscribe("sql.active_record") do |*args|
8
+ event = ::ActiveSupport::Notifications::Event.new(*args)
9
+
10
+ Thread.current[:rails_api_profiler_db_queries] ||= 0
11
+ Thread.current[:rails_api_profiler_db_time] ||= 0.0
12
+
13
+ # Skip schema & cached queries
14
+ next if event.payload[:name] == "SCHEMA"
15
+
16
+ Thread.current[:rails_api_profiler_db_queries] += 1
17
+ Thread.current[:rails_api_profiler_db_time] += event.duration
18
+ end
19
+ end
20
+
21
+ def self.reset!
22
+ Thread.current[:rails_api_profiler_db_queries] = 0
23
+ Thread.current[:rails_api_profiler_db_time] = 0.0
24
+ end
25
+
26
+ def self.stats
27
+ {
28
+ queries: Thread.current[:rails_api_profiler_db_queries] || 0,
29
+ time_ms: (Thread.current[:rails_api_profiler_db_time] || 0.0).round(2)
30
+ }
31
+ end
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RailsApiProfiler
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,17 @@
1
+ require "rails_api_profiler/version"
2
+ require "rails_api_profiler/configuration"
3
+ require "rails_api_profiler/middleware"
4
+ require "rails_api_profiler/subscribers/active_record"
5
+ require "rails_api_profiler/railtie"
6
+
7
+ module RailsApiProfiler
8
+ class << self
9
+ def configure
10
+ yield(configuration)
11
+ end
12
+
13
+ def configuration
14
+ @configuration ||= Configuration.new
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,4 @@
1
+ module RailsApiProfiler
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,82 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: rails_api_profiler
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Sparsh Garg
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2026-01-13 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rails
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '5.0'
20
+ - - "<"
21
+ - !ruby/object:Gem::Version
22
+ version: '9.0'
23
+ type: :runtime
24
+ prerelease: false
25
+ version_requirements: !ruby/object:Gem::Requirement
26
+ requirements:
27
+ - - ">="
28
+ - !ruby/object:Gem::Version
29
+ version: '5.0'
30
+ - - "<"
31
+ - !ruby/object:Gem::Version
32
+ version: '9.0'
33
+ description: Rails API Profiler is a lightweight, middleware-based tool for profiling
34
+ API requests in Rails applications. It measures request duration, database query
35
+ count, and database execution time with zero code changes, supporting Rails 5 and
36
+ above.
37
+ email:
38
+ - sparshgarg2000@outlook.com
39
+ executables: []
40
+ extensions: []
41
+ extra_rdoc_files: []
42
+ files:
43
+ - ".rspec"
44
+ - CHANGELOG.md
45
+ - CODE_OF_CONDUCT.md
46
+ - LICENSE.txt
47
+ - README.md
48
+ - Rakefile
49
+ - lib/rails_api_profiler.rb
50
+ - lib/rails_api_profiler/configuration.rb
51
+ - lib/rails_api_profiler/middleware.rb
52
+ - lib/rails_api_profiler/railtie.rb
53
+ - lib/rails_api_profiler/subscribers/active_record.rb
54
+ - lib/rails_api_profiler/version.rb
55
+ - sig/rails_api_profiler.rbs
56
+ homepage: https://github.com/sparsh9/rails-api-profiler
57
+ licenses:
58
+ - MIT
59
+ metadata:
60
+ homepage_uri: https://github.com/sparsh9/rails-api-profiler
61
+ source_code_uri: https://github.com/sparsh9/rails-api-profiler
62
+ changelog_uri: https://github.com/sparsh9/rails-api-profiler/blob/main/CHANGELOG.md
63
+ post_install_message:
64
+ rdoc_options: []
65
+ require_paths:
66
+ - lib
67
+ required_ruby_version: !ruby/object:Gem::Requirement
68
+ requirements:
69
+ - - ">="
70
+ - !ruby/object:Gem::Version
71
+ version: 2.4.0
72
+ required_rubygems_version: !ruby/object:Gem::Requirement
73
+ requirements:
74
+ - - ">="
75
+ - !ruby/object:Gem::Version
76
+ version: '0'
77
+ requirements: []
78
+ rubygems_version: 3.3.27
79
+ signing_key:
80
+ specification_version: 4
81
+ summary: Lightweight performance profiler for Rails API requests
82
+ test_files: []