Skip to content

Commit

Permalink
Also show the max and min for api usage
Browse files Browse the repository at this point in the history
  • Loading branch information
mlandauer committed Sep 19, 2024
1 parent d21dc05 commit f34344a
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 5 deletions.
19 changes: 15 additions & 4 deletions app/models/daily_api_usage.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,22 @@ def self.increment(api_key_id:, date:)
# rubocop:enable Rails/SkipsModelValidations
end

sig { params(date_from: Date, date_to: Date, number: Integer).returns(T::Array[{ api_key: ApiKey, sum: Numeric }]) }
sig { params(date_from: Date, date_to: Date, number: Integer).returns(T::Array[{ api_key: ApiKey, sum: Numeric, min: Numeric, max: Numeric }]) }
def self.top_usage_in_date_range(date_from:, date_to:, number:)
api_keys = top_by_usage_in_date_range(date_from:, date_to:, number:)
sums = where(date: date_from..date_to, api_key: api_keys).group(:api_key_id).sum(:count)
api_keys.map { |api_key| { api_key:, sum: T.must(sums[api_key.id]) } }
grouped = where(date: date_from..date_to, api_key: api_keys).group(:api_key_id)
sums = grouped.sum(:count)
# Note that the "minimum" is only for the days on which there were requests
minimums = grouped.minimum(:count)
maximums = grouped.maximum(:count)
api_keys.map do |api_key|
{
api_key:,
sum: T.must(sums[api_key.id]),
min: minimums[api_key.id],
max: maximums[api_key.id]
}
end
end

sig { params(date_from: Date, date_to: Date, number: Integer).returns(T::Enumerable[ApiKey]) }
Expand All @@ -36,7 +47,7 @@ def self.top_by_usage_in_date_range(date_from:, date_to:, number:)
def self.top_average_usage_in_date_range(date_from:, date_to:, number:)
n = (date_to - date_from + 1)
top_usage_in_date_range(date_from:, date_to:, number:).map do |r|
{ api_key: r[:api_key], mean: r[:sum].to_f / n }
{ api_key: r[:api_key], mean: r[:sum].to_f / n, min: r[:min], max: r[:max] }
end
end
end
6 changes: 5 additions & 1 deletion app/views/admin/api_usages/index.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@
<th>Commercial</th>
<th>Community</th>
<th>Daily Limit</th>
<th>Average daily requests</th>
<th>Average daily</th>
<th>Min daily</th>
<th>Max daily</th>
</thead>
<tbody>
<% @result.each do |r| %>
Expand All @@ -35,6 +37,8 @@
<td><%= link_to r[:api_key].community.to_s, admin_api_key_path(r[:api_key]) %></td>
<td><%= link_to r[:api_key].daily_limit.to_s, admin_api_key_path(r[:api_key]) %></td>
<td><%= r[:mean].round %></td>
<td><%= r[:min] %></td>
<td><%= r[:max] %></td>
</tr>
<% end %>
</tbody>
Expand Down

0 comments on commit f34344a

Please sign in to comment.