prontuno 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: 693d991a3c76ce8136d0d8aa176c971554ea4693359516d23d60b7fd3449b470
4
+ data.tar.gz: e5fbdd1a335bee749536a064f0b891b0823719dbbe33059a390a16863351776a
5
+ SHA512:
6
+ metadata.gz: cccd90aad8b441326dbd565c1f64b801c78babafadcd3bd17dbaf93b4e34341c625477587cdd20f7ea3ee4a978b6199815ddb110fc514e16badefaaa1226e391
7
+ data.tar.gz: 9f1172380eeccf608335422350a962ced6f6c37f4ebfab5a0c5f4e798bdbb6f14b0b65ce36f42a7ec3a255f4f4480e4bc4608bfebdfe60087e21bc3ab39fca8e
data/LICENSE.md ADDED
@@ -0,0 +1,9 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) Prontuno
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,495 @@
1
+ # Prontuno Ruby SDK
2
+
3
+ Ruby client for the [Prontuno API](https://prontuno.com/api-reference/general/introduction/). It supports email delivery, sending domains, suppressions, webhook endpoints, API keys, SMTP credentials, usage, cursor pagination, and signed webhook events.
4
+
5
+ ## Installation
6
+
7
+ Add the gem to your Gemfile:
8
+
9
+ ```ruby
10
+ gem "prontuno"
11
+ ```
12
+
13
+ Or install it directly:
14
+
15
+ ```bash
16
+ gem install prontuno
17
+ ```
18
+
19
+ Ruby 3.1 or newer is required. The SDK has no runtime dependencies: it uses Ruby's standard `net/http`, `json`, `openssl`, and `uri` libraries.
20
+
21
+ ## Quick start
22
+
23
+ Prontuno has two kinds of API key: a **sending key**, which can only send email from one verified domain, and a **management key**, which can do everything else. Give the client both and it uses the right one for each call:
24
+
25
+ ```ruby
26
+ require "prontuno"
27
+ require "securerandom"
28
+
29
+ prontuno = Prontuno::Client.new(
30
+ sending_key: ENV["PRONTUNO_SENDING_KEY"], # emails.send and emails.send_batch
31
+ management_key: ENV["PRONTUNO_MANAGEMENT_KEY"] # everything else
32
+ )
33
+
34
+ result = prontuno.emails.send(
35
+ {
36
+ from: "Acme <hello@mg.example.com>",
37
+ to: "ada@example.com",
38
+ subject: "Welcome to Acme",
39
+ html: "<h1>Welcome!</h1>"
40
+ },
41
+ idempotency_key: SecureRandom.uuid
42
+ )
43
+
44
+ puts result[:emails]
45
+ ```
46
+
47
+ Requests and responses use the API's snake_case field names, so they match the Prontuno API directly. Responses are Hashes with Symbol keys, for example `result[:emails][0][:id]`. Request fields can use Symbol or String keys.
48
+
49
+ Pass an email as a Hash in braces, then any request options as keywords. Without braces, Ruby treats the email's fields as keyword arguments, and the SDK raises an `ArgumentError` that says so.
50
+
51
+ ## API keys and routing
52
+
53
+ | Method | Key used |
54
+ | -------------------------------------------------------------- | ---------------- |
55
+ | `emails.send`, `emails.send_batch` | `sending_key` |
56
+ | Everything else, including `emails.list` and `emails.retrieve` | `management_key` |
57
+
58
+ - **One key for everything:** `Prontuno::Client.new(api_key)` or `Prontuno::Client.new(api_key: api_key)` uses that key for every request, for example a send-only app with just a sending key. `sending_key` and `management_key` take precedence over `api_key`.
59
+ - **Missing keys fail early:** calling a method whose key isn't configured raises a `Prontuno::ConfigError` before any request is made. A send-only client calling `domains.list` gets "GET /domains requires a management API key; pass management_key (or api_key) when creating the client" instead of a `403` from the API.
60
+ - **Blank keys count as unset**, so an empty environment variable doesn't send an empty `Authorization` header.
61
+ - **Several sending domains:** each sending key belongs to one domain. Use `with_sending_key` to get a client for another domain that keeps all other settings, including the management key:
62
+
63
+ ```ruby
64
+ billing = prontuno.with_sending_key(ENV["PRONTUNO_BILLING_SENDING_KEY"])
65
+ billing.emails.send({ from: "billing@billing.example.com", to: "ada@example.com", subject: "Invoice", text: "Hi" })
66
+ ```
67
+
68
+ ## Configuration
69
+
70
+ ```ruby
71
+ prontuno = Prontuno::Client.new(
72
+ sending_key: ENV["PRONTUNO_SENDING_KEY"],
73
+ management_key: ENV["PRONTUNO_MANAGEMENT_KEY"],
74
+ base_url: "https://api.prontuno.net/v1",
75
+ timeout: 30, # seconds, per attempt
76
+ max_retries: 2,
77
+ max_response_size: 10 * 1024 * 1024, # bytes
78
+ app_info: "my-app/1.2.0"
79
+ )
80
+ ```
81
+
82
+ `app_info` identifies your application in Prontuno's logs. It's added after the SDK's own User-Agent, so requests are sent as `prontuno-ruby/0.1.0 my-app/1.2.0`. It must be a single line.
83
+
84
+ The base URL defaults to `https://api.prontuno.net/v1`. To point every client at a different endpoint without code changes, set `PRONTUNO_BASE_URL` in the environment; an explicit `base_url` option takes precedence, and a blank value falls back to the default.
85
+
86
+ Custom API endpoints must use HTTPS. Plain HTTP is only accepted for `localhost`, `127.0.0.1`, and `[::1]`.
87
+
88
+ GET and DELETE requests are retried for transient responses (`408`, `429`, and `5xx`), network errors, and timeouts. POST send requests are retried only when an `idempotency_key` is present, including while the API reports `409 idempotency_request_in_progress`; other POST and PATCH requests are never automatically retried. Retries back off exponentially from 0.5 seconds up to 5 seconds, with jitter. The timeout applies to each attempt, so waiting between retries doesn't count against it; `Retry-After` is honoured up to 60 seconds. If a DELETE is retried after an attempt whose outcome is unknown (a network error, timeout, `408`, or `5xx`) and the retry finds the resource already gone (`404`, or `409 already_revoked`), the call succeeds. Identifiers are checked before any request, so an empty ID raises a `Prontuno::ConfigError`. Responses are limited to 10 MiB by default; use `max_response_size` to choose a different positive byte limit.
89
+
90
+ The metadata for the most recently completed response is available on `prontuno.last_response`, including the request ID and rate-limit values:
91
+
92
+ ```ruby
93
+ prontuno.last_response.request_id
94
+ prontuno.last_response.rate_limit # => #<struct Prontuno::RateLimit limit=100, remaining=99, reset=42>
95
+ ```
96
+
97
+ A client is safe to share between threads, but `last_response` reflects whichever request finished last.
98
+
99
+ ### Custom transports
100
+
101
+ The client sends requests with `Net::HTTP` by default, opening a new connection per attempt. To use another HTTP library, or to stub requests in your own tests, pass any object with a `call(request)` method that returns a `Prontuno::Transport::Response`:
102
+
103
+ ```ruby
104
+ transport = lambda do |request|
105
+ # request.http_method, request.url, request.headers, request.body,
106
+ # request.timeout (seconds), request.max_response_size (bytes)
107
+ Prontuno::Transport::Response.new(status: 200, headers: { "content-type" => "application/json" },
108
+ body: '{"data":[],"pagination":{"limit":20,"has_more":false,"next_cursor":null}}')
109
+ end
110
+
111
+ prontuno = Prontuno::Client.new("test-key", transport: transport)
112
+ ```
113
+
114
+ The client still applies retries, the response size limit, and error handling to the transport's responses. A transport should raise `Prontuno::TimeoutError` (or any `Timeout::Error`) when an attempt runs past `request.timeout`; other exceptions are reported as `Prontuno::ConnectionError`.
115
+
116
+ ## Emails
117
+
118
+ ### Send one email
119
+
120
+ ```ruby
121
+ prontuno.emails.send(
122
+ {
123
+ from: "Acme <hello@mg.example.com>",
124
+ to: ["ada@example.com", "grace@example.com"],
125
+ cc: "team@example.com",
126
+ reply_to: "support@example.com",
127
+ subject: "Your report",
128
+ text: "The report is attached.",
129
+ headers: { "X-Entity-Ref-ID" => "report-123" },
130
+ attachments: [
131
+ {
132
+ filename: "report.pdf",
133
+ content: File.binread("report.pdf"),
134
+ content_type: "application/pdf"
135
+ }
136
+ ]
137
+ }
138
+ )
139
+ ```
140
+
141
+ How attachment `content` is sent depends on what you pass:
142
+
143
+ | `content` | Sent as |
144
+ | ------------------------------------------------------------------------------ | ---------------------------------------------------------------------------- |
145
+ | A binary String (`Encoding::BINARY`, as returned by `File.binread` or `String#b`) | Base64-encoded by the SDK, with `encoding: "base64"` |
146
+ | An IO (`File.open("report.pdf", "rb")`, `StringIO`, anything with `read`) | Read, then base64-encoded by the SDK, with `encoding: "base64"` |
147
+ | Any other String | As it is. The API reads it as base64 unless you set `encoding` |
148
+
149
+ So pass a base64 String as it is, and for plain text set `encoding: "utf8"`:
150
+
151
+ ```ruby
152
+ { filename: "notes.txt", content: "Hello!", encoding: "utf8" }
153
+ ```
154
+
155
+ A UTF-8 String without `encoding` is **not** encoded for you, because the API expects it to already be base64. Read files with `File.binread` (or open them with `"rb"`) so their bytes are encoded rather than misread as text.
156
+
157
+ Every email needs a `text` body, an `html` body, or both. Each email can have up to 100 recipients across `to`, `cc`, and `bcc`, and must be 25 MB or less once encoded with its attachments (larger emails are rejected with `413 message_too_large`). A batch holds up to 1,000 emails; if any item is invalid, nothing is sent.
158
+
159
+ ### Send a batch
160
+
161
+ ```ruby
162
+ prontuno.emails.send_batch(
163
+ [
164
+ { from: "hello@mg.example.com", to: "ada@example.com", subject: "Hello", text: "Hi Ada" },
165
+ { from: "hello@mg.example.com", to: "grace@example.com", subject: "Hello", text: "Hi Grace" }
166
+ ],
167
+ idempotency_key: SecureRandom.uuid
168
+ )
169
+ ```
170
+
171
+ ### Retrieve and list
172
+
173
+ ```ruby
174
+ email = prontuno.emails.retrieve("email_01kx...")
175
+ puts email[:status], email[:text], email[:html] # bodies are nil when absent or unavailable
176
+
177
+ page = prontuno.emails.list(limit: 50, status: "delivered", domain_id: "dom_01kx...")
178
+ page[:data] # => [{ id: "email_01kx...", status: "delivered", ... }, ...]
179
+ page[:pagination] # => { limit: 50, has_more: true, next_cursor: "..." }
180
+
181
+ prontuno.emails.list_all(status: "bounced").each do |email|
182
+ puts email[:id], email[:rejection_reason]
183
+ end
184
+ ```
185
+
186
+ `list_all` fetches pages as you iterate. With a block it yields every item; without one it returns an `Enumerator`, so `prontuno.domains.list_all.first(5)` only fetches the pages it needs, and `.lazy` gives a lazy chain. Each iteration starts again from the first page.
187
+
188
+ Automatic pagination rejects repeated cursors and inconsistent pagination metadata with a `Prontuno::ConnectionError`. It reads at most 1,000 pages by default; pass `max_pages:` to `list_all` to choose a different positive limit. Pass `cursor:` to resume from a cursor.
189
+
190
+ `retrieve` returns the full email, including its stored `text` and `html` bodies and its `attachments`. List results contain only the status and metadata, so call `retrieve` when you need the content.
191
+
192
+ ### Attachments
193
+
194
+ Attachments on a sent email come with a short-lived signed `download_url` that is valid for one hour, until `expires_at`. Both are `nil` while a file hasn't finished uploading, and `emails.attachments.retrieve` raises a `403 attachment_unavailable` until it has.
195
+
196
+ ```ruby
197
+ page = prontuno.emails.attachments.list("email_01kx...", limit: 20)
198
+
199
+ prontuno.emails.attachments.list_all("email_01kx...").each do |attachment|
200
+ puts attachment[:filename], attachment[:size], attachment[:download_url]
201
+ end
202
+
203
+ # Fetch a fresh link for one attachment, then download it.
204
+ attachment = prontuno.emails.attachments.retrieve("email_01kx...", "att_01kx...")
205
+ if attachment[:download_url]
206
+ file = Net::HTTP.get(URI(attachment[:download_url]))
207
+ end
208
+ ```
209
+
210
+ Download links expire, so request a fresh one with `emails.attachments.retrieve` (or `emails.retrieve`) instead of storing them. Treat `download_url` as opaque: it may be served from Prontuno's CDN or directly from storage, so don't parse it or depend on its host or path. Fetch it directly, without your API key. The file downloads under its original filename. `content_disposition` (`inline` or `attachment`) describes how the file was attached to the email, not how the link is served. A temporary storage outage returns a retryable `503 storage_unavailable`, which the SDK retries automatically.
211
+
212
+ ## Domains
213
+
214
+ Fields for `create` and `update` methods can be passed as keywords or as a Hash: `create(domain: "x")` and `create({ domain: "x" }, timeout: 5)` are equivalent apart from the timeout.
215
+
216
+ ```ruby
217
+ domain = prontuno.domains.create(domain: "mg.example.com")
218
+ puts domain[:dns_records]
219
+
220
+ current = prontuno.domains.retrieve(domain[:id])
221
+ page = prontuno.domains.list(limit: 50)
222
+
223
+ prontuno.domains.list_all.each do |item|
224
+ puts item[:domain], item[:is_verified]
225
+ end
226
+ ```
227
+
228
+ ## Suppressions
229
+
230
+ ```ruby
231
+ suppression = prontuno.suppressions.create(email: "user@example.com")
232
+
233
+ prontuno.suppressions.retrieve(suppression[:id])
234
+ prontuno.suppressions.retrieve("user@example.com")
235
+ prontuno.suppressions.delete(suppression[:id])
236
+
237
+ prontuno.suppressions.list_all(email: "user@example.com").each do |item|
238
+ puts item[:email], item[:type]
239
+ end
240
+ ```
241
+
242
+ Only manual suppressions can be deleted through the API.
243
+
244
+ ## Webhook endpoints
245
+
246
+ ```ruby
247
+ webhook = prontuno.webhooks.create(
248
+ name: "Production app",
249
+ url: "https://example.com/webhooks/prontuno",
250
+ events: ["email.delivered", "email.bounced", "email.complained"]
251
+ # Omit domain_id for a team-wide webhook, or scope it to one verified domain:
252
+ # domain_id: "dom_01kx..."
253
+ )
254
+
255
+ # The signing secret is returned only once. Store it securely.
256
+ puts webhook[:secret]
257
+
258
+ prontuno.webhooks.retrieve(webhook[:id])
259
+ prontuno.webhooks.update(webhook[:id], is_enabled: false)
260
+ # Switching scope needs is_global as well as domain_id:
261
+ prontuno.webhooks.update(webhook[:id], is_global: false, domain_id: "dom_01kx...")
262
+
263
+ secret = prontuno.webhooks.rotate_secret(webhook[:id])[:secret]
264
+
265
+ prontuno.webhooks.list_all.each do |item|
266
+ puts item[:name], item[:events].inspect
267
+ end
268
+
269
+ prontuno.webhooks.delete(webhook[:id])
270
+ ```
271
+
272
+ ### Event types
273
+
274
+ | Event | Sent when |
275
+ | ------------------ | ----------------------------------------------------------------------------------------------------------- |
276
+ | `email.sent` | Prontuno's outbound mail server accepted the email for delivery. |
277
+ | `email.delivered` | The recipient's mail server accepted the email. |
278
+ | `email.deferred` | The recipient's mail server temporarily refused the email. Delivery is retried. |
279
+ | `email.bounced` | The recipient's mail server permanently refused the email. |
280
+ | `email.expired` | Delivery was retried until the retry period ran out without success. |
281
+ | `email.rejected` | Prontuno refused the email before sending it, for example because the recipient is on the suppression list. |
282
+ | `email.complained` | The recipient reported the email as spam to their mailbox provider. |
283
+
284
+ Subscribe to any combination with `events`. Each event's `data` describes the email it relates to. The list is also available as `Prontuno::Webhook::EVENT_TYPES`.
285
+
286
+ Rotating a secret invalidates the previous one immediately, so update your receiver right away.
287
+
288
+ ## API keys
289
+
290
+ Managing API keys requires a `management` API key.
291
+
292
+ ```ruby
293
+ # Key permissions (scopes) come from its type and can't be chosen individually.
294
+ sending_key = prontuno.api_keys.create(
295
+ name: "Production sender",
296
+ type: "sending", # email:send from one verified domain
297
+ domain_id: "dom_01kx..."
298
+ )
299
+
300
+ # The plaintext key is returned only once. Store it securely.
301
+ puts sending_key[:key]
302
+
303
+ prontuno.api_keys.create(name: "Support agent", type: "mcp")
304
+ prontuno.api_keys.create(name: "Agent that sends", type: "mcp", allow_email_sending: true, domain_id: "dom_01kx...")
305
+ prontuno.api_keys.create(name: "Ops automation", type: "management")
306
+
307
+ prontuno.api_keys.retrieve(sending_key[:id]) # includes revoked keys
308
+
309
+ prontuno.api_keys.list_all(status: "all", type: "sending").each do |key|
310
+ puts key[:name], key[:status], key[:last_used_at]
311
+ end
312
+
313
+ # Requests using a revoked key fail immediately. Revoking twice raises 409 already_revoked.
314
+ prontuno.api_keys.revoke(sending_key[:id])
315
+ ```
316
+
317
+ | Type | Scopes |
318
+ | ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
319
+ | `sending` | `email:send` for one verified domain (`domain_id` required) |
320
+ | `mcp` | Account scopes such as `domains:*`, `emails:read`, `suppressions:*`, `usage:read`, and `webhooks:*`, plus `email:send` with `allow_email_sending: true` and a `domain_id` |
321
+ | `management` | The `mcp` account scopes without `email:send`, plus `api_keys:*` and `smtp_credentials:*` |
322
+
323
+ `list` and `list_all` return active keys by default; pass `status: "revoked"` or `"all"` to include others.
324
+
325
+ ## SMTP credentials
326
+
327
+ ```ruby
328
+ credential = prontuno.smtp_credentials.create(name: "Legacy CRM", domain_id: "dom_01kx...")
329
+
330
+ # Use these as the SMTP login. The password is returned only once.
331
+ puts credential[:username], credential[:password]
332
+
333
+ password = prontuno.smtp_credentials.reset_password(credential[:id])[:password] # old password stops working
334
+
335
+ prontuno.smtp_credentials.retrieve(credential[:id])
336
+ prontuno.smtp_credentials.list_all(status: "all").each do |item|
337
+ puts item[:username], item[:status]
338
+ end
339
+
340
+ prontuno.smtp_credentials.revoke(credential[:id]) # SMTP logins fail immediately
341
+ ```
342
+
343
+ Creating API keys and SMTP credentials, and resetting passwords, are never retried automatically, so a timeout can't create a duplicate secret.
344
+
345
+ ## Usage
346
+
347
+ ```ruby
348
+ usage = prontuno.usage.retrieve
349
+
350
+ if usage.dig(:subscription, :is_active)
351
+ puts usage[:subscription][:recipients_remaining] # nil on the unlimited plan
352
+ end
353
+ puts usage[:credits][:balance] # prepaid credits; one covers one recipient
354
+ puts usage[:limits][:domains] # { used: 12, limit: 1000 }, limit is nil when unlimited
355
+ ```
356
+
357
+ Sends draw on the subscription allowance first while it's active, then on prepaid credits. `subscription` is `nil` when the team has no plan, and `recipients_remaining` is `0` while the subscription isn't active.
358
+
359
+ ## Errors
360
+
361
+ Every error the SDK raises inherits from `Prontuno::Error`.
362
+
363
+ ```ruby
364
+ begin
365
+ prontuno.emails.retrieve("email_missing")
366
+ rescue Prontuno::ApiError => e
367
+ e.status # 404
368
+ e.code # "not_found"
369
+ e.message # "Email not found"
370
+ e.request_id # x-request-id
371
+ e.retryable? # also available as e.retryable
372
+ e.suggested_action # for example "fix_input" or "retry_later", or nil
373
+ e.details # validation/batch details, when present
374
+ e.retry_after # seconds, when the API sends Retry-After
375
+ e.rate_limit # #<struct Prontuno::RateLimit limit=..., remaining=..., reset=...>
376
+ e.body # the parsed error body
377
+ e.headers # response headers, with lowercase names
378
+ end
379
+ ```
380
+
381
+ | Error | Raised when |
382
+ | --------------------------------------------- | --------------------------------------------------------------------------------------------------------------- |
383
+ | `Prontuno::ConfigError` | The client options or a method's arguments are invalid, or the needed API key is missing. Nothing was sent. |
384
+ | `Prontuno::ApiError` | The API answered with a non-2xx status. |
385
+ | `Prontuno::ConnectionError` | The request couldn't be completed: a network failure, an empty or invalid response, or inconsistent pagination. |
386
+ | `Prontuno::TimeoutError` | An attempt took longer than `timeout`. A subclass of `ConnectionError`. |
387
+ | `Prontuno::ResponseSizeError` | The response was larger than `max_response_size`. A subclass of `ConnectionError`, never retried. |
388
+ | `Prontuno::WebhookSignatureVerificationError` | A webhook signature is missing, malformed, stale, or doesn't match. |
389
+ | `Prontuno::WebhookPayloadError` | A verified webhook payload isn't a valid event. |
390
+
391
+ ## Webhooks
392
+
393
+ Prontuno signs the exact raw request body with HMAC-SHA256. Verify the raw body before parsing it, and don't parse and re-serialize it first.
394
+
395
+ ```ruby
396
+ event = Prontuno::Webhook.construct_event(raw_body, signature_header, ENV.fetch("PRONTUNO_WEBHOOK_SIGNING_SECRET"))
397
+ ```
398
+
399
+ `construct_event` verifies the signature, then returns the event as a Hash with Symbol keys. Event types added to Prontuno after this SDK version are returned as they are, so handle unknown `type` values with a default branch and acknowledge them.
400
+
401
+ ### Rails
402
+
403
+ ```ruby
404
+ class ProntunoWebhooksController < ActionController::API
405
+ def create
406
+ event = Prontuno::Webhook.construct_event(
407
+ request.raw_post,
408
+ request.headers["Prontuno-Signature"],
409
+ Rails.application.credentials.prontuno_webhook_signing_secret
410
+ )
411
+
412
+ case event[:type]
413
+ when "email.delivered"
414
+ Rails.logger.info("Delivered #{event[:data][:email_id]} at #{event[:data][:delivered_at]}")
415
+ when "email.bounced"
416
+ Rails.logger.info("Bounced: #{event[:data][:reason]} (#{event[:data].dig(:bounce, :type)})")
417
+ when "email.complained"
418
+ Rails.logger.info("Recipient marked the email as spam: #{event[:data][:to_email]}")
419
+ else
420
+ # Event types added after this SDK version arrive here; acknowledge them.
421
+ end
422
+
423
+ head :no_content
424
+ rescue Prontuno::WebhookSignatureVerificationError, Prontuno::WebhookPayloadError
425
+ head :bad_request
426
+ end
427
+ end
428
+ ```
429
+
430
+ ### Rack and Sinatra
431
+
432
+ ```ruby
433
+ require "sinatra"
434
+ require "prontuno"
435
+
436
+ WEBHOOK_SECRET = ENV.fetch("PRONTUNO_WEBHOOK_SIGNING_SECRET")
437
+
438
+ post "/webhooks/prontuno" do
439
+ event = Prontuno::Webhook.construct_event(
440
+ request.body.read,
441
+ request.env["HTTP_PRONTUNO_SIGNATURE"],
442
+ WEBHOOK_SECRET
443
+ )
444
+ # Use event[:event_id] to make the handler idempotent.
445
+ puts "#{event[:type]} #{event[:event_id]}"
446
+ status 204
447
+ rescue Prontuno::WebhookSignatureVerificationError, Prontuno::WebhookPayloadError
448
+ halt 400, "Invalid webhook"
449
+ end
450
+ ```
451
+
452
+ In a plain Rack app, read the body from `env["rack.input"]` and the header from `env["HTTP_PRONTUNO_SIGNATURE"]`.
453
+
454
+ The default timestamp tolerance is five minutes. Pass `tolerance: 0` to skip the timestamp check. To verify without parsing, call `Prontuno::Webhook.verify_signature(raw_body, signature, secret)`, which returns `true` or raises. `prontuno.webhooks.verify_signature` and `prontuno.webhooks.construct_event` do the same. The webhook helpers don't need an API key. Signatures are compared in constant time, and a header with several `v1` signatures passes if any of them matches.
455
+
456
+ Webhook requests include these useful headers:
457
+
458
+ - `Prontuno-Event`
459
+ - `Prontuno-Event-Id`
460
+ - `Prontuno-Webhook-Id`
461
+ - `Prontuno-Signature` (`t=<unix-seconds>,v1=<hex-hmac>`)
462
+ - `Prontuno-Delivery-Attempt`
463
+ - `Idempotency-Key` (the event ID)
464
+
465
+ See [Event types](#event-types) for every event and when it's sent.
466
+
467
+ Respond with any `2xx` status after processing. Use the event ID to make your handler idempotent because deliveries can be retried.
468
+
469
+ ## Request options
470
+
471
+ Every resource method accepts per-request options as keywords: a timeout, retry count, response size limit, and extra headers. `emails.send` and `emails.send_batch` also accept `idempotency_key:`.
472
+
473
+ ```ruby
474
+ prontuno.emails.retrieve(
475
+ "email_01kx...",
476
+ timeout: 10,
477
+ max_retries: 1,
478
+ max_response_size: 2 * 1024 * 1024,
479
+ headers: { "X-Correlation-Id" => "job_123" }
480
+ )
481
+ ```
482
+
483
+ Extra headers can't replace the `Authorization`, `Accept`, or `User-Agent` headers the SDK sets. Unknown options raise an `ArgumentError`.
484
+
485
+ ## Development
486
+
487
+ ```bash
488
+ bundle install
489
+ bundle exec rake # RuboCop and the test suite
490
+ bundle exec rake test # tests only; they never use the network
491
+ ```
492
+
493
+ ## License
494
+
495
+ The Prontuno Ruby SDK is open-sourced software licensed under the [MIT license](LICENSE.md).
@@ -0,0 +1,64 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Prontuno
4
+ # The Prontuno API client.
5
+ #
6
+ # @example One key for everything
7
+ # client = Prontuno::Client.new(ENV.fetch("PRONTUNO_API_KEY"))
8
+ #
9
+ # @example Separate sending and management keys
10
+ # client = Prontuno::Client.new(
11
+ # sending_key: ENV["PRONTUNO_SENDING_KEY"], # emails.send and emails.send_batch
12
+ # management_key: ENV["PRONTUNO_MANAGEMENT_KEY"] # everything else
13
+ # )
14
+ class Client
15
+ attr_reader :emails, :domains, :suppressions, :webhooks, :api_keys, :smtp_credentials, :usage
16
+
17
+ # @param api_key [String, nil] one key for every request; `sending_key` and
18
+ # `management_key` take precedence over it. May also be passed as `api_key:`.
19
+ # @param options [Hash] `api_key:`, `sending_key:`, `management_key:`, `base_url:`,
20
+ # `timeout:` (seconds), `max_retries:`, `max_response_size:` (bytes), `app_info:`,
21
+ # `transport:`, `sleeper:`
22
+ def initialize(api_key = nil, **options)
23
+ unless api_key.nil?
24
+ raise ConfigError, "Pass the API key positionally or as api_key:, not both" if options.key?(:api_key)
25
+
26
+ options = options.merge(api_key: api_key)
27
+ end
28
+ @options = options.freeze
29
+ @http = HttpClient.new(**options)
30
+ @emails = Resources::Emails.new(@http)
31
+ @domains = Resources::Domains.new(@http)
32
+ @suppressions = Resources::Suppressions.new(@http)
33
+ @webhooks = Resources::Webhooks.new(@http)
34
+ @api_keys = Resources::ApiKeys.new(@http)
35
+ @smtp_credentials = Resources::SmtpCredentials.new(@http)
36
+ @usage = Resources::Usage.new(@http)
37
+ end
38
+
39
+ # Returns a client that sends with a different domain's sending key, keeping every other
40
+ # setting, including the management key.
41
+ def with_sending_key(sending_key)
42
+ if !sending_key.is_a?(String) || sending_key.strip.empty?
43
+ raise ConfigError, "with_sending_key requires a non-empty sending key"
44
+ end
45
+
46
+ self.class.new(**@options, sending_key: sending_key)
47
+ end
48
+
49
+ # Metadata for the most recently completed response, or nil before the first one.
50
+ # @return [ResponseMetadata, nil]
51
+ def last_response
52
+ @http.last_response
53
+ end
54
+
55
+ # @return [String]
56
+ def base_url
57
+ @http.base_url
58
+ end
59
+
60
+ def inspect
61
+ "#<#{self.class.name} base_url=#{base_url.inspect}>"
62
+ end
63
+ end
64
+ end
@@ -0,0 +1,92 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Prontuno
4
+ # Rate-limit values from the `RateLimit-*` response headers. Each is nil when absent.
5
+ RateLimit = Struct.new(:limit, :remaining, :reset, keyword_init: true)
6
+
7
+ # Metadata for the most recently completed response, available on `client.last_response`.
8
+ ResponseMetadata = Struct.new(:request_id, :rate_limit, keyword_init: true)
9
+
10
+ # Base class for every error raised by the SDK.
11
+ class Error < StandardError; end
12
+
13
+ # Invalid client configuration or arguments, raised before any request is made.
14
+ class ConfigError < Error; end
15
+
16
+ # The API answered with a non-2xx status.
17
+ class ApiError < Error
18
+ attr_reader :status, :code, :request_id, :suggested_action, :details, :body, :headers,
19
+ :retry_after, :rate_limit
20
+
21
+ # @param status [Integer]
22
+ # @param body [Hash] the parsed error body (symbol keys)
23
+ # @param headers [Hash{String=>String}] response headers with lowercase names
24
+ def initialize(status:, body:, headers:)
25
+ primary = primary_error(status, body)
26
+ super(primary[:message])
27
+ @status = status
28
+ @code = primary[:code]
29
+ @request_id = headers["x-request-id"]
30
+ @retryable = primary[:retryable].nil? ? status >= 500 : primary[:retryable] == true
31
+ @suggested_action = primary[:suggested_action]
32
+ @details = body[:errors]
33
+ @body = body
34
+ @headers = headers
35
+ @retry_after = Util.integer_header(headers["retry-after"])
36
+ @rate_limit = RateLimit.new(
37
+ limit: Util.integer_header(headers["ratelimit-limit"]),
38
+ remaining: Util.integer_header(headers["ratelimit-remaining"]),
39
+ reset: Util.integer_header(headers["ratelimit-reset"])
40
+ )
41
+ end
42
+
43
+ def retryable?
44
+ @retryable
45
+ end
46
+ alias retryable retryable?
47
+
48
+ private
49
+
50
+ def primary_error(status, body)
51
+ fallback = "Prontuno API request failed with status #{status}"
52
+ error = body[:error]
53
+ return { code: "api_error", message: fallback, retryable: status >= 500 } unless error.is_a?(Hash)
54
+
55
+ code = error[:code].is_a?(String) ? error[:code] : "api_error"
56
+ message = error[:message].is_a?(String) ? error[:message] : fallback
57
+ error.merge(code: code, message: message)
58
+ end
59
+ end
60
+
61
+ # The request could not be completed: a network failure, an unusable response, or
62
+ # inconsistent pagination.
63
+ class ConnectionError < Error
64
+ def initialize(message = "Could not connect to the Prontuno API")
65
+ super
66
+ end
67
+ end
68
+
69
+ # One attempt took longer than the configured timeout.
70
+ class TimeoutError < ConnectionError
71
+ # @return [Numeric] the per-attempt timeout in seconds
72
+ attr_reader :timeout
73
+
74
+ def initialize(timeout)
75
+ @timeout = timeout
76
+ super("Prontuno API request timed out after #{timeout}s")
77
+ end
78
+ end
79
+
80
+ # The response was larger than `max_response_size`. Never retried.
81
+ class ResponseSizeError < ConnectionError
82
+ def initialize(max_response_size)
83
+ super("Prontuno API response exceeded the maximum size of #{max_response_size} bytes")
84
+ end
85
+ end
86
+
87
+ # A webhook's `Prontuno-Signature` header is missing, malformed, stale, or doesn't match.
88
+ class WebhookSignatureVerificationError < Error; end
89
+
90
+ # A verified webhook payload isn't valid JSON or doesn't match the event schema.
91
+ class WebhookPayloadError < Error; end
92
+ end