killbill-aviate 2.6.0.pre.1 → 2.6.0.pre.3

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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: a62b8480ef36de4d4b7b940fe459b21f8558d709ca383d166f7646db74fbcc0f
4
- data.tar.gz: 687a487132071980ab83a7fa071eedd743b03278426f91741a5f0b779c362bd7
3
+ metadata.gz: 8e192bcb34cf039c6503aece2901e10272816a85323fddb3ce57c709b4661076
4
+ data.tar.gz: 1a718ebcaa2cacb461f646231b5e11b2abff99d3396262138b306de2065ead53
5
5
  SHA512:
6
- metadata.gz: 4e35b059d90bd65d1b894d219694a79ea2b6c16ae232c781eb4e7e76306da5911739e4879758d51c6a504920a57ce0dc062a5a50666a8d8a8688737135c7a026
7
- data.tar.gz: dd2ff55665575f2f1fb4e1e60f92866d555d72250015cfdb22da0c77b9a25958091c3f91d5bd2b5bda7b004c42beb98a6ab8dc54d3e2dc18c3ea4bfa331f85ef
6
+ metadata.gz: 43134388a6001914fc8725f5fa56c0c3d9264c35725ba86ae79ec904fcd2f7aaee94e9a331cefd4ddd9dc76fe5bf9d3bb8a4545e49f6b2616cb78d13a0649f3d
7
+ data.tar.gz: dca7793e8ef08b995f8d9a87f863c00c4d34264b19b06b01ad75289fa151b66267a76ab2118e622f86fa50483fe195ce939954310c347f55827407f0f0686e2c
@@ -35,12 +35,21 @@ module Aviate
35
35
 
36
36
  # Step 3: Retrieve unit types from catalog
37
37
  unit_types = fetch_unit_types(@subscription, start_date, cached_options)
38
+
39
+ # Step 4: Rolled-up usage from the standard Kill Bill usage API (fast; delegates to the
40
+ # Aviate plugin's usage API for Aviate-metered subscriptions, so it covers both catalog
41
+ # kinds). Drives the Units Consumed stat and whether the expensive series fetch is needed.
42
+ rolled_up_units = fetch_rolled_up_units(subscription_id, start_date, end_date, cached_options)
43
+ unit_types = rolled_up_units.keys if unit_types.empty? && rolled_up_units.present?
38
44
  @unit_types = unit_types
45
+ @units_consumed = unit_types.index_with { |unit| rolled_up_units&.[](unit) }
39
46
 
40
- # Step 4: Fetch daily usage time-series in parallel
41
- samples_by_unit = fetch_all_samples(subscription_id, unit_types, start_date, end_date, cached_options)
47
+ # Step 5: Fetch daily usage time-series in parallel — skipped when the rolled-up API
48
+ # authoritatively reports no usage in the period: the chart would be empty anyway and
49
+ # host_samples is expensive. nil (fetch failed) keeps the old behavior.
50
+ samples_by_unit = rolled_up_units == {} ? {} : fetch_all_samples(subscription_id, unit_types, start_date, end_date, cached_options)
42
51
 
43
- # Step 5: Build cumulative series per unit type
52
+ # Step 6: Build cumulative series per unit type
44
53
  @chart_data = build_chart_data(samples_by_unit, unit_types)
45
54
 
46
55
  # Step 6: Fetch invoice dry run for accrued cost
@@ -142,7 +151,7 @@ module Aviate
142
151
  "#{KillBillClient::Model::Catalog::KILLBILL_API_CATALOG_PREFIX}/phase",
143
152
  {
144
153
  subscriptionId: subscription.subscription_id,
145
- requestedDate: start_date.to_s
154
+ requestedDate: phase_requested_date(subscription, start_date)
146
155
  },
147
156
  cached_options
148
157
  )
@@ -170,6 +179,39 @@ module Aviate
170
179
  []
171
180
  end
172
181
 
