killbill-client 4.0.11 → 4.0.12

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: 510b468787e3d7b5c8b187f63d387f9ad4ba180215fc767d31de279044ace654
4
- data.tar.gz: a42f828b26cfe0eccd2d86859e8aaad31d1d5f158664c83a871507bb6aa2d765
3
+ metadata.gz: b48adb2cc1e4e7f535271ad99672a10e32f4b3fa14f8df9d8230ac0ed9e3fbef
4
+ data.tar.gz: 7d0f22af43b3a442720e42b2445d79506a215a1ec908b14773073f0e7b216830
5
5
  SHA512:
6
- metadata.gz: d1003f5b54c25730271f64f9d7658a64cdf293d66a7b59af26bb958ed84f8bc3ea343a399f43e3c0a019e8eb9f808a87c098eab371a3e950c5deb49bbc2e4e64
7
- data.tar.gz: 92b10cb4cf6e04973c142fd1fd8390fc5c7ced5aecbab76ec0e339c2ee0cf9fe1c90a551a82ad40ae41dd30653c5f420e47cf4c7609991af0d19f2d18c50a2ff
6
+ metadata.gz: 2213b71e35f2be99446f8d8c21044853d9fc91c041b940e25dff6032c789054367d308f0b9da1c72eee456355a8850d5944a602820f9dc0861240dfa61a6eba5
7
+ data.tar.gz: e5c3bbef6e03df26bbf95e0a1fb1317440093cfcdb662af3d4700540fb480d914b19835b96f69efe04abb8f5f086b584387b76e2ffd1a19e08846f64e7055282
@@ -0,0 +1,69 @@
1
+ #!/usr/bin/env ruby
2
+ #
3
+ # Micro-benchmark for the hot path that turns Kill Bill JSON responses into models (and back):
4
+ # Utils.underscore / Utils.camelize and Resource.from_json / #to_hash.
5
+ #
6
+ # Only uses the standard library. Run it on two checkouts (e.g. master vs a branch) to compare:
7
+ #
8
+ # ruby -Ilib benchmark/conversions.rb
9
+ # jruby -Ilib benchmark/conversions.rb
10
+ #
11
+ # ITERATIONS (default 20) and INVOICES (default 300, i.e. a large account) can be set in the environment.
12
+ # On CRuby the number of allocated objects per operation is reported too.
13
+
14
+ require 'json'
15
+ require 'killbill_client'
16
+
17
+ ITERATIONS = Integer(ENV['ITERATIONS'] || 20)
18
+ INVOICES = Integer(ENV['INVOICES'] || 300)
19
+ ITEMS_PER_INVOICE = 3
20
+ WARMUP_ROUNDS = 5
21
+
22
+ def json_hash_for(model_class, overrides = {})
23
+ model_class.json_attributes.each_with_object({}) do |name, hash|
24
+ hash[KillBillClient::Utils.camelize(name, :lower)] = "value-#{name}"
25
+ end.merge(overrides)
26
+ end
27
+
28
+ # A list of invoices with items, shaped like GET /1.0/kb/accounts/{id}/invoices?withItems=true
29
+ invoices = Array.new(INVOICES) do |i|
30
+ items = Array.new(ITEMS_PER_INVOICE) { |j| json_hash_for(KillBillClient::Model::InvoiceItem, 'amount' => j * 10.0) }
31
+ json_hash_for(KillBillClient::Model::Invoice, 'amount' => i * 1.5, 'items' => items, 'credits' => [], 'auditLogs' => [])
32
+ end
33
+ INVOICES_JSON = JSON.generate(invoices)
34
+ KEYS = (KillBillClient::Model::Invoice.json_attributes + KillBillClient::Model::InvoiceItem.json_attributes +
35
+ KillBillClient::Model::Account.json_attributes).uniq.map { |n| KillBillClient::Utils.camelize(n, :lower) }
36
+
37
+ def allocated_objects
38
+ GC.respond_to?(:stat) && GC.stat.key?(:total_allocated_objects) ? GC.stat(:total_allocated_objects) : nil
39
+ end
40
+
41
+ def measure(label, ops_per_iteration)
42
+ WARMUP_ROUNDS.times { yield }
43
+ before_allocs = allocated_objects
44
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
45
+ ITERATIONS.times { yield }
46
+ elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
47
+ after_allocs = allocated_objects
48
+
49
+ ops = ITERATIONS * ops_per_iteration
50
+ line = format('%-42s %10.1f ms/iter %12.0f ops/s', label, elapsed * 1000 / ITERATIONS, ops / elapsed)
51
+ line += format(' %10.1f objs/op', (after_allocs - before_allocs).to_f / ops) if before_allocs && after_allocs
52
+ puts line
53
+ end
54
+
55
+ puts "#{RUBY_ENGINE} #{RUBY_ENGINE == 'jruby' ? JRUBY_VERSION : RUBY_VERSION}, killbill-client #{KillBillClient::VERSION}, " \
56
+ "#{INVOICES} invoices x #{ITEMS_PER_INVOICE} items (#{INVOICES_JSON.bytesize / 1024} KiB of JSON), #{ITERATIONS} iterations"
57
+
58
+ measure("Utils.underscore (#{KEYS.size} keys x 1000)", KEYS.size * 1000) do
59
+ 1000.times { KEYS.each { |k| KillBillClient::Utils.underscore(k) } }
60
+ end
61
+
62
+ records = nil
63
+ measure('Resource.from_json (invoice list)', INVOICES) do
64
+ records = KillBillClient::Model::Resource.send(:from_json, KillBillClient::Model::Invoice, INVOICES_JSON)
65
+ end
66
+
67
+ measure('Resource#to_hash (invoice list)', INVOICES) do
68
+ records.each(&:to_hash)
69
+ end
@@ -0,0 +1,100 @@
1
+ # Benchmark for Resource.from_json / instantiate_record_from_json and Utils.underscore.
2
+ #
3
+ # ruby -Ilib benchmark/from_json.rb # synthetic payloads
4
+ # PAYLOAD_DIR=/path/to/captures ruby -Ilib benchmark/from_json.rb
5
+ #
6
+ # PAYLOAD_DIR: JSON files captured from a real Kill Bill (e.g. with curl), named
7
+ # <ModelName>.<anything>.json, where ModelName is a class under KillBillClient::Model
8
+ # (e.g. Account.json, Invoice.list.json, InvoicePayment.list.json, AccountTimeline.json).
9
+ # Without it, payloads are generated from the models' declared attributes (plus a few
10
+ # unknown fields), which is only a rough stand-in for real responses.
11
+ #
12
+ # Needs the benchmark-ips gem (gem install benchmark-ips).
13
+ require 'json'
14
+ require 'benchmark/ips'
15
+ require 'killbill_client'
16
+
17
+ Resource = KillBillClient::Model::Resource
18
+ Model = KillBillClient::Model
19
+
20
+ UNKNOWN_FIELDS = { 'someNewField' => 'x', 'anotherUnknownField' => 42 }.freeze
21
+
22
+ def camel(name)
23
+ KillBillClient::Utils.camelize(name, :lower)
24
+ end
25
+
26
+ # Fills every declared attribute (and has_one/has_many, down to `depth`) of a model.
27
+ def synthetic(clazz, depth = 2)
28
+ nested = Resource.class_variable_get(:@@attribute_names)
29
+ hash = {}
30
+ clazz.ancestors.each do |ancestor|
31
+ (ancestor.respond_to?(:json_attributes) ? ancestor.json_attributes : []).each { |attr| hash[camel(attr)] ||= "#{attr}-value" }
32
+ (nested[ancestor.name] || {}).each do |attr, desc|
33
+ next if desc[:type].nil? || depth.zero?
34
+ child = synthetic(desc[:type], depth - 1)
35
+ hash[camel(attr)] = desc[:cardinality] == :many ? [child, child] : child
36
+ end
37
+ end
38
+ hash.merge(UNKNOWN_FIELDS)
39
+ end
40
+
41
+ def synthetic_list(clazz, n)
42
+ Array.new(n) { synthetic(clazz, 1) }
43
+ end
44
+
45
+ def synthetic_timeline(n)
46
+ synthetic(Model::AccountTimeline, 0).merge(
47
+ 'account' => synthetic(Model::Account, 0),
48
+ 'invoices' => synthetic_list(Model::Invoice, n),
49
+ 'payments' => synthetic_list(Model::InvoicePayment, n),
50
+ 'bundles' => synthetic_list(Model::Bundle, n / 10)
51
+ )
52
+ end
53
+
54
+ def load_payloads
55
+ dir = ENV['PAYLOAD_DIR']
56
+ if dir
57
+ Dir[File.join(dir, '*.json')].sort.map do |file|
58
+ [File.basename(file, '.json'), Model.const_get(File.basename(file).split('.').first), File.read(file)]
59
+ end
60
+ else
61
+ [
62
+ ['Account (synthetic)', Model::Account, synthetic(Model::Account, 0).to_json],
63
+ ['Invoice list x50 (synthetic)', Model::Invoice, synthetic_list(Model::Invoice, 50).to_json],
64
+ ['InvoicePayment list x50 (synthetic)', Model::InvoicePayment, synthetic_list(Model::InvoicePayment, 50).to_json],
65
+ ['AccountTimeline, 300 invoices/payments (synthetic)', Model::AccountTimeline, synthetic_timeline(300).to_json]
66
+ ]
67
+ end
68
+ end
69
+
70
+ def allocations
71
+ GC.stat[:total_allocated_objects].to_i
72
+ end
73
+
74
+ payloads = load_payloads
75
+ puts "#{RUBY_ENGINE} #{RUBY_VERSION} (#{RUBY_PLATFORM}), killbill_client #{KillBillClient::VERSION}"
76
+ puts
77
+
78
+ puts 'Per payload: size, objects allocated per parse (CRuby only), exceptions raised per parse'
79
+ payloads.each do |label, clazz, json|
80
+ Resource.from_json(clazz, json) # warm up (fills caches, if any)
81
+
82
+ raised = Hash.new(0)
83
+ trace = TracePoint.new(:raise) { |tp| raised[tp.raised_exception.class] += 1 }
84
+ before = allocations
85
+ trace.enable { Resource.from_json(clazz, json) }
86
+ allocated = allocations - before
87
+
88
+ printf(" %-55s %8d bytes %9s allocations exceptions: %s\n", label, json.bytesize,
89
+ allocated.zero? ? 'n/a' : allocated, raised.empty? ? 0 : raised.inspect)
90
+ end
91
+ puts
92
+
93
+ Benchmark.ips do |x|
94
+ x.config(:time => 5, :warmup => 3)
95
+ payloads.each do |label, clazz, json|
96
+ x.report("from_json #{label}") { Resource.from_json(clazz, json) }
97
+ end
98
+ x.report('Utils.underscore (camelCase key)') { KillBillClient::Utils.underscore('invoicePaymentId') }
99
+ x.report('Utils.underscore (already underscored)') { KillBillClient::Utils.underscore('invoice_payment_id') }
100
+ end
@@ -212,9 +212,13 @@ module KillBillClient
212
212
  def get_invoice_template(is_manual_pay, locale = nil, options = {})
