ringwillow 1.0.1 → 1.1.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: d9834315a1f32b8933f26ba9dcd2cc3d82a61c29d68274473666ecb64554738a
4
- data.tar.gz: e55428994554e4f792967857174e98aeef326c0439f11bbfd265a8d2d7b77e4d
3
+ metadata.gz: 9feb815514940553f6047110812ac09c99e4ece6dbe15b907beb2629a4f8e019
4
+ data.tar.gz: fc6ba74c484cb59905d760bbdee396c310671df9cb9080a976f084f636e8080f
5
5
  SHA512:
6
- metadata.gz: cf87e43521ac7bdfead095b5065d9b680a40de8bddd89244a009aec8ad7862a4488435fa479d5f15bdc814e00be21c09d82de4ca1cbd04470be3efd956b0e988
7
- data.tar.gz: 98de033acab82c6364bb67b07d858ac3a8d4bc8c65087d172c1b824deeee98bd998b9fadf8437a905a8db8c4cc978641e65ea1c79b951d34d0bb4a7e54b0d472
6
+ metadata.gz: cd2b7532517aff4af80e91f4c28c671547527e050362cc7bbbfea8890309ac0ced8b23941bfa0659b86907a25addd9792e9d2012ebde13cacc6042c2948a9770
7
+ data.tar.gz: 84ea4043fa94908ba8c8e94090df1038a7870254d48bcbe17850fcbbcfdf74fa8aa871865996bfb4ece07177cd14ed1d66f21df385299eb76e8a9f9efaf57888
@@ -1,3 +1,3 @@
1
1
  module Ringwillow
2
- VERSION = "1.0.1"
2
+ VERSION = "1.1.0"
3
3
  end
data/lib/ringwillow.rb CHANGED
@@ -8,6 +8,7 @@
8
8
  require "json"
9
9
  require "net/http"
10
10
  require "openssl"
11
+ require "securerandom"
11
12
  require "uri"
12
13
  require_relative "ringwillow/version"
13
14
 
@@ -17,21 +18,27 @@ module Ringwillow
17
18
  call.completed call.step voicemail.created message.received message.status message.taken
18
19
  lead.created callback.requested
19
20
  registration.updated registration.approved registration.rejected registration.needs_info
20
- contact.opted_out contact.opted_in
21
+ contact.opted_out contact.opted_in call.transcript.ready action.failed order.created order.updated
22
+ catalog.synced number.released webhook.endpoint.disabled
21
23
  ].freeze
22
24
 
25
+ # An API error. Branch on #code (stable, e.g. "invalid_field", "rate_limited"), show #message,
26
+ # highlight #field when set, log #request_id.
23
27
  class Error < StandardError
24
- attr_reader :status, :retry_after
28
+ attr_reader :status, :retry_after, :code, :field, :request_id
25
29
 
26
- def initialize(message, status, retry_after = nil)
30
+ def initialize(message, status, retry_after = nil, code: "", field: nil, request_id: nil)
27
31
  super(message)
28
32
  @status = status
29
33
  @retry_after = retry_after
34
+ @code = code
35
+ @field = field
36
+ @request_id = request_id
30
37
  end
31
38
  end
32
39
 
33
40
  class Client
34
- attr_reader :base_url, :business, :numbers, :flows, :calls, :messages, :webhooks, :registration, :agents, :actions
41
+ attr_reader :base_url, :business, :numbers, :flows, :calls, :messages, :webhooks, :registration, :agents, :actions, :integration
35
42
  attr_accessor :max_retries, :timeout
36
43
 
37
44
  def initialize(api_key: nil, base_url: nil, max_retries: 2, timeout: 30)
@@ -49,30 +56,43 @@ module Ringwillow
49
56
  @registration = Group.new(self) { |c| { get: -> { c.request(:get, "/registration") } } }
50
57
  @agents = Agents.new(self)
51
58
  @actions = Group.new(self) { |c| { list: -> { c.request(:get, "/actions") } } }
59
+ @integration = Group.new(self) do |c|
60
+ { health: -> { c.request(:get, "/integration/health") }, check: -> { c.request(:post, "/integration/health/check") } }
61
+ end
52
62
  end
53
63
 
54
- # Any endpoint: rw.request(:get, "/agents")
55
- def request(method, path, body = nil, query = nil)
64
+ # Any endpoint: rw.request(:get, "/agents"). Writes carry an Idempotency-Key (a new UUID unless you pass
65
+ # idempotency_key:), reused across retries; 429, 5xx and network errors retry with backoff and jitter.
66
+ def request(method, path, body = nil, query = nil, idempotency_key: nil)
56
67
  q = (query || {}).reject { |_, v| v.nil? || v == "" }
57
68
  uri = URI(@base_url + (path.start_with?("/") ? path : "/#{path}"))
58
69
  uri.query = URI.encode_www_form(q) unless q.empty?
70
+ idem = %i[get head].include?(method.to_s.downcase.to_sym) ? nil : (idempotency_key || SecureRandom.uuid)
59
71
  attempt = 0
60
72
  loop do
61
73
  req = Net::HTTP.const_get(method.to_s.capitalize).new(uri)
62
74
  req["Authorization"] = "Bearer #{@key}"
63
75
  req["Accept"] = "application/json"
64
76
  req["User-Agent"] = "ringwillow-ruby/#{VERSION}"
77
+ req["Idempotency-Key"] = idem if idem
65
78
  unless body.nil?
66
79
  req["Content-Type"] = "application/json"
67
80
  req.body = JSON.generate(body)
68
81
  end
69
- res = transport(uri, req)
82
+ begin
83
+ res = transport(uri, req)
84
+ rescue IOError, SystemCallError, Timeout::Error, OpenSSL::SSL::SSLError
85
+ raise unless attempt < @max_retries
86
+ sleep(backoff(attempt))
87
+ attempt += 1
88
+ next
89
+ end
70
90
  code = res.code.to_i
71
91
  ra = res["Retry-After"]
72
92
  ra = ra && ra =~ /\A\d+\z/ ? ra.to_i : nil
73
- if code == 429 && attempt < @max_retries
93
+ if (code == 429 || code >= 500 || (code == 409 && ra)) && attempt < @max_retries
94
+ sleep(ra ? [ra, 30].min : backoff(attempt))
74
95
  attempt += 1
75
- sleep([ra || 1, 30].min)
76
96
  next
77
97
  end
78
98
  raw = res.body.to_s
@@ -81,11 +101,18 @@ module Ringwillow
81
101
  rescue JSON::ParserError
82
102
  nil
83
103
  end
84
- raise Error.new((data.is_a?(Hash) && data["error"]) || raw, code, ra) if code >= 300
104
+ if code >= 300
105
+ h = data.is_a?(Hash) ? data : {}
106
+ raise Error.new(h["message"] || h["error"] || raw, code, ra, code: h["code"].to_s, field: h["field"],
107
+ request_id: h["requestId"] || res["X-Request-Id"])
108
+ end
85
109
  return data
86
110
  end
87
111
  end
88
112
 
113
+ # 0.5 s, 1 s, 2 s ... capped at 8 s, times 0.5-1 (jitter).
114
+ def backoff(attempt) = [0.5 * (2**attempt), 8.0].min * (0.5 + rand / 2)
115
+
89
116
  # Seam for tests.
90
117
  def transport(uri, req)
91
118
  Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", open_timeout: @timeout, read_timeout: @timeout) { |h| h.request(req) }
@@ -124,7 +151,9 @@ module Ringwillow
124
151
  def list(q: nil, limit: nil, before: nil) = @c.request(:get, "/messages", nil, { q: q, limit: limit, before: before })
125
152
 
126
153
  # Needs approved texting (10DLC) and credit; 409 if the contact replied STOP.
127
- def send_message(to:, body:, from: nil) = @c.request(:post, "/messages", { to: to, body: body, from: from }.compact)
154
+ def send_message(to:, body:, from: nil, idempotency_key: nil)
155
+ @c.request(:post, "/messages", { to: to, body: body, from: from }.compact, idempotency_key: idempotency_key)
156
+ end
128
157
  alias create send_message
129
158
  end
130
159
 
@@ -132,8 +161,18 @@ module Ringwillow
132
161
  def list = @c.request(:get, "/webhooks")
133
162
 
134
163
  # Returns {"endpoint"=>{...}, "secret"=>"whsec_..."}; the secret is shown once.
135
- def create(url:, events: nil) = @c.request(:post, "/webhooks", { url: url, events: events }.compact)
164
+ def create(url:, events: nil, description: nil) = @c.request(:post, "/webhooks", { url: url, events: events, description: description }.compact)
165
+ def update(id, **fields) = @c.request(:patch, "/webhooks/#{esc(id)}", fields)
136
166
  def delete(id) = @c.request(:delete, "/webhooks/#{esc(id)}")
167
+ # Sends one signed test event now and reports the answer.
168
+ def test(id, event: "ping") = @c.request(:post, "/webhooks/#{esc(id)}/test", { event: event })
169
+ # Delivery log: {"data"=>[...], "nextCursor"=>"..."}.
170
+ def deliveries(id, status: nil, event: nil, before: nil, limit: nil)
171
+ @c.request(:get, "/webhooks/#{esc(id)}/deliveries", nil, { status: status, event: event, before: before, limit: limit })
172
+ end
173
+ def replay(id, delivery_id) = @c.request(:post, "/webhooks/#{esc(id)}/deliveries/#{Integer(delivery_id)}/replay")
174
+ def replay_failed(id, since: nil) = @c.request(:post, "/webhooks/#{esc(id)}/replay", since ? { since: since } : {})
175
+ def rotate_secret(id, grace_hours: 24) = @c.request(:post, "/webhooks/#{esc(id)}/rotate-secret", { graceHours: grace_hours })
137
176
  end
138
177
 
139
178
  class Agents < Group
@@ -144,17 +183,26 @@ module Ringwillow
144
183
  module Webhook
145
184
  module_function
146
185
 
147
- # Checks Ringwillow-Signature ("t=<unix>,v1=<hex>") against the raw body. tolerance 0 skips the age check.
186
+ # Checks Ringwillow-Signature ("t=<unix>,v1=<hex>[,v1=<hex>]") against the raw body. Any v1 may match
187
+ # (two are sent while a secret rotates). tolerance 0 skips the age check.
148
188
  def verify(secret, header, raw_body, tolerance: 300)
149
189
  return false if secret.to_s.empty? || header.to_s.empty?
150
- parts = header.split(",").map { |p| p.strip.split("=", 2) }.select { |p| p.size == 2 }.to_h
151
- return false unless parts["t"] =~ /\A\d+\z/ && parts["v1"]
152
- t = parts["t"].to_i
153
- return false if tolerance.positive? && (Time.now.to_i - t).abs > tolerance
154
- want = OpenSSL::HMAC.hexdigest("SHA256", secret, "#{t}.#{raw_body}")
155
- OpenSSL.fixed_length_secure_compare(want, parts["v1"]) rescue false
190
+ ts = nil
191
+ sigs = []
192
+ header.split(",").each do |p|
193
+ k, v = p.strip.split("=", 2)
194
+ ts = v if k == "t"
195
+ sigs << v if k == "v1" && v
196
+ end
197
+ return false unless ts =~ /\A\d+\z/ && !sigs.empty?
198
+ return false if tolerance.positive? && (Time.now.to_i - ts.to_i).abs > tolerance
199
+ want = OpenSSL::HMAC.hexdigest("SHA256", secret, "#{ts}.#{raw_body}")
200
+ sigs.any? { |s| s.bytesize == want.bytesize && OpenSSL.fixed_length_secure_compare(want, s) }
156
201
  end
157
202
 
203
+ # Same scheme for action requests (the action's rws_ secret).
204
+ def verify_action(secret, header, raw_body) = verify(secret, header, raw_body)
205
+
158
206
  # Verifies, then parses the delivery. Raises Ringwillow::Error (400) if the signature is wrong.
159
207
  def parse(secret, header, raw_body, tolerance: 300)
160
208
  raise Error.new("Bad Ringwillow-Signature", 400) unless verify(secret, header, raw_body, tolerance: tolerance)
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: ringwillow
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.0.1
4
+ version: 1.1.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - O2A2 LLC
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-12-04 00:00:00.000000000 Z
11
+ date: 2026-12-05 00:00:00.000000000 Z
12
12
  dependencies: []
13
13
  description: Phone numbers, call flows, AI voice, texting (A2P 10DLC) and signed webhooks.
14
14
  email: