rasket 0.1.1

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,284 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "securerandom"
5
+
6
+ module Rasket
7
+ # The one request path. Every generated method ends here, so the rules are written once, the
8
+ # same as packages/sdk/src/http.ts in the Node client:
9
+ #
10
+ # 1. User-Agent, always.
11
+ # 2. Idempotency-Key, passed through on the routes that take one, and refused before a request is
12
+ # spent when its length is outside 1-256 (UTF-16 units, as the API counts). Never generated.
13
+ # 3. The error body, typed, and never a JSON::ParserError for a body that is not JSON.
14
+ # 4. The rate-limit headers read off every response, and bounded retries that repeat only what
15
+ # is safe to repeat: a GET, or a request carrying an idempotency key.
16
+ #
17
+ # Internal: use Rasket::Client.
18
+ class HttpClient
19
+ DEFAULT_BASE_URL = "https://api.rasket.com"
20
+ MIN_IDEMPOTENCY_KEY = 1
21
+ MAX_IDEMPOTENCY_KEY = 256
22
+ # A quota, not a moment: waiting does not refill it, so these 429s are never retried.
23
+ QUOTA_429 = %w[daily_quota_exceeded monthly_quota_exceeded marketing_quota_exceeded sms_quota_exceeded].freeze
24
+ # encodeURIComponent leaves these alone and escapes every other byte.
25
+ UNRESERVED = /[^A-Za-z0-9\-_.!~*'()]/
26
+
27
+ def initialize(api_key:, base_url: nil, user_agent: nil, timeout: 30, retry_attempts: 3, retry_min_delay: 0.5,
28
+ retry_max_delay: 8.0, transport: nil, sleep: nil, random: nil)
29
+ raise ArgumentError, "rasket: an API key is required." if api_key.nil? || api_key.to_s.empty?
30
+
31
+ @api_key = api_key.to_s
32
+ @base_url = (base_url || DEFAULT_BASE_URL).to_s.sub(%r{/+\z}, "")
33
+ own = "rasket-ruby/#{VERSION} ruby/#{RUBY_VERSION}"
34
+ extra = user_agent.to_s.strip
35
+ @user_agent = extra.empty? ? own : "#{own} #{extra}"
36
+ @timeout = timeout.to_f
37
+ @attempts = [1, retry_attempts.to_i].max
38
+ @min_delay = [0.0, retry_min_delay.to_f].max
39
+ @max_delay = [@min_delay, retry_max_delay.to_f].max
40
+ @transport = transport || NetHttpTransport.new
41
+ @sleep = sleep || ->(seconds) { Kernel.sleep(seconds) }
42
+ @random = random || -> { Kernel.rand }
43
+ end
44
+
45
+ # What JavaScript's string length counts: an astral character is two units.
46
+ def self.utf16_length(value)
47
+ value.encode(Encoding::UTF_16LE).bytesize / 2
48
+ rescue EncodingError
49
+ value.bytesize
50
+ end
51
+
52
+ def self.assert_idempotency_key(key)
53
+ length = utf16_length(key.to_s)
54
+ return if length.between?(MIN_IDEMPOTENCY_KEY, MAX_IDEMPOTENCY_KEY)
55
+
56
+ raise ApiError.new(status_code: 400, name: "invalid_idempotency_key", source: :client,
57
+ message: "Idempotency-Key must be between #{MIN_IDEMPOTENCY_KEY} and #{MAX_IDEMPOTENCY_KEY} characters.")
58
+ end
59
+
60
+ # One path segment, escaped like encodeURIComponent: a space is %20, never +.
61
+ def self.segment(value)
62
+ value.to_s.b.gsub(UNRESERVED) { |byte| format("%%%02X", byte.ord) }
63
+ end
64
+
65
+ def request(method, path, query: nil, body: nil, has_body: false, file_fields: nil, idempotent: false,
66
+ idempotency_key: nil, timeout: nil)
67
+ key = idempotent ? idempotency_key : nil
68
+ self.class.assert_idempotency_key(key) unless key.nil?
69
+
70
+ url = "#{@base_url}#{path}#{query_string(query)}"
71
+ headers = { "Authorization" => "Bearer #{@api_key}", "User-Agent" => @user_agent, "Accept" => "application/json" }
72
+ # Serialised once, before the loop: every attempt sends the same bytes, which is what makes a
73
+ # keyed retry a replay rather than a different payload.
74
+ payload = nil
75
+ if has_body && !file_fields.nil?
76
+ payload, headers["Content-Type"] = multipart(body, file_fields)
77
+ elsif has_body && !body.nil?
78
+ payload = JSON.generate(body)
79
+ headers["Content-Type"] = "application/json"
80
+ end
81
+ headers["Idempotency-Key"] = key.to_s unless key.nil?
82
+
83
+ repeatable = method == "GET" || !key.nil?
84
+ attempt = 1
85
+ loop do
86
+ answer = nil
87
+ begin
88
+ answer = @transport.call(method, url, headers, payload, (timeout || @timeout).to_f)
89
+ return success(answer) if answer.status.between?(200, 299)
90
+
91
+ failure = error_from(answer)
92
+ rescue ConnectionError => e
93
+ failure = e
94
+ end
95
+ raise failure if !repeatable || attempt >= @attempts
96
+
97
+ wait = retry_delay(attempt, answer, failure)
98
+ raise failure if wait.nil?
99
+
100
+ @sleep.call(wait)
101
+ attempt += 1
102
+ end
103
+ end
104
+
105
+ # Walks a list route a page at a time, passing the last item's id as after. With has_more it
106
+ # stops when that is false; without it (contacts.list) on an empty page.
107
+ def self.paginate(query, mode, &fetch)
108
+ query = (query || {}).transform_keys(&:to_sym)
109
+ unless query[:before].nil?
110
+ raise ApiError.new(status_code: 400, name: "validation_error", source: :client,
111
+ message: "A paging walk moves forward with after; leave before unset.")
112
+ end
113
+
114
+ Enumerator.new do |out|
115
+ loop do
116
+ body = fetch.call(query).body
117
+ items = body.is_a?(Hash) && body[:data].is_a?(Array) ? body[:data] : []
118
+ items.each { |item| out << item }
119
+ more = mode == "has_more" ? (body.is_a?(Hash) && body[:has_more] == true) : !items.empty?
120
+ break if !more || items.empty?
121
+
122
+ last = items.last
123
+ unless last.is_a?(Hash) && last[:id].is_a?(String)
124
+ raise ApiError.new(status_code: 0, name: ApiError::UNKNOWN_ERROR, source: :client,
125
+ message: "A listed item has no id to page from.")
126
+ end
127
+
128
+ query = query.merge(after: last[:id])
129
+ end
130
+ end
131
+ end
132
+
133
+ private
134
+
135
+ def query_string(query)
136
+ return "" if query.nil?
137
+
138
+ pairs = query.filter_map do |name, value|
139
+ next if value.nil?
140
+
141
+ "#{self.class.segment(name)}=#{self.class.segment(value.to_s)}"
142
+ end
143
+ pairs.empty? ? "" : "?#{pairs.join('&')}"
144
+ end
145
+
146
+ # A file field takes the bytes as a String, an IO, or { contents:, filename: }; every other
147
+ # field is sent as text. Nils are left out.
148
+ def multipart(body, file_fields)
149
+ raise ArgumentError, "rasket: a multipart body is a Hash of field names to values." unless body.is_a?(Hash)
150
+
151
+ boundary = "rasket-#{SecureRandom.hex(12)}"
152
+ parts = +"".b
153
+ body.each do |name, value|
154
+ next if value.nil?
155
+
156
+ field = name.to_s.delete("\"\r\n")
157
+ if file_fields.include?(field)
158
+ contents, filename = file_part(value, field)
159
+ parts << "--#{boundary}\r\nContent-Disposition: form-data; name=\"#{field}\"; filename=\"#{filename}\"\r\n" \
160
+ "Content-Type: application/octet-stream\r\n\r\n".b << contents.b << "\r\n".b
161
+ else
162
+ parts << "--#{boundary}\r\nContent-Disposition: form-data; name=\"#{field}\"\r\n\r\n".b << value.to_s.b << "\r\n".b
163
+ end
164
+ end
165
+ parts << "--#{boundary}--\r\n".b
166
+ [parts, "multipart/form-data; boundary=#{boundary}"]
167
+ end
168
+
169
+ def file_part(value, field)
170
+ if value.is_a?(Hash)
171
+ contents = value[:contents] || value["contents"]
172
+ filename = value[:filename] || value["filename"] || field
173
+ contents = contents.read if contents.respond_to?(:read)
174
+ return [contents.to_s, filename.to_s.delete("\"\r\n")]
175
+ end
176
+ return [value.read.to_s, field] if value.respond_to?(:read)
177
+
178
+ [value.to_s, field]
179
+ end
180
+
181
+ # How long to wait before the next try, or nil to stop now.
182
+ def retry_delay(attempt, answer, failure)
183
+ return backoff(attempt) if answer.nil?
184
+
185
+ name = failure.is_a?(ApiError) ? failure.name : ApiError::UNKNOWN_ERROR
186
+ status = answer.status
187
+ retryable = (status == 429 && !QUOTA_429.include?(name)) ||
188
+ (status >= 500 && status != 501) ||
189
+ (status == 409 && name == "concurrent_idempotent_requests")
190
+ return nil unless retryable
191
+
192
+ retry_after = integer_header(answer.headers, "retry-after")
193
+ return backoff(attempt) if retry_after.nil?
194
+
195
+ retry_after > @max_delay ? nil : retry_after.to_f
196
+ end
197
+
198
+ # Full jitter: uniformly random between 0 and the capped exponential ceiling, in seconds.
199
+ def backoff(attempt)
200
+ ceiling = [@max_delay, @min_delay * (2**(attempt - 1))].min
201
+ (@random.call * ceiling * 1000).floor / 1000.0
202
+ end
203
+
204
+ def integer_header(headers, name)
205
+ raw = headers[name]
206
+ return nil if raw.nil?
207
+
208
+ Float(raw.to_s.strip).to_i
209
+ rescue ArgumentError
210
+ nil
211
+ end
212
+
213
+ def rate_limit(headers)
214
+ limit = integer_header(headers, "ratelimit-limit")
215
+ remaining = integer_header(headers, "ratelimit-remaining")
216
+ reset = integer_header(headers, "ratelimit-reset")
217
+ return nil if limit.nil? || remaining.nil? || reset.nil?
218
+
219
+ RateLimit.new(limit: limit, remaining: remaining, reset_seconds: reset,
220
+ retry_after_seconds: integer_header(headers, "retry-after"))
221
+ end
222
+
223
+ def success(answer)
224
+ request_id = answer.headers["x-request-id"]
225
+ limits = rate_limit(answer.headers)
226
+ begin
227
+ body = JSON.parse(answer.body, symbolize_names: true)
228
+ rescue JSON::ParserError
229
+ raise ApiError.new(status_code: answer.status, name: ApiError::UNKNOWN_ERROR, source: :server,
230
+ message: "The server answered #{answer.status} with a body that is not JSON.",
231
+ request_id: request_id, rate_limit: limits)
232
+ end
233
+ Response.new(body: body, rate_limit: limits, request_id: request_id,
234
+ idempotent_replayed: answer.headers["idempotent-replayed"] == "true", etag: answer.headers["etag"])
235
+ end
236
+
237
+ def error_from(answer)
238
+ request_id = answer.headers["x-request-id"]
239
+ limits = rate_limit(answer.headers)
240
+ body = begin
241
+ JSON.parse(answer.body)
242
+ rescue JSON::ParserError
243
+ nil
244
+ end
245
+ if body.is_a?(Hash) && body["name"].is_a?(String) && body["message"].is_a?(String) && body["statusCode"].is_a?(Integer)
246
+ errors = if body["errors"].is_a?(Array)
247
+ body["errors"].filter_map do |issue|
248
+ next unless issue.is_a?(Hash) && issue["path"].is_a?(String) && issue["message"].is_a?(String)
249
+
250
+ ValidationIssue.new(path: issue["path"], message: issue["message"])
251
+ end
252
+ end
253
+ return ApiError.new(status_code: body["statusCode"], name: body["name"], message: body["message"], source: :server,
254
+ code: body["code"].is_a?(Integer) ? body["code"] : nil, errors: errors,
255
+ claimable: [true, false].include?(body["claimable"]) ? body["claimable"] : nil,
256
+ details: details(body["details"]), request_id: request_id, rate_limit: limits)
257
+ end
258
+ ApiError.new(status_code: answer.status, name: ApiError::UNKNOWN_ERROR, source: :server,
259
+ message: "The server answered #{answer.status} without a Rasket error body.",
260
+ request_id: request_id, rate_limit: limits)
261
+ end
262
+
263
+ def details(value)
264
+ return nil unless value.is_a?(Hash)
265
+
266
+ if value["recipient"].is_a?(String) && value["region"].is_a?(String) &&
267
+ value["allowed"].is_a?(Array) && value["allowed"].all?(String)
268
+ return SandboxRefusal.new(recipient: value["recipient"], region: value["region"], allowed: value["allowed"])
269
+ end
270
+ return NextStepRefusal.new(next_step: "checkout") if value["next"] == "checkout"
271
+
272
+ if value["checks"].is_a?(Array)
273
+ checks = value["checks"].map do |check|
274
+ return nil unless check.is_a?(Hash) && %w[code status title message].all? { |k| check[k].is_a?(String) }
275
+
276
+ EmailCheckResult.new(code: check["code"], status: check["status"], title: check["title"],
277
+ message: check["message"], block_id: check["block_id"].is_a?(String) ? check["block_id"] : nil)
278
+ end
279
+ return ChecksRefusal.new(checks: checks)
280
+ end
281
+ nil
282
+ end
283
+ end
284
+ end
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rasket
4
+ # What every method returns. body is the parsed JSON with symbol keys; for a list route it is the
5
+ # { object:, has_more:, data: } envelope. rate_limit is nil only when the answer did not come
6
+ # from the API. request_id is x-request-id: quote it when asking about a request.
7
+ Response = Data.define(:body, :rate_limit, :request_id, :idempotent_replayed, :etag)
8
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "openssl"
5
+ require "uri"
6
+
7
+ module Rasket
8
+ # One raw answer from a transport. headers has lower-cased names.
9
+ TransportResponse = Data.define(:status, :headers, :body)
10
+
11
+ # The default transport, over Net::HTTP. Any object with the same call method can be passed as
12
+ # transport: to the client instead.
13
+ class NetHttpTransport
14
+ NETWORK_ERRORS = [SocketError, SystemCallError, IOError, EOFError, OpenSSL::SSL::SSLError,
15
+ Net::HTTPBadResponse, Net::ProtocolError].freeze
16
+ TIMEOUT_ERRORS = [Net::OpenTimeout, Net::ReadTimeout, Net::WriteTimeout].freeze
17
+
18
+ def call(method, url, headers, body, timeout)
19
+ uri = URI.parse(url)
20
+ request = Net::HTTPGenericRequest.new(method, !body.nil?, true, uri.request_uri, headers)
21
+ request.body = body unless body.nil?
22
+ response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", open_timeout: timeout,
23
+ read_timeout: timeout, write_timeout: timeout) do |http|
24
+ http.request(request)
25
+ end
26
+ received = {}
27
+ response.each_header { |name, value| received[name.downcase] = value }
28
+ TransportResponse.new(status: response.code.to_i, headers: received, body: response.body.to_s)
29
+ rescue *TIMEOUT_ERRORS
30
+ raise ConnectionError.new(:timeout, "No response within #{(timeout * 1000).round} ms.")
31
+ rescue *NETWORK_ERRORS => e
32
+ raise ConnectionError.new(:network, "Could not reach #{url}: #{e.message}")
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rasket
4
+ # This client's version. It is sent in the User-Agent and is the gem's version.
5
+ VERSION = "0.1.1"
6
+ end
@@ -0,0 +1,100 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "openssl"
5
+
6
+ module Rasket
7
+ # Verify a Rasket webhook signature, the same five steps @rasket/webhook-verify runs:
8
+ #
9
+ # 1. require svix-id, svix-timestamp, svix-signature
10
+ # 2. reject if |now - timestamp| > 300 s
11
+ # 3. expected = base64(hmac_sha256(base64decode(secret without whsec_), "{id}.{timestamp}.{body}"))
12
+ # 4. for each "v1,<sig>" in svix-signature: constant-time compare
13
+ # 5. any match: the parsed body; none: Rasket::WebhookVerificationError
14
+ #
15
+ # The body must be the raw request body: request.raw_post in Rails, request.body.read in Rack or
16
+ # Sinatra, never params.
17
+ module Webhooks
18
+ REPLAY_TOLERANCE_SECONDS = 300
19
+
20
+ module_function
21
+
22
+ # Verify one delivery and return its parsed payload (symbol keys). headers is any Hash of
23
+ # header names in any casing, or a Rack env (HTTP_SVIX_ID).
24
+ def verify(raw_body, headers, secret, now: nil, tolerance_seconds: REPLAY_TOLERANCE_SECONDS)
25
+ id = header(headers, "svix-id")
26
+ raise WebhookVerificationError.new(:missing_id, "Missing svix-id header.") if id.nil?
27
+
28
+ timestamp = header(headers, "svix-timestamp")
29
+ raise WebhookVerificationError.new(:missing_timestamp, "Missing svix-timestamp header.") if timestamp.nil?
30
+
31
+ signature = header(headers, "svix-signature")
32
+ raise WebhookVerificationError.new(:missing_signature, "Missing svix-signature header.") if signature.nil?
33
+
34
+ sent_at = begin
35
+ Float(timestamp.strip)
36
+ rescue ArgumentError
37
+ nil
38
+ end
39
+ if sent_at.nil? || !sent_at.finite?
40
+ raise WebhookVerificationError.new(:invalid_timestamp, "svix-timestamp is not a Unix timestamp.")
41
+ end
42
+
43
+ now_seconds = (now || Time.now).to_i
44
+ if now_seconds - sent_at > tolerance_seconds
45
+ raise WebhookVerificationError.new(:timestamp_too_old, "svix-timestamp is outside the window.")
46
+ end
47
+ if sent_at - now_seconds > tolerance_seconds
48
+ raise WebhookVerificationError.new(:timestamp_too_new, "svix-timestamp is in the future.")
49
+ end
50
+
51
+ body = raw_body.to_s
52
+ expected = OpenSSL::HMAC.digest("SHA256", signing_key(secret), "#{id}.#{timestamp}.".b + body.b)
53
+ unless matches?(signature, expected)
54
+ raise WebhookVerificationError.new(:no_matching_signature, "No signature in svix-signature matches the body.")
55
+ end
56
+
57
+ begin
58
+ JSON.parse(body, symbolize_names: true)
59
+ rescue JSON::ParserError
60
+ raise WebhookVerificationError.new(:invalid_payload, "The signed body is not valid JSON.")
61
+ end
62
+ end
63
+
64
+ def header(headers, name)
65
+ lowered = name.downcase
66
+ rack = "HTTP_#{name.upcase.tr('-', '_')}"
67
+ headers.each do |key, value|
68
+ next unless key.to_s.downcase == lowered || key.to_s == rack
69
+
70
+ return value.is_a?(Array) ? value.first&.to_s : value&.to_s
71
+ end
72
+ nil
73
+ end
74
+
75
+ # The key bytes behind a whsec_ secret. unpack1("m") is base64 without the base64 gem (bundled,
76
+ # not default, since Ruby 3.4) and takes a secret pasted without its padding.
77
+ def signing_key(secret)
78
+ body = secret.to_s.delete_prefix("whsec_")
79
+ body.unpack1("m")
80
+ end
81
+
82
+ def matches?(header, expected)
83
+ # Every candidate of the right length is compared, and the loop does not stop at the first
84
+ # match, so the number of comparisons does not depend on which one matched.
85
+ matched = false
86
+ header.split(" ").each do |part|
87
+ version, value = part.split(",", 2)
88
+ next if version != "v1" || value.nil? || value.empty?
89
+
90
+ candidate = value.unpack1("m")
91
+ next if candidate.bytesize != expected.bytesize
92
+
93
+ matched = true if OpenSSL.fixed_length_secure_compare(candidate, expected)
94
+ end
95
+ matched
96
+ end
97
+
98
+ private_class_method :header, :signing_key, :matches?
99
+ end
100
+ end
data/lib/rasket.rb ADDED
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The Rasket Ruby client. The resources are generated from the API's own OpenAPI document; the
4
+ # request path (Rasket::HttpClient) is written once, with the same rules as the Node and Python
5
+ # clients.
6
+ #
7
+ # rasket = Rasket::Client.new(api_key: ENV.fetch("RASKET_API_KEY"))
8
+ # sent = rasket.emails.send(
9
+ # { from: "Acme <billing@acme.example>", to: ["ronald.williams@example.com"],
10
+ # subject: "Your receipt", html: "<p>Thanks.</p>" },
11
+ # idempotency_key: "receipt-1042"
12
+ # )
13
+ # sent.body[:id]
14
+ module Rasket
15
+ end
16
+
17
+ require_relative "rasket/version"
18
+ require_relative "rasket/errors"
19
+ require_relative "rasket/response"
20
+ require_relative "rasket/transport"
21
+ require_relative "rasket/http_client"
22
+ require_relative "rasket/webhooks"
23
+ require_relative "rasket/generated/error_names"
24
+ require_relative "rasket/generated/resources"
25
+ require_relative "rasket/client"