182
+ # Rolled-up usage per unit type for the period, from the standard Kill Bill usage API
183
+ # (GET /1.0/kb/usages/{id}); for Aviate-metered subscriptions Kill Bill delegates to the
184
+ # Aviate plugin's usage API, so this covers both catalog kinds. Returns nil on error so
185
+ # callers can fall back to the (slower) sample-based behavior.
186
+ def fetch_rolled_up_units(subscription_id, start_date, end_date, cached_options)
187
+ usage = KillBillClient::Model::RolledUpUsage.find_by_subscription_id(subscription_id, start_date.to_s, end_date.to_s, cached_options)
188
+ return {} if usage.nil? || usage.rolled_up_units.blank?
189
+
190
+ usage.rolled_up_units.to_h { |unit| [unit.unit_type, unit.amount.to_f] }
191
+ rescue StandardError => e
192
+ Rails.logger.warn("Rolled-up usage fetch failed: #{e.message}")
193
+ nil
194
+ end
195
+
196
+ # The catalog phase API rejects a requestedDate before the subscription start date-time
197
+ # ("<date> is before the subscription start date"). A plain date is interpreted as
198
+ # midnight, which is before the actual start time on the subscription's first day:
199
+ # fall forward to the subscription start in that case.
200
+ def phase_requested_date(subscription, start_date)
201
+ requested = start_date.in_time_zone('UTC')
202
+ subscription_start = parse_kb_datetime(subscription.start_date)
203
+ requested = subscription_start if subscription_start.present? && subscription_start > requested
204
+ requested.strftime('%Y-%m-%dT%H:%M:%S')
205
+ end
206
+
207
+ def parse_kb_datetime(date_str)
208
+ return nil if date_str.blank?
209
+
210
+ Time.iso8601(date_str.to_s).utc
211
+ rescue ArgumentError
212
+ nil
213
+ end
214
+
173
215
  def fetch_all_samples(subscription_id, unit_types, start_date, end_date, cached_options)
174
216
  samples_by_unit = {}
175
217
  from = start_date.to_s
@@ -21,7 +21,7 @@
21
21
  <% @unit_types.each do |unit_type| %>
22
22
  <div class="stat-card card p-3">
23
23
  <div class="stat-label text-muted small">Units Consumed (<%= unit_type %>)</div>
24
- <div class="stat-value h4"><%= @chart_data[unit_type]&.last&.dig('y') || 0 %></div>
24
+ <div class="stat-value h4"><%= @units_consumed[unit_type] || @chart_data[unit_type]&.last&.dig('y') || 0 %></div>
25
25
  </div>
26
26
  <% end %>
27
27
 
data/lib/aviate/client.rb CHANGED
@@ -7,6 +7,17 @@ module Killbill
7
7
 
8
8
  CATALOG_STATE_AVIATE = 'CATALOG_STATE_AVIATE'
9
9
 
10
+ # Cap on points returned per host_samples series: enough for any chart while
11
+ # keeping multi-MB raw payloads from being expanded into millions of objects.
12
+ HOST_SAMPLES_MAX_POINTS = 500
13
+ # Short server-side cache for sample series (seconds): usage data is append-only
14
+ # and slightly stale charts are fine, repeat page views shouldn't re-pull MBs.
15
+ HOST_SAMPLES_CACHE_TTL = 300
16
+ # Per-request read timeout (ms) for the slow host_samples endpoint, kept just
17
+ # under the 60s killbill-client default so the page degrades to "no chart"
18
+ # (handled by callers) instead of hanging past upstream proxy timeouts.
19
+ HOST_SAMPLES_READ_TIMEOUT = 45_000
20
+
10
21
  class << self
11
22
  def aviate_plugin_available?(options = nil)
12
23
  path = "#{KILLBILL_AVIATE_PREFIX}/health/data"
@@ -126,17 +137,16 @@ module Killbill
126
137
  JSON.parse(e.message)
127
138
  end
128
139
 
140
+ # Returns the usage time-series for the given subscription/unit type over
141
+ # [from_date, to_date], downsampled to at most HOST_SAMPLES_MAX_POINTS points.
142
+ # Raw series can hold millions of samples (multi-MB payloads, tens of seconds per
143
+ # call), so results are bucketed (preserving totals) and briefly cached to keep
144
+ # page loads fast and memory bounded until the plugin can downsample server-side.
129
145
  def host_samples(subscription_id, sample_kind, from_date, to_date, options = nil)
130
- path = "#{KILLBILL_AVIATE_PREFIX}/health/host_samples"
131
- query_params = {
132
- from: from_date,
133
- to: to_date,
134
- category_and_sample_kind: "#{subscription_id},#{sample_kind}"
135
- }
136
-
137
- request_options = build_request_options(options)
138
- response = KillBillClient::API.get path, query_params, request_options
139
- parse_csv_response(response.body, subscription_id, sample_kind)
146
+ cache_key = "aviate/host_samples/v1/#{subscription_id}/#{sample_kind}/#{from_date}/#{to_date}"
147
+ Rails.cache.fetch(cache_key, expires_in: HOST_SAMPLES_CACHE_TTL) do
148
+ fetch_host_samples(subscription_id, sample_kind, from_date, to_date, options)
149
+ end
140
150
  rescue KillBillClient::API::ResponseError
141
151
  []
142
152
  end
@@ -168,13 +178,33 @@ module Killbill
168
178
  account_id.present? ? { accountId: account_id } : {}
169
179
  end
170
180
 
