stats-middleware 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 +7 -0
- data/CHANGELOG.md +5 -0
- data/CODE_OF_CONDUCT.md +132 -0
- data/README.md +165 -0
- data/Rakefile +8 -0
- data/lib/stats/middleware/ip_tracker.rb +62 -0
- data/lib/stats/middleware/stats_reporter.rb +110 -0
- data/lib/stats/middleware/user_agent_tracker.rb +47 -0
- data/lib/stats/middleware/version.rb +7 -0
- data/lib/stats/middleware.rb +12 -0
- data/lib/tasks/stats_middleware.rake +72 -0
- data/sig/stats/middleware.rbs +6 -0
- metadata +96 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA256:
|
3
|
+
metadata.gz: 2fd79a483dd7fec954d9fb3e155f9ef7594d397ea6954d0a25c797f2cc4cd48d
|
4
|
+
data.tar.gz: 70c012b9152e2ba7aa142fd7233639494ddaa31f9888935ff96a86f99b11c00a
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: 156350b3c74629c8c6417622d6b2d77dfd78cd7f254359d8f5668b56263c80489fe428ff473f3696dde27aefa24594c975dd16110ffe3497da91e3359662dd8b
|
7
|
+
data.tar.gz: 8dfad14ce93c5b2a6282f81e17033ed4f02015d43049ed304512100b9ac5b82d1332f91bab6950a7901e4cdff0e3f205112464045b895f30bb04eecfcd200fe3
|
data/CHANGELOG.md
ADDED
data/CODE_OF_CONDUCT.md
ADDED
@@ -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/README.md
ADDED
@@ -0,0 +1,165 @@
|
|
1
|
+
# Stats::Middleware
|
2
|
+
|
3
|
+
A collection of Rack middleware components for tracking API usage statistics including user agent and IP address data with Redis storage.
|
4
|
+
|
5
|
+
This gem was extracted from and built for [Ecosyste.ms](https://ecosyste.ms), an open source platform for monitoring and understanding the health and sustainability of open source software ecosystems.
|
6
|
+
|
7
|
+
## Features
|
8
|
+
|
9
|
+
- **IP Address Tracking**: Track unique IP addresses making API requests
|
10
|
+
- **User Agent Tracking**: Monitor user agents accessing your API
|
11
|
+
- **Redis Storage**: Efficient storage using Redis sorted sets with automatic expiration
|
12
|
+
- **Configurable**: Flexible configuration options for different use cases
|
13
|
+
- **Error Resilient**: Redis errors don't break requests - they're logged instead
|
14
|
+
- **Smart IP Detection**: Properly handles Cloudflare and proxy headers
|
15
|
+
|
16
|
+
## Installation
|
17
|
+
|
18
|
+
Add this line to your application's Gemfile:
|
19
|
+
|
20
|
+
```ruby
|
21
|
+
gem 'stats-middleware'
|
22
|
+
```
|
23
|
+
|
24
|
+
And then execute:
|
25
|
+
|
26
|
+
```bash
|
27
|
+
bundle install
|
28
|
+
```
|
29
|
+
|
30
|
+
Or install it yourself as:
|
31
|
+
|
32
|
+
```bash
|
33
|
+
gem install stats-middleware
|
34
|
+
```
|
35
|
+
|
36
|
+
## Usage
|
37
|
+
|
38
|
+
### Basic Rails Configuration
|
39
|
+
|
40
|
+
Add the middleware to your Rails application in `config/application.rb`:
|
41
|
+
|
42
|
+
```ruby
|
43
|
+
class Application < Rails::Application
|
44
|
+
# Track IP addresses for API requests
|
45
|
+
config.middleware.use Stats::Middleware::IpTracker, redis: REDIS
|
46
|
+
|
47
|
+
# Track user agents for API requests
|
48
|
+
config.middleware.use Stats::Middleware::UserAgentTracker, redis: REDIS
|
49
|
+
end
|
50
|
+
```
|
51
|
+
|
52
|
+
### Configuration Options
|
53
|
+
|
54
|
+
Both middleware classes accept the following options:
|
55
|
+
|
56
|
+
```ruby
|
57
|
+
config.middleware.use Stats::Middleware::IpTracker,
|
58
|
+
redis: redis_instance, # Redis client instance
|
59
|
+
path_filter: ->(path) { path.start_with?('/api/') }, # Custom path filtering
|
60
|
+
logger: Rails.logger, # Custom logger
|
61
|
+
expiry_days: 31 # Redis key expiration in days
|
62
|
+
|
63
|
+
config.middleware.use Stats::Middleware::UserAgentTracker,
|
64
|
+
redis: redis_instance,
|
65
|
+
path_filter: ->(path) { path.start_with?('/api/') },
|
66
|
+
logger: Rails.logger,
|
67
|
+
expiry_days: 31,
|
68
|
+
redis_key_prefix: 'api_requests' # Custom Redis key prefix
|
69
|
+
```
|
70
|
+
|
71
|
+
### IP Address Tracking
|
72
|
+
|
73
|
+
The `IpTracker` middleware:
|
74
|
+
- Stores IP addresses in Redis sorted sets with daily keys: `api_requests:ips:YYYY-MM-DD`
|
75
|
+
- Handles Cloudflare's `CF-Connecting-IP` header
|
76
|
+
- Supports `X-Forwarded-For` headers for proxy/load balancer setups
|
77
|
+
- Increments counters for repeated requests from the same IP
|
78
|
+
|
79
|
+
### User Agent Tracking
|
80
|
+
|
81
|
+
The `UserAgentTracker` middleware:
|
82
|
+
- Stores user agents in Redis sorted sets with daily keys: `api_requests:YYYY-MM-DD`
|
83
|
+
- Tracks full user agent strings with request counts
|
84
|
+
- Handles missing user agent headers gracefully
|
85
|
+
|
86
|
+
### Redis Data Structure
|
87
|
+
|
88
|
+
Data is stored in Redis sorted sets where:
|
89
|
+
- **Key**: Daily timestamp (e.g., `api_requests:ips:2025-07-29`)
|
90
|
+
- **Member**: IP address or user agent string
|
91
|
+
- **Score**: Number of requests
|
92
|
+
|
93
|
+
Example Redis commands to view data:
|
94
|
+
```redis
|
95
|
+
# View top IPs for today
|
96
|
+
ZREVRANGE api_requests:ips:2025-07-29 0 10 WITHSCORES
|
97
|
+
|
98
|
+
# View top user agents for today
|
99
|
+
ZREVRANGE api_requests:2025-07-29 0 10 WITHSCORES
|
100
|
+
```
|
101
|
+
|
102
|
+
### Non-Rails Usage
|
103
|
+
|
104
|
+
For non-Rails Rack applications:
|
105
|
+
|
106
|
+
```ruby
|
107
|
+
require 'stats/middleware'
|
108
|
+
|
109
|
+
use Stats::Middleware::IpTracker, redis: Redis.new
|
110
|
+
use Stats::Middleware::UserAgentTracker, redis: Redis.new
|
111
|
+
```
|
112
|
+
|
113
|
+
## Statistics Reporting
|
114
|
+
|
115
|
+
The gem includes a `StatsReporter` class for generating usage reports and rake tasks for easy access.
|
116
|
+
|
117
|
+
### Using the StatsReporter Class
|
118
|
+
|
119
|
+
```ruby
|
120
|
+
require 'stats/middleware'
|
121
|
+
|
122
|
+
reporter = Stats::Middleware::StatsReporter.new(redis: REDIS)
|
123
|
+
|
124
|
+
# Get raw statistics data
|
125
|
+
stats = reporter.summary(days: 30)
|
126
|
+
puts stats[:user_agents] # Hash of user agents with request counts
|
127
|
+
puts stats[:ips] # Hash of IPs with request counts
|
128
|
+
|
129
|
+
# Display formatted summary
|
130
|
+
reporter.display_summary(days: 7, limit: 10)
|
131
|
+
```
|
132
|
+
|
133
|
+
### Rake Tasks
|
134
|
+
|
135
|
+
The gem provides several rake tasks for viewing statistics:
|
136
|
+
|
137
|
+
```bash
|
138
|
+
# Display summary for past 30 days (default)
|
139
|
+
rake stats_middleware:summary
|
140
|
+
|
141
|
+
# Display summary for specific number of days
|
142
|
+
rake stats_middleware:summary[7]
|
143
|
+
|
144
|
+
# Display detailed summary with multiple time periods (3, 7, 30 days)
|
145
|
+
rake stats_middleware:detailed_summary
|
146
|
+
|
147
|
+
# Export statistics to JSON file
|
148
|
+
rake stats_middleware:export[30,my_stats.json]
|
149
|
+
```
|
150
|
+
|
151
|
+
**Note**: These rake tasks require a `REDIS` constant to be defined in your application.
|
152
|
+
|
153
|
+
## Development
|
154
|
+
|
155
|
+
After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
|
156
|
+
|
157
|
+
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 the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
|
158
|
+
|
159
|
+
## Contributing
|
160
|
+
|
161
|
+
Bug reports and pull requests are welcome on GitHub at https://github.com/ecosyste-ms/stats-middleware. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/ecosyste-ms/stats-middleware/blob/main/CODE_OF_CONDUCT.md).
|
162
|
+
|
163
|
+
## Code of Conduct
|
164
|
+
|
165
|
+
Everyone interacting in the Stats::Middleware project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/ecosyste-ms/stats-middleware/blob/main/CODE_OF_CONDUCT.md).
|
data/Rakefile
ADDED
@@ -0,0 +1,62 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require 'logger'
|
4
|
+
|
5
|
+
module Stats
|
6
|
+
module Middleware
|
7
|
+
class IpTracker
|
8
|
+
def initialize(app, options = {})
|
9
|
+
@app = app
|
10
|
+
@redis = options[:redis] || (defined?(REDIS) && REDIS) || nil
|
11
|
+
@path_filter = options[:path_filter] || ->(path) { path&.start_with?('/api/') }
|
12
|
+
@logger = options[:logger] || (defined?(Rails) && Rails.respond_to?(:logger) ? Rails.logger : Logger.new(STDOUT))
|
13
|
+
@expiry_days = options[:expiry_days] || 31
|
14
|
+
end
|
15
|
+
|
16
|
+
def call(env)
|
17
|
+
track_request(env) if should_track?(env)
|
18
|
+
@app.call(env)
|
19
|
+
end
|
20
|
+
|
21
|
+
private
|
22
|
+
|
23
|
+
def should_track?(env)
|
24
|
+
@path_filter.call(env['PATH_INFO'])
|
25
|
+
end
|
26
|
+
|
27
|
+
def track_request(env)
|
28
|
+
return unless @redis
|
29
|
+
|
30
|
+
ip_address = get_client_ip(env)
|
31
|
+
today = Date.today.to_s
|
32
|
+
|
33
|
+
# Use a sorted set for each day with IP addresses as members and counts as scores
|
34
|
+
day_key = "api_requests:ips:#{today}"
|
35
|
+
|
36
|
+
# Increment the count for this IP address
|
37
|
+
@redis.zincrby(day_key, 1, ip_address)
|
38
|
+
|
39
|
+
# Set expiration to configured days (convert to seconds)
|
40
|
+
@redis.expire(day_key, @expiry_days * 24 * 60 * 60)
|
41
|
+
rescue => e
|
42
|
+
@logger&.error "Stats::Middleware::IpTracker error: #{e.message}"
|
43
|
+
end
|
44
|
+
|
45
|
+
def get_client_ip(env)
|
46
|
+
# Check for Cloudflare's original IP header first
|
47
|
+
cf_connecting_ip = env['HTTP_CF_CONNECTING_IP']
|
48
|
+
return cf_connecting_ip.strip if cf_connecting_ip && !cf_connecting_ip.empty?
|
49
|
+
|
50
|
+
# Check for forwarded IPs (when behind proxy/load balancer)
|
51
|
+
forwarded_for = env['HTTP_X_FORWARDED_FOR']
|
52
|
+
if forwarded_for && !forwarded_for.empty?
|
53
|
+
# Take the first IP if there are multiple (client -> proxy1 -> proxy2)
|
54
|
+
forwarded_for.split(',').first.strip
|
55
|
+
else
|
56
|
+
# Direct connection
|
57
|
+
env['REMOTE_ADDR'] || 'Unknown'
|
58
|
+
end
|
59
|
+
end
|
60
|
+
end
|
61
|
+
end
|
62
|
+
end
|
@@ -0,0 +1,110 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module Stats
|
4
|
+
module Middleware
|
5
|
+
class StatsReporter
|
6
|
+
def initialize(redis:, redis_key_prefix: 'api_requests')
|
7
|
+
@redis = redis
|
8
|
+
@redis_key_prefix = redis_key_prefix
|
9
|
+
end
|
10
|
+
|
11
|
+
def summary(days: 30)
|
12
|
+
user_agents = {}
|
13
|
+
ips = {}
|
14
|
+
|
15
|
+
# Collect data for the specified number of days
|
16
|
+
days.times do |i|
|
17
|
+
date = (Date.today - i).to_s
|
18
|
+
|
19
|
+
# Collect user agents
|
20
|
+
ua_key = "#{@redis_key_prefix}:#{date}"
|
21
|
+
if @redis.exists?(ua_key)
|
22
|
+
@redis.zrevrange(ua_key, 0, -1, with_scores: true).each do |agent, count|
|
23
|
+
user_agents[agent] ||= 0
|
24
|
+
user_agents[agent] += count.to_i
|
25
|
+
end
|
26
|
+
end
|
27
|
+
|
28
|
+
# Collect IPs
|
29
|
+
ip_key = "#{@redis_key_prefix}:ips:#{date}"
|
30
|
+
if @redis.exists?(ip_key)
|
31
|
+
@redis.zrevrange(ip_key, 0, -1, with_scores: true).each do |ip, count|
|
32
|
+
ips[ip] ||= 0
|
33
|
+
ips[ip] += count.to_i
|
34
|
+
end
|
35
|
+
end
|
36
|
+
end
|
37
|
+
|
38
|
+
{
|
39
|
+
user_agents: user_agents,
|
40
|
+
ips: ips,
|
41
|
+
days: days
|
42
|
+
}
|
43
|
+
end
|
44
|
+
|
45
|
+
def summary_report(days: 30, limit: 10)
|
46
|
+
stats = summary(days: days)
|
47
|
+
|
48
|
+
output = []
|
49
|
+
output << "=" * 80
|
50
|
+
output << "API Usage Statistics Summary"
|
51
|
+
output << "=" * 80
|
52
|
+
output << "Period: Past #{days} days"
|
53
|
+
output << "-" * 40
|
54
|
+
|
55
|
+
output << format_user_agents(stats[:user_agents], limit: limit)
|
56
|
+
output << format_ips(stats[:ips], limit: limit)
|
57
|
+
output << format_totals(stats[:user_agents], stats[:ips])
|
58
|
+
|
59
|
+
output << "=" * 80
|
60
|
+
output.join("\n")
|
61
|
+
end
|
62
|
+
|
63
|
+
def display_summary(days: 30, limit: 10)
|
64
|
+
puts summary_report(days: days, limit: limit)
|
65
|
+
end
|
66
|
+
|
67
|
+
private
|
68
|
+
|
69
|
+
def format_user_agents(user_agents, limit: 10)
|
70
|
+
output = ["\nTop User Agents:"]
|
71
|
+
if user_agents.empty?
|
72
|
+
output << " No user agent data available"
|
73
|
+
else
|
74
|
+
sorted_agents = user_agents.sort_by { |_, count| -count }.first(limit)
|
75
|
+
max_agent_length = sorted_agents.map { |agent, _| agent.length }.max || 0
|
76
|
+
max_agent_length = [max_agent_length, 50].min # Cap at 50 chars for display
|
77
|
+
|
78
|
+
sorted_agents.each_with_index do |(agent, count), index|
|
79
|
+
display_agent = agent.length > 50 ? "#{agent[0..47]}..." : agent
|
80
|
+
output << sprintf(" %2d. %-#{max_agent_length}s : %6d requests", index + 1, display_agent, count)
|
81
|
+
end
|
82
|
+
end
|
83
|
+
output.join("\n")
|
84
|
+
end
|
85
|
+
|
86
|
+
def format_ips(ips, limit: 10)
|
87
|
+
output = ["\nTop IP Addresses:"]
|
88
|
+
if ips.empty?
|
89
|
+
output << " No IP data available"
|
90
|
+
else
|
91
|
+
sorted_ips = ips.sort_by { |_, count| -count }.first(limit)
|
92
|
+
max_ip_length = sorted_ips.map { |ip, _| ip.length }.max || 0
|
93
|
+
|
94
|
+
sorted_ips.each_with_index do |(ip, count), index|
|
95
|
+
output << sprintf(" %2d. %-#{max_ip_length}s : %6d requests", index + 1, ip, count)
|
96
|
+
end
|
97
|
+
end
|
98
|
+
output.join("\n")
|
99
|
+
end
|
100
|
+
|
101
|
+
def format_totals(user_agents, ips)
|
102
|
+
output = ["\nSummary:"]
|
103
|
+
output << " Total unique user agents: #{user_agents.keys.count}"
|
104
|
+
output << " Total unique IPs: #{ips.keys.count}"
|
105
|
+
output << " Total API requests: #{user_agents.values.sum}"
|
106
|
+
output.join("\n")
|
107
|
+
end
|
108
|
+
end
|
109
|
+
end
|
110
|
+
end
|
@@ -0,0 +1,47 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require 'logger'
|
4
|
+
|
5
|
+
module Stats
|
6
|
+
module Middleware
|
7
|
+
class UserAgentTracker
|
8
|
+
def initialize(app, options = {})
|
9
|
+
@app = app
|
10
|
+
@redis = options[:redis] || (defined?(REDIS) && REDIS) || nil
|
11
|
+
@path_filter = options[:path_filter] || ->(path) { path&.start_with?('/api/') }
|
12
|
+
@logger = options[:logger] || (defined?(Rails) && Rails.respond_to?(:logger) ? Rails.logger : Logger.new(STDOUT))
|
13
|
+
@expiry_days = options[:expiry_days] || 31
|
14
|
+
@redis_key_prefix = options[:redis_key_prefix] || 'api_requests'
|
15
|
+
end
|
16
|
+
|
17
|
+
def call(env)
|
18
|
+
track_request(env) if should_track?(env)
|
19
|
+
@app.call(env)
|
20
|
+
end
|
21
|
+
|
22
|
+
private
|
23
|
+
|
24
|
+
def should_track?(env)
|
25
|
+
@path_filter.call(env['PATH_INFO'])
|
26
|
+
end
|
27
|
+
|
28
|
+
def track_request(env)
|
29
|
+
return unless @redis
|
30
|
+
|
31
|
+
user_agent = env['HTTP_USER_AGENT'] || 'Unknown'
|
32
|
+
today = Date.today.to_s
|
33
|
+
|
34
|
+
# Use a sorted set for each day with user agents as members and counts as scores
|
35
|
+
day_key = "#{@redis_key_prefix}:#{today}"
|
36
|
+
|
37
|
+
# Increment the count for this user agent
|
38
|
+
@redis.zincrby(day_key, 1, user_agent)
|
39
|
+
|
40
|
+
# Set expiration to configured days (convert to seconds)
|
41
|
+
@redis.expire(day_key, @expiry_days * 24 * 60 * 60)
|
42
|
+
rescue => e
|
43
|
+
@logger&.error "Stats::Middleware::UserAgentTracker error: #{e.message}"
|
44
|
+
end
|
45
|
+
end
|
46
|
+
end
|
47
|
+
end
|
@@ -0,0 +1,12 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require_relative "middleware/version"
|
4
|
+
require_relative "middleware/ip_tracker"
|
5
|
+
require_relative "middleware/user_agent_tracker"
|
6
|
+
require_relative "middleware/stats_reporter"
|
7
|
+
|
8
|
+
module Stats
|
9
|
+
module Middleware
|
10
|
+
class Error < StandardError; end
|
11
|
+
end
|
12
|
+
end
|
@@ -0,0 +1,72 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require 'stats/middleware'
|
4
|
+
|
5
|
+
namespace :stats_middleware do
|
6
|
+
desc "Display API usage statistics summary"
|
7
|
+
task :summary, [:days] => :environment do |task, args|
|
8
|
+
days = args[:days]&.to_i || 30
|
9
|
+
|
10
|
+
unless defined?(REDIS)
|
11
|
+
puts "Error: REDIS constant not defined. Please ensure Redis is configured in your application."
|
12
|
+
puts "Example: REDIS = Redis.new(url: ENV['REDIS_URL'])"
|
13
|
+
exit 1
|
14
|
+
end
|
15
|
+
|
16
|
+
reporter = Stats::Middleware::StatsReporter.new(redis: REDIS)
|
17
|
+
puts reporter.summary_report(days: days)
|
18
|
+
end
|
19
|
+
|
20
|
+
desc "Display API usage statistics for multiple time periods"
|
21
|
+
task :detailed_summary => :environment do
|
22
|
+
unless defined?(REDIS)
|
23
|
+
puts "Error: REDIS constant not defined. Please ensure Redis is configured in your application."
|
24
|
+
exit 1
|
25
|
+
end
|
26
|
+
|
27
|
+
reporter = Stats::Middleware::StatsReporter.new(redis: REDIS)
|
28
|
+
|
29
|
+
puts "=" * 80
|
30
|
+
puts "API Usage Statistics - Detailed Summary"
|
31
|
+
puts "=" * 80
|
32
|
+
|
33
|
+
[3, 7, 30].each do |days|
|
34
|
+
puts "\nPast #{days} Days:"
|
35
|
+
puts "-" * 40
|
36
|
+
puts reporter.summary_report(days: days)
|
37
|
+
end
|
38
|
+
end
|
39
|
+
|
40
|
+
desc "Export API usage statistics to JSON"
|
41
|
+
task :export, [:days, :output_file] => :environment do |task, args|
|
42
|
+
days = args[:days]&.to_i || 30
|
43
|
+
output_file = args[:output_file] || "api_stats_#{Date.today}_#{days}days.json"
|
44
|
+
|
45
|
+
unless defined?(REDIS)
|
46
|
+
puts "Error: REDIS constant not defined. Please ensure Redis is configured in your application."
|
47
|
+
exit 1
|
48
|
+
end
|
49
|
+
|
50
|
+
require 'json'
|
51
|
+
|
52
|
+
reporter = Stats::Middleware::StatsReporter.new(redis: REDIS)
|
53
|
+
stats = reporter.summary(days: days)
|
54
|
+
|
55
|
+
export_data = {
|
56
|
+
generated_at: Time.now.iso8601,
|
57
|
+
period_days: days,
|
58
|
+
summary: {
|
59
|
+
total_unique_user_agents: stats[:user_agents].keys.count,
|
60
|
+
total_unique_ips: stats[:ips].keys.count,
|
61
|
+
total_requests: stats[:user_agents].values.sum
|
62
|
+
},
|
63
|
+
user_agents: stats[:user_agents].sort_by { |_, count| -count },
|
64
|
+
ips: stats[:ips].sort_by { |_, count| -count }
|
65
|
+
}
|
66
|
+
|
67
|
+
File.write(output_file, JSON.pretty_generate(export_data))
|
68
|
+
puts "Statistics exported to: #{output_file}"
|
69
|
+
puts "Period: #{days} days"
|
70
|
+
puts "Total requests: #{export_data[:summary][:total_requests]}"
|
71
|
+
end
|
72
|
+
end
|
metadata
ADDED
@@ -0,0 +1,96 @@
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
2
|
+
name: stats-middleware
|
3
|
+
version: !ruby/object:Gem::Version
|
4
|
+
version: 0.1.0
|
5
|
+
platform: ruby
|
6
|
+
authors:
|
7
|
+
- Andrew Nesbitt
|
8
|
+
bindir: exe
|
9
|
+
cert_chain: []
|
10
|
+
date: 1980-01-02 00:00:00.000000000 Z
|
11
|
+
dependencies:
|
12
|
+
- !ruby/object:Gem::Dependency
|
13
|
+
name: redis
|
14
|
+
requirement: !ruby/object:Gem::Requirement
|
15
|
+
requirements:
|
16
|
+
- - ">="
|
17
|
+
- !ruby/object:Gem::Version
|
18
|
+
version: '4.0'
|
19
|
+
type: :runtime
|
20
|
+
prerelease: false
|
21
|
+
version_requirements: !ruby/object:Gem::Requirement
|
22
|
+
requirements:
|
23
|
+
- - ">="
|
24
|
+
- !ruby/object:Gem::Version
|
25
|
+
version: '4.0'
|
26
|
+
- !ruby/object:Gem::Dependency
|
27
|
+
name: rack
|
28
|
+
requirement: !ruby/object:Gem::Requirement
|
29
|
+
requirements:
|
30
|
+
- - ">="
|
31
|
+
- !ruby/object:Gem::Version
|
32
|
+
version: '2.0'
|
33
|
+
type: :runtime
|
34
|
+
prerelease: false
|
35
|
+
version_requirements: !ruby/object:Gem::Requirement
|
36
|
+
requirements:
|
37
|
+
- - ">="
|
38
|
+
- !ruby/object:Gem::Version
|
39
|
+
version: '2.0'
|
40
|
+
- !ruby/object:Gem::Dependency
|
41
|
+
name: logger
|
42
|
+
requirement: !ruby/object:Gem::Requirement
|
43
|
+
requirements:
|
44
|
+
- - ">="
|
45
|
+
- !ruby/object:Gem::Version
|
46
|
+
version: '0'
|
47
|
+
type: :runtime
|
48
|
+
prerelease: false
|
49
|
+
version_requirements: !ruby/object:Gem::Requirement
|
50
|
+
requirements:
|
51
|
+
- - ">="
|
52
|
+
- !ruby/object:Gem::Version
|
53
|
+
version: '0'
|
54
|
+
description: A collection of Rack middleware components for tracking API usage statistics
|
55
|
+
including user agent and IP address data with Redis storage.
|
56
|
+
email:
|
57
|
+
- andrew@ecosyste.ms
|
58
|
+
executables: []
|
59
|
+
extensions: []
|
60
|
+
extra_rdoc_files: []
|
61
|
+
files:
|
62
|
+
- CHANGELOG.md
|
63
|
+
- CODE_OF_CONDUCT.md
|
64
|
+
- README.md
|
65
|
+
- Rakefile
|
66
|
+
- lib/stats/middleware.rb
|
67
|
+
- lib/stats/middleware/ip_tracker.rb
|
68
|
+
- lib/stats/middleware/stats_reporter.rb
|
69
|
+
- lib/stats/middleware/user_agent_tracker.rb
|
70
|
+
- lib/stats/middleware/version.rb
|
71
|
+
- lib/tasks/stats_middleware.rake
|
72
|
+
- sig/stats/middleware.rbs
|
73
|
+
homepage: https://github.com/ecosyste-ms/stats-middleware
|
74
|
+
licenses: []
|
75
|
+
metadata:
|
76
|
+
homepage_uri: https://github.com/ecosyste-ms/stats-middleware
|
77
|
+
source_code_uri: https://github.com/ecosyste-ms/stats-middleware
|
78
|
+
changelog_uri: https://github.com/ecosyste-ms/stats-middleware/blob/main/CHANGELOG.md
|
79
|
+
rdoc_options: []
|
80
|
+
require_paths:
|
81
|
+
- lib
|
82
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
83
|
+
requirements:
|
84
|
+
- - ">="
|
85
|
+
- !ruby/object:Gem::Version
|
86
|
+
version: 3.2.0
|
87
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
88
|
+
requirements:
|
89
|
+
- - ">="
|
90
|
+
- !ruby/object:Gem::Version
|
91
|
+
version: '0'
|
92
|
+
requirements: []
|
93
|
+
rubygems_version: 3.6.9
|
94
|
+
specification_version: 4
|
95
|
+
summary: Rack middleware for tracking user agent and IP statistics
|
96
|
+
test_files: []
|