openreceive-server 0.4.34 → 0.5.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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: be4eaffde1a7f0c6ac8168fa150746e296a537e48156cea8610940c45ab83b88
4
- data.tar.gz: 0e16a7b8167811ed82904d795b7152035201653958acb5ce524d2ffb87b51c12
3
+ metadata.gz: b8964e64cf4990025ea16c270029ecac37538ab261dd8632554135b1a4a59df8
4
+ data.tar.gz: 2ba6fe190a9a55bbc4377dd6cf680d93d142504090e00c2f9dd7619e0b2822d4
5
5
  SHA512:
6
- metadata.gz: 2a9c8ef3c77d1f79a8bd9b9748e50b1eac955b1830c9e99b6cfe2297a3f5f89ad4bbcf2f02a31dfa8f749e882af12c77eb70905b1777815ad1f0f7661a01b50c
7
- data.tar.gz: 56a1dcb6fd4cb354ec6138471347e9bbae73a90e989fbc06d67811968a21624273c26efe1b1da9bd31e4d5e4b7973dfe50e5907d47f519e5a4f6b357ab449027
6
+ metadata.gz: fb784bd3461955fe371d412c3f5dda02f3f3e64f4267908caf1e918817edf78ce33ee7081921c6bb6d9c62dc60058747c33fc2bc4b0a23931724b0502d30d4eb
7
+ data.tar.gz: e215c25ee2e938f66cd6b022b4e8a9aee21a25f46ae3076adaa69ac81e145b413cc997eec280408661eae1301d4b7c04696bb5afeb78bf76942a62d204ad46e6
data/CHANGELOG.md CHANGED
@@ -1,5 +1,39 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.5.0 - 2026-11-16
4
+
5
+ No breaking API change in this gem. The breaking changes of 0.5.0 are in the
6
+ JavaScript API a custom ("headless") checkout is built from; see the root
7
+ changelog.
8
+
9
+ - Changed (swaps): the request guard that keeps a site inside its swap
10
+ provider's API limits is now sized by the provider, read from the host in
11
+ the `LSC_URI_*` code. With Lightning Swap it allows 30 new swaps and 400 API
12
+ calls a minute per server process. FixedFloat, and any provider the library
13
+ does not know, keep three new swaps a minute, which every provider used to
14
+ be held to.
15
+ - Changed (swaps): a provider's 429 is obeyed for the wait it names
16
+ (`Retry-After`, or `retry_after` in the response), not always for 60
17
+ seconds. With Lightning Swap a refused new swap stops new swaps only, for
18
+ that wait and five minutes at most; swaps already started keep updating.
19
+ - Changed (swaps): a new swap the guard would refuse is now refused before
20
+ anything is made for it.
21
+ - Added (swaps): one `swap.provider.rate_limited` warning a minute in the
22
+ server log says whether the library's own guard refused a swap call or the
23
+ provider answered 429, and until when.
24
+ - Changed (rate limiting): the opt-in per-IP limit never counts a loopback or
25
+ private address. That address is the site's own proxy, not a payer. Such a
26
+ request is allowed and the log says so once. A site that relied on the limit
27
+ with a private client address must pass the payer's address; see the rate
28
+ limiting guide.
29
+ - Added (rate limiting): a refusal names the refused address, the count and
30
+ the limit in the server log, at most once a minute.
31
+
32
+ ## 0.4.35 - 2026-11-12
33
+
34
+ Release with the complete 0.4.35 package family. No runtime changes from
35
+ 0.4.34.
36
+
3
37
  ## 0.4.34 - 2026-11-10
4
38
 
5
39
  Release with the complete 0.4.34 package family. No runtime changes from
@@ -38,6 +38,53 @@ module OpenReceive
38
38
  "#{hextets.first(4).join(':')}::/64"
39
39
  end
40
40
 