171
- def parse_csv_response(body, expected_category = nil, expected_sample_kind = nil)
181
+ def fetch_host_samples(subscription_id, sample_kind, from_date, to_date, options = nil)
182
+ path = "#{KILLBILL_AVIATE_PREFIX}/health/host_samples"
183
+ query_params = {
184
+ from: from_date,
185
+ to: to_date,
186
+ category_and_sample_kind: "#{subscription_id},#{sample_kind}"
187
+ }
188
+
189
+ request_options = build_request_options(options)
190
+ request_options[:read_timeout] = HOST_SAMPLES_READ_TIMEOUT
191
+ response = KillBillClient::API.get path, query_params, request_options
192
+ parse_csv_response(response.body, subscription_id, sample_kind)
193
+ end
194
+
195
+ # The host_samples endpoint returns a JSON array. Each element has a
196
+ # "samples" field with usage data serialized as flat comma-separated
197
+ # timestamp/value pairs: "ts1,val1,ts2,val2,..." (observed format).
198
+ # Newlines, if ever present, are normalized to commas before parsing.
199
+ #
200
+ # Raw series can contain millions of pairs for a single billing period,
201
+ # far more than any chart can display. To keep memory bounded, consecutive
202
+ # pairs are aggregated into at most +max_points+ buckets (per entry): each
203
+ # returned point carries the SUM of its bucket's values and the timestamp
204
+ # of the bucket's last sample, so downstream cumulative sums stay exact.
205
+ def parse_csv_response(body, expected_category = nil, expected_sample_kind = nil, max_points = HOST_SAMPLES_MAX_POINTS)
172
206
  return [] if body.nil? || body.strip.empty?
173
207
 
174
- # The host_samples endpoint returns a JSON array. Each element has a
175
- # "samples" field with usage data serialized as flat comma-separated
176
- # timestamp/value pairs: "ts1,val1,ts2,val2,..." (observed format).
177
- # Newlines, if ever present, are normalized to commas before parsing.
178
208
  parsed = JSON.parse(body)
179
209
  return [] unless parsed.is_a?(Array)
180
210
 
@@ -189,16 +219,38 @@ module Killbill
189
219
  samples_str = entry['samples']
190
220
  next if samples_str.nil? || samples_str.strip.empty?
191
221
 
192
- tokens = samples_str.tr("\n", ',').split(',').map(&:strip).reject(&:empty?)
193
- tokens.each_slice(2) do |ts_str, val_str|
194
- next if ts_str.nil? || val_str.nil?
222
+ # Normalize separators and drop empty tokens (equivalent to the old
223
+ # split/reject, without materializing millions of token strings).
224
+ normalized = samples_str.tr("\n", ',').squeeze(',')
225
+ normalized = normalized[1..] if normalized.start_with?(',')
226
+ normalized = normalized.chomp(',')
227
+ next if normalized.empty?
228
+
229
+ pair_count = (normalized.count(',') + 1) / 2
230
+ stride = [(pair_count / max_points.to_f).ceil, 1].max
231
+
232
+ bucket_sum = 0.0
233
+ bucket_size = 0
234
+ bucket_ts = nil
235
+
236
+ normalized.scan(/([^,]*),([^,]*)(?:,|\z)/) do |ts_str, val_str|
237
+ ts = ts_str.strip.to_i
238
+ val = val_str.strip
239
+ next if ts.zero? || val.empty?
240
+
241
+ bucket_sum += val.to_f
242
+ bucket_ts = ts
243
+ bucket_size += 1
244
+ next if bucket_size < stride
245
+
246
+ result << { date: Time.at(bucket_ts).utc.strftime('%Y-%m-%dT%H:%M:%S'), value: bucket_sum }
247
+ bucket_sum = 0.0
248
+ bucket_size = 0
249
+ end
195
250
 
196
- ts = ts_str.to_i
197
- next if ts.zero?
251
+ next unless bucket_size.positive?
198
252
 
199
- date = Time.at(ts).utc.strftime('%Y-%m-%dT%H:%M:%S')
200
- result << { date: date, value: val_str.to_f }
201
- end
253
+ result << { date: Time.at(bucket_ts).utc.strftime('%Y-%m-%dT%H:%M:%S'), value: bucket_sum }
202
254
  end
203
255
 
204
256
  # Samples may span multiple entries (e.g. one per node): keep them chronological
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Aviate
4
- VERSION = '2.6.0.pre.1'
4
+ VERSION = '2.6.0.pre.3'
5
5
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: killbill-aviate
3
3
  version: !ruby/object:Gem::Version
4
- version: 2.6.0.pre.1
4
+ version: 2.6.0.pre.3
5
5
  platform: ruby
6
6
  authors:
7
7
  - Kill Bill core team
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-09-25 00:00:00.000000000 Z
11
+ date: 2026-09-30 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: killbill-assets-ui