213
213
 
214
214
  require_multi_tenant_options!(options, "Retrieving an invoice template supported in multi-tenant mode")
215
- locale ||= 'en'
216
215
 
217
- get "#{KILLBILL_API_INVOICES_PREFIX}/#{is_manual_pay ? "manualPayTemplate/#{locale}" : "template"}",
216
+ # Manual-pay templates are tenant-scoped, not locale-scoped. Keep the
217
+ # locale argument for backwards compatibility with callers, but don't
218
+ # include it in the endpoint path.
219
+ template_path = is_manual_pay ? "manualPayTemplate" : "template"
220
+
221
+ get "#{KILLBILL_API_INVOICES_PREFIX}/#{template_path}",
218
222
  {},
219
223
  {
220
224
  :head => {'Accept' => 'text/html'},
@@ -14,6 +14,11 @@ module KillBillClient
14
14
 
15
15
  @@attribute_names = {}
16
16
 
17
+ UNKNOWN_JSON_ATTRIBUTE = [].freeze
18
+ # class => { json key => [setter, cardinality, type] | UNKNOWN_JSON_ATTRIBUTE }
19
+ @@json_attribute_cache = {}
20
+ @@json_attribute_cache_lock = Mutex.new
21
+
17
22
  def initialize(hash = nil)
18
23
  @uri = nil
19
24
  # Make sure we support ActiveSupport::HashWithIndifferentAccess for Kaui
@@ -143,44 +148,81 @@ module KillBillClient
143
148
  def instantiate_record_from_json(resource_class, data)
144
149
  record = resource_class.send :new
145
150
 
146
- kb_ancestors = resource_class.ancestors.select { |ancestor| !@@attribute_names[ancestor.name].nil? }
151
+ # One hash lookup per JSON key (see json_attribute_for)
152
+ table = @@json_attribute_cache[resource_class] || {}
147
153
  data.each do |name, value|
148
- name = Utils.underscore name
149
- attr_desc = nil
154
+ entry = table[name] || json_attribute_for(resource_class, name)
155
+ assign_json_attribute(record, entry, value) unless entry.equal?(UNKNOWN_JSON_ATTRIBUTE)
156
+ end
157
+
158
+ record
159
+ end
150
160
 
151
- # Allow for inheritance
152
- kb_ancestors.each do |ancestor|
153
- attr_desc = @@attribute_names[ancestor.name][name.to_sym]
154
- break unless attr_desc.nil?
161
+ def assign_json_attribute(record, entry, value)
162
+ type = entry[2]
163
+ unless type.nil?
164
+ if entry[1] == :many
165
+ value = build_many(type, value) if value.is_a?(Array)
166
+ elsif entry[1] == :one
167
+ value = instantiate_record_from_json(type, value) if value.is_a?(Hash)
155
168
  end
169
+ end
156
170
 
157
- unless attr_desc.nil?
158
- type = attr_desc[:type]
159
- if attr_desc[:cardinality] == :many && !type.nil? && value.is_a?(Array)
160
- newValue = []
161
- value.each do |val|
162
- if val.is_a?(Hash)
163
- newValue << instantiate_record_from_json(type, val)
164
- else
165
- newValue << val
166
- end
167
- end
168
- value = newValue
169
- elsif attr_desc[:cardinality] == :one && !type.nil? && value.is_a?(Hash)
170
- value = instantiate_record_from_json(type, value)
171
- end
172
- end #end unless attr_desc.nil? or data_elem.blank?
171
+ # TODO Be lenient for now to support different API formats
172
+ begin
173
+ record.send(entry[0], value)
174
+ rescue StandardError
175
+ nil
176
+ end
177
+ end
173
178
 
174
- # TODO Be lenient for now to support different API formats
175
- record.send("#{Utils.underscore name}=", value) rescue nil
179
+ def build_many(type, values)
180
+ records = []
181
+ values.each do |val|
182
+ records << (val.is_a?(Hash) ? instantiate_record_from_json(type, val) : val)
183
+ end
184
+ records
185
+ end
176
186
 
177
- end #end data.each
187
+ # Resolves (and caches) what to do with a JSON key for a given class:
188
+ # [setter, cardinality, type] or UNKNOWN_JSON_ATTRIBUTE if the class doesn't have a matching setter.
189
+ #
190
+ # The cache is copy-on-write: readers never lock (and never see a Hash being mutated), writers are serialized.
191
+ def json_attribute_for(resource_class, json_key)
192
+ @@json_attribute_cache_lock.synchronize do
193
+ table = @@json_attribute_cache[resource_class] || {}
194
+ return table[json_key] if table.key?(json_key)
195
+
196
+ entry = resolve_json_attribute(resource_class, json_key)
197
+ @@json_attribute_cache = @@json_attribute_cache.merge(resource_class => table.merge(json_key => entry))
198
+ entry
199
+ end
200
+ end
178
201
 
179
- record
202
+ def resolve_json_attribute(resource_class, json_key)
203
+ name = Utils.underscore json_key
204
+ setter = "#{name}=".to_sym
205
+ return UNKNOWN_JSON_ATTRIBUTE unless resource_class.method_defined?(setter) || resource_class.private_method_defined?(setter)
206
+
207
+ # Allow for inheritance: the closest ancestor declaring the attribute wins
208
+ attr_desc = nil
209
+ resource_class.ancestors.each do |ancestor|
210
+ declared = @@attribute_names[ancestor.name]
211
+ next if declared.nil?
212
+ attr_desc = declared[name.to_sym]
213
+ break unless attr_desc.nil?
214
+ end
215
+
216
+ [setter, attr_desc && attr_desc[:cardinality], attr_desc && attr_desc[:type]].freeze
217
+ end
218
+
219
+ def clear_json_attribute_cache
220
+ @@json_attribute_cache_lock.synchronize { @@json_attribute_cache = {} }
180
221
  end
181
222
 
182
223
  def attribute(name)
183
224
  send('attr_accessor', name.to_sym)
225
+ clear_json_attribute_cache
184
226
  attributes = @json_attributes ||= []
185
227
 
186
228
  if respond_to?(:json_attributes, true)
@@ -198,6 +240,7 @@ module KillBillClient
198
240
  #add it to attribute_names
199
241
  @@attribute_names[self.name] ||= {}
200
242
  @@attribute_names[self.name][attr_name.to_sym] = {:type => type, :cardinality => :many}
243
+ clear_json_attribute_cache
201
244
  end
202
245
 
203
246
  def has_one(attr_name, type = nil)
@@ -206,6 +249,7 @@ module KillBillClient
206
249
  #add it to attribute_names
207
250
  @@attribute_names[self.name] ||= {}
208
251
  @@attribute_names[self.name][attr_name.to_sym] = {:type => type, :cardinality => :one}
252
+ clear_json_attribute_cache
209
253
  end
210
254
 
211
255
  #hack to cater the api return attributes and javax attributes without editing gen scripts
@@ -213,6 +257,7 @@ module KillBillClient
213
257
  def create_alias(new_name, old_name)
214
258
  alias_method new_name.to_sym, old_name.to_sym #getter
215
259
  alias_method "#{new_name}=".to_sym, "#{old_name}=".to_sym #setter
260
+ clear_json_attribute_cache
216
261
  end
217
262
 
218
263
  # Extract the session id from a response
@@ -2,7 +2,65 @@ module KillBillClient
2
2
  module Utils
3
3
  ACRONYMS = %w(CBA).freeze
4
4
 
5
+ # Upper bound on the number of cached conversions per cache. Attribute names come from the Kill Bill API,
6
+ # so the set of distinct inputs is small in practice: this is only a safety net against unbounded growth.
7
+ MAX_CACHE_SIZE = 10_000
8
+
9
+ # Thread-safe memoization for the string conversions below. They run for every JSON key of every
10
+ # Kill Bill response and request, on a small set of distinct inputs, so caching them avoids a lot of
11
+ # regex work and allocations (in particular on JRuby).
12
+ #
13
+ # Reads never take the lock: they read a frozen Hash, and writers replace it with an updated frozen copy.
14
+ # Cached values are frozen, since they are shared between callers.
15
+ class ConversionCache
16
+ def initialize(max_size = MAX_CACHE_SIZE)
17
+ @max_size = max_size
18
+ @entries = {}.freeze
19
+ @lock = Mutex.new
20
+ end
21
+
22
+ def fetch(key)
23
+ value = @entries[key]
24
+ return value unless value.nil?
25
+
26
+ value = yield(key).freeze
27
+ @lock.synchronize do
28
+ if @entries.size < @max_size && !@entries.key?(key)
29
+ @entries = @entries.merge((key.frozen? ? key : key.dup.freeze) => value).freeze
30
+ end
31
+ end
32
+ value
33
+ end
34
+
35
+ def size
36
+ @entries.size
37
+ end
38
+ end
39
+
40
+ UNDERSCORE_CACHE = ConversionCache.new
41
+ CAMELIZE_UPPER_CACHE = ConversionCache.new
42
+ CAMELIZE_LOWER_CACHE = ConversionCache.new
43
+
44
+ # Note: the returned String is frozen (and shared), dup it before modifying it.
5
45
  def camelize(underscored_word, first_letter = :upper)
46
+ cache = first_letter == :lower ? CAMELIZE_LOWER_CACHE : CAMELIZE_UPPER_CACHE
47
+ cache.fetch(underscored_word.to_s) { |word| camelize_uncached(word, first_letter) }
48
+ end
49
+
50
+ def demodulize(class_name_in_module)
51
+ class_name_in_module.to_s.sub(/^.*::/, '')
52
+ end
53
+
54
+ # Note: the returned String is frozen (and shared), dup it before modifying it.
55
+ def underscore(camel_cased_word)
56
+ UNDERSCORE_CACHE.fetch(camel_cased_word.to_s) { |word| underscore_uncached(word) }
57
+ end
58
+
59
+ def acronym?(word)
60
+ ACRONYMS.include?(word.to_s.upcase)
61
+ end
62
+
63
+ def camelize_uncached(underscored_word, first_letter = :upper)
6
64
  camelized = underscored_word.to_s.split('_').map do |word|
7
65
  if acronym?(word)
8
66
  word.upcase
@@ -14,24 +72,18 @@ module KillBillClient
14
72
  camelized
15
73
  end
16
74
 
17
- def demodulize(class_name_in_module)
18
- class_name_in_module.to_s.sub(/^.*::/, '')
19
- end
20
-
21
- def underscore(camel_cased_word)
75
+ def underscore_uncached(camel_cased_word)
22
76
  word = camel_cased_word.to_s.dup
23
77
  word.gsub!(/::/, '/')
24
- word.gsub!(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
78
+ # Same result as /([A-Z]+)([A-Z][a-z])/ => '\1_\2' ("HTTPResponse" => "HTTP_Response"), but without the
79
+ # quantifier that backtracks polynomially on long runs of capitals (36s for 50,000 "A"s on JRuby).
80
+ word.gsub!(/([A-Z])(?=[A-Z][a-z])/, '\1_')
25
81
  word.gsub!(/([a-z\d])([A-Z])/, '\1_\2')
26
82
  word.tr! '-', '_'
27
83
  word.downcase!
28
84
  word
29
85
  end
30
86
 
31
- def acronym?(word)
32
- ACRONYMS.include?(word.to_s.upcase)
33
- end
34
-
35
87
  extend self
36
88
  end
37
89
  end
@@ -1,3 +1,3 @@
1
1
  module KillBillClient
2
- VERSION = '4.0.11'
2
+ VERSION = '4.0.12'
3
3
  end
@@ -0,0 +1,143 @@
1
+ require 'spec_helper'
2
+
3
+ # Test-only models (named, since has_one/has_many metadata is keyed by class name)
4
+ module InstantiateRecordSpec
5
+ class Leaf < KillBillClient::Model::Resource
6
+ attribute :id
7
+ attribute :first_name
8
+ end
9
+
10
+ class Base < KillBillClient::Model::Resource
11
+ attribute :name
12
+ has_one :owner, Leaf
13
+ has_many :leaves, Leaf
14
+ end
15
+
16
+ class Child < Base
17
+ attribute :extra
18
+ has_many :more_leaves, Leaf
19
+ end
20
+ end
21
+
22
+ describe KillBillClient::Model::Resource do
23
+ let(:leaf) { InstantiateRecordSpec::Leaf }
24
+ let(:base) { InstantiateRecordSpec::Base }
25
+ let(:child) { InstantiateRecordSpec::Child }
26
+
27
+ def parse(clazz, hash)
28
+ described_class.from_json(clazz, hash.to_json)
29
+ end
30
+
31
+ describe '.from_json / instantiate_record_from_json' do
32
+ it 'maps camelCase keys to attributes' do
33
+ record = parse(leaf, 'id' => 'a', 'firstName' => 'Bob')
34
+ expect(record.id).to eq('a')
35
+ expect(record.first_name).to eq('Bob')
36
+ end
37
+
38
+ it 'instantiates nested has_one' do
39
+ record = parse(base, 'name' => 'n', 'owner' => { 'id' => 'o', 'firstName' => 'Ann' })
40
+ expect(record.owner).to be_a(leaf)
41
+ expect(record.owner.first_name).to eq('Ann')
42
+ end
43
+
44
+ it 'instantiates nested has_many, leaving non-hash elements untouched' do
45
+ record = parse(base, 'leaves' => [{ 'id' => '1' }, { 'id' => '2' }, 'raw'])
46
+ expect(record.leaves.map(&:class)).to eq([leaf, leaf, String])
47
+ expect(record.leaves.first(2).map(&:id)).to eq(%w(1 2))
48
+ expect(record.leaves.last).to eq('raw')
49
+ end
50
+
51
+ it 'does not instantiate when the JSON shape does not match the declaration' do
52
+ record = parse(base, 'owner' => 'not-a-hash', 'leaves' => { 'id' => '1' })
53
+ expect(record.owner).to eq('not-a-hash')
54
+ expect(record.leaves).to eq({ 'id' => '1' })
55
+ end
56
+
57
+ it 'keeps null values' do
58
+ record = parse(base, 'owner' => nil, 'leaves' => nil)
59
+ expect(record.owner).to be_nil
60
+ expect(record.leaves).to be_nil
61
+ end
62
+
63
+ it 'inherits has_one/has_many declarations from ancestors' do
64
+ record = parse(child, 'name' => 'n', 'extra' => 'e',
65
+ 'owner' => { 'id' => 'o' },
66
+ 'leaves' => [{ 'id' => '1' }],
67
+ 'moreLeaves' => [{ 'id' => '2' }])
68
+ expect(record.name).to eq('n')
69
+ expect(record.extra).to eq('e')
70
+ expect(record.owner).to be_a(leaf)
71
+ expect(record.leaves.first).to be_a(leaf)
72
+ expect(record.more_leaves.first).to be_a(leaf)
73
+ end
74
+
75
+ it 'does not leak a subclass declaration to its parent' do
76
+ record = parse(base, 'moreLeaves' => [{ 'id' => '2' }])
77
+ expect(record).not_to respond_to(:more_leaves)
78
+ end
79
+
80
+ it 'ignores unknown fields' do
81
+ record = parse(base, 'name' => 'n', 'doesNotExist' => 1, 'nested' => { 'a' => 1 })
82
+ expect(record.name).to eq('n')
83
+ expect(record).not_to respond_to(:does_not_exist)
84
+ end
85
+
86
+ it 'does not use exceptions as control flow for unknown fields' do
87
+ parse(base, 'name' => 'warm-up', 'doesNotExist' => 1) # fill the cache
88
+
89
+ raised = []
90
+ trace = TracePoint.new(:raise) { |tp| raised << tp.raised_exception.class }
91
+ trace.enable { parse(base, 'name' => 'n', 'doesNotExist' => 1, 'alsoUnknown' => 2) }
92
+
93
+ expect(raised).to be_empty
94
+ end
95
+
96
+ it 'stays lenient when a setter raises' do
97
+ klass = Class.new(KillBillClient::Model::Resource) do
98
+ attribute :ok
99
+ def boom=(_); raise 'boom'; end
100
+ end
101
+ record = described_class.from_json(klass, { 'ok' => 1, 'boom' => 2 }.to_json)
102
+ expect(record.ok).to eq(1)
103
+ end
104
+
105
+ it 'parses arrays of records' do
106
+ records = parse(base, [{ 'name' => 'a' }, { 'name' => 'b' }])
107
+ expect(records.map(&:name)).to eq(%w(a b))
108
+ end
109
+
110
+ it 'picks up declarations added after a first parse' do
111
+ klass = Class.new(KillBillClient::Model::Resource) { attribute :id }
112
+ expect(described_class.from_json(klass, { 'id' => 1, 'late' => 2 }.to_json)).not_to respond_to(:late)
113
+
114
+ klass.send(:attribute, :late)
115
+ expect(described_class.from_json(klass, { 'id' => 1, 'late' => 2 }.to_json).late).to eq(2)
116
+ end
117
+
118
+ it 'is safe to use from several threads' do
119
+ payload = { 'name' => 'n', 'owner' => { 'id' => 'o' }, 'leaves' => [{ 'id' => '1' }], 'unknownKey' => 1 }.to_json
120
+ results = 8.times.map do
121
+ Thread.new { 50.times.map { described_class.from_json(base, payload) } }
122
+ end.flat_map(&:value)
123
+ expect(results.map { |r| [r.name, r.owner.id, r.leaves.first.id] }.uniq).to eq([%w(n o 1)])
124
+ end
125
+ end
126
+
127
+ it 'parses an AccountTimeline with real models' do
128
+ json = {
129
+ 'account' => { 'accountId' => 'acc', 'name' => 'Bob' },
130
+ 'invoices' => [{ 'invoiceId' => 'i1', 'items' => [{ 'invoiceItemId' => 'it1' }] }],
131
+ 'payments' => [{ 'paymentId' => 'p1' }],
132
+ 'bundles' => [{ 'bundleId' => 'b1' }],
133
+ 'somethingNew' => true
134
+ }.to_json
135
+ timeline = described_class.from_json(KillBillClient::Model::AccountTimeline, json)
136
+ expect(timeline.account).to be_a(KillBillClient::Model::Account)
137
+ expect(timeline.account.account_id).to eq('acc')
138
+ expect(timeline.invoices.first).to be_a(KillBillClient::Model::Invoice)
139
+ expect(timeline.invoices.first.items.first).to be_a(KillBillClient::Model::InvoiceItem)
140
+ expect(timeline.payments.first).to be_a(KillBillClient::Model::InvoicePayment)
141
+ expect(timeline.bundles.first.bundle_id).to eq('b1')
142
+ end
143
+ end
@@ -0,0 +1,195 @@
1
+ require 'spec_helper'
2
+
3
+ describe KillBillClient::Utils do
4
+ # Real attribute names, as sent by Kill Bill (camelCase) and as used by the models (snake_case)
5
+ let(:camel_cased) do
6
+ %w(accountId externalKey billCycleDayLocal accountCBA accountBalance isPaymentDelegatedToParent
7
+ paymentMethodId referenceTime timeZone CBA HTTPResponse X-Killbill-ApiKey Foo::BarBaz already_underscored id)
8
+ end
9
+ let(:underscored) do
10
+ %w(account_id external_key bill_cycle_day_local account_cba account_balance
11
+ is_payment_delegated_to_parent payment_method_id reference_time time_zone cba id)
12
+ end
13
+
14
+ describe '.underscore' do
15
+ {
16
+ 'accountId' => 'account_id',
17
+ 'AccountId' => 'account_id',
18
+ 'invoiceID' => 'invoice_id',
19
+ 'accountCBA' => 'account_cba',
20
+ 'accountCBAId' => 'account_cba_id',
21
+ 'HTTPServer' => 'http_server',
22
+ 'ABCde' => 'ab_cde',
23
+ 'ABcDEf' => 'a_bc_d_ef',
24
+ 'plan2Name' => 'plan2_name',
25
+ 'some-dashed-key' => 'some_dashed_key',
26
+ 'CBA' => 'cba',
27
+ 'HTTPResponse' => 'http_response',
28
+ 'X-Killbill-ApiKey' => 'x_killbill_api_key',
29
+ 'Foo::BarBaz' => 'foo/bar_baz',
30
+ 'already_underscored' => 'already_underscored',
31
+ 'id' => 'id',
32
+ '' => ''
33
+ }.each do |input, expected|
34
+ it "converts #{input.inspect} to #{expected.inspect}" do
35
+ expect(described_class.underscore(input)).to eq(expected)
36
+ end
37
+ end
38
+
39
+ it 'accepts symbols and nil, like before' do
40
+ expect(described_class.underscore(:accountId)).to eq('account_id')
41
+ expect(described_class.underscore(nil)).to eq('')
42
+ end
43
+
44
+ it 'does not mutate its argument' do
45
+ input = +'accountId'
46
+ described_class.underscore(input)
47
+ expect(input).to eq('accountId')
48
+ end
49
+
50
+ it 'returns the same result as the uncached implementation' do
51
+ camel_cased.each do |word|
52
+ expect(described_class.underscore(word)).to eq(described_class.underscore_uncached(word))
53
+ end
54
+ end
55
+
56
+ # The implementation from before the caching change, which used /([A-Z]+)([A-Z][a-z])/
57
+ def original_underscore(camel_cased_word)
58
+ word = camel_cased_word.to_s.dup
59
+ word.gsub!(/::/, '/')
60
+ word.gsub!(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
61
+ word.gsub!(/([a-z\d])([A-Z])/, '\1_\2')
62
+ word.tr! '-', '_'
63
+ word.downcase!
64
+ word
65
+ end
66
+
67
+ it 'matches the original implementation on tricky and random inputs' do
68
+ tricky = %w(HTTPResponse XMLHttpRequest ABCdEFg ABcDEf AbCDe AAAb aAAb A Aa AA AAa getHTTPStatusCode
69
+ account2FA x-Killbill-ApiKey Foo::BARBaz)
70
+ tricky.each { |word| expect(described_class.underscore_uncached(word)).to eq(original_underscore(word)) }
71
+
72
+ alphabet = ('A'..'Z').to_a + ('a'..'z').to_a + %w(0 1 _ - :)
73
+ rng = Random.new(42)
74
+ 2_000.times do
75
+ word = Array.new(rng.rand(1..14)) { alphabet[rng.rand(alphabet.size)] }.join
76
+ expect(described_class.underscore_uncached(word)).to eq(original_underscore(word))
77
+ end
78
+ end
79
+
80
+ it 'runs in linear time on long runs of capital letters' do
81
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
82
+ expect(described_class.underscore_uncached('A' * 50_000)).to eq('a' * 50_000)
83
+ expect(Process.clock_gettime(Process::CLOCK_MONOTONIC) - started).to be < 2
84
+ end
85
+
86
+ it 'is idempotent, so underscoring an already underscored name is a no-op' do
87
+ camel_cased.each do |word|
88
+ once = described_class.underscore(word)
89
+ expect(described_class.underscore(once)).to eq(once)
90
+ end
91
+ end
92
+
93
+ it 'returns a frozen, cached String' do
94
+ first = described_class.underscore('paymentMethodId')
95
+ expect(first).to be_frozen
96
+ expect(described_class.underscore('paymentMethodId')).to be(first)
97
+ end
98
+
99
+ it 'is not affected by later changes to the input String' do
100
+ input = +'subscriptionId'
101
+ expect(described_class.underscore(input)).to eq('subscription_id')
102
+ input << 'Suffix'
103
+ expect(described_class.underscore('subscriptionId')).to eq('subscription_id')
104
+ expect(described_class.underscore(input)).to eq('subscription_id_suffix')
105
+ end
106
+ end
107
+
108
+ describe '.camelize' do
109
+ {
110
+ ['account_id', :upper] => 'AccountId',
111
+ ['account_id', :lower] => 'accountId',
112
+ ['account_cba', :lower] => 'accountCBA',
113
+ ['cba', :upper] => 'CBA',
114
+ ['bill_cycle_day_local', :lower] => 'billCycleDayLocal',
115
+ ['id', :lower] => 'id'
116
+ }.each do |(input, first_letter), expected|
117
+ it "converts #{input.inspect} (#{first_letter}) to #{expected.inspect}" do
118
+ expect(described_class.camelize(input, first_letter)).to eq(expected)
119
+ end
120
+ end
121
+
122
+ it 'defaults to an upper case first letter' do
123
+ expect(described_class.camelize('account_id')).to eq('AccountId')
124
+ end
125
+
126
+ it 'caches upper and lower case variants separately' do
127
+ expect(described_class.camelize('tenant_id', :lower)).to eq('tenantId')
128
+ expect(described_class.camelize('tenant_id', :upper)).to eq('TenantId')
129
+ expect(described_class.camelize('tenant_id', :lower)).to eq('tenantId')
130
+ end
131
+
132
+ it 'returns the same result as the uncached implementation' do
133
+ underscored.each do |word|
134
+ [:upper, :lower].each do |first_letter|
135
+ expect(described_class.camelize(word, first_letter)).to eq(described_class.camelize_uncached(word, first_letter))
136
+ end
137
+ end
138
+ end
139
+
140
+ it 'returns a frozen, cached String' do
141
+ first = described_class.camelize('payment_id', :lower)
142
+ expect(first).to be_frozen
143
+ expect(described_class.camelize('payment_id', :lower)).to be(first)
144
+ end
145
+ end
146
+
147
+ describe KillBillClient::Utils::ConversionCache do
148
+ it 'computes a value once per key' do
149
+ cache = described_class.new
150
+ calls = 0
151
+ 2.times { expect(cache.fetch('a') { |k| calls += 1; k.upcase }).to eq('A') }
152
+ expect(calls).to eq(1)
153
+ expect(cache.size).to eq(1)
154
+ end
155
+
156
+ it 'stops caching once full, but keeps returning correct values' do
157
+ cache = described_class.new(2)
158
+ %w(a b c d).each { |k| expect(cache.fetch(k, &:upcase)).to eq(k.upcase) }
159
+ expect(cache.size).to eq(2)
160
+ expect(cache.fetch('d', &:upcase)).to eq('D')
161
+ end
162
+
163
+ it 'is safe to use from many threads at once' do
164
+ cache = described_class.new
165
+ words = (1..200).map { |i| "attributeName#{i}" }
166
+ results = Array.new(8) do
167
+ Thread.new { words.shuffle.map { |w| [w, cache.fetch(w) { |k| KillBillClient::Utils.underscore_uncached(k) }] } }
168
+ end.map(&:value)
169
+
170
+ results.each do |pairs|
171
+ pairs.each { |w, v| expect(v).to eq(KillBillClient::Utils.underscore_uncached(w)) }
172
+ end
173
+ expect(cache.size).to eq(words.size)
174
+ end
175
+ end
176
+
177
+ describe 'JSON round trip through the models' do
178
+ it 'maps camelCase JSON keys to model attributes and back' do
179
+ json = { 'accountId' => 'a1', 'externalKey' => 'ext', 'accountCBA' => 12.5, 'billCycleDayLocal' => 3,
180
+ 'unknownAttribute' => 'ignored' }.to_json
181
+
182
+ account = KillBillClient::Model::Account.send(:from_json, KillBillClient::Model::Account, json)
183
+ expect(account.account_id).to eq('a1')
184
+ expect(account.external_key).to eq('ext')
185
+ expect(account.account_cba).to eq(12.5)
186
+ expect(account.bill_cycle_day_local).to eq(3)
187
+
188
+ hash = account.to_hash
189
+ expect(hash['accountId']).to eq('a1')
190
+ expect(hash['accountCBA']).to eq(12.5)
191
+ expect(hash['billCycleDayLocal']).to eq(3)
192
+ expect(hash).not_to have_key('unknownAttribute')
193
+ end
194
+ end
195
+ end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: killbill-client
3
3
  version: !ruby/object:Gem::Version
4
- version: 4.0.11
4
+ version: 4.0.12
5
5
  platform: ruby
6
6
  authors:
7
7
  - Killbill core team
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-10-29 00:00:00.000000000 Z
11
+ date: 2026-11-18 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: gem-release
@@ -69,6 +69,8 @@ files:
69
69
  - Gemfile
70
70
  - README.md
71
71
  - Rakefile
72
+ - benchmark/conversions.rb
73
+ - benchmark/from_json.rb
72
74
  - bin/retry
73
75
  - docker/docker-compose.ci.mysql.yml
74
76
  - docker/docker-compose.ci.postgresql.yml
@@ -204,6 +206,7 @@ files:
204
206
  - spec/killbill_client/base_uri_spec.rb
205
207
  - spec/killbill_client/errors_spec.rb
206
208
  - spec/killbill_client/http_adapter_spec.rb
209
+ - spec/killbill_client/instantiate_record_from_json_spec.rb
207
210
  - spec/killbill_client/model_relation_spec.rb
208
211
  - spec/killbill_client/raw_response_spec.rb
209
212
  - spec/killbill_client/remote/api_spec.rb
@@ -211,6 +214,7 @@ files:
211
214
  - spec/killbill_client/resource_spec.rb
212
215
  - spec/killbill_client/resources_spec.rb
213
216
  - spec/killbill_client/role_definition_spec.rb
217
+ - spec/killbill_client/utils_spec.rb
214
218
  - spec/spec_helper.rb
215
219
  homepage: http://www.killbilling.org
216
220
  licenses: