leverprice 0.3.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.
@@ -0,0 +1,940 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "monitor"
4
+
5
+ module Leverprice
6
+ # Prices products, logs exposures and reports purchases. Thread-safe and fork-safe; share one instance.
7
+ class Client
8
+ DEFAULT_API_URL = "https://api.leverprice.com"
9
+ USER_AGENT = "leverprice-sdk-ruby/#{VERSION}".freeze
10
+ SDK_INFO = { "name" => "leverprice-ruby", "version" => VERSION }.freeze
11
+ KEY_RE = /\App_sk_(?:live|test)_[0-9A-Za-z]{40}\z/
12
+ COOKIE_NAME_RE = /\A[!\#$%&'*+\-.^_`|~0-9A-Za-z]+\z/
13
+ SIG_RE = /\A[0-9a-f]{16}\z/
14
+ DIGITS_RE = /\A\d+\z/
15
+ PIN_MAX_AGE_SECONDS = 1800
16
+ REQUEST_TIMEOUT_MS = 10_000
17
+ STALL_MS = REQUEST_TIMEOUT_MS + 5_000
18
+ MAX_QUEUE = 5_000
19
+ AUTO_FLUSH_AT = 100
20
+ SEND_ATTEMPTS = 3
21
+ MAX_BACKOFF_MS = 30_000
22
+ CATCH_UP_GAP_MS = 5_000
23
+ MAX_DEDUPE = 10_000
24
+ IDLE_WAIT_SECONDS = 60
25
+
26
+ Guard = Struct.new(:currency, :fallback_price, :min_price, :max_price)
27
+ Scope = Struct.new(:mutex, :cookie, :pinned)
28
+ ScopeCookie = Struct.new(:input, :user_id, :assignment_key, :state)
29
+ Context = Struct.new(:cookie, :user_agent, :user_id, :exposure, :bot, keyword_init: true)
30
+ private_constant :Guard, :Scope, :ScopeCookie, :Context
31
+
32
+ # @api private
33
+ class Flight
34
+ attr_reader :started_at
35
+
36
+ def initialize(started_at)
37
+ @started_at = started_at
38
+ @mutex = Mutex.new
39
+ @finished = ConditionVariable.new
40
+ @done = false
41
+ end
42
+
43
+ def finish
44
+ @mutex.synchronize do
45
+ @done = true
46
+ @finished.broadcast
47
+ end
48
+ end
49
+
50
+ def wait(seconds)
51
+ deadline = Util.monotonic + seconds
52
+ @mutex.synchronize do
53
+ until @done
54
+ remaining = deadline - Util.monotonic
55
+ break unless remaining.positive?
56
+
57
+ @finished.wait(@mutex, remaining)
58
+ end
59
+ end
60
+ @done
61
+ end
62
+ end
63
+ private_constant :Flight
64
+
65
+ # @param products [Hash] product key => `{ currency:, fallback_price:, min_price:, max_price: }` (minor units)
66
+ # @param secret_key [String, nil] `pp_sk_live_…` or `pp_sk_test_…`; missing or malformed turns the SDK off
67
+ # @raise [ArgumentError] for invalid products or cookie_name
68
+ def initialize(products:, secret_key: nil, disabled: false, api_url: nil, timeout_ms: nil,
69
+ refresh_interval_ms: nil, max_stale_ms: nil, cookie_name: nil, cookie_max_age_seconds: nil,
70
+ cookie_secure: nil, cookie_domain: nil, flush_interval_ms: nil, trusted_root_keys: nil,
71
+ transport: nil, on_error: nil, logger: nil, clock: nil, sleeper: nil)
72
+ @guards = normalize_guards(products)
73
+ @disabled = disabled == true
74
+ @api_url = (api_url || DEFAULT_API_URL).to_s.sub(%r{/+\z}, "")
75
+ @timeout_ms = timeout_ms || 500
76
+ @refresh_interval_ms = refresh_interval_ms || 30_000
77
+ @max_stale_ms = max_stale_ms || 86_400_000
78
+ @cookie_name = cookie_name || "__pp"
79
+ unless Util.str_match?(COOKIE_NAME_RE, @cookie_name)
80
+ raise ArgumentError, "Leverprice: cookie_name is not a valid cookie name"
81
+ end
82
+
83
+ @cookie_max_age = Util.safe_int(cookie_max_age_seconds) || cookie_max_age_seconds || 15_552_000
84
+ @cookie_secure = cookie_secure != false
85
+ @cookie_domain = cookie_domain
86
+ @flush_interval_ms = flush_interval_ms || 2_000
87
+ @transport = transport || NetHTTPTransport.new
88
+ raise ArgumentError, "Leverprice: transport must respond to #call" unless @transport.respond_to?(:call)
89
+
90
+ @on_error = on_error
91
+ @logger = logger
92
+ @clock = clock
93
+ @sleeper = sleeper || ->(seconds) { sleep(seconds) }
94
+ @trust = TrustChain.new(trusted_root_keys || ROOT_PUBLIC_KEYS, MIN_KEYSET_VERSION)
95
+ key = secret_key.is_a?(String) ? Util.trim(secret_key) : ""
96
+ @secret_key = Util.str_match?(KEY_RE, key) ? key : nil
97
+ @acceptance = Acceptance.new(@trust, @secret_key)
98
+ @exposed = {}
99
+ @etag = nil
100
+ @fetched_at = 0
101
+ @failures = 0
102
+ @retry_at = 0
103
+ @server_version = 0
104
+ @catch_up_at = 0
105
+ @hmac_cache = nil
106
+ @closed = false
107
+ reset_runtime
108
+ @scope_ivar = :"@__leverprice_scope_#{ForkTracker.register(self)}"
109
+ return if key.empty? || @secret_key || @disabled || Leverprice.env_disabled?
110
+
111
+ emit(Error.new("Leverprice: secret_key is not a pp_sk_live_… / pp_sk_test_… key; serving fallback prices."))
112
+ end
113
+
114
+ # Returns the price to show and charge. Raises only for a product key missing from `products`.
115
+ # @param product_key [String, Symbol]
116
+ # @param request [Object, nil] Rack env, Rack/ActionDispatch request, object with `#headers`, or a header Hash
117
+ # @param cookie [String, nil] the Cookie header (or the bare `__pp` value); overrides `request`
118
+ # @param user_agent [String, nil] overrides the request's User-Agent
119
+ # @param user_id [String, Integer, nil] your signed-in user's id; only its HMAC leaves your server
120
+ # @param exposure [:auto, :manual, nil] `:manual` assigns without logging; call {#log_exposure} later
121
+ # @param bot [Boolean, nil] your own bot verdict, skipping the built-in check
122
+ # @return [Quote]
123
+ # @raise [ArgumentError] when `product_key` is not configured
124
+ def get_price(product_key, request: nil, cookie: nil, user_agent: nil, user_id: nil, exposure: nil, bot: nil)
125
+ key = product_key.to_s
126
+ guard = @guards[key]
127
+ raise ArgumentError, %(Leverprice: unknown product "#{key}". Add it to the products option.) unless guard
128
+ return fallback_quote(key, guard, "disabled") if off?
129
+
130
+ check_fork
131
+ context = Context.new(cookie: cookie, user_agent: user_agent, user_id: user_id, exposure: exposure, bot: bot)
132
+ scope = scope_for(request)
133
+ return compute_quote(key, guard, request, context, nil) unless scope
134
+
135
+ scope.mutex.synchronize { compute_quote(key, guard, request, context, scope) }
136
+ end
137
+
138
+ # Logs the exposure of a quote obtained with `exposure: :manual`. Never raises.
139
+ # @param quote [Quote]
140
+ # @return [Boolean] true when an exposure was queued
141
+ def log_exposure(quote)
142
+ return false if off?
143
+
144
+ check_fork
145
+ return false unless quote.respond_to?(:reason) && quote.reason == "experiment" && !quote.exposure_logged
146
+
147
+ experiment_id = quote.experiment_id
148
+ variant_id = quote.variant_id
149
+ visitor_id = quote.visitor_id
150
+ return false if [experiment_id, variant_id, visitor_id].any? { |id| id.nil? || id.empty? }
151
+
152
+ queued = record_exposure(experiment_id, variant_id, visitor_id)
153
+ quote.exposure_logged = true
154
+ queued
155
+ rescue StandardError => e
156
+ report(e)
157
+ false
158
+ end
159
+
160
+ # Reports a completed purchase and sends it right away. Never raises.
161
+ # @param provider [String, Symbol] "stripe", "polar", "lemonsqueezy", "dodo" or "other"
162
+ # @param order_id [String, Integer] the id your provider's webhook reports
163
+ # @param amount [Integer] minor units, after discounts, excluding tax
164
+ # @param currency [String]
165
+ # @param metadata [Hash, nil] the checkout's metadata (pp_exp, pp_var, pp_vid, pp_sig)
166
+ # @param timestamp [Integer, Time, nil] milliseconds or Unix seconds; defaults to now
167
+ # @return [nil]
168
+ def track_purchase(provider: nil, order_id: nil, amount: nil, currency: nil, metadata: nil, timestamp: nil,
169
+ **unknown)
170
+ return nil if off?
171
+
172
+ check_fork
173
+ report_unknown("track_purchase", unknown)
174
+ enqueue(
175
+ "type" => "purchase",
176
+ "provider" => Util.utf8(provider.to_s),
177
+ "orderId" => id_of(order_id),
178
+ "amount" => amount_of(amount),
179
+ "currency" => Util.utf8(currency.to_s).downcase,
180
+ "timestamp" => timestamp_of(timestamp),
181
+ "attribution" => attribution_of(metadata)
182
+ )
183
+ flush
184
+ rescue StandardError => e
185
+ report(e)
186
+ nil
187
+ end
188
+
189
+ # Reports a refund (one refund by id with its amount, or the order's cumulative refunded total). Never raises.
190
+ # @param refund_id [String, Integer, nil] with `amount`
191
+ # @param refunded_total [Integer, nil] instead of `refund_id` and `amount`
192
+ # @return [nil]
193
+ def track_refund(provider: nil, order_id: nil, currency: nil, refund_id: nil, amount: nil, refunded_total: nil,
194
+ timestamp: nil, **unknown)
195
+ return nil if off?
196
+
197
+ check_fork
198
+ report_unknown("track_refund", unknown)
199
+ event = {
200
+ "type" => "refund",
201
+ "provider" => Util.utf8(provider.to_s),
202
+ "orderId" => id_of(order_id),
203
+ "currency" => Util.utf8(currency.to_s).downcase,
204
+ "timestamp" => timestamp_of(timestamp)
205
+ }
206
+ if refunded_total.nil?
207
+ event["refundId"] = id_of(refund_id)
208
+ event["amount"] = amount_of(amount)
209
+ else
210
+ event["refundedTotal"] = amount_of(refunded_total)
211
+ end
212
+ enqueue(event)
213
+ flush
214
+ rescue StandardError => e
215
+ report(e)
216
+ nil
217
+ end
218
+
219
+ # Sends queued events now and waits until done. Never raises.
220
+ # @return [nil]
221
+ def flush
222
+ check_fork
223
+ @lock.synchronize { @flush_due = nil }
224
+ @drain_lock.synchronize { drain }
225
+ nil
226
+ rescue StandardError => e
227
+ report(e)
228
+ nil
229
+ end
230
+
231
+ # Fetches the config now and waits for it. Never raises.
232
+ # @return [nil]
233
+ def refresh
234
+ return nil if off?
235
+
236
+ check_fork
237
+ previous = @lock.synchronize { @inflight }
238
+ previous&.wait(STALL_MS / 1000.0)
239
+ @lock.synchronize { start_fetch(force: true) }&.wait(STALL_MS / 1000.0)
240
+ nil
241
+ rescue StandardError => e
242
+ report(e)
243
+ nil
244
+ end
245
+
246
+ # Fetches the config unless one is usable, so the first visitors do not wait. Never raises.
247
+ # @return [nil]
248
+ def preload
249
+ return nil if off?
250
+
251
+ check_fork
252
+ flight = @lock.synchronize { usable(now) ? nil : start_fetch(force: true) }
253
+ return nil unless flight
254
+
255
+ flight.wait(STALL_MS / 1000.0)
256
+ @lock.synchronize { @retry_at = 0 unless usable(now) }
257
+ nil
258
+ rescue StandardError => e
259
+ report(e)
260
+ nil
261
+ end
262
+
263
+ # Flushes queued events and stops the background flush thread. Never raises.
264
+ # @return [nil]
265
+ def close
266
+ check_fork
267
+ flusher = @lock.synchronize do
268
+ @closed = true
269
+ @flush_due = nil
270
+ @wakeup.broadcast
271
+ @flusher
272
+ end
273
+ flush
274
+ flusher&.join(1)
275
+ nil
276
+ rescue StandardError => e
277
+ report(e)
278
+ nil
279
+ end
280
+
281
+ # @return [Boolean] true while the kill switch is on or no valid secret key is configured
282
+ def disabled?
283
+ off?
284
+ end
285
+
286
+ # @return [String]
287
+ def inspect
288
+ "#<#{self.class.name} api_url=#{@api_url.inspect} products=#{@guards.keys.inspect} disabled=#{off?}>"
289
+ end
290
+
291
+ # @api private
292
+ def after_fork
293
+ reset_runtime unless @pid == Process.pid
294
+ end
295
+
296
+ private
297
+
298
+ def reset_runtime
299
+ @lock = Monitor.new
300
+ @wakeup = @lock.new_cond
301
+ @drain_lock = Monitor.new
302
+ @inflight = nil
303
+ @queue = []
304
+ @flusher = nil
305
+ @flush_due = nil
306
+ @flush_now = false
307
+ @pid = Process.pid
308
+ end
309
+
310
+ def check_fork
311
+ return if @pid == Process.pid
312
+
313
+ ForkTracker.lock.synchronize { after_fork }
314
+ end
315
+
316
+ def off?
317
+ @disabled || @secret_key.nil? || Leverprice.env_disabled?
318
+ end
319
+
320
+ def now
321
+ @clock ? @clock.call : Util.wall_millis
322
+ end
323
+
324
+ def report(error)
325
+ emit(error) unless off?
326
+ end
327
+
328
+ def emit(error)
329
+ error = Error.new(error.to_s) unless error.is_a?(Exception)
330
+ if @on_error
331
+ @on_error.call(error)
332
+ elsif @logger
333
+ @logger.warn(error.message)
334
+ else
335
+ Kernel.warn(error.message)
336
+ end
337
+ rescue StandardError
338
+ nil
339
+ end
340
+
341
+ def report_unknown(method, unknown)
342
+ return if unknown.empty?
343
+
344
+ report(Error.new("Leverprice: #{method} ignores unknown keywords #{unknown.keys.join(", ")}"))
345
+ end
346
+
347
+ def spawn(name)
348
+ Thread.new do
349
+ Thread.current.name = name
350
+ Thread.current.report_on_exception = false
351
+ yield
352
+ end
353
+ end
354
+
355
+ def compute_quote(key, guard, request, context, scope)
356
+ bot = false
357
+ info = Request.read(request: request, cookie: context.cookie, user_agent: context.user_agent,
358
+ cookie_name: @cookie_name)
359
+ bot = [true, false].include?(context.bot) ? context.bot : Bots.bot?(info.user_agent)
360
+ return bot_quote(key, guard) if bot
361
+
362
+ if info.pinned || scope&.pinned
363
+ @lock.synchronize { kick(now) }
364
+ return fallback_quote(key, guard, "pinned_fallback", [pin_cookie])
365
+ end
366
+
367
+ config = current_config
368
+ return no_config(key, guard, scope) unless config
369
+
370
+ product = config.products[key]
371
+ return fallback_quote(key, guard, "unknown_product") unless product
372
+ return fallback_quote(key, guard, "currency_mismatch") unless product.currency == guard.currency
373
+
374
+ experiment = product.experiment
375
+ return base_quote(key, guard, product) unless experiment
376
+ if experiment.variants.empty? || !experiment.variants.all? { |v| in_bounds?(guard, product, v.price) }
377
+ return fallback_quote(key, guard, "out_of_bounds")
378
+ end
379
+
380
+ experiment_quote(key, guard, context, info, scope, config, product)
381
+ rescue StandardError => e
382
+ report(e)
383
+ bot ? fallback_quote(key, guard, "bot") : no_config(key, guard, scope)
384
+ end
385
+
386
+ def base_quote(key, guard, product)
387
+ return fallback_quote(key, guard, "out_of_bounds") unless in_bounds?(guard, product, product.price)
388
+
389
+ price_quote(key, guard, product.price, "base_price", product.checkout_url)
390
+ end
391
+
392
+ def bot_quote(key, guard)
393
+ product = current_config&.products&.fetch(key, nil)
394
+ if product && product.currency == guard.currency && in_bounds?(guard, product, product.price)
395
+ return price_quote(key, guard, product.price, "bot", product.checkout_url)
396
+ end
397
+
398
+ fallback_quote(key, guard, "bot")
399
+ end
400
+
401
+ def experiment_quote(key, guard, context, info, scope, config, product)
402
+ experiment = product.experiment
403
+ hmac_key = hmac_key_for(config.assignment_key)
404
+ user_id = normalize_user_id(context.user_id)
405
+ state = prior_state(scope, info, user_id, config) || verified_state(hmac_key, info)
406
+ changed = state.nil?
407
+ state ||= Cookie.new_state(Util.random_hex(16))
408
+
409
+ visitor_key = user_id ? "u:#{user_id}" : "a:#{state.v}"
410
+ visitor_id = Util.hmac_hex(hmac_key, "pp:visitor:v1:#{visitor_key}", 32)
411
+ assigned = state.a[experiment.id]
412
+ sticky = assigned && experiment.variants.find { |v| v.id == assigned }
413
+ variant = sticky || Util.pick_variant(experiment.variants, Util.bucket_for(experiment.salt, visitor_id))
414
+ unless sticky
415
+ Cookie.assign(state, experiment.id, variant.id)
416
+ changed = true
417
+ end
418
+
419
+ logged = state.x.include?(experiment.id) || exposed?(experiment.id, visitor_id)
420
+ if !logged && auto_exposure?(context.exposure) && !info.prefetch
421
+ record_exposure(experiment.id, variant.id, visitor_id)
422
+ logged = true
423
+ end
424
+ changed = true if logged && Cookie.mark_exposed(state, experiment.id)
425
+ scope.cookie = ScopeCookie.new(info.cookie_input, user_id, config.assignment_key, state) if scope
426
+
427
+ signature = Util.hmac_hex(hmac_key, "pp:attr:v1:#{experiment.id}:#{variant.id}:#{visitor_id}", 16)
428
+ Quote.new(
429
+ product_key: key,
430
+ price: variant.price,
431
+ currency: guard.currency,
432
+ is_fallback: false,
433
+ reason: "experiment",
434
+ experiment_id: experiment.id,
435
+ variant_id: variant.id,
436
+ visitor_id: visitor_id,
437
+ metadata: { "pp_exp" => experiment.id, "pp_var" => variant.id, "pp_vid" => visitor_id, "pp_sig" => signature },
438
+ set_cookie: changed ? [assignment_cookie(hmac_key, state)] : [],
439
+ checkout_url: variant.checkout_url || product.checkout_url,
440
+ exposure_logged: logged
441
+ )
442
+ end
443
+
444
+ def prior_state(scope, info, user_id, config)
445
+ prior = scope&.cookie
446
+ return nil unless prior && prior.input == info.cookie_input && prior.user_id == user_id &&
447
+ prior.assignment_key == config.assignment_key
448
+
449
+ Cookie.clone_state(prior.state)
450
+ end
451
+
452
+ def verified_state(hmac_key, info)
453
+ info.assignment_cookies.first(4).each do |raw|
454
+ state = Cookie.verify(hmac_key, raw)
455
+ return state if state
456
+ end
457
+ nil
458
+ end
459
+
460
+ def no_config(key, guard, scope)
461
+ scope.pinned = true if scope
462
+ fallback_quote(key, guard, "no_config", [pin_cookie])
463
+ end
464
+
465
+ def assignment_cookie(hmac_key, state)
466
+ Cookie.header(@cookie_name, Cookie.sign(hmac_key, state), @cookie_max_age,
467
+ secure: @cookie_secure, domain: @cookie_domain)
468
+ end
469
+
470
+ def pin_cookie
471
+ Cookie.header("#{@cookie_name}_f", "1", PIN_MAX_AGE_SECONDS, secure: @cookie_secure, domain: @cookie_domain)
472
+ end
473
+
474
+ def fallback_quote(key, guard, reason, set_cookie = [])
475
+ Quote.new(
476
+ product_key: key,
477
+ price: guard.fallback_price,
478
+ currency: guard.currency,
479
+ is_fallback: true,
480
+ reason: reason,
481
+ experiment_id: nil,
482
+ variant_id: nil,
483
+ visitor_id: nil,
484
+ metadata: {},
485
+ set_cookie: set_cookie,
486
+ checkout_url: nil,
487
+ exposure_logged: false
488
+ )
489
+ end
490
+
491
+ def price_quote(key, guard, price, reason, checkout_url)
492
+ quote = fallback_quote(key, guard, reason)
493
+ quote.price = price
494
+ quote.is_fallback = false
495
+ quote.checkout_url = checkout_url
496
+ quote
497
+ end
498
+
499
+ def in_bounds?(guard, product, price)
500
+ value = Util.safe_int(price)
501
+ !value.nil? && value.positive? && value >= [guard.min_price, product.min_price].max &&
502
+ value <= [guard.max_price, product.max_price].min
503
+ end
504
+
505
+ def auto_exposure?(exposure)
506
+ exposure.nil? || exposure.to_s == "auto"
507
+ end
508
+
509
+ def hmac_key_for(assignment_key)
510
+ cached = @hmac_cache
511
+ return cached[1] if cached && cached[0] == assignment_key
512
+
513
+ key = Util.b64url_decode(assignment_key)
514
+ @hmac_cache = [assignment_key, key].freeze
515
+ key
516
+ end
517
+
518
+ def scope_for(request)
519
+ holder = Request.scope_holder(request)
520
+ return nil if holder.nil? || holder.frozen?
521
+
522
+ @lock.synchronize do
523
+ holder.instance_variable_get(@scope_ivar) ||
524
+ holder.instance_variable_set(@scope_ivar, Scope.new(Mutex.new, nil, false))
525
+ end
526
+ rescue StandardError
527
+ nil
528
+ end
529
+
530
+ def normalize_guards(products)
531
+ products ||= {}
532
+ raise ArgumentError, "Leverprice: products must be a Hash" unless products.is_a?(Hash)
533
+
534
+ products.each_with_object({}) do |(key, guard), guards|
535
+ guards[key.to_s] = normalize_guard("Leverprice: products.#{key}", guard)
536
+ end.freeze
537
+ end
538
+
539
+ def normalize_guard(where, guard)
540
+ currency = option(guard, :currency)
541
+ unless Util.str_match?(Wire::CURRENCY_RE, currency)
542
+ raise ArgumentError, %(#{where}.currency must be an ISO 4217 code such as "usd")
543
+ end
544
+
545
+ fallback_price = Util.safe_int(option(guard, :fallback_price, :fallbackPrice))
546
+ unless fallback_price&.positive?
547
+ raise ArgumentError, "#{where}.fallback_price must be a positive integer (minor units)"
548
+ end
549
+
550
+ min_price = option(guard, :min_price, :minPrice)
551
+ max_price = option(guard, :max_price, :maxPrice)
552
+ min_price = min_price.nil? ? 1 : Util.safe_int(min_price)
553
+ max_price = max_price.nil? ? Util::MAX_SAFE_INTEGER : Util.safe_int(max_price)
554
+ unless min_price && max_price && min_price <= max_price
555
+ raise ArgumentError, "#{where}: min_price and max_price must be integers with min_price <= max_price"
556
+ end
557
+
558
+ Guard.new(currency.downcase, fallback_price, min_price, max_price).freeze
559
+ end
560
+
561
+ def option(hash, *names)
562
+ return nil unless hash.is_a?(Hash)
563
+
564
+ names.each do |name|
565
+ return hash[name] if hash.key?(name)
566
+ return hash[name.to_s] if hash.key?(name.to_s)
567
+ end
568
+ nil
569
+ end
570
+
571
+ def normalize_user_id(value)
572
+ case value
573
+ when String then value.empty? ? nil : Util.utf8(value)
574
+ when Integer then value.to_s
575
+ when Float then Util.safe_int(value)&.to_s
576
+ end
577
+ end
578
+
579
+ def current_config
580
+ started = now
581
+ flight = nil
582
+ @lock.synchronize do
583
+ ready = usable(started)
584
+ kick(started)
585
+ return ready if ready
586
+
587
+ flight = live_flight(started)
588
+ end
589
+ return nil unless flight
590
+
591
+ remaining = @timeout_ms - (started - flight.started_at)
592
+ flight.wait(remaining / 1000.0) if remaining.positive?
593
+ @lock.synchronize { usable(now) }
594
+ end
595
+
596
+ def usable(at)
597
+ loaded = @acceptance.loaded
598
+ return nil unless loaded
599
+
600
+ config = loaded.config
601
+ return nil if at >= config.expires_at || at - @fetched_at >= @max_stale_ms
602
+ return nil unless @trust.trusted?(loaded.signing_key)
603
+
604
+ config
605
+ end
606
+
607
+ def loaded_version
608
+ @acceptance.config&.version || 0
609
+ end
610
+
611
+ def kick(at)
612
+ return if live_flight(at)
613
+
614
+ if @server_version > loaded_version && at >= @catch_up_at
615
+ @catch_up_at = at + CATCH_UP_GAP_MS
616
+ start_fetch(unconditional: true)
617
+ elsif !usable(at) || at - @fetched_at >= @refresh_interval_ms
618
+ start_fetch
619
+ end
620
+ end
621
+
622
+ def live_flight(at)
623
+ flight = @inflight
624
+ flight if flight && at - flight.started_at < STALL_MS
625
+ end
626
+
627
+ def start_fetch(force: false, unconditional: false)
628
+ at = now
629
+ live = live_flight(at)
630
+ return live if live
631
+ return nil if !force && at < @retry_at
632
+
633
+ flight = Flight.new(at)
634
+ @inflight = flight
635
+ begin
636
+ spawn("leverprice-config") { run_fetch(flight, unconditional) }
637
+ rescue ThreadError => e
638
+ @inflight = nil
639
+ flight.finish
640
+ report(e)
641
+ return nil
642
+ end
643
+ flight
644
+ end
645
+
646
+ def run_fetch(flight, unconditional)
647
+ load_config(unconditional)
648
+ ensure
649
+ @lock.synchronize { @inflight = nil if @inflight.equal?(flight) }
650
+ flight.finish
651
+ end
652
+
653
+ def load_config(unconditional)
654
+ headers = {}
655
+ @lock.synchronize { headers["If-None-Match"] = @etag if !unconditional && @etag && usable(now) }
656
+ response = http("GET", "/v1/config", headers)
657
+ warning = @lock.synchronize { apply_config(response, headers.key?("If-None-Match")) }
658
+ report(Error.new(warning)) if warning
659
+ rescue StandardError => e
660
+ @lock.synchronize do
661
+ @failures += 1
662
+ @retry_at = now + [MAX_BACKOFF_MS, 500 * (2**[@failures, 16].min)].min
663
+ end
664
+ report(e)
665
+ end
666
+
667
+ def apply_config(response, revalidating)
668
+ warning = nil
669
+ unless response.status == 304 && revalidating
670
+ unless (200..299).cover?(response.status)
671
+ raise Error, "Leverprice config: HTTP #{response.status}#{error_code(response.body)}"
672
+ end
673
+
674
+ warning = @acceptance.accept(parse_envelope(response.body), now).warning
675
+ @etag = response.header("ETag")
676
+ end
677
+ @fetched_at = now
678
+ @failures = 0
679
+ @retry_at = 0
680
+ note_server_version(response)
681
+ warning
682
+ end
683
+
684
+ def parse_envelope(body)
685
+ Util.parse_json(body)
686
+ rescue StandardError
687
+ raise Error, "Leverprice config: response is not JSON"
688
+ end
689
+
690
+ def note_server_version(response)
691
+ raw = response.header(Wire::CONFIG_VERSION_HEADER)
692
+ value = raw.nil? ? "" : Util.trim(raw)
693
+ return unless Util.str_match?(DIGITS_RE, value)
694
+
695
+ version = Util.safe_int(value.to_i)
696
+ return unless version && version > @server_version
697
+
698
+ @server_version = version
699
+ kick(now) if version > loaded_version
700
+ end
701
+
702
+ def error_code(body)
703
+ parsed = Util.parse_json(body)
704
+ code = parsed.is_a?(Hash) && parsed["error"].is_a?(Hash) ? parsed["error"]["code"] : nil
705
+ code.is_a?(String) ? " (#{code})" : ""
706
+ rescue StandardError
707
+ ""
708
+ end
709
+
710
+ def http(method, path, headers, body = nil)
711
+ request_headers = headers.merge("Authorization" => "Bearer #{@secret_key}", "User-Agent" => USER_AGENT)
712
+ raw = with_deadline(method, path) do
713
+ @transport.call(method: method, url: "#{@api_url}#{path}", headers: request_headers, body: body,
714
+ timeout: REQUEST_TIMEOUT_MS / 1000.0)
715
+ end
716
+ to_response(raw)
717
+ end
718
+
719
+ def with_deadline(method, path)
720
+ result = nil
721
+ failure = nil
722
+ worker = spawn("leverprice-http") do
723
+ result = yield
724
+ rescue StandardError => e
725
+ failure = e
726
+ end
727
+ unless worker.join(REQUEST_TIMEOUT_MS / 1000.0)
728
+ worker.kill
729
+ raise Error, "Leverprice: #{method} #{path} timed out after #{REQUEST_TIMEOUT_MS} ms"
730
+ end
731
+ raise failure if failure.is_a?(Error)
732
+ raise Error, "Leverprice: #{method} #{path} failed: #{failure.message} (#{failure.class})" if failure
733
+
734
+ result
735
+ end
736
+
737
+ def to_response(raw)
738
+ status, headers, body = raw.is_a?(Array) ? raw : [raw.status, raw.headers, raw.body]
739
+ body = body.join if body.is_a?(Array)
740
+ Response.new(Integer(status), headers || {}, Util.text(body))
741
+ rescue StandardError => e
742
+ raise Error, "Leverprice: the transport returned an unusable response (#{e.class})"
743
+ end
744
+
745
+ def exposed?(experiment_id, visitor_id)
746
+ @lock.synchronize { @exposed.key?("#{experiment_id}:#{visitor_id}") }
747
+ end
748
+
749
+ def record_exposure(experiment_id, variant_id, visitor_id)
750
+ key = "#{experiment_id}:#{visitor_id}"
751
+ fresh = @lock.synchronize do
752
+ next false if @exposed.key?(key)
753
+
754
+ @exposed.clear if @exposed.size >= MAX_DEDUPE
755
+ @exposed[key] = true
756
+ end
757
+ return false unless fresh
758
+
759
+ enqueue(
760
+ "type" => "exposure",
761
+ "experimentId" => experiment_id,
762
+ "variantId" => variant_id,
763
+ "visitorId" => visitor_id,
764
+ "timestamp" => now
765
+ )
766
+ end
767
+
768
+ def attribution_of(metadata)
769
+ ids = %w[pp_exp pp_var pp_vid].map { |name| metadata_value(metadata, name) }
770
+ return nil unless ids.all? { |id| Util.id?(id) }
771
+
772
+ signature = metadata_value(metadata, "pp_sig")
773
+ {
774
+ "experimentId" => ids[0],
775
+ "variantId" => ids[1],
776
+ "visitorId" => ids[2],
777
+ "signature" => Util.str_match?(SIG_RE, signature) ? signature : nil
778
+ }
779
+ end
780
+
781
+ def metadata_value(metadata, name)
782
+ source = metadata_source(metadata)
783
+ return nil unless source
784
+
785
+ [name, name.to_sym].each { |key| return source[key] if source.key?(key) }
786
+ nil
787
+ rescue StandardError
788
+ nil
789
+ end
790
+
791
+ def metadata_source(metadata)
792
+ return metadata if metadata.is_a?(Hash) || (metadata.respond_to?(:key?) && metadata.respond_to?(:[]))
793
+ return metadata.to_hash if metadata.respond_to?(:to_hash)
794
+
795
+ metadata.to_h if metadata.respond_to?(:to_h)
796
+ end
797
+
798
+ def id_of(value)
799
+ case value
800
+ when String then Util.utf8(value)
801
+ when Integer then value.to_s
802
+ when Float then Util.safe_int(value).to_s
803
+ else ""
804
+ end
805
+ end
806
+
807
+ def amount_of(value)
808
+ return value unless value.is_a?(Numeric) && value.real?
809
+ return value if value.is_a?(Float) && !value.finite?
810
+
811
+ Util.js_round(value)
812
+ end
813
+
814
+ def timestamp_of(value)
815
+ case value
816
+ when nil
817
+ now
818
+ when Time
819
+ Util.js_round(value.to_r * 1000)
820
+ when Numeric
821
+ return value unless value.real? && (!value.is_a?(Float) || value.finite?)
822
+
823
+ Util.js_round(value < 1e12 ? value * 1000 : value)
824
+ else
825
+ value.respond_to?(:to_time) && !value.is_a?(String) ? Util.js_round(value.to_time.to_r * 1000) : value
826
+ end
827
+ end
828
+
829
+ def enqueue(event)
830
+ problem = Wire.event_problem(event)
831
+ if problem
832
+ report(Error.new("Leverprice: dropped invalid #{event["type"]} event: #{problem}"))
833
+ return false
834
+ end
835
+
836
+ dropped = @lock.synchronize do
837
+ @queue << event
838
+ overflow = trim_queue
839
+ if @queue.size >= AUTO_FLUSH_AT
840
+ @flush_now = true
841
+ else
842
+ @flush_due ||= Util.monotonic + (@flush_interval_ms / 1000.0)
843
+ end
844
+ ensure_flusher
845
+ @wakeup.broadcast
846
+ overflow
847
+ end
848
+ dropped.each { |error| report(error) }
849
+ true
850
+ end
851
+
852
+ def trim_queue
853
+ errors = []
854
+ while @queue.size > MAX_QUEUE
855
+ dropped = @queue.delete_at(@queue.index { |e| e["type"] == "exposure" } || 0)
856
+ next if dropped["type"] == "exposure"
857
+
858
+ errors << Error.new("Leverprice: event queue full, dropped #{dropped["type"]} #{dropped["orderId"]}")
859
+ end
860
+ errors
861
+ end
862
+
863
+ def ensure_flusher
864
+ return if @closed || @flusher&.alive?
865
+
866
+ @flusher = spawn("leverprice-flush") { flusher_loop }
867
+ rescue ThreadError
868
+ @flusher = nil
869
+ end
870
+
871
+ def flusher_loop
872
+ @drain_lock.synchronize { drain } while wait_for_flush
873
+ end
874
+
875
+ def wait_for_flush
876
+ @lock.synchronize do
877
+ loop do
878
+ return false if @closed
879
+
880
+ if @flush_now || (@flush_due && Util.monotonic >= @flush_due)
881
+ @flush_now = false
882
+ @flush_due = nil
883
+ return true
884
+ end
885
+ @wakeup.wait(@flush_due ? [@flush_due - Util.monotonic, 0.001].max : IDLE_WAIT_SECONDS)
886
+ end
887
+ end
888
+ end
889
+
890
+ def drain
891
+ return if off?
892
+
893
+ size = Wire::MAX_EVENTS_PER_REQUEST
894
+ batches = @lock.synchronize { (@queue.size + size - 1) / size }
895
+ batches.times do
896
+ batch = @lock.synchronize { @queue.shift(size) }
897
+ break if batch.empty? || !send_batch(batch)
898
+ end
899
+ rescue StandardError => e
900
+ report(e)
901
+ end
902
+
903
+ def send_batch(events)
904
+ body = JSON.generate({ "events" => events, "sdk" => SDK_INFO })
905
+ last_error = nil
906
+ SEND_ATTEMPTS.times do |attempt|
907
+ break if off?
908
+
909
+ @sleeper.call(0.25 * (4**(attempt - 1))) if attempt.positive?
910
+ begin
911
+ response = http("POST", "/v1/events", { "Content-Type" => "application/json" }, body)
912
+ @lock.synchronize { note_server_version(response) }
913
+ return true if (200..299).cover?(response.status)
914
+
915
+ if response.status < 500 && ![408, 429].include?(response.status)
916
+ report(Error.new("Leverprice events rejected: HTTP #{response.status} #{response.body[0, 300]}"))
917
+ return true
918
+ end
919
+ last_error = Error.new("Leverprice events: HTTP #{response.status}")
920
+ rescue StandardError => e
921
+ last_error = e
922
+ end
923
+ end
924
+ requeue(events)
925
+ report(last_error) if last_error
926
+ false
927
+ end
928
+
929
+ def requeue(events)
930
+ money = events.reject { |e| e["type"] == "exposure" }
931
+ return if money.empty?
932
+
933
+ dropped = @lock.synchronize do
934
+ @queue.unshift(*money)
935
+ trim_queue
936
+ end
937
+ dropped.each { |error| report(error) }
938
+ end
939
+ end
940
+ end