41
+ # Whether the limiter may count this client value as one payer. Ports
42
+ # the JS isPayerAddress; pinned across engines by
43
+ # spec/test-vectors/rate-limit-address.json.
44
+ #
45
+ # False for an IP address no payer on the internet can have: loopback,
46
+ # private (RFC 1918), carrier-shared (100.64.0.0/10), link-local, the
47
+ # unspecified address, and their IPv6 counterparts (::1, fc00::/7,
48
+ # fe80::/10). A server sees one of those only when the request came
49
+ # from its own proxy or network, so the address stands for every payer
50
+ # at once.
51
+ #
52
+ # True for every other IP, and for a value that is not an IP at all: a
53
+ # host that passes its own identifier (an account id, a session key)
54
+ # chose it deliberately. Accepts raw addresses and the buckets `bucket`
55
+ # returns.
56
+ def payer_address?(value)
57
+ address = value.to_s.strip.downcase
58
+ address = address.delete_prefix("::ffff:") if address.start_with?("::ffff:") && address.include?(".")
59
+ unless address.include?(":")
60
+ octets = ipv4_octets(address)
61
+ return true if octets.nil?
62
+ first, second = octets
63
+ return !(
64
+ first.zero? ||
65
+ first == 10 ||
66
+ first == 127 ||
67
+ (first == 100 && second.between?(64, 127)) ||
68
+ (first == 169 && second == 254) ||
69
+ (first == 172 && second.between?(16, 31)) ||
70
+ (first == 192 && second == 168)
71
+ )
72
+ end
73
+ without_zone = address.split("%", -1).first || ""
74
+ hextets = expand_ipv6(without_zone.delete_suffix("/64"))
75
+ return true if hextets.nil?
76
+ # :: and ::1 (a /64 bucket of either is all zeros in its first four groups).
77
+ return false if hextets.first(7).all?("0") && /\A[01]\z/.match?(hextets[7])
78
+ leading = hextets.first.to_i(16)
79
+ !((leading & 0xfe00) == 0xfc00 || (leading & 0xffc0) == 0xfe80)
80
+ end
81
+
82
+ def ipv4_octets(value)
83
+ return nil unless /\A\d{1,3}(\.\d{1,3}){3}\z/.match?(value)
84
+ octets = value.split(".").map { |octet| Integer(octet, 10) }
85
+ octets.any? { |octet| octet > 255 } ? nil : octets
86
+ end
87
+
41
88
  def expand_ipv6(value)
42
89
  parts = value.split("::", -1)
43
90
  return nil if parts.length > 2 || value.empty?
@@ -31,6 +31,9 @@ module OpenReceive
31
31
  SWAP_PROVIDER_REFUSED_MESSAGE = "The swap provider refused this request."
32
32
  SWAP_PROVIDER_RATE_LIMITED_MESSAGE = "The swap provider is rate limited. Please try again shortly."
33
33
  SWAP_PROVIDER_UNREACHABLE_MESSAGE = "The swap provider is temporarily unreachable. Please try again shortly."
34
+ # A swap call refused for rate is logged once per cause in this many
35
+ # seconds (the JS RATE_LIMIT_LOG_INTERVAL_SECONDS).
36
+ SWAP_RATE_LIMIT_LOG_INTERVAL_SECONDS = 60
34
37
 
35
38
  # A wallet check that could not reach the relay runs again on the first
36
39
  # wallet call after this wait. The wait doubles after each failure up to
@@ -102,6 +105,8 @@ module OpenReceive
102
105
  @monotonic = monotonic || -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) }
103
106
  @env = env
104
107
  @logger = logger
108
+ @swap_rate_limit_logged_at = {}
109
+ @swap_rate_limit_log_lock = Mutex.new
105
110
  @price_currencies = Array(price_currencies || ["USD"]).map { |value| value.to_s.upcase }
106
111
  @price_provider = price_provider == false ? nil : price_provider || default_price_provider(env)
107
112
  @swap_providers =
@@ -346,6 +351,12 @@ module OpenReceive
346
351
  raise ValidationError, e.message
347
352
  end
348
353
  provider = select_provider(asset)
354
+ # Refuse before the invoice is made when the provider guard would
355
+ # refuse the create anyway: a refused swap then costs nothing. A
356
+ # provider without the check is simply not asked.
357
+ if provider.respond_to?(:assert_create_available)
358
+ through_provider { provider.assert_create_available }
359
+ end
349
360
  expiry = provider.respond_to?(:invoice_expiry_seconds) ? provider.invoice_expiry_seconds(pay_in_asset: asset) : SWAP_INVOICE_EXPIRY_SECONDS
350
361
  # The shadow-invoice expiry is provider-mandated: build the checkout
351
362
  # input explicitly from validated fields so no payer-supplied key (e.g.
@@ -604,7 +615,8 @@ module OpenReceive
604
615
 
605
616
  # Mirrors the JS createOpenReceive provider wiring: one shared transient
606
617
  # cache and one per-provider weight budget, attached to every provider
607
- # that supports them (host-supplied or auto-built).
618
+ # that supports them (host-supplied or auto-built). The budget is sized
619
+ # by the provider's own limits.
608
620
  def attach_swap_provider_runtime!
609
621
  return if @swap_providers.empty?
610
622
 
@@ -613,12 +625,19 @@ module OpenReceive
613
625
  provider.attach_swap_cache(cache) if provider.respond_to?(:attach_swap_cache)
614
626
  if provider.respond_to?(:attach_weight_budget)
615
627
  provider.attach_weight_budget(
616
- Swap::SwapProviderWeightBudget.new(provider.name, @clock)
628
+ Swap::SwapProviderWeightBudget.new(provider.name, @clock, swap_provider_limits(provider))
617
629
  )
618
630
  end
619
631
  end
620
632
  end
621
633
 
634
+ # A provider that names no limits (a custom provider, a test double)
635
+ # gets the FixedFloat ones, the stricter of the two.
636
+ def swap_provider_limits(provider)
637
+ limits = provider.respond_to?(:limits) ? provider.limits : nil
638
+ limits.is_a?(Swap::SwapProviderLimits) ? limits : Swap::FIXEDFLOAT_SWAP_PROVIDER_LIMITS
639
+ end
640
+
622
641
  # Use exactly one live provider's catalog: primary when healthy,
623
642
  # otherwise the first backup that answers. Never merge catalogs.
624
643
  def resolve_swap_provider_catalog
@@ -896,7 +915,11 @@ module OpenReceive
896
915
  failure = Swap.classify_transport_failure(e)
897
916
  raise if failure.nil?
898
917
 
899
- @logger&.warn("swap.provider.#{failure}: #{OpenReceive::Nwc.redact_error_text("#{e.class}: #{e.message}")}")
918
+ if failure == "rate_limited"
919
+ log_swap_provider_rate_limit(e)
920
+ else
921
+ @logger&.warn("swap.provider.#{failure}: #{OpenReceive::Nwc.redact_error_text("#{e.class}: #{e.message}")}")
922
+ end
900
923
  raise ServiceError.new(502, "INTERNAL", SWAP_PROVIDER_REFUSED_MESSAGE) if failure == "refused"
901
924
 
902
925
  raise ServiceError.new(
@@ -907,6 +930,54 @@ module OpenReceive
907
930
  )
908
931
  end
909
932
 
933
+ # Say in the server log why a swap call was refused for rate, and until
934
+ # when (the JS logProviderRateLimit). The payer only reads "try again
935
+ # shortly"; the operator needs to know whether this library's own guard
936
+ # stopped the call or the provider answered 429. Status polls arrive
937
+ # every few seconds per open checkout: one line a minute per cause
938
+ # (provider, path, reason) says what is happening without burying the
939
+ # log.
940
+ def log_swap_provider_rate_limit(error)
941
+ return if @logger.nil?
942
+
943
+ denial = Swap.weight_budget_denial(error)
944
+ cause = "#{denial&.[]('provider')}:#{denial&.[]('path')}:#{denial&.[]('reason') || 'provider'}"
945
+ now = @clock.call
946
+ due = @swap_rate_limit_log_lock.synchronize do
947
+ last = @swap_rate_limit_logged_at[cause]
948
+ next false if !last.nil? && now - last < SWAP_RATE_LIMIT_LOG_INTERVAL_SECONDS
949
+
950
+ @swap_rate_limit_logged_at[cause] = now
951
+ true
952
+ end
953
+ return unless due
954
+
955
+ @logger.warn("swap.provider.rate_limited: #{swap_provider_rate_limit_line(denial, error)}")
956
+ end
957
+
958
+ # The Logger sink takes one string, so the fields the JS line carries
959
+ # (provider, path, reason, used, gate, creates, create_limit,
960
+ # backoff_until) follow the sentence as key=value, in parentheses. A
961
+ # provider's 429 carries no denial; its own words follow instead,
962
+ # redacted.
963
+ def swap_provider_rate_limit_line(denial, error)
964
+ if denial.nil?
965
+ return "The swap provider answered 429 (rate limited); new calls stand off until its " \
966
+ "wait is over. (#{OpenReceive::Nwc.redact_error_text("#{error.class}: #{error.message}")})"
967
+ end
968
+
969
+ sentence =
970
+ if denial["reason"] == "backoff"
971
+ "Swap provider call refused locally: standing off after the provider's 429."
972
+ else
973
+ "Swap provider call refused locally: this process reached the provider's per-minute limit."
974
+ end
975
+ fields = %w[provider path reason used gate creates create_limit backoff_until].filter_map do |key|
976
+ "#{key}=#{denial[key]}" unless denial[key].nil?
977
+ end
978
+ fields.empty? ? sentence : "#{sentence} (#{fields.join(' ')})"
979
+ end
980
+
910
981
  def call_provider(provider, method, *args)
911
982
  if args.length == 1 && args.first.is_a?(Hash) && keyword_style?(provider.method(method))
912
983
  provider.public_send(method, **args.first.transform_keys(&:to_sym))
@@ -62,7 +62,9 @@ module OpenReceive
62
62
  DEFAULT_INVOICE_EXPIRY_MARGIN_SECONDS = 5 * 60
63
63
  PROVIDER_ID_PATTERN = /\A[a-z0-9][a-z0-9_-]{0,63}\z/
64
64
 
65
- attr_reader :name
65
+ # `limits` are the provider's API limits (a SwapProviderLimits), which
66
+ # size the request guard the service attaches.
67
+ attr_reader :name, :limits
66
68
 
67
69
  def initialize(key:, secret:, id: "fixedfloat", base_url: nil, lightning_ccy: nil,
68
70
  http: nil, now: nil, cache_seconds: nil, rates_cache_seconds: nil,
@@ -77,6 +79,9 @@ module OpenReceive
77
79
  @key = key
78
80
  @secret = secret
79
81
  @base_url = (base_url || DEFAULT_BASE_URL).sub(%r{/+\z}, "")
82
+ # The host names the provider, and the provider sets the limits: the
83
+ # same wire contract is served at very different rates.
84
+ @limits = SwapProviderLimits.for_base_url(@base_url)
80
85
  normalized_lightning = lightning_ccy.to_s.strip
81
86
  @lightning_ccy = normalized_lightning.empty? ? nil : normalized_lightning
82
87
  @http = http || Swap.method(:default_http_request)
@@ -153,6 +158,15 @@ module OpenReceive
153
158
  nil
154
159
  end
155
160
 
161
+ # Raise now when the attached guard would refuse a create, so the
162
+ # service can refuse a new swap before it does any other work for it.
163
+ # Uses no budget; the create itself still reserves.
164
+ def assert_create_available
165
+ budget = @weight_budget
166
+ budget.assert_available("create") if budget.respond_to?(:assert_available)
167
+ nil
168
+ end
169
+
156
170
  def supported_pay_in_assets
157
171
  resolve_currencies.fetch("pay_in").keys
158
172
  end
@@ -343,7 +357,16 @@ module OpenReceive
343
357
  log_api_response(path: path, status: status, ok: ok,
344
358
  code: parsed["code"], msg: parsed["msg"], data: parsed["data"])
345
359
  unless ok
346
- @weight_budget&.mark_rate_limited if status == 429
360
+ if status == 429
361
+ # The guard hears which call was refused and the wait the
362
+ # provider named, when it named one.
363
+ @weight_budget&.mark_rate_limited(
364
+ **{
365
+ path: path,
366
+ retry_after_seconds: self.class.read_retry_after_seconds(response, parsed["data"])
367
+ }.compact
368
+ )
369
+ end
347
370
  raise FixedFloatApiError.new(
348
371
  path: path,
349
372
  kind: status == 429 ? "rate_limited" : "http",
@@ -588,6 +611,29 @@ module OpenReceive
588
611
  fractional.empty? ? whole_btc.to_s : "#{whole_btc}.#{fractional}"
589
612
  end
590
613
 
614
+ # How long a 429 asks the caller to wait: the Retry-After header in
615
+ # whole seconds, else a positive `retry_after` number in the response
616
+ # data. nil when the provider named no wait.
617
+ def read_retry_after_seconds(response, data)
618
+ header = read_response_header(response, "retry-after")
619
+ return Integer(header, 10) if !header.nil? && /\A\d{1,9}\z/.match?(header)
620
+
621
+ from_body = data.is_a?(Hash) ? data["retry_after"] : nil
622
+ numeric = from_body.is_a?(Integer) || (from_body.is_a?(Float) && from_body.finite?)
623
+ numeric && from_body.positive? ? from_body : nil
624
+ end
625
+
626
+ # One response header by case-insensitive name, trimmed; nil when the
627
+ # transport returned no headers or not this one.
628
+ def read_response_header(response, name)
629
+ headers = response[:headers] || response["headers"]
630
+ return nil unless headers.respond_to?(:each_pair)
631
+
632
+ _, value = headers.each_pair.find { |key, _| key.to_s.downcase == name }
633
+ value = value.first if value.is_a?(Array)
634
+ value.nil? ? nil : value.to_s.strip
635
+ end
636
+
591
637
  def format_api_error_message(path, status, msg)
592
638
  fixedfloat_message = read_string(msg)
593
639
  if fixedfloat_message.nil?
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "monitor"
4
+ require "uri"
4
5
 
5
6
  module OpenReceive
6
7
  module Server
@@ -10,7 +11,7 @@ module OpenReceive
10
11
  # provider_rate_limited, mirroring the JS weightBudget error tag.
11
12
  class WeightBudgetError < StandardError
12
13
  # The denial diagnostics (provider, path, reason, used/cost/gate,
13
- # window start, backoff) ride the error itself.
14
+ # window start, backoff, creates) ride the error itself.
14
15
  attr_reader :denial
15
16
 
16
17
  def initialize(message, denial = {})
@@ -23,79 +24,215 @@ module OpenReceive
23
24
  end
24
25
  end
25
26
 
27
+ LIGHTNING_SWAP_HOST = "lightning-swap.com"
28
+
29
+ # What one provider allows an API key per window, as far as the request
30
+ # guard needs to know it. The guard exists so a busy site stays inside
31
+ # the provider's limits; the provider remains the authority and its 429
32
+ # always wins. Twin of the JS SwapProviderLimits; the numbers are pinned
33
+ # across engines by spec/test-vectors/swap-provider-limits.json.
34
+ #
35
+ # - profile: whose published limits these are.
36
+ # - soft_cap: weight every call in one window may add up to.
37
+ # - create_gate: weight a create may bring the window up to.
38
+ # - create_limit: creates per window, for a provider that counts them on
39
+ # their own; nil for one that does not.
40
+ # - backoff_seconds: stand-off after a 429 that names no wait.
41
+ # - min_backoff_seconds, max_backoff_seconds: shortest and longest
42
+ # stand-off a 429's own wait is honored for.
43
+ # - create_backoff_only: true when the provider counts new swaps apart
44
+ # from its other calls, so a 429 answering a create stops creates
45
+ # only. Status and refund calls for swaps that already exist keep
46
+ # working.
47
+ SwapProviderLimits = Struct.new(
48
+ :profile, :soft_cap, :create_gate, :create_weight, :default_weight, :create_limit,
49
+ :backoff_seconds, :min_backoff_seconds, :max_backoff_seconds, :create_backoff_only,
50
+ keyword_init: true
51
+ ) do
52
+ # The limits to guard a provider API with, chosen by its HTTPS host:
53
+ # lightning-swap.com or a subdomain of it is Lightning Swap; every
54
+ # other host, and a URL that does not parse, gets the FixedFloat ones.
55
+ def self.for_base_url(base_url)
56
+ host =
57
+ begin
58
+ URI.parse(base_url.to_s.strip).host.to_s.downcase
59
+ rescue URI::InvalidURIError
60
+ ""
61
+ end
62
+ if host == LIGHTNING_SWAP_HOST || host.end_with?(".#{LIGHTNING_SWAP_HOST}")
63
+ LIGHTNING_SWAP_PROVIDER_LIMITS
64
+ else
65
+ FIXEDFLOAT_SWAP_PROVIDER_LIMITS
66
+ end
67
+ end
68
+ end
69
+
70
+ # FixedFloat: 250 weight a minute per key, a create costs 50, and going
71
+ # over blocks the key for longer each time. The guard stops well short:
72
+ # three creates a minute, 200 weight in all. Also the default for a
73
+ # provider this library does not know, because it is the stricter of
74
+ # the two.
75
+ FIXEDFLOAT_SWAP_PROVIDER_LIMITS = SwapProviderLimits.new(
76
+ profile: "fixedfloat",
77
+ soft_cap: 200,
78
+ create_gate: 150,
79
+ create_weight: 50,
80
+ default_weight: 1,
81
+ create_limit: nil,
82
+ backoff_seconds: 60,
83
+ min_backoff_seconds: 60,
84
+ max_backoff_seconds: 3_600,
85
+ create_backoff_only: false
86
+ ).freeze
87
+
88
+ # Lightning Swap: per account, 30 new swaps and 400 API calls a minute
89
+ # once the account has completed a swap, every call counting as one. It
90
+ # refuses with a 429 that says how long to wait and never blocks a key
91
+ # for going over, so the guard sits at the limit itself. An account on
92
+ # lower limits (one that has not completed a swap yet) is held to them
93
+ # by the provider's own 429, which this guard then obeys.
94
+ LIGHTNING_SWAP_PROVIDER_LIMITS = SwapProviderLimits.new(
95
+ profile: "lightning-swap",
96
+ soft_cap: 400,
97
+ create_gate: 400,
98
+ create_weight: 1,
99
+ default_weight: 1,
100
+ create_limit: 30,
101
+ backoff_seconds: 60,
102
+ min_backoff_seconds: 1,
103
+ max_backoff_seconds: 300,
104
+ create_backoff_only: true
105
+ ).freeze
106
+
26
107
  # Ruby port of packages/js/node/src/swap/weight-budget.ts: a disposable
27
- # per-process request guard; the provider remains the global rate-limit
28
- # authority.
108
+ # per-process request guard, sized by the provider's limits; the
109
+ # provider remains the global rate-limit authority.
29
110
  class SwapProviderWeightBudget
30
111
  WINDOW_SECONDS = 60
31
- SOFT_CAP = 200
32
- CREATE_GATE = 150
33
- CREATE_WEIGHT = 50
34
- DEFAULT_WEIGHT = 1
35
- BACKOFF_SECONDS = 60
112
+ # The FixedFloat numbers under the names they had before the guard
113
+ # was sized by provider.
114
+ SOFT_CAP = FIXEDFLOAT_SWAP_PROVIDER_LIMITS.soft_cap
115
+ CREATE_GATE = FIXEDFLOAT_SWAP_PROVIDER_LIMITS.create_gate
116
+ CREATE_WEIGHT = FIXEDFLOAT_SWAP_PROVIDER_LIMITS.create_weight
117
+ DEFAULT_WEIGHT = FIXEDFLOAT_SWAP_PROVIDER_LIMITS.default_weight
118
+ BACKOFF_SECONDS = FIXEDFLOAT_SWAP_PROVIDER_LIMITS.backoff_seconds
36
119
 
37
- def initialize(provider_id, clock)
120
+ def initialize(provider_id, clock, limits = FIXEDFLOAT_SWAP_PROVIDER_LIMITS)
38
121
  @provider_id = provider_id
39
122
  @clock = clock
123
+ @limits = limits
40
124
  @window_start = clock.call
41
125
  @used = 0
126
+ @creates = 0
42
127
  @backoff_until = nil
128
+ @create_backoff_until = nil
43
129
  @monitor = Monitor.new
44
130
  end
45
131
 
46
132
  def weight_for_path(path)
47
- path == "create" ? CREATE_WEIGHT : DEFAULT_WEIGHT
133
+ path == "create" ? @limits.create_weight : @limits.default_weight
134
+ end
135
+
136
+ # Raise the same denial reserve would, without using any budget. Lets
137
+ # a caller refuse a new swap before it does any other work for it.
138
+ def assert_available(path)
139
+ @monitor.synchronize { check(path) }
140
+ nil
48
141
  end
49
142
 
50
143
  def reserve(path)
51
144
  @monitor.synchronize do
52
- roll_window
53
- now = @clock.call
54
- cost = weight_for_path(path)
55
- limit = gate(path)
56
- if !@backoff_until.nil? && @backoff_until > now
57
- deny(path, "backoff", cost, limit,
58
- "Swap provider API is in backoff until #{@backoff_until}.")
59
- end
60
- if @used + cost > limit
61
- deny(path, "exhausted", cost, limit,
62
- "Swap provider API weight budget exhausted (#{@used}+#{cost} > #{limit}).")
63
- end
64
- @used += cost
145
+ check(path)
146
+ @used += weight_for_path(path)
147
+ @creates += 1 if path == "create"
65
148
  end
66
149
  nil
67
150
  end
68
151
 
69
- def mark_rate_limited
152
+ # The provider answered 429. `path` is the API path it answered and
153
+ # `retry_after_seconds` the provider's own wait, from Retry-After or
154
+ # its response body; nil when it named none. A later, shorter 429
155
+ # never shortens a stand-off already running.
156
+ def mark_rate_limited(path: nil, retry_after_seconds: nil)
70
157
  @monitor.synchronize do
71
- now = @clock.call
72
- @used = [@used, SOFT_CAP].max
73
- @backoff_until = now + BACKOFF_SECONDS
158
+ standoff_end = @clock.call + backoff_seconds(retry_after_seconds)
159
+ if @limits.create_backoff_only && path == "create"
160
+ @create_backoff_until = [@create_backoff_until || 0, standoff_end].max
161
+ else
162
+ @backoff_until = [@backoff_until || 0, standoff_end].max
163
+ # The provider's own window is spent until then and fresh after
164
+ # it, so this guard's window restarts when the stand-off ends.
165
+ # Keeping the old count would go on refusing calls the provider
166
+ # has started accepting.
167
+ @window_start = @backoff_until
168
+ @used = 0
169
+ @creates = 0
170
+ end
74
171
  end
75
172
  nil
76
173
  end
77
174
 
78
175
  private
79
176
 
177
+ def check(path)
178
+ roll_window
179
+ now = @clock.call
180
+ cost = weight_for_path(path)
181
+ limit = gate(path)
182
+ backoff_until = active_backoff(path, now)
183
+ unless backoff_until.nil?
184
+ deny(path, "backoff", cost, limit,
185
+ "Swap provider API is in backoff until #{backoff_until}.", backoff_until)
186
+ end
187
+ if @used + cost > limit
188
+ deny(path, "exhausted", cost, limit,
189
+ "Swap provider API weight budget exhausted (#{@used}+#{cost} > #{limit}).")
190
+ end
191
+ create_limit = @limits.create_limit
192
+ return unless path == "create" && !create_limit.nil? && @creates + 1 > create_limit
193
+
194
+ deny(path, "exhausted", cost, limit,
195
+ "Swap provider create budget exhausted (#{@creates}+1 > #{create_limit}).")
196
+ end
197
+
198
+ def backoff_seconds(retry_after_seconds)
199
+ named = retry_after_seconds
200
+ unless (named.is_a?(Integer) || named.is_a?(Float)) && named.finite? && named.positive?
201
+ return @limits.backoff_seconds
202
+ end
203
+
204
+ named.ceil.clamp(@limits.min_backoff_seconds, @limits.max_backoff_seconds)
205
+ end
206
+
207
+ def active_backoff(path, now)
208
+ return @backoff_until if !@backoff_until.nil? && @backoff_until > now
209
+ if path == "create" && !@create_backoff_until.nil? && @create_backoff_until > now
210
+ return @create_backoff_until
211
+ end
212
+
213
+ nil
214
+ end
215
+
80
216
  # The weight window rolls; the 429 backoff does NOT ride along with it.
81
217
  # Clearing it here cut a backoff arbitrarily short — mark_rate_limited
82
218
  # at second 59 of the window was forgiven one second later — so the
83
- # backoff expires on its own clock, checked in reserve. Mirrors JS.
219
+ # backoff expires on its own clock, checked in check. Mirrors JS.
84
220
  def roll_window
85
221
  now = @clock.call
86
222
  return if now - @window_start < WINDOW_SECONDS
87
223
 
88
224
  @window_start = now
89
225
  @used = 0
226
+ @creates = 0
90
227
  end
91
228
 
92
229
  def gate(path)
93
- path == "create" ? CREATE_GATE : SOFT_CAP
230
+ path == "create" ? @limits.create_gate : @limits.soft_cap
94
231
  end
95
232
 
96
233
  # The denial carries its own diagnostics on the raised error: there is
97
234
  # no observer hook, because there was never a caller for one. Mirrors JS.
98
- def deny(path, reason, cost, limit, message)
235
+ def deny(path, reason, cost, limit, message, backoff_until = nil)
99
236
  denial = {
100
237
  "provider" => @provider_id,
101
238
  "path" => path,
@@ -105,8 +242,10 @@ module OpenReceive
105
242
  "cost" => cost,
106
243
  "gate" => limit,
107
244
  "window_start" => @window_start,
108
- **(@backoff_until.nil? ? {} : { "backoff_until" => @backoff_until })
109
- }
245
+ "backoff_until" => backoff_until || @backoff_until,
246
+ "creates" => @limits.create_limit.nil? ? nil : @creates,
247
+ "create_limit" => @limits.create_limit
248
+ }.compact
110
249
  raise WeightBudgetError.new(message, denial)
111
250
  end
112
251
  end
@@ -47,7 +47,9 @@ module OpenReceive
47
47
 
48
48
  # Default HTTP transport on stdlib Net::HTTP. Injectable replacements
49
49
  # must be callable as call(method:, url:, headers:, body:, timeout_ms:)
50
- # and return a Hash with :status (Integer) and :body (String).
50
+ # and return a Hash with :status (Integer) and :body (String). They may
51
+ # add :headers (a Hash of response headers, names in any case): the
52
+ # wait a 429 names in Retry-After is read from it.
51
53
  def default_http_request(method:, url:, headers:, body: nil, timeout_ms: nil)
52
54
  uri = URI.parse(url)
53
55
  http = Net::HTTP.new(uri.host, uri.port)
@@ -67,7 +69,7 @@ module OpenReceive
67
69
  headers.each { |key, value| request[key] = value }
68
70
  request.body = body unless body.nil?
69
71
  response = http.start { |connection| connection.request(request) }
70
- { status: Integer(response.code), body: response.body.to_s }
72
+ { status: Integer(response.code), headers: response.each_header.to_h, body: response.body.to_s }
71
73
  end
72
74
 
73
75
  # Timeout classification shared by the API client and the rates feed
@@ -84,6 +86,14 @@ module OpenReceive
84
86
  error.respond_to?(:weight_budget?) && error.weight_budget? == true
85
87
  end
86
88
 
89
+ # The denial a weight-budget error carries, for the log line that
90
+ # reports it; nil for any other error.
91
+ def weight_budget_denial(error)
92
+ return nil unless weight_budget_error?(error) && error.respond_to?(:denial)
93
+
94
+ error.denial
95
+ end
96
+
87
97
  # A provider call's failure as "unreachable" (no answer: network,
88
98
  # timeout, 5xx, unparsable body), "rate_limited" (a 429, or this
89
99
  # process's own weight budget) or "refused" (the provider answered no);
@@ -2,6 +2,6 @@
2
2
 
3
3
  module OpenReceive
4
4
  module Server
5
- VERSION = "0.4.34"
5
+ VERSION = "0.5.0"
6
6
  end
7
7
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: openreceive-server
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.4.34
4
+ version: 0.5.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - OpenReceive
@@ -15,14 +15,14 @@ dependencies:
15
15
  requirements:
16
16
  - - '='
17
17
  - !ruby/object:Gem::Version
18
- version: 0.4.34
18
+ version: 0.5.0
19
19
  type: :runtime
20
20
  prerelease: false
21
21
  version_requirements: !ruby/object:Gem::Requirement
22
22
  requirements:
23
23
  - - '='
24
24
  - !ruby/object:Gem::Version
25
- version: 0.4.34
25
+ version: 0.5.0
26
26
  description: |
27
27
  Accept Bitcoin Lightning payments directly into a wallet you control, from your
28
28
  Ruby or Rack application. OpenReceive provides invoice creation, payment checks,