ahasend-rails 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: 71f6cd21dba192c6d74f88734ad6e2d3704cbe71353ca3a0d3e48647024f101f
4
+ data.tar.gz: 0052500c2508a616c379bb44274e963495d7ff66214e1715c3975c62e304c568
5
+ SHA512:
6
+ metadata.gz: 25a576108e84c6acf34d5dfcdf862468bfc942d9312eb2bb27269092262ce6d512db82ff4c21dae5ccdb846ba3c42ab2f59e93121f76b7bd110882661acbdf4e
7
+ data.tar.gz: a348d234fe8c4507c84248e98f2088aa360477b6602c2e8e29feea8db0d1b27ec0b99937a86df1c5efa830ed29526b1e4a0de98f3597350d01fa4ddf0080ecb2
data/CHANGELOG.md ADDED
@@ -0,0 +1,49 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses
5
+ [Semantic Versioning](https://semver.org/).
6
+
7
+ ## [Unreleased]
8
+
9
+ ## [0.1.0] - 2026-11-25
10
+
11
+ First release.
12
+
13
+ ### Added
14
+
15
+ - `AhaSend::DeliveryMethod`: ActionMailer / Mail delivery method that sends
16
+ through the AhaSend v2 HTTP API (`delivery_method = :ahasend`), with a
17
+ Railtie registering it and `config.action_mailer.ahasend_settings`.
18
+ - Endpoint selection: `/messages` for To-only and Bcc-only mail (one copy per
19
+ recipient), `/messages/conversation` for To with Cc/Bcc. An explicit
20
+ `smtp_envelope_to` (e.g. from a redirecting interceptor) is honoured: mail is
21
+ sent only to the envelope addresses.
22
+ - Attachments and inline images (Content-ID sent in angle brackets, as the API
23
+ requires), custom headers, text/HTML/AMP bodies.
24
+ - Per-message options via `AhaSend-*` headers (AhaSend's SMTP header names
25
+ where SMTP has one) or `message.ahasend`: tags, tracking, retention, sandbox,
26
+ sandbox_result, substitutions, schedule, idempotency_key; settings-level
27
+ defaults for all but the idempotency key. Nested options merge field by field.
28
+ - Validation with clear errors: `ConfigurationError` for settings (checked on
29
+ first send, not at boot), `MessageError` for malformed or unknown option
30
+ headers/values and for messages the API cannot represent (Cc without To,
31
+ substitutions with Cc/Bcc, more than 100 recipients or 50 To+Cc+Bcc).
32
+ - `AhaSend::Client`: automatic `Idempotency-Key`; retries with `Retry-After` or
33
+ jittered exponential backoff on 429, 5xx, network errors and in-progress
34
+ idempotent requests (409), reusing the same key and body; typed errors
35
+ following the API v2 contract (`ValidationError`, `AuthenticationError`,
36
+ `ForbiddenError`, `IdempotencyError`, `RateLimitError`, `ServerError`, ...).
37
+ - `AhaSend::DeliveryResult` with per-recipient status and `replayed?`;
38
+ responses are validated against the documented shape
39
+ (`UnexpectedResponseError` otherwise). A partial delivery (some recipients
40
+ rejected) returns normally and reports the rejections, so a retried job
41
+ cannot send duplicates; `DeliveryError` only when every recipient is
42
+ rejected. Each entry has the message's `id` and its `message_id_header`;
43
+ the Message-ID header is written back to the mail.
44
+ - `deliver.ahasend` ActiveSupport notification linking Rails' Message-ID to
45
+ AhaSend's IDs, per-recipient statuses and rejected recipients.
46
+ - Supported: Ruby 3.1+, Rails 7.0–8.1, and the plain `mail` gem (2.7+) without Rails.
47
+
48
+ [Unreleased]: https://github.com/AhaSend/ahasend-rails/compare/v0.1.0...HEAD
49
+ [0.1.0]: https://github.com/AhaSend/ahasend-rails/releases/tag/v0.1.0
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 AhaSend
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
13
+ all 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
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,328 @@
1
+ # ahasend-rails
2
+
3
+ [![CI](https://github.com/AhaSend/ahasend-rails/actions/workflows/main.yml/badge.svg)](https://github.com/AhaSend/ahasend-rails/actions/workflows/main.yml)
4
+
5
+ ActionMailer delivery method for the [AhaSend](https://ahasend.com) email API.
6
+ Your existing mailers keep working unchanged; mail goes out over AhaSend's
7
+ HTTPS API (v2) instead of SMTP, with attachments, inline images, tags,
8
+ open/click tracking, scheduling, sandbox mode and safe automatic retries.
9
+
10
+ Works with Rails 7.0 – 8.1 on Ruby 3.1+, and with the plain
11
+ [`mail`](https://github.com/mikel/mail) gem outside Rails.
12
+
13
+ ## Installation
14
+
15
+ ```ruby
16
+ # Gemfile
17
+ gem "ahasend-rails"
18
+ ```
19
+
20
+ You need an AhaSend **API key** allowed to send from your domain (the
21
+ `messages:send:all` role, or the send role for that domain) and your
22
+ **account ID** (both in the AhaSend dashboard under *API Keys*), plus a
23
+ [verified sending domain](https://ahasend.com/docs/domains).
24
+
25
+ ## Rails setup
26
+
27
+ ```ruby
28
+ # config/environments/production.rb
29
+ config.action_mailer.delivery_method = :ahasend
30
+ config.action_mailer.ahasend_settings = {
31
+ api_key: Rails.application.credentials.dig(:ahasend, :api_key),
32
+ account_id: Rails.application.credentials.dig(:ahasend, :account_id)
33
+ }
34
+ ```
35
+
36
+ That's it. `UserMailer.welcome(user).deliver_later` now sends through AhaSend.
37
+
38
+ Use `deliver_later` inside web requests. `deliver_now` waits for the API,
39
+ including retries: with the default settings a single delivery can block for
40
+ about two to three minutes in the worst case (three attempts, each allowed
41
+ 10 s to connect and 30 s to read, plus up to 30 s between attempts). Lower
42
+ `max_retries` and the timeouts if you must send inline.
43
+
44
+ ### Settings reference
45
+
46
+ | Key | Default | Description |
47
+ | --- | --- | --- |
48
+ | `api_key` | — | **Required.** AhaSend API key (`aha-sk-...`). |
49
+ | `account_id` | — | **Required.** The account the key belongs to. |
50
+ | `base_url` | `https://api.ahasend.com` | An `http(s)` URL; override for testing against a mock server. |
51
+ | `open_timeout` | `10` | Seconds (positive number) to wait for the TCP/TLS connection. |
52
+ | `read_timeout` | `30` | Seconds (positive number) to wait for the response. |
53
+ | `max_retries` | `2` | Retries (Integer ≥ 0) on 429, 5xx, network errors and in-progress requests (see [Retries](#retries-and-idempotency)). |
54
+ | `sandbox`, `tags`, `tracking`, `retention`, `schedule`, `sandbox_result`, `substitutions` | — | Defaults for every message; the same keys and values as the [per-message options](#per-message-options). |
55
+
56
+ Settings are checked the first time a message is sent, not when the app
57
+ boots, so test and development environments using another delivery method
58
+ need no AhaSend credentials. A missing or invalid setting, or an unknown key
59
+ (a typo such as `sandbx:`), raises `AhaSend::ConfigurationError`.
60
+
61
+ A common pattern is to turn on sandbox mode for staging so the API validates
62
+ everything but delivers nothing:
63
+
64
+ ```ruby
65
+ # config/environments/staging.rb
66
+ config.action_mailer.ahasend_settings = { api_key: ..., account_id: ..., sandbox: true }
67
+ ```
68
+
69
+ ## Per-message options
70
+
71
+ AhaSend features that have no equivalent in a standard email are set either
72
+ through `AhaSend-*` headers or through `message.ahasend` in Ruby. The headers
73
+ are consumed by the gem and never sent to the API.
74
+
75
+ ```ruby
76
+ class UserMailer < ApplicationMailer
77
+ def welcome(user)
78
+ headers["AhaSend-Tags"] = "welcome,onboarding"
79
+ headers["AhaSend-Track-Opens"] = "true"
80
+ headers["AhaSend-Idempotency-Key"] = "welcome-#{user.id}"
81
+
82
+ mail(to: user.email, subject: "Welcome!")
83
+ end
84
+
85
+ def invoice(invoice)
86
+ message = mail(to: invoice.customer_email, subject: "Your invoice")
87
+ message.ahasend.tags = ["invoice"]
88
+ message.ahasend.schedule = { first_attempt: invoice.send_at } # a Time or an RFC 3339 String
89
+ message.ahasend.retention = { metadata: 30, data: 7 }
90
+ message
91
+ end
92
+ end
93
+ ```
94
+
95
+ Set options inside the mailer action, as above. `deliver_later` queues the
96
+ mailer's arguments, not the built message, so options must be set where the
97
+ message is built to survive the job.
98
+
99
+ | Header | `message.ahasend` | Value |
100
+ | --- | --- | --- |
101
+ | `AhaSend-Tags` | `tags` | Comma-separated list / `Array<String>` |
102
+ | `AhaSend-Track-Opens`, `AhaSend-Track-Clicks` | `tracking` | `true`/`false` / `{ open: true, click: false }` |
103
+ | `AhaSend-Metadata-Retention`, `AhaSend-Data-Retention` | `retention` | Whole days / `{ metadata: 30, data: 0 }` |
104
+ | `AhaSend-Sandbox` | `sandbox` | `true`/`false` |
105
+ | `AhaSend-Sandbox-Result` | `sandbox_result` | `deliver`, `bounce`, `defer`, `fail` or `suppress` |
106
+ | `AhaSend-Substitutions` | `substitutions` | JSON object / `Hash` of template variables for `{{ name }}` in the subject and body |
107
+ | `AhaSend-Schedule-First-Attempt`, `AhaSend-Schedule-Expires` | `schedule` | RFC 3339 timestamps / `{ first_attempt:, expires: }` (Strings or Times) |
108
+ | `AhaSend-Idempotency-Key` | `idempotency_key` | A unique String of up to 255 characters (see [Retries](#retries-and-idempotency)) |
109
+
110
+ - The first five rows use the same header names as AhaSend's
111
+ [SMTP special headers](https://ahasend.com/docs/smtp/special-headers), so an
112
+ app moving from SMTP keeps working. Header names are case-insensitive.
113
+ - `true`/`false` also accept `1`/`0`, `yes`/`no` and `on`/`off`.
114
+ - **Precedence:** settings defaults < headers < `message.ahasend`. Nested
115
+ options merge field by field: with a default `retention: { metadata: 30, data: 0 }`,
116
+ a message that sets only `AhaSend-Metadata-Retention: 1` sends
117
+ `{ metadata: 1, data: 0 }`. String and Symbol keys are equivalent.
118
+ - **Mistakes raise instead of being ignored:** a malformed value
119
+ (`AhaSend-Sandbox: tru`, a non-numeric retention, invalid JSON) or an
120
+ unknown `AhaSend-*` header raises `AhaSend::MessageError` naming the header,
121
+ before anything is sent.
122
+
123
+ Any other custom header (`X-Campaign`, `List-Unsubscribe`, ...) is forwarded
124
+ to AhaSend as a message header.
125
+
126
+ ## How messages map to the API
127
+
128
+ | The message has | Sent with | Result |
129
+ | --- | --- | --- |
130
+ | To only | `POST /messages` | Each To address receives its own copy; recipients do not see one another. |
131
+ | To plus Cc and/or Bcc | `POST /messages/conversation` | One message with the full To/Cc/Bcc headers, the way a mail client sends it. |
132
+ | Bcc only (no To) | `POST /messages` | Each Bcc address receives its own copy, so no recipient sees another. |
133
+ | An explicit `smtp_envelope_to` that differs from To/Cc/Bcc | `POST /messages` | Sent **only** to the envelope addresses, one copy each; the header recipients receive nothing. This is how an interceptor redirects mail (for example to a test inbox). |
134
+ | Cc but no To | — | `AhaSend::MessageError`: AhaSend needs a To address alongside Cc. |
135
+ | More than 100 recipients on `/messages`, or more than 50 To + Cc + Bcc on a conversation | — | `AhaSend::MessageError`, before anything is sent. Split the send into batches. |
136
+ | Substitutions plus Cc or Bcc | — | `AhaSend::MessageError`: the conversation endpoint does not render substitutions, so the template would go out with its `{{ }}` placeholders. Send substitutions without Cc/Bcc. |
137
+
138
+ - `from`, `reply_to`, `subject`, text/HTML/AMP parts and attachments are
139
+ mapped directly.
140
+ - Inline images (`attachments.inline[...]`, referenced from the HTML with
141
+ `attachments["logo.png"].url`) are sent with their MIME Content-ID in angle
142
+ brackets, which is what makes them render inline.
143
+ - AhaSend assigns the `Message-ID` header; after delivery it is available as
144
+ `message.message_id`.
145
+
146
+ ## Delivery results and errors
147
+
148
+ `deliver_now` / `deliver!` return as usual. The delivery method itself returns
149
+ an `AhaSend::DeliveryResult` with one entry per recipient:
150
+
151
+ ```ruby
152
+ result = AhaSend::DeliveryMethod.new(settings).deliver!(mail)
153
+ result.id # => "4f1e..." (the message's ID)
154
+ result.message_id_header # => "<4f1e...@yourdomain.com>" (the email's Message-ID header)
155
+ result.status # => "queued" (or "scheduled")
156
+ result.replayed? # => true when the API answered from its idempotency store
157
+ result.messages # => [#<struct id:, message_id_header:, status:, recipient:, error:, schedule:>, ...]
158
+ result.partial? # => true when some recipients were accepted and others rejected
159
+ result.failed # => the rejected entries (see Partial delivery below)
160
+ ```
161
+
162
+ `id` is the ID that AhaSend's Get Message and Cancel Message endpoints take,
163
+ and that message webhooks carry as `data.id`. `message_id_header` is the
164
+ `Message-ID` header of the email itself.
165
+
166
+ Errors are typed, so you can rescue what you care about:
167
+
168
+ | Error | When |
169
+ | --- | --- |
170
+ | `AhaSend::ConfigurationError` | A setting is missing, invalid or unknown |
171
+ | `AhaSend::MessageError` | The message cannot be sent as built (see above, including the recipient limits); raised before any request |
172
+ | `AhaSend::ValidationError` | 400: the API rejected the request (`error.body` has its message) |
173
+ | `AhaSend::AuthenticationError` | 401: the API key is missing or invalid |
174
+ | `AhaSend::ForbiddenError` | 403: the key cannot send from this domain, the account cannot send, or sending from the domain is paused |
175
+ | `AhaSend::IdempotencyError` | 409: a request with the same Idempotency-Key is still in progress, after retries (`error.in_progress?`, `error.retry_after`); or 422: the key was already used for a different request |
176
+ | `AhaSend::RateLimitError` | 429 after retries are exhausted (`error.retry_after`) |
177
+ | `AhaSend::ServerError` | 5xx after retries are exhausted |
178
+ | `AhaSend::ConnectionError` | No HTTP response (timeout, DNS, TLS); the cause is in `error.cause` |
179
+ | `AhaSend::UnexpectedResponseError` | A 2xx response that is not the documented message list. **Delivery state unknown**: the email may have gone out |
180
+ | `AhaSend::DeliveryError` | The API rejected **every** recipient (`status: "error"` for each, e.g. a 553 for a blocked recipient domain); nothing was sent. `error.result` has the per-recipient errors |
181
+
182
+ All of them inherit from `AhaSend::Error`. With ActionMailer's default
183
+ `raise_delivery_errors = true` they propagate out of `deliver_now` (and fail the
184
+ job for `deliver_later`).
185
+
186
+ ### Partial delivery
187
+
188
+ The API can accept some recipients of a message and reject others in the same
189
+ response. That is **not** raised: the accepted recipients are already being
190
+ sent, and a failed `deliver_later` job would be retried with a new
191
+ Idempotency-Key, sending them a second copy. The rejected recipients are
192
+ reported instead, in `result.failed` (with `result.partial?`) and in the
193
+ `deliver.ahasend` notification's `:failed_recipients` (see
194
+ [Monitoring](#monitoring)).
195
+
196
+ `AhaSend::DeliveryError` is raised only when every recipient was rejected, so
197
+ retrying it cannot duplicate anything. A permanent rejection will fail again on
198
+ every retry, though; to stop retrying it, handle it in your mailer
199
+ (`ActionMailer::MailDeliveryJob` passes job exceptions to the mailer's
200
+ `rescue_from`):
201
+
202
+ ```ruby
203
+ class ApplicationMailer < ActionMailer::Base
204
+ rescue_from AhaSend::DeliveryError do |error|
205
+ Rails.logger.warn("AhaSend rejected all recipients: #{error.message}")
206
+ end
207
+ end
208
+ ```
209
+
210
+ ## Retries and idempotency
211
+
212
+ Every request carries an `Idempotency-Key`. If you don't set one, the gem
213
+ generates a UUID per delivery. Because of that, retrying is safe: a request
214
+ the API already completed is answered from its store instead of sending the
215
+ email again.
216
+
217
+ The client retries 429, 500, 502, 503, 504, network failures, and a 409 that
218
+ says a request with the same key is still in progress. It always resends the
219
+ same key and the same body, waits for the API's `Retry-After` when present
220
+ (capped at 30 s) and otherwise backs off exponentially with jitter
221
+ (0.5 s, 1 s, 2 s, ... capped at 8 s). `max_retries: 0` turns this off.
222
+ Other client errors (400, 401, 403, 422, ...) are never retried.
223
+
224
+ Set your own key when you want *your* retries to be safe too, for example
225
+ when a background job may run twice:
226
+
227
+ ```ruby
228
+ headers["AhaSend-Idempotency-Key"] = "order-confirmation-#{order.id}"
229
+ ```
230
+
231
+ The API accepts a key again only for a byte-identical request, and a retried
232
+ job rebuilds the message. Keep the rebuilt message identical: in particular,
233
+ give inline images a fixed Content-ID, because otherwise Mail generates a
234
+ random one each time (in the attachment and in the HTML that references it)
235
+ and the API rejects the rebuilt request with `AhaSend::IdempotencyError` (422):
236
+
237
+ ```ruby
238
+ attachments.inline["logo.png"] = {
239
+ content: File.binread(Rails.root.join("app/assets/images/logo.png")),
240
+ content_id: "<logo.png@yourapp.example>"
241
+ }
242
+ # in the view: image_tag attachments["logo.png"].url
243
+ ```
244
+
245
+ ## Monitoring
246
+
247
+ Rails logs each delivery in its `deliver.action_mailer` notification with the
248
+ Message-ID Mail generated *before* sending. AhaSend then assigns its own. To
249
+ connect the two, the gem emits a `deliver.ahasend` notification around every
250
+ API call:
251
+
252
+ ```ruby
253
+ ActiveSupport::Notifications.subscribe("deliver.ahasend") do |event|
254
+ event.payload[:mail_message_id] # the ID in Rails' deliver.action_mailer event
255
+ event.payload[:message_ids] # AhaSend's message IDs, one per recipient
256
+ event.payload[:recipients] # [{ email:, status:, id:, message_id_header:, error: }, ...]
257
+ event.payload[:failed_recipients] # emails the API rejected, e.g. in a partial delivery
258
+ event.payload[:replayed] # true when answered from the idempotency store
259
+ event.payload[:endpoint] # :messages or :conversation
260
+ event.payload[:sandbox] # true for sandbox sends
261
+ end
262
+ ```
263
+
264
+ The payload never contains credentials or message content. When delivery
265
+ fails, ActiveSupport adds the exception under `:exception`. Without
266
+ ActiveSupport (plain Ruby), no event is emitted.
267
+
268
+ ## Without Rails
269
+
270
+ ```ruby
271
+ require "ahasend-rails"
272
+
273
+ Mail.defaults do
274
+ delivery_method AhaSend::DeliveryMethod, api_key: "aha-sk-...", account_id: "..."
275
+ end
276
+
277
+ Mail.deliver do
278
+ from "noreply@example.com"
279
+ to "someone@example.com"
280
+ subject "Hello"
281
+ body "Sent through AhaSend"
282
+ end
283
+ ```
284
+
285
+ ## Testing your app
286
+
287
+ Keep ActionMailer's `:test` delivery method in your test environment as usual;
288
+ nothing here changes that. To exercise the real API without delivering, use
289
+ `sandbox: true` in `ahasend_settings` (optionally with `sandbox_result:` to
290
+ simulate bounces and failures).
291
+
292
+ ## Development
293
+
294
+ ```sh
295
+ bundle install
296
+ bundle exec rake # rspec + rubocop (offline; HTTP is stubbed with WebMock)
297
+ bin/console # IRB with the gem loaded
298
+ ```
299
+
300
+ The suite checks payloads against a request contract generated from
301
+ AhaSend's OpenAPI spec (`spec/fixtures/api`, with its source recorded), and
302
+ runs the Rails delivery lifecycle (deliver_later, interceptors, observers,
303
+ `perform_deliveries`, `raise_delivery_errors`, `delivery_method_options`) in a
304
+ real Rails app booted in a separate process. CI covers each Rails minor from
305
+ 7.0 to 8.1, the oldest supported `mail` (2.7), and plain Ruby with no Rails
306
+ installed.
307
+
308
+ `bin/live_check` runs a set of sandbox sends against the real API:
309
+
310
+ ```sh
311
+ AHASEND_API_KEY=aha-sk-... AHASEND_ACCOUNT_ID=... AHASEND_FROM_EMAIL=you@verified-domain.com bin/live_check
312
+ ```
313
+
314
+ ## Releasing
315
+
316
+ Releases are published to RubyGems.org by GitHub Actions through
317
+ [Trusted Publishing](https://guides.rubygems.org/trusted-publishing/); no API
318
+ key is stored in the repository.
319
+
320
+ 1. Bump `AhaSend::VERSION` in `lib/ahasend/version.rb` and move the
321
+ `Unreleased` notes in `CHANGELOG.md` under the new version.
322
+ 2. Commit, then create a GitHub release tagged `vX.Y.Z`.
323
+ 3. The `Release` workflow verifies the tag matches the version, runs the
324
+ suite and pushes the gem.
325
+
326
+ ## License
327
+
328
+ MIT
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
@@ -0,0 +1,171 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "json"
5
+ require "uri"
6
+ require "securerandom"
7
+
8
+ module AhaSend
9
+ # Minimal HTTP client for the AhaSend v2 message endpoints.
10
+ #
11
+ # Every POST carries an Idempotency-Key (generated when the caller doesn't
12
+ # supply one), which is what makes the automatic retries safe: a request
13
+ # the API already completed is answered from its store instead of sending
14
+ # the email a second time. Retried: 429, 5xx, network failures, and a 409
15
+ # saying the same key is still in progress. The request (key and body) is
16
+ # built once and reused for every attempt.
17
+ class Client
18
+ # A 2xx answer. `body` is the parsed JSON (or the raw String when the body
19
+ # was not JSON); header names are lower case.
20
+ Response = Struct.new(:status, :headers, :body) do
21
+ # True when the API answered from its idempotency store: an identical
22
+ # request with this key had already completed, and nothing was re-sent.
23
+ def replayed? = headers["idempotent-replayed"] == "true"
24
+ end
25
+
26
+ SETTINGS = %i[api_key account_id base_url open_timeout read_timeout max_retries].freeze
27
+
28
+ DEFAULT_BASE_URL = "https://api.ahasend.com"
29
+ DEFAULT_OPEN_TIMEOUT = 10
30
+ DEFAULT_READ_TIMEOUT = 30
31
+ DEFAULT_MAX_RETRIES = 2
32
+ MAX_BACKOFF = 8.0
33
+ # Longest Retry-After we are willing to sleep inside a caller's job/thread.
34
+ MAX_RETRY_AFTER = 30.0
35
+
36
+ RETRYABLE_STATUSES = [429, 500, 502, 503, 504].freeze
37
+ NETWORK_ERRORS = [
38
+ Timeout::Error, Errno::ECONNRESET, Errno::ECONNREFUSED, Errno::ECONNABORTED, Errno::EHOSTUNREACH,
39
+ Errno::ENETUNREACH, Errno::ETIMEDOUT, Errno::EPIPE, EOFError, SocketError, IOError,
40
+ OpenSSL::SSL::SSLError, Net::HTTPBadResponse
41
+ ].freeze
42
+
43
+ attr_reader :account_id, :base_url, :open_timeout, :read_timeout, :max_retries
44
+
45
+ def initialize(api_key: nil, account_id: nil, base_url: nil, open_timeout: nil, read_timeout: nil,
46
+ max_retries: nil)
47
+ @api_key = required_string(api_key, :api_key)
48
+ @account_id = required_string(account_id, :account_id)
49
+ @base_url = (base_url.nil? ? DEFAULT_BASE_URL : base_url).to_s.chomp("/")
50
+ @base_uri = parse_base_url(@base_url)
51
+ @open_timeout = positive_seconds(open_timeout.nil? ? DEFAULT_OPEN_TIMEOUT : open_timeout, :open_timeout)
52
+ @read_timeout = positive_seconds(read_timeout.nil? ? DEFAULT_READ_TIMEOUT : read_timeout, :read_timeout)
53
+ @max_retries = retry_count(max_retries.nil? ? DEFAULT_MAX_RETRIES : max_retries)
54
+ end
55
+
56
+ # POST /v2/accounts/{account_id}/messages[/conversation]. Returns a
57
+ # Response for any 2xx; raises an ApiError subclass otherwise.
58
+ def send_message(payload, conversation: false, idempotency_key: nil)
59
+ path = "/v2/accounts/#{account_id}/messages#{"/conversation" if conversation}"
60
+ post(path, payload, idempotency_key: idempotency_key)
61
+ end
62
+
63
+ def post(path, payload, idempotency_key: nil)
64
+ request = build_request(path, payload, idempotency_key || SecureRandom.uuid)
65
+
66
+ (max_retries + 1).times do |attempt|
67
+ last = attempt == max_retries
68
+ begin
69
+ response = perform(request)
70
+ rescue *NETWORK_ERRORS => e
71
+ raise ConnectionError, "#{e.class}: #{e.message}" if last
72
+
73
+ wait(backoff(attempt))
74
+ next
75
+ end
76
+
77
+ headers = response.each_header.to_h
78
+ body = parse_body(response)
79
+ return Response.new(response.code.to_i, headers, body) if response.is_a?(Net::HTTPSuccess)
80
+
81
+ error = ApiError.for(status: response.code.to_i, headers: headers, body: body)
82
+ raise error if last || !retryable?(error)
83
+
84
+ wait(backoff(attempt, retry_after: error.retry_after))
85
+ end
86
+ end
87
+
88
+ private
89
+
90
+ def retryable?(error)
91
+ RETRYABLE_STATUSES.include?(error.status) || (error.is_a?(IdempotencyError) && error.in_progress?)
92
+ end
93
+
94
+ def build_request(path, payload, idempotency_key)
95
+ # Keep any path prefix on base_url (e.g. a proxy mounted under /ahasend).
96
+ request = Net::HTTP::Post.new(@base_uri.path.chomp("/") + path)
97
+ request["Authorization"] = "Bearer #{@api_key}"
98
+ request["Content-Type"] = "application/json"
99
+ request["Accept"] = "application/json"
100
+ request["User-Agent"] = "ahasend-rails/#{VERSION} ruby/#{RUBY_VERSION}"
101
+ request["Idempotency-Key"] = idempotency_key
102
+ request.body = encode(payload)
103
+ request
104
+ end
105
+
106
+ def encode(payload)
107
+ JSON.generate(payload)
108
+ rescue JSON::GeneratorError => e
109
+ raise MessageError, "the message could not be encoded as JSON (#{e.message.lines.first.strip}); " \
110
+ "check that its text parts are valid UTF-8"
111
+ end
112
+
113
+ def perform(request)
114
+ http = Net::HTTP.new(@base_uri.host, @base_uri.port)
115
+ http.use_ssl = @base_uri.scheme == "https"
116
+ http.open_timeout = open_timeout
117
+ http.read_timeout = read_timeout
118
+ http.request(request)
119
+ end
120
+
121
+ # Retry-After wins when the API sent one; otherwise exponential backoff
122
+ # with jitter, capped so a long outage fails fast rather than hanging.
123
+ def backoff(attempt, retry_after: nil)
124
+ return [retry_after, MAX_RETRY_AFTER].min if retry_after
125
+
126
+ base = [0.5 * (2**attempt), MAX_BACKOFF].min
127
+ base * (0.5 + (rand * 0.5))
128
+ end
129
+
130
+ def wait(seconds)
131
+ sleep(seconds)
132
+ end
133
+
134
+ def parse_body(response)
135
+ body = response.body
136
+ return nil if body.nil? || body.empty?
137
+
138
+ JSON.parse(body)
139
+ rescue JSON::ParserError
140
+ body
141
+ end
142
+
143
+ def required_string(value, name)
144
+ string = value.to_s
145
+ return string unless string.strip.empty?
146
+
147
+ raise ConfigurationError, "ahasend_settings[:#{name}] is required"
148
+ end
149
+
150
+ def positive_seconds(value, name)
151
+ return value if value.is_a?(Numeric) && value.positive?
152
+
153
+ raise ConfigurationError, "ahasend_settings[:#{name}] must be a positive number of seconds, got #{value.inspect}"
154
+ end
155
+
156
+ def retry_count(value)
157
+ return value if value.is_a?(Integer) && !value.negative?
158
+
159
+ raise ConfigurationError, "ahasend_settings[:max_retries] must be an Integer of 0 or more, got #{value.inspect}"
160
+ end
161
+
162
+ def parse_base_url(value)
163
+ uri = URI.parse(value)
164
+ return uri if uri.is_a?(URI::HTTP) && !uri.host.to_s.empty?
165
+
166
+ raise ConfigurationError, "ahasend_settings[:base_url] must be an http(s) URL with a host, got #{value.inspect}"
167
+ rescue URI::InvalidURIError
168
+ raise ConfigurationError, "ahasend_settings[:base_url] must be an http(s) URL with a host, got #{value.inspect}"
169
+ end
170
+ end
171
+ end
@@ -0,0 +1,68 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AhaSend
4
+ # Mail / ActionMailer delivery method.
5
+ #
6
+ # # Rails
7
+ # config.action_mailer.delivery_method = :ahasend
8
+ # config.action_mailer.ahasend_settings = { api_key: "...", account_id: "..." }
9
+ #
10
+ # # Plain Mail
11
+ # Mail.defaults { delivery_method AhaSend::DeliveryMethod, api_key: "...", account_id: "..." }
12
+ #
13
+ # Settings: api_key, account_id (required); base_url, open_timeout,
14
+ # read_timeout, max_retries (client); plus any message option except
15
+ # idempotency_key (tags, tracking, sandbox, ...) as a default for every
16
+ # message. Settings are validated on first use, not at boot.
17
+ class DeliveryMethod
18
+ # ActiveSupport::Notifications event emitted around every API call, when
19
+ # ActiveSupport is loaded. Payload: :mail_message_id (the ID Rails logged
20
+ # in deliver.action_mailer), :endpoint, :sandbox, and after a response
21
+ # :message_ids, :recipients (email/status/id/message_id_header/error),
22
+ # :failed_recipients and :replayed. No credentials or message content.
23
+ NOTIFICATION = "deliver.ahasend"
24
+
25
+ attr_reader :settings
26
+
27
+ def initialize(settings = {})
28
+ @settings = settings.to_h.transform_keys(&:to_sym)
29
+ end
30
+
31
+ # Sends the message and returns an AhaSend::DeliveryResult. The
32
+ # Message-ID header AhaSend gave the first accepted recipient's email is
33
+ # written back onto the mail object.
34
+ #
35
+ # Raises DeliveryError only when the API rejected every recipient. When
36
+ # some were accepted it returns normally: raising would make a retried
37
+ # job (which sends with a new Idempotency-Key) deliver a second copy to
38
+ # the recipients who already got one. The rejected recipients are in
39
+ # DeliveryResult#failed and the notification's :failed_recipients.
40
+ def deliver!(mail)
41
+ built = MessagePayload.build(mail, defaults: settings.except(*Client::SETTINGS))
42
+ instrument(mail, built) do |event|
43
+ response = client.send_message(built.payload, conversation: built.conversation?,
44
+ idempotency_key: built.idempotency_key)
45
+ result = DeliveryResult.from_response(response)
46
+ event.merge!(result.to_notification)
47
+ raise DeliveryError, result if result.accepted.empty?
48
+
49
+ header = result.accepted.first.message_id_header
50
+ mail.message_id = header if header
51
+ result
52
+ end
53
+ end
54
+
55
+ def client
56
+ @client ||= Client.new(**settings.slice(*Client::SETTINGS))
57
+ end
58
+
59
+ private
60
+
61
+ def instrument(mail, built, &)
62
+ event = { mail_message_id: mail.message_id, endpoint: built.endpoint, sandbox: built.payload["sandbox"] == true }
63
+ return yield(event) unless defined?(ActiveSupport::Notifications)
64
+
65
+ ActiveSupport::Notifications.instrument(NOTIFICATION, event, &)
66
+ end
67
+ end
68
+ end