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.
@@ -0,0 +1,103 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AhaSend
4
+ # The API's answer to a send: one entry per recipient. `id` and `status`
5
+ # expose the first entry for convenience; `messages` has them all.
6
+ #
7
+ # The body is validated against the documented response shape before
8
+ # anything is reported as delivered. A 2xx with any other shape raises
9
+ # UnexpectedResponseError: the email may or may not have gone out.
10
+ class DeliveryResult
11
+ STATUSES = %w[queued scheduled error].freeze
12
+
13
+ # `id` is AhaSend's ID for the message, which Get Message and Cancel
14
+ # Message take; `message_id_header` is the Message-ID header of the email
15
+ # sent. Both are nil for a rejected recipient.
16
+ Message = Struct.new(:id, :message_id_header, :status, :recipient, :error, :schedule, keyword_init: true) do
17
+ def error? = status == "error"
18
+ end
19
+
20
+ attr_reader :raw, :messages
21
+
22
+ def self.from_response(response)
23
+ new(response.body, replayed: response.replayed?)
24
+ end
25
+
26
+ def initialize(raw, replayed: false)
27
+ @raw = raw
28
+ @replayed = replayed
29
+ @messages = parse_messages(raw)
30
+ end
31
+
32
+ # The first message's ID and Message-ID header (nil when that recipient
33
+ # was rejected).
34
+ def id = messages.first.id
35
+ def message_id_header = messages.first.message_id_header
36
+ def status = messages.first.status
37
+ def failed = messages.select(&:error?)
38
+ def accepted = messages.reject(&:error?)
39
+ def success? = failed.empty?
40
+
41
+ # Some recipients were accepted and others rejected. The accepted ones
42
+ # are being sent, so this is not raised as an error (a retried job would
43
+ # send them a second copy); the rejections are in #failed and in the
44
+ # deliver.ahasend notification.
45
+ def partial? = failed.any? && accepted.any?
46
+
47
+ # True when the API answered from its idempotency store: this exact
48
+ # request (same Idempotency-Key) had already been processed, and these
49
+ # are the original results.
50
+ def replayed? = @replayed
51
+
52
+ # Instrumentation payload: provider IDs and per-recipient statuses only,
53
+ # never message content.
54
+ def to_notification
55
+ {
56
+ message_ids: messages.map(&:id).compact,
57
+ recipients: messages.map do |m|
58
+ { email: m.recipient, status: m.status, id: m.id, message_id_header: m.message_id_header, error: m.error }
59
+ end,
60
+ failed_recipients: failed.map(&:recipient),
61
+ replayed: replayed?
62
+ }
63
+ end
64
+
65
+ private
66
+
67
+ def parse_messages(raw)
68
+ data = raw["data"] if raw.is_a?(Hash)
69
+ raise UnexpectedResponseError, raw unless data.is_a?(Array) && !data.empty?
70
+
71
+ data.map { |entry| parse_message(entry) || raise(UnexpectedResponseError, raw) }
72
+ end
73
+
74
+ # Per CreateSingleMessageResponse: a known status, a recipient object
75
+ # with an email, and an ID unless the recipient was rejected (an error
76
+ # entry may have none).
77
+ def parse_message(entry)
78
+ return unless entry.is_a?(Hash) && STATUSES.include?(entry["status"])
79
+
80
+ recipient = entry["recipient"]
81
+ return unless recipient.is_a?(Hash) && recipient["email"].is_a?(String)
82
+ return unless valid_id?(entry) && (entry["error"].nil? || entry["error"].is_a?(String))
83
+
84
+ header = header_of(entry)
85
+ return unless header.nil? || header.is_a?(String)
86
+
87
+ Message.new(id: entry["id"], message_id_header: header, status: entry["status"], recipient: recipient["email"],
88
+ error: entry["error"], schedule: entry["schedule"])
89
+ end
90
+
91
+ # The older response form has no `message_id_header` and gives the
92
+ # Message-ID header as `id`. A request repeated with an earlier
93
+ # Idempotency-Key can still return it for 24 hours after the API change.
94
+ def header_of(entry)
95
+ entry.fetch("message_id_header") { entry["id"] }
96
+ end
97
+
98
+ def valid_id?(entry)
99
+ id = entry["id"]
100
+ (id.is_a?(String) && !id.empty?) || (id.nil? && entry["status"] == "error")
101
+ end
102
+ end
103
+ end
@@ -0,0 +1,136 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AhaSend
4
+ # Base class for every error raised by this gem.
5
+ class Error < StandardError; end
6
+
7
+ # Invalid delivery-method settings: missing credentials, a negative retry
8
+ # count, a base_url that is not http(s), an unknown settings key, ...
9
+ # Checked the first time the delivery method sends, never at boot, so apps
10
+ # using the :test delivery method need no AhaSend credentials.
11
+ class ConfigurationError < Error; end
12
+
13
+ # The message cannot be sent as built. Detected before any request is made:
14
+ # a malformed or unknown AhaSend-* header or option, or a combination the
15
+ # API cannot represent (substitutions with Cc/Bcc, Cc without To, no
16
+ # recipients, no From).
17
+ class MessageError < Error; end
18
+
19
+ # The request never produced an HTTP response (DNS, TCP, TLS, timeout).
20
+ # The underlying exception is available via `cause`.
21
+ class ConnectionError < Error; end
22
+
23
+ # A non-2xx HTTP response from the API. Instances carry the raw status,
24
+ # headers (lower-case names) and body (parsed when JSON).
25
+ class ApiError < Error
26
+ attr_reader :status, :headers, :body
27
+
28
+ def initialize(message = nil, status:, headers: {}, body: nil)
29
+ @status = status
30
+ @headers = headers
31
+ @body = body
32
+ super(message || default_message)
33
+ end
34
+
35
+ # Picks the most specific subclass for an HTTP status, following the
36
+ # send endpoints' contract (AhaSend API v2):
37
+ # 400 invalid request, 401 bad API key, 403 not allowed to send (key
38
+ # scope, account, or a paused sending domain), 409 with
39
+ # `Idempotent-Replayed: false` and a positive `Retry-After` = a request
40
+ # with the same Idempotency-Key is still running, 422 = the
41
+ # Idempotency-Key was already used for a different request.
42
+ def self.for(status:, headers: {}, body: nil)
43
+ klass =
44
+ case status
45
+ when 400 then ValidationError
46
+ when 401 then AuthenticationError
47
+ when 403 then ForbiddenError
48
+ when 404 then NotFoundError
49
+ when 409 then idempotency_in_progress?(headers) ? IdempotencyError : ApiError
50
+ when 422 then IdempotencyError
51
+ when 429 then RateLimitError
52
+ when 500..599 then ServerError
53
+ else ApiError
54
+ end
55
+ klass.new(status: status, headers: headers, body: body)
56
+ end
57
+
58
+ # The API marks an in-progress idempotent request only by this header
59
+ # pair; the message text is not a stable discriminator.
60
+ def self.idempotency_in_progress?(headers)
61
+ headers["idempotent-replayed"] == "false" && headers["retry-after"].to_s.match?(/\A[1-9]\d*\z/)
62
+ end
63
+
64
+ # Seconds the API asked us to wait before retrying (Retry-After), if any.
65
+ def retry_after
66
+ value = headers["retry-after"]
67
+ Float(value) if value&.match?(/\A\d+(\.\d+)?\z/)
68
+ end
69
+
70
+ # True when this response is a stored replay of an earlier request with
71
+ # the same Idempotency-Key.
72
+ def replayed?
73
+ headers["idempotent-replayed"] == "true"
74
+ end
75
+
76
+ # Message returned by the API, when its JSON body carries one.
77
+ def api_message
78
+ body["message"] if body.is_a?(Hash)
79
+ end
80
+
81
+ private
82
+
83
+ def default_message
84
+ text = api_message || (body.is_a?(String) && !body.empty? ? body : nil)
85
+ text ? "AhaSend API error #{status}: #{text}" : "AhaSend API error #{status}"
86
+ end
87
+ end
88
+
89
+ class ValidationError < ApiError; end
90
+ class AuthenticationError < ApiError; end
91
+ class ForbiddenError < ApiError; end
92
+ class NotFoundError < ApiError; end
93
+ class RateLimitError < ApiError; end
94
+ class ServerError < ApiError; end
95
+
96
+ # A problem with the request's Idempotency-Key: the same key is still in
97
+ # progress (409, retried automatically within max_retries), or it was
98
+ # already used for a different request (422, never retried: a rebuilt
99
+ # message must be byte-for-byte identical to reuse its key).
100
+ class IdempotencyError < ApiError
101
+ # True when the original request with this key is still running; retry
102
+ # later (see #retry_after) with the same key and the same message.
103
+ def in_progress?
104
+ status == 409
105
+ end
106
+ end
107
+
108
+ # A 2xx response whose body is not the documented message list, so there is
109
+ # no Message-ID or per-recipient status to report. Nothing is assumed about
110
+ # whether the email went out; check the AhaSend dashboard or logs.
111
+ class UnexpectedResponseError < Error
112
+ attr_reader :body
113
+
114
+ def initialize(body)
115
+ @body = body
116
+ super("AhaSend returned a success status without a valid message list; delivery state unknown: " \
117
+ "#{body.inspect[0, 200]}")
118
+ end
119
+ end
120
+
121
+ # The API accepted the request (202) but rejected every recipient
122
+ # (`status: "error"` for each). Nothing was sent, so retrying cannot
123
+ # duplicate anything; a permanent rejection (such as a blocked recipient
124
+ # domain) will fail again, though. `result` holds the per-recipient errors.
125
+ # When only some recipients are rejected, nothing is raised: see
126
+ # DeliveryResult#partial?.
127
+ class DeliveryError < Error
128
+ attr_reader :result
129
+
130
+ def initialize(result)
131
+ @result = result
132
+ failed = result.failed.map { |m| "#{m.recipient}: #{m.error || "unknown error"}" }
133
+ super("AhaSend rejected #{failed.size} of #{result.messages.size} recipient(s): #{failed.join("; ")}")
134
+ end
135
+ end
136
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AhaSend
4
+ # Per-message AhaSend options set from Ruby rather than headers:
5
+ #
6
+ # message = mail(to: ..., subject: ...)
7
+ # message.ahasend.tags = %w[welcome onboarding]
8
+ # message.ahasend.tracking = { open: true, click: false }
9
+ #
10
+ # Anything set here overrides the equivalent `AhaSend-*` header.
11
+ class MessageOptions
12
+ ATTRIBUTES = %i[tags substitutions tracking retention schedule sandbox sandbox_result idempotency_key].freeze
13
+
14
+ attr_accessor(*ATTRIBUTES)
15
+
16
+ def initialize(**attrs)
17
+ attrs.each { |key, value| public_send(:"#{key}=", value) }
18
+ end
19
+
20
+ def to_h
21
+ ATTRIBUTES.each_with_object({}) do |key, hash|
22
+ value = public_send(key)
23
+ hash[key] = value unless value.nil?
24
+ end
25
+ end
26
+ end
27
+
28
+ # Adds `Mail::Message#ahasend`.
29
+ module MailExtension
30
+ def ahasend
31
+ @ahasend ||= MessageOptions.new
32
+ end
33
+ end
34
+ end
35
+
36
+ Mail::Message.include(AhaSend::MailExtension)
@@ -0,0 +1,223 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AhaSend
4
+ # Translates a Mail::Message into the JSON body for the AhaSend send
5
+ # endpoints and decides which endpoint it belongs to:
6
+ #
7
+ # * To only -> POST /messages, a separate message per To address
8
+ # * To with Cc/Bcc -> POST /messages/conversation, one message carrying
9
+ # the full To/Cc/Bcc headers
10
+ # * Bcc only, no To -> POST /messages, a separate message per Bcc
11
+ # address, so no recipient sees another
12
+ # * smtp_envelope_to -> POST /messages to the envelope addresses only,
13
+ # set explicitly e.g. by an interceptor redirecting delivery
14
+ #
15
+ # Cc without any To, and substitutions on the conversation endpoint (which
16
+ # does not support them), raise MessageError instead of sending something
17
+ # other than what was built.
18
+ #
19
+ # AhaSend options come from settings defaults, `AhaSend-*` headers and
20
+ # `message.ahasend` (see Options). The headers are consumed, never
21
+ # forwarded to the API.
22
+ class MessagePayload
23
+ Built = Struct.new(:payload, :conversation, :idempotency_key, keyword_init: true) do
24
+ def conversation? = conversation
25
+ def endpoint = conversation ? :conversation : :messages
26
+ end
27
+
28
+ # Headers that are mapped to dedicated payload fields or that the API
29
+ # regenerates itself; everything else is forwarded under `headers`.
30
+ CONSUMED_HEADERS = %w[
31
+ from to cc bcc reply-to subject date message-id mime-version
32
+ content-type content-transfer-encoding content-disposition content-id
33
+ return-path received delivered-to
34
+ ].freeze
35
+
36
+ OPTION_FIELDS = %i[tags substitutions tracking retention schedule sandbox sandbox_result].freeze
37
+
38
+ # Per-request recipient limits (CreateMessageRequest.recipients and the
39
+ # conversation endpoint's combined To + Cc + Bcc).
40
+ MAX_RECIPIENTS = 100
41
+ MAX_CONVERSATION_RECIPIENTS = 50
42
+
43
+ def self.build(mail, defaults: {})
44
+ new(mail, defaults: defaults).build
45
+ end
46
+
47
+ def initialize(mail, defaults: {})
48
+ @mail = mail
49
+ @defaults = defaults.to_h.transform_keys(&:to_sym)
50
+ end
51
+
52
+ def build
53
+ options = Options.merge(
54
+ Options.from_settings(@defaults),
55
+ Options.from_headers(mail),
56
+ Options.from_message_options(mail.ahasend)
57
+ )
58
+ conversation, recipients = routing
59
+ check_recipient_limit!(conversation, recipients)
60
+ if conversation && !options.fetch(:substitutions, {}).empty?
61
+ raise MessageError,
62
+ "substitutions cannot be combined with Cc/Bcc: AhaSend's conversation endpoint does not support " \
63
+ "them, so the template would be sent unrendered. Remove the substitutions or the Cc/Bcc recipients."
64
+ end
65
+
66
+ payload = base_payload.merge(recipients).merge(option_fields(options))
67
+ Built.new(payload: payload, conversation: conversation, idempotency_key: options[:idempotency_key])
68
+ end
69
+
70
+ private
71
+
72
+ attr_reader :mail
73
+
74
+ # Returns [conversation?, recipient fields].
75
+ def routing
76
+ envelope = envelope_override
77
+ return [false, { "recipients" => envelope.map { |email| { "email" => email } } }] if envelope
78
+
79
+ to, cc, bcc = %i[to cc bcc].map { |field| addresses(field).map { |address| address_hash(address) } }
80
+ return header_routing(to, cc, bcc) if to.any?
81
+
82
+ raise MessageError, "the message has Cc but no To recipient; AhaSend needs at least one To address alongside Cc" if cc.any?
83
+ raise MessageError, "the message has no recipients" if bcc.empty?
84
+
85
+ # Bcc only: an individual message per address keeps them hidden from
86
+ # each other, which the conversation endpoint (To required) cannot do.
87
+ [false, { "recipients" => bcc }]
88
+ end
89
+
90
+ # The API rejects larger requests with a 400; fail before sending instead.
91
+ def check_recipient_limit!(conversation, recipients)
92
+ count = recipients.values.sum(&:size)
93
+ if conversation && count > MAX_CONVERSATION_RECIPIENTS
94
+ raise MessageError, "the message has #{count} To/Cc/Bcc recipients; AhaSend accepts at most " \
95
+ "#{MAX_CONVERSATION_RECIPIENTS} in total on a message with Cc or Bcc"
96
+ end
97
+ return if conversation || count <= MAX_RECIPIENTS
98
+
99
+ raise MessageError, "the message has #{count} recipients; AhaSend accepts at most #{MAX_RECIPIENTS} " \
100
+ "per message, so send it in batches"
101
+ end
102
+
103
+ def header_routing(to, cc, bcc)
104
+ return [false, { "recipients" => to }] if cc.empty? && bcc.empty?
105
+
106
+ [true, { "to" => to, "cc" => cc, "bcc" => bcc }.reject { |_, list| list.empty? }]
107
+ end
108
+
109
+ # An explicit `smtp_envelope_to` that differs from the To/Cc/Bcc headers
110
+ # redirects delivery: SMTP would send only to the envelope addresses, so
111
+ # only they become API recipients (each gets an individual message; the
112
+ # header recipients receive nothing). Mail falls back to the header
113
+ # addresses when no envelope is set, which compares equal here.
114
+ def envelope_override
115
+ envelope = Array(mail.smtp_envelope_to).map { |value| bare_address(value) }.uniq
116
+ destinations = Array(mail.destinations).map { |value| bare_address(value) }.uniq
117
+ return nil if envelope.map(&:downcase).sort == destinations.map(&:downcase).sort
118
+ raise MessageError, "smtp_envelope_to is set but empty; there is no one to deliver to" if envelope.empty?
119
+
120
+ envelope
121
+ end
122
+
123
+ def bare_address(value)
124
+ address = Mail::Address.new(value.to_s).address
125
+ raise MessageError, "#{value.inspect} is not a valid email address" if address.to_s.empty?
126
+
127
+ address
128
+ rescue Mail::Field::ParseError
129
+ raise MessageError, "#{value.inspect} is not a valid email address"
130
+ end
131
+
132
+ def base_payload
133
+ from = addresses(:from).first
134
+ raise MessageError, "the message has no From address" if from.nil?
135
+
136
+ {
137
+ "from" => address_hash(from),
138
+ "reply_to" => addresses(:reply_to).first&.then { |address| address_hash(address) },
139
+ "subject" => mail.subject.to_s,
140
+ "text_content" => part_body("text/plain"),
141
+ "html_content" => part_body("text/html"),
142
+ "amp_content" => part_body("text/x-amp-html"),
143
+ "attachments" => (attachments if mail.attachments.any?),
144
+ "headers" => (custom_headers unless custom_headers.empty?)
145
+ }.compact
146
+ end
147
+
148
+ def option_fields(options)
149
+ OPTION_FIELDS.each_with_object({}) do |name, fields|
150
+ value = options[name]
151
+ next if value.nil? || (value.respond_to?(:empty?) && value.empty?)
152
+
153
+ fields[name.to_s] = value
154
+ end
155
+ end
156
+
157
+ def addresses(field_name)
158
+ field = mail[field_name]
159
+ return [] if field.nil?
160
+
161
+ field = field.first if field.is_a?(Array)
162
+ field.respond_to?(:addrs) ? field.addrs : []
163
+ end
164
+
165
+ def address_hash(address)
166
+ hash = { "email" => address.address }
167
+ name = address.display_name
168
+ hash["name"] = name unless name.nil? || name.empty?
169
+ hash
170
+ end
171
+
172
+ def part_body(mime_type)
173
+ part =
174
+ if mail.multipart?
175
+ mail.find_first_mime_type(mime_type)
176
+ elsif (mail.mime_type || "text/plain") == mime_type && !mail.attachment?
177
+ mail
178
+ end
179
+ return nil if part.nil?
180
+
181
+ body = part.decoded
182
+ body.empty? ? nil : body
183
+ end
184
+
185
+ def attachments
186
+ mail.attachments.map do |part|
187
+ attachment = {
188
+ "file_name" => part.filename,
189
+ "content_type" => part.mime_type,
190
+ "data" => [part.body.decoded].pack("m0"), # strict Base64, no base64 gem needed (Ruby 3.4+)
191
+ "base64" => true
192
+ }
193
+ if part.inline?
194
+ attachment["content_disposition"] = "inline"
195
+ attachment["content_id"] = content_id(part)
196
+ end
197
+ attachment
198
+ end
199
+ end
200
+
201
+ # The MIME Content-ID with its angle brackets, as the API requires
202
+ # (`<logo@example.com>`); without them AhaSend delivers the file as a
203
+ # regular attachment. The HTML references it bracket-free
204
+ # (`cid:logo@example.com`, which is what `attachments[...].url` returns).
205
+ # Mail generates a random ID when the attachment was given none; pass
206
+ # `content_id:` when attaching for an ID that is stable across rebuilds.
207
+ def content_id(part)
208
+ part.add_content_id unless part.has_content_id?
209
+ "<#{part.content_id.to_s.strip.delete_prefix("<").delete_suffix(">")}>"
210
+ end
211
+
212
+ def custom_headers
213
+ @custom_headers ||= mail.header.fields.each_with_object({}) do |field, headers|
214
+ name = field.name.to_s
215
+ key = name.downcase
216
+ next if CONSUMED_HEADERS.include?(key) || key.start_with?(Options::HEADER_PREFIX)
217
+
218
+ value = field.value.to_s
219
+ headers[name] = headers.key?(name) ? "#{headers[name]}, #{value}" : value
220
+ end
221
+ end
222
+ end
223
+ end