billionsend 0.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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 615c7d748eb7394d1b99a7ff8b5a4a1ea3085a0d5131ef75e7beedc255106cca
4
+ data.tar.gz: 044e709070d13b59b32c9c58249963d732963a98527c2675614428ae6dba3ae5
5
+ SHA512:
6
+ metadata.gz: a2450436b37a494a5bc855d2e86212677815a12774062c55ece197d87e54435c36ab21e499d4aa41125dd509ff8a063e3047f81108ed2fa5bd85c8aad47b924e
7
+ data.tar.gz: 834659dcaf28c007dc4f3cfa9a72088f12f76639da87d68f631d405bfc7eafc46881250f7271af78b1f8a4449860aa89ed73c0fa1654c7fff97af4eb0325e8d8
data/CHANGELOG.md ADDED
@@ -0,0 +1,15 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 (2026-11-17)
4
+
5
+ First release of the BillionSend Ruby SDK.
6
+
7
+ - `BillionSend::Client` covering every operation of the BillionSend API (139), named after each operation's `operationId` in snake_case and grouped into resources: emails (with metrics, receiving, attachments and their extracted text), domains, API keys, contacts, audiences, contact properties, segments, topics, broadcasts, templates, webhooks, suppressions, unsubscribes, verifications, usage, deliverability, inboxes (agent and safety settings, labels, threads, quarantine, codes, drafts, event streams) and agent signup. An `operationId` that is also the group of others is that group's `call` (`client.emails.metrics.call`).
8
+ - Answers returned as parsed JSON: Hashes with string keys.
9
+ - Errors raised as `BillionSend::Error` subclasses carrying `status_code`, `name`, `message` and `request_id` (the API's `x-request-id`); a call without an API key raises `AuthenticationError` (`missing_api_key`) before sending.
10
+ - Sending methods always send an `Idempotency-Key`: the caller's, or a UUID made up for the call and shared by its retries.
11
+ - Retries for requests safe to repeat (GET, PUT, DELETE and keyed requests) on 429, 5xx, failures without an answer and 409 `concurrent_idempotent_requests`, honouring `Retry-After` up to 60 seconds, else exponential backoff with jitter.
12
+ - Server-sent event streams yielding `InboxStreamEvent` and `StreamGapEvent` objects, resuming with `Last-Event-ID` after the server closes them or the connection drops, and waiting what a 429 or 5xx's `Retry-After` asks before the next reconnect (over 60 seconds raises that error at once), and after `max_reconnects` reconnects in a row that fail to open raising the API's error for the last one, or `APIConnectionError` when it got no answer (a connection that opens starts the count again, so a quiet inbox keeps its stream); an error the block raises passes through as it is.
13
+ - `*_all` methods returning lazy enumerators over every item of a cursor list.
14
+ - `BillionSend.verify_webhook` checks a webhook delivery's signature and timestamp and returns the parsed event.
15
+ - No runtime dependencies.
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 BillionSend
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,258 @@
1
+ # BillionSend Ruby SDK
2
+
3
+ The official Ruby client for the [BillionSend](https://billionsend.com) API: send and receive email, run inboxes for agents and people, manage domains, contacts, broadcasts, templates, webhooks and more.
4
+
5
+ - Every operation of the API (139), named after the API's own `operationId`s.
6
+ - No runtime dependencies: `net/http`, `json` and `openssl` from the standard library.
7
+ - Sends that never go out twice, retries, auto-paging enumerators, live event streams that resume where they stopped, and webhook signature verification.
8
+
9
+ Documentation: https://billionsend.com/docs.
10
+
11
+ ## Install
12
+
13
+ ```bash
14
+ gem install billionsend
15
+ ```
16
+
17
+ or in a Gemfile:
18
+
19
+ ```ruby
20
+ gem "billionsend"
21
+ ```
22
+
23
+ Ruby 3.1 or newer.
24
+
25
+ ## Quick start
26
+
27
+ ```ruby
28
+ require "billionsend"
29
+
30
+ client = BillionSend::Client.new # reads BILLIONSEND_API_KEY
31
+
32
+ email = client.emails.send({
33
+ from: "Acme <hello@acme.dev>",
34
+ to: ["ada@example.com"],
35
+ subject: "Welcome to Acme",
36
+ html: "<p>Thanks for signing up!</p>"
37
+ })
38
+ puts email["id"]
39
+ ```
40
+
41
+ Every method returns the API's JSON answer parsed into plain Ruby: a `Hash` with string keys (`email["id"]`, not `email[:id]`), arrays and scalars as JSON has them. There are no model classes in this version; the fields of every answer are in the API reference at https://billionsend.com/docs.
42
+
43
+ The request body is a `Hash` in braces, with symbol or string keys: the braces matter, because a method's keyword arguments (`idempotency_key:`, `timeout:`…) are separate from the body.
44
+
45
+ ## Authentication
46
+
47
+ Pass an API key (`bs_…`) as `api_key:` or set `BILLIONSEND_API_KEY`. Keys are made in the dashboard or with `client.api_keys.create`. A key scoped to one inbox can only reach that inbox.
48
+
49
+ An agent can also create its own account, the one call that needs no key:
50
+
51
+ ```ruby
52
+ signup = BillionSend::Client.new.agent.signup({ human_email: "owner@example.com", name: "Scout" })
53
+ client = BillionSend::Client.new(api_key: signup["api_key"])
54
+ puts signup["inbox"]["email_address"], client.agent.status["status"]
55
+ ```
56
+
57
+ ## Sending once
58
+
59
+ Every sending method (`emails.send`, `emails.batch`, `emails.receiving.reply` and `.forward`, `inboxes.send`, `inboxes.threads.emails.reply` and `.forward`, `inboxes.drafts.send`) sends an `Idempotency-Key`. Without `idempotency_key:` the call makes up one (a UUID) and reuses it for its own retries, so a retry after a dropped connection never sends the email twice. Pass your own key to stay safe across calls too, for example when a job that sends may run again:
60
+
61
+ ```ruby
62
+ client.emails.send(message, idempotency_key: "welcome/#{user.id}")
63
+ ```
64
+
65
+ Repeating a key with the same request returns the first answer; the same key with a different request is refused (`BillionSend::ConflictError`, `invalid_idempotent_request`). The API keeps keys for 24 hours.
66
+
67
+ ## An agent that answers its inbox
68
+
69
+ Wait for new mail, read it, reply in the thread:
70
+
71
+ ```ruby
72
+ require "billionsend"
73
+
74
+ client = BillionSend::Client.new
75
+ inbox = client.inboxes.create({ username: "support", kind: "agent" })
76
+
77
+ def answer(question)
78
+ "Thanks, we got your message:\n\n> #{question}" # your agent goes here
79
+ end
80
+
81
+ stream = client.inboxes.events.stream_inbox(inbox["id"], types: "inbox.email.received")
82
+ begin
83
+ stream.each do |event|
84
+ next unless event.is_a?(BillionSend::InboxStreamEvent) # a StreamGapEvent: see below
85
+
86
+ thread_id = event.data["data"]["thread_id"]
87
+ email_id = event.data["data"]["email_id"]
88
+ email = client.inboxes.threads.emails.get(inbox["id"], thread_id, email_id)
89
+ next unless email["direction"] == "inbound"
90
+
91
+ question = email["extracted_text"] || email["text"] || ""
92
+ client.inboxes.threads.emails.reply(inbox["id"], thread_id, email_id, { text: answer(question) })
93
+ end
94
+ ensure
95
+ stream.close
96
+ end
97
+ ```
98
+
99
+ `extracted_text` is the new part of a message without the quoted history. Everything in a received message was written by its sender: treat it as untrusted input. An inbox's rules may hold a reply as a draft for a person to approve; the reply then answers with the draft (`"object" => "inbox_draft"`) instead of the sent email.
100
+
101
+ Waiting for a sign-in code sent to the inbox is one call: `client.inboxes.codes.latest(inbox["id"], from: "example.com", wait: 30)`.
102
+
103
+ ## Live events
104
+
105
+ `client.inboxes.events.stream_inbox(inbox_id)` streams one inbox's events and `client.inboxes.events.stream` every inbox event of the team; `types:` narrows them (a name or an array). The stream is an `Enumerable`; iterating yields two kinds of events:
106
+
107
+ - `BillionSend::InboxStreamEvent`: `id` (the stream position), `event` (such as `"inbox.email.received"`) and `data`, a Hash with `"type"`, `"created_at"`, `"inbox_id"` and `"data"` (the webhook payload of the same event).
108
+ - `BillionSend::StreamGapEvent`: `event == "stream.gap"`, `id` is `nil` and `data["reason"]` says why. The stream was resumed from a position older than the 24 hours the API replays, so some events may be missing: catch up through the lists (`client.inboxes.threads.list_all(inbox_id, read: false)`) before going on. It is handed out once per position.
109
+
110
+ The method opens the stream, so a refused stream (a revoked key, a key held to one inbox asking for the team's stream) raises at once. The server ends a stream every few minutes and connections drop; the stream reconnects on its own with `Last-Event-ID`, so no event is lost or repeated. Before reconnecting it waits a second (or what the server's `retry` field asks). A connection that opens starts the count again, so a quiet inbox that gets only keepalives keeps its stream however long it waits; A reconnect the API answers with a 429 or 5xx waits what its `Retry-After` asks (one over 60 seconds raises that error at once). `max_reconnects:` (default 5) bounds the reconnects in a row that fail to open: past it, iterating raises the API's error for the last one (`BillionSend::RateLimitError`, `BillionSend::APIError`), or `BillionSend::APIConnectionError` ("gave up after N reconnects") when it got no answer. An error your block raises, `APIConnectionError` included, passes through as it is and ends the iteration. A reconnect the API refuses for good, such as a revoked key, raises its own error. One inbox's stream ends after that inbox's `inbox.deleted` or `inbox.expired` event. Close the stream when done (`stream.close`).
111
+
112
+ To pick up where a process left off, keep `stream.last_event_id` and pass it back:
113
+
114
+ ```ruby
115
+ stream = client.inboxes.events.stream(last_event_id: saved_position)
116
+ ```
117
+
118
+ ## Webhooks
119
+
120
+ Verify a delivery before trusting it. Pass the raw body exactly as received, the request headers and the endpoint's signing secret (`whsec_…`, shown when the webhook is created or rotated):
121
+
122
+ ```ruby
123
+ # Rails; any framework works the same way
124
+ class BillionSendWebhooksController < ActionController::API
125
+ def create
126
+ headers = %w[webhook-id webhook-timestamp webhook-signature].to_h { |name| [name, request.headers[name]] }
127
+ event = BillionSend.verify_webhook(request.raw_post, headers, ENV.fetch("BILLIONSEND_WEBHOOK_SECRET"))
128
+ mark_bounced(event["data"]["email_id"]) if event["type"] == "email.bounced"
129
+ head :no_content
130
+ rescue BillionSend::WebhookVerificationError
131
+ head :bad_request
132
+ end
133
+ end
134
+ ```
135
+
136
+ With Rack or Sinatra, `request.get_header("HTTP_WEBHOOK_ID")` and so on read the same headers. `BillionSend.verify_webhook` (also `BillionSend::Webhooks.verify`) checks the `webhook-id`, `webhook-timestamp` and `webhook-signature` headers (Standard Webhooks: HMAC-SHA256 over `id.timestamp.body`), accepts any of several signatures (both secrets sign during a rotation's overlap) and refuses a timestamp more than `tolerance:` seconds (default 300) from now, which bounds replays. It returns the parsed event (`"type"`, `"created_at"`, `"data"`). Parse the body only after verifying: re-serialised JSON does not verify. A secret that is not a `whsec_` secret raises `ArgumentError`.
137
+
138
+ ## Resources
139
+
140
+ | Method | Covers |
141
+ | --- | --- |
142
+ | `emails` | send, batch, list, get, update, cancel, delete, insights; `emails.metrics` (see below) |
143
+ | `emails.receiving` (`.attachments`) | received mail: list, get, delete, reply, forward; attachments and their extracted text |
144
+ | `domains` | create, list, get, update, delete, verify |
145
+ | `api_keys` | create, list, delete |
146
+ | `contacts` (`.topics`, `.segments`, `.batch`) | create, list, get, update, delete, preferences_link; `batch.create`, `batch.get`, `batch.remove` |
147
+ | `audiences.contacts` | contacts addressed through an audience |
148
+ | `contact_properties`, `segments` (`.contacts`), `topics` | contact data and grouping |
149
+ | `broadcasts` | create, list, get, update, delete, send, duplicate, cancel |
150
+ | `templates` | create, list, get, update, delete, publish, duplicate |
151
+ | `webhooks` | create, list, get, update, delete, rotate |
152
+ | `suppressions` (`.batch`), `unsubscribes` | suppression list (`batch.add`, `batch.remove`) and opt-outs |
153
+ | `verifications` | availability, estimate, create, list, get |
154
+ | `usage`, `deliverability` | account usage and sending health |
155
+ | `inboxes` (`.events`) | create, list, get, update, delete, send; `events.stream`, `events.stream_inbox` |
156
+ | `inboxes.agent`, `.safety`, `.labels`, `.codes`, `.quarantine`, `.drafts` | inbox settings, labels, verification codes, held mail, drafts |
157
+ | `inboxes.threads` (`.labels`, `.emails`) | list, search, get, update, delete; thread labels; messages, reply and forward |
158
+ | `agent` | signup, status, claim_email |
159
+
160
+ A few resources have a method named `send` (`emails.send`, `inboxes.send`, `broadcasts.send`), as their `operationId`s say; it hides `Object#send` on those objects, so reach other methods of a resource dynamically with `public_send` or `__send__`.
161
+
162
+ Each method is named after its operation's `operationId` in the API document: `emails.receiving.attachments.list` is `client.emails.receiving.attachments.list`, with camelCase written in snake_case (`agent.claimEmail` is `client.agent.claim_email`). An `operationId` that is also the group of others is that group's `call`: `emails.metrics` (beside `emails.metrics.links`, `.countries` and `.clients`) is `client.emails.metrics.call(metrics: ["sent", "delivered"])`, or `client.emails.metrics.(…)`.
163
+
164
+ Path parameters are positional (`client.domains.get(domain_id)`), the request body is a Hash (`client.domains.create({ name: "acme.dev" })`) and query parameters are keyword arguments (`client.emails.list(limit: 50)`); a list parameter takes an array. Every method also takes `extra_headers:` and `timeout:`. Anything the methods do not cover goes through `client.request("GET", "/path", query: {…})`.
165
+
166
+ ## Pagination
167
+
168
+ List methods return one page (`{"object" => "list", "data" => [...], "has_more" => …}`). Every cursor list also has a `*_all` method (`search_all` for thread search) returning a lazy `Enumerator` that fetches the following pages as you go:
169
+
170
+ ```ruby
171
+ client.contacts.list_all(limit: 100).each do |contact|
172
+ puts contact["email"]
173
+ end
174
+
175
+ first_ten = client.domains.list_all.first(10) # fetches only the pages it needs
176
+ ```
177
+
178
+ An enumerator walks in the list's own order from `after:` (or the first page); start it with `before:` to walk the other way. It raises the same errors as the methods.
179
+
180
+ ## Errors
181
+
182
+ Every error is a `BillionSend::Error` with the API's error shape, `status_code`, `name` and `message`, plus `request_id`, the API's id of the request (its `x-request-id` header; quote it when asking for support).
183
+
184
+ ```ruby
185
+ begin
186
+ client.domains.get("6a1f1d38-3c55-4a4e-9a57-0f2b3c4d5e6f")
187
+ rescue BillionSend::NotFoundError
188
+ puts "no such domain"
189
+ rescue BillionSend::RateLimitError => e
190
+ puts "retry in #{e.retry_after}"
191
+ rescue BillionSend::Error => e
192
+ puts e.status_code, e.name, e.message, e.request_id
193
+ end
194
+ ```
195
+
196
+ | Status | Error |
197
+ | --- | --- |
198
+ | 400, 422 | `ValidationError` |
199
+ | 401 | `AuthenticationError` |
200
+ | 403 | `PermissionDeniedError` |
201
+ | 404 | `NotFoundError` |
202
+ | 409 | `ConflictError` |
203
+ | 429 | `RateLimitError` (`retry_after` in seconds) |
204
+ | 5xx | `APIError` |
205
+ | no answer | `APIConnectionError`, and `APITimeoutError` (a subclass) for timeouts; `status_code` and `request_id` are `nil` |
206
+
207
+ An answer that is not JSON keeps the same shape, with `name` set to `"application_error"`. `WebhookVerificationError` (`name` `"webhook_verification_error"`) is a `BillionSend::Error` too. `error.to_s` reads `"404 not_found: Domain not found"`.
208
+
209
+ ## Retries
210
+
211
+ A request is retried when repeating it is safe: GET, PUT and DELETE, and any request carrying an idempotency key (every send does). It is retried on 429, on 5xx, when no answer came back (connection failure, timeout), and, for a keyed request, on 409 `concurrent_idempotent_requests` (a retry that caught the first attempt still running). The wait is the answer's `Retry-After` when there is one, otherwise exponential backoff with jitter (0.5 s, 1 s, 2 s… up to 8 s). An answer asking to wait more than 60 seconds, such as a used-up daily quota, is raised at once. `max_retries:` (default 2) bounds the retries of one call; `0` turns them off.
212
+
213
+ ## Configuration
214
+
215
+ | Argument | Environment | Default |
216
+ | --- | --- | --- |
217
+ | `api_key:` | `BILLIONSEND_API_KEY` | none (only `agent.signup` works without one; any other call raises `AuthenticationError`, `missing_api_key`) |
218
+ | `base_url:` | `BILLIONSEND_BASE_URL` | `https://api.billionsend.com` |
219
+ | `timeout:` | | `60` seconds per attempt (an event stream waits at least 60 s for each read) |
220
+ | `max_retries:` | | `2` |
221
+ | `default_headers:` | | none |
222
+ | `transport:` | | the HTTP layer: anything with `call(request)` and `open_stream(request)` like `BillionSend::NetHTTPTransport` (proxies, instrumentation, tests) |
223
+
224
+ A client holds no open connections between calls and is safe to share between threads.
225
+
226
+ ## Development
227
+
228
+ ```bash
229
+ bundle install
230
+ bundle exec rake # generate:check, then the tests
231
+ script/test.sh # the same in the pinned Ruby image (podman or docker)
232
+ ```
233
+
234
+ The SDK is built from a snapshot of the API's OpenAPI document, `openapi/api.openapi.json`. The snapshot is the contract: `script/generate.rb` writes `lib/billionsend/resources.rb` from it (method names from each `operationId`, idempotency keys where an operation declares the `Idempotency-Key` header, enumerators for cursor lists), and the tests check every request the SDK sends and every answer it reads against it through a contract mock (`test/support/contract.rb`). A coverage test fails when an operation of the snapshot has no SDK method, or when the SDK has a method that is not an operation.
235
+
236
+ When the API changes:
237
+
238
+ ```bash
239
+ ruby script/sync_openapi.rb # or: --from path/to/api.openapi.json
240
+ ruby script/generate.rb
241
+ bundle exec rake test
242
+ ```
243
+
244
+ Whatever fails is what the SDK has to follow. CI runs `script/generate.rb --check` so the generated code never drifts from the snapshot.
245
+
246
+ ## Releasing
247
+
248
+ Publishing is manual; nothing is published on push.
249
+
250
+ 1. On RubyGems, the owner of the `billionsend` gem adds a Trusted Publisher (for the first version, a pending one under the account's Trusted Publishers): repository `billionsend/billionsend-ruby`, workflow `release.yml`, environment `rubygems`.
251
+ 2. Set `VERSION` in `lib/billionsend/version.rb`, turn the changelog's `Unreleased` heading into that version, commit, then tag and push: `git tag v0.1.0 && git push origin main v0.1.0`.
252
+ 3. Actions → `release` → Run workflow, on the version tag. The workflow refuses a branch or a tag that differs from `BillionSend::VERSION`, runs every check, builds the gem and pushes it with RubyGems Trusted Publishing (no key stored).
253
+
254
+ Without Trusted Publishing, the same release from a clean checkout of the tag is `gem build billionsend.gemspec && gem push billionsend-0.1.0.gem` with an API key scoped to pushing the `billionsend` gem in `GEM_HOST_API_KEY`.
255
+
256
+ ## License
257
+
258
+ MIT
@@ -0,0 +1,253 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "securerandom"
5
+ require "time"
6
+ require "uri"
7
+
8
+ module BillionSend
9
+ # The BillionSend API client.
10
+ #
11
+ # client = BillionSend::Client.new # reads BILLIONSEND_API_KEY
12
+ # client.emails.send({ from: "Acme <hello@acme.com>", to: ["user@example.com"],
13
+ # subject: "Hi", text: "Hello" })
14
+ #
15
+ # Operations are grouped into resources named after each operation's
16
+ # +operationId+ (+emails.receiving.attachments.list+ is
17
+ # +client.emails.receiving.attachments.list+). Every method returns the
18
+ # parsed JSON answer as a Hash with string keys.
19
+ class Client
20
+ include Resources::Root
21
+
22
+ DEFAULT_BASE_URL = "https://api.billionsend.com"
23
+ DEFAULT_TIMEOUT = 60
24
+ DEFAULT_MAX_RETRIES = 2
25
+ # A Retry-After longer than this is not waited out: the error is raised at once.
26
+ MAX_RETRY_DELAY = 60.0
27
+ # A retry of a keyed request can meet the first attempt still running on the server.
28
+ CONCURRENT_IDEMPOTENT = "concurrent_idempotent_requests"
29
+ IDEMPOTENT_METHODS = %w[GET HEAD OPTIONS PUT DELETE].freeze
30
+
31
+ attr_reader :api_key, :base_url, :timeout, :max_retries
32
+
33
+ # Waits between retries; replace it in tests.
34
+ attr_writer :sleeper
35
+
36
+ # @param api_key [String, nil] defaults to BILLIONSEND_API_KEY
37
+ # @param base_url [String, nil] defaults to BILLIONSEND_BASE_URL, else https://api.billionsend.com
38
+ # @param timeout [Numeric] seconds per request (an event stream waits at least 60 s per read)
39
+ # @param max_retries [Integer] retries after the first attempt (see "Retries" in the README)
40
+ # @param default_headers [Hash{String => String}] sent with every request
41
+ # @param transport [#call, #open_stream] the HTTP layer (NetHTTPTransport by default)
42
+ def initialize(api_key: nil, base_url: nil, timeout: DEFAULT_TIMEOUT, max_retries: DEFAULT_MAX_RETRIES,
43
+ default_headers: {}, transport: nil)
44
+ raise ArgumentError, "max_retries must be 0 or more" if max_retries.negative?
45
+
46
+ @api_key = api_key || ENV.fetch("BILLIONSEND_API_KEY", nil)
47
+ resolved = base_url || ENV.fetch("BILLIONSEND_BASE_URL", nil)
48
+ resolved = DEFAULT_BASE_URL if resolved.nil? || resolved.empty?
49
+ @base_url = resolved.sub(%r{/+\z}, "")
50
+ @timeout = timeout
51
+ @max_retries = max_retries
52
+ @default_headers = default_headers.to_h
53
+ @transport = transport || NetHTTPTransport.new
54
+ @sleeper = ->(seconds) { sleep(seconds) }
55
+ end
56
+
57
+ def inspect
58
+ "#<#{self.class.name} base_url=#{base_url.inspect}>"
59
+ end
60
+
61
+ # Sends one request with retries and returns the parsed JSON answer.
62
+ # The generated resource methods call it; use it for anything they do not cover.
63
+ def request(method, path, query: nil, headers: nil, body: nil, idempotency_key: nil,
64
+ auto_idempotency_key: false, auth: true, extra_headers: nil, timeout: nil)
65
+ all_headers = build_headers(auth: auth, body: !body.nil?, idempotency_key: idempotency_key,
66
+ headers: headers, extra_headers: extra_headers)
67
+ keyed = all_headers.keys.any? { |k| k.casecmp?("idempotency-key") }
68
+ if auto_idempotency_key && !keyed
69
+ all_headers["Idempotency-Key"] = SecureRandom.uuid
70
+ keyed = true
71
+ end
72
+ payload = body.nil? ? nil : JSON.generate(body)
73
+ req = Request.new(method: method, url: url(path, query), headers: all_headers, body: payload,
74
+ timeout: timeout || @timeout)
75
+ attempt = 0
76
+ loop do
77
+ begin
78
+ response = @transport.call(req)
79
+ return parse_json(response) if response.success?
80
+
81
+ error = Client.error_from(response)
82
+ rescue APIConnectionError => e
83
+ error = e
84
+ end
85
+ delay = retry_delay(attempt, error, method: method, keyed: keyed)
86
+ raise error if delay.nil?
87
+
88
+ @sleeper.call(delay)
89
+ attempt += 1
90
+ end
91
+ end
92
+
93
+ # Opens an event stream (see {EventStream}); raises at once when the API refuses it.
94
+ def stream_events(path, query: nil, last_event_id: nil, max_reconnects: 5, extra_headers: nil, timeout: nil)
95
+ stream = EventStream.new(self, path, query: query, last_event_id: last_event_id,
96
+ max_reconnects: max_reconnects, extra_headers: extra_headers,
97
+ timeout: timeout)
98
+ stream.open
99
+ stream
100
+ end
101
+
102
+ # @api private
103
+ def open_stream(path, query:, last_event_id:, extra_headers:, timeout:)
104
+ headers = build_headers(auth: true, body: false, accept: "text/event-stream",
105
+ headers: { "Last-Event-ID" => last_event_id }, extra_headers: extra_headers)
106
+ req = Request.new(method: "GET", url: url(path, query), headers: headers, body: nil,
107
+ timeout: timeout || @timeout)
108
+ stream = @transport.open_stream(req)
109
+ return stream if stream.status >= 200 && stream.status < 300
110
+
111
+ body = begin
112
+ stream.read
113
+ ensure
114
+ stream.close
115
+ end
116
+ raise Client.error_from(Response.new(status: stream.status, headers: stream.headers, body: body))
117
+ end
118
+
119
+ # @api private
120
+ def pause(seconds)
121
+ @sleeper.call(seconds)
122
+ end
123
+
124
+ # Encodes one path segment (an id, or an inbox address such as support@example.com).
125
+ def self.encode_path(value)
126
+ value.to_s.b.gsub(/[^A-Za-z0-9\-._~@]/) { |c| format("%%%02X", c.ord) }
127
+ end
128
+
129
+ # Drops unset values, writes booleans as true/false and lists comma-separated in one key.
130
+ def self.encode_query(query)
131
+ pairs = (query || {}).filter_map do |key, value|
132
+ next if value.nil?
133
+
134
+ value = value.map { |item| query_text(item) }.join(",") if value.is_a?(Array)
135
+ [key.to_s, query_text(value)]
136
+ end
137
+ URI.encode_www_form(pairs)
138
+ end
139
+
140
+ def self.query_text(value)
141
+ case value
142
+ when true then "true"
143
+ when false then "false"
144
+ else value.to_s
145
+ end
146
+ end
147
+ private_class_method :query_text
148
+
149
+ # Seconds a Retry-After header asks for, or nil.
150
+ def self.retry_after(response)
151
+ header = response.header("retry-after")
152
+ return nil if header.nil? || header.empty?
153
+ return [Float(header), 0.0].max if header.match?(/\A\s*\d+(\.\d+)?\s*\z/)
154
+
155
+ [Time.httpdate(header) - Time.now, 0.0].max
156
+ rescue ArgumentError
157
+ nil
158
+ end
159
+
160
+ # Maps an error answer to the matching error, keeping the API's error shape.
161
+ def self.error_from(response)
162
+ status = response.status
163
+ name = "application_error"
164
+ message = "HTTP #{status}"
165
+ begin
166
+ body = JSON.parse(response.body.to_s)
167
+ if body.is_a?(Hash)
168
+ name = body["name"] if body["name"].is_a?(String)
169
+ message = body["message"] if body["message"].is_a?(String)
170
+ end
171
+ rescue JSON::ParserError
172
+ text = response.body.to_s.strip
173
+ message = text[0, 500] unless text.empty?
174
+ end
175
+ klass = BillionSend.error_class(status)
176
+ if klass == RateLimitError
177
+ return RateLimitError.new(message, name: name, status_code: status, response: response,
178
+ retry_after: retry_after(response))
179
+ end
180
+ klass.new(message, name: name, status_code: status, response: response)
181
+ end
182
+
183
+ private
184
+
185
+ def url(path, query)
186
+ encoded = Client.encode_query(query)
187
+ encoded.empty? ? @base_url + path : "#{@base_url}#{path}?#{encoded}"
188
+ end
189
+
190
+ def build_headers(auth:, body:, accept: "application/json", idempotency_key: nil, headers: nil,
191
+ extra_headers: nil)
192
+ out = { "Accept" => accept, "User-Agent" => "billionsend-ruby/#{VERSION}" }
193
+ if auth
194
+ if @api_key.nil? || @api_key.empty?
195
+ raise AuthenticationError.new("No API key: pass api_key: or set BILLIONSEND_API_KEY",
196
+ name: "missing_api_key")
197
+ end
198
+
199
+ out["Authorization"] = "Bearer #{@api_key}"
200
+ end
201
+ out["Content-Type"] = "application/json" if body
202
+ out["Idempotency-Key"] = idempotency_key unless idempotency_key.nil?
203
+ merge!(out, @default_headers)
204
+ merge!(out, (headers || {}).compact)
205
+ merge!(out, extra_headers || {})
206
+ out
207
+ end
208
+
209
+ # Sets headers, replacing any already there under another spelling of the name.
210
+ def merge!(headers, more)
211
+ more.each do |name, value|
212
+ headers.delete_if { |existing, _| existing.casecmp?(name.to_s) }
213
+ headers[name.to_s] = value.to_s
214
+ end
215
+ end
216
+
217
+ def parse_json(response)
218
+ return nil if response.body.nil? || response.body.empty?
219
+
220
+ JSON.parse(response.body)
221
+ rescue JSON::ParserError
222
+ content_type = response.header("content-type") || "no content type"
223
+ raise Error.new("Expected a JSON answer, got #{content_type}", status_code: response.status,
224
+ response: response)
225
+ end
226
+
227
+ # Seconds to wait before retrying after +error+, or nil to raise it.
228
+ #
229
+ # Retried: requests that are safe to repeat (GET, PUT, DELETE, or any
230
+ # request with an idempotency key) failing with 429, 5xx or no answer at
231
+ # all, and a keyed request whose first attempt is still running (409
232
+ # concurrent_idempotent_requests).
233
+ def retry_delay(attempt, error, method:, keyed:)
234
+ return nil if attempt >= @max_retries
235
+ return nil unless IDEMPOTENT_METHODS.include?(method) || keyed
236
+
237
+ status = error.status_code
238
+ unless error.is_a?(APIConnectionError)
239
+ if status == 409
240
+ return nil unless keyed && error.name == CONCURRENT_IDEMPOTENT
241
+ elsif status.nil? || (status != 429 && status < 500)
242
+ return nil
243
+ end
244
+ end
245
+ if error.response
246
+ hinted = Client.retry_after(error.response)
247
+ return hinted <= MAX_RETRY_DELAY ? hinted : nil unless hinted.nil?
248
+ end
249
+ base = [0.5 * (2.0**attempt), 8.0].min
250
+ base * (1 - (0.25 * rand))
251
+ end
252
+ end
253
+ end
@@ -0,0 +1,115 @@
1
+ # frozen_string_literal: true
2
+
3
+ module BillionSend
4
+ # Base class of every error the SDK raises.
5
+ #
6
+ # Every error carries the API's error shape: +status_code+, +name+ and
7
+ # +message+, plus the +request_id+ the API answered with (its +x-request-id+
8
+ # header). A failure that never produced an API answer (a network error, a
9
+ # timeout, an answer that is not JSON) takes the same shape, with +name+
10
+ # +"application_error"+.
11
+ class Error < StandardError
12
+ # @return [Integer, nil] the HTTP status of the answer, nil when there was none
13
+ attr_reader :status_code
14
+ # @return [String] the API's error name, such as "validation_error"
15
+ attr_reader :name
16
+ # @return [String, nil] the API's id of the request (x-request-id), when it sent one
17
+ attr_reader :request_id
18
+ # @return [BillionSend::Response, nil] the HTTP answer, when there was one
19
+ attr_reader :response
20
+
21
+ def initialize(message, name: "application_error", status_code: nil, response: nil)
22
+ super(message)
23
+ @api_message = message
24
+ @name = name
25
+ @status_code = status_code
26
+ @response = response
27
+ @request_id = response&.header("x-request-id")
28
+ end
29
+
30
+ # @return [String] a human-readable explanation, as the API wrote it
31
+ def message
32
+ @api_message
33
+ end
34
+
35
+ # "<status> <name>: <message>"
36
+ def to_s
37
+ status = status_code ? "#{status_code} " : ""
38
+ "#{status}#{name}: #{@api_message}"
39
+ end
40
+
41
+ def inspect
42
+ "#<#{self.class.name} status_code=#{status_code.inspect} name=#{name.inspect} " \
43
+ "message=#{message.inspect} request_id=#{request_id.inspect}>"
44
+ end
45
+ end
46
+
47
+ # The request never got an answer: DNS, connection, TLS or protocol failure.
48
+ class APIConnectionError < Error
49
+ def initialize(message = "Connection error")
50
+ super(message, name: "application_error")
51
+ end
52
+ end
53
+
54
+ # The request timed out.
55
+ class APITimeoutError < APIConnectionError
56
+ def initialize(message = "Request timed out")
57
+ super
58
+ end
59
+ end
60
+
61
+ # 400 or 422: the request was refused as invalid.
62
+ class ValidationError < Error; end
63
+
64
+ # 401: the API key is missing, malformed or revoked.
65
+ class AuthenticationError < Error; end
66
+
67
+ # 403: the key may not do this.
68
+ class PermissionDeniedError < Error; end
69
+
70
+ # 404: no such resource.
71
+ class NotFoundError < Error; end
72
+
73
+ # 409: the request conflicts with the current state (or an idempotency key).
74
+ class ConflictError < Error; end
75
+
76
+ # 429: too many requests; +retry_after+ holds the server's hint in seconds.
77
+ class RateLimitError < Error
78
+ # @return [Float, nil]
79
+ attr_reader :retry_after
80
+
81
+ def initialize(message, name: "rate_limit_exceeded", status_code: 429, response: nil, retry_after: nil)
82
+ super(message, name: name, status_code: status_code, response: response)
83
+ @retry_after = retry_after
84
+ end
85
+ end
86
+
87
+ # 5xx: the API failed to answer the request.
88
+ class APIError < Error; end
89
+
90
+ # A webhook delivery whose signature, timestamp or headers do not check out.
91
+ class WebhookVerificationError < Error
92
+ def initialize(message)
93
+ super(message, name: "webhook_verification_error")
94
+ end
95
+ end
96
+
97
+ BY_STATUS = {
98
+ 400 => ValidationError,
99
+ 401 => AuthenticationError,
100
+ 403 => PermissionDeniedError,
101
+ 404 => NotFoundError,
102
+ 409 => ConflictError,
103
+ 422 => ValidationError
104
+ }.freeze
105
+ private_constant :BY_STATUS
106
+
107
+ # The error class of an HTTP status.
108
+ def self.error_class(status)
109
+ return BY_STATUS[status] if BY_STATUS.key?(status)
110
+ return RateLimitError if status == 429
111
+ return APIError if status >= 500
112
+
113
+ Error
114
+ end
115
+ end