diff --git a/.changeset/email-batch-sends.md b/.changeset/email-batch-sends.md new file mode 100644 index 00000000..00a64940 --- /dev/null +++ b/.changeset/email-batch-sends.md @@ -0,0 +1,5 @@ +--- +"posthog-ruby": minor +--- + +Send the same transactional email to many recipients with `emails.batch`, one email each, from a template made in PostHog with `template_data` per recipient, or from content your code rendered. The client sends at most 100 recipients in one request, refusing more before anything is sent, and returns a result per recipient in order: `queued`, `failed` or `unconfirmed`. Each recipient has its own `idempotency_key`, given or made by the client, so the client's own retries never send an email twice. To rerun a batch that was cut off, pass the keys you stored: a rerun with the same keys within 24 hours replays the emails that went out. A request that fails as a whole raises `EmailBatchError` with every recipient's result, such as a 413 `content_too_large` when PostHog finds the batch too large to take at once, with PostHog's fix to split it into smaller batches, or, for a batch of one recipient, the advice to make the email smaller. A recipient that any attempt may have queued stays `unconfirmed`, also when a retry is refused. A failed batch never calls the logger, and a logger that raises while logging an accepted batch's warnings doesn't lose its results. diff --git a/lib/posthog/email_batch.rb b/lib/posthog/email_batch.rb new file mode 100644 index 00000000..2808af37 --- /dev/null +++ b/lib/posthog/email_batch.rb @@ -0,0 +1,202 @@ +# frozen_string_literal: true + +require 'json' + +require 'posthog/email_error' + +module PostHog + # The recipients of one {Emails#batch} call, sent in one request, and what PostHog answered. + # + # @api private + class EmailBatch + MAX_RECIPIENTS = 100 + UNCONFIRMED_CODES = %w[idempotency_key_in_flight delivery_unavailable api_error].freeze + RESEND_FIX = 'Send it again with the same idempotency_key within 24 hours of the first request that used it, so ' \ + 'it goes out once.' + UNAVAILABLE_FIX = "Until batch sends are on for the project, send each email the batch didn't queue with " \ + "emails.send and its recipient's idempotency_key." + NO_TEMPLATE = { + 'code' => 'not_found', + 'detail' => "PostHog found no template with this ID, or batch sends aren't available for this project, so it " \ + 'sent no email of this request.', + 'fix' => "Check template_id. If it's right, send each recipient on its own with emails.send and its " \ + 'idempotency_key until batch sends are available.' + }.freeze + NO_CODE_BATCH = { + 'code' => 'not_found', + 'detail' => "Batch sends, or sends from code, aren't available for this project, so PostHog sent no email of " \ + 'this request.', + 'fix' => 'If this project can send email from code, send each recipient on its own with emails.send and its ' \ + 'idempotency_key until batch sends are available.' + }.freeze + TOO_LARGE = { + 'code' => 'content_too_large', + 'detail' => 'PostHog refused the batch as too large, so no email was sent.', + 'fix' => 'Split the recipients into smaller batches.' + }.freeze + SMALLER_FIX = 'Make the email smaller, such as its template_data.' + EARLIER_ATTEMPT = 'An earlier attempt of this batch may have queued this email, so it may still go out. ' \ + 'The last attempt ended with:' + RESULT_DEFAULTS = { message_id: nil, replayed: false, error: nil }.freeze + private_constant :UNCONFIRMED_CODES, :RESEND_FIX, :EARLIER_ATTEMPT, :UNAVAILABLE_FIX, :NO_TEMPLATE, :NO_CODE_BATCH, + :TOO_LARGE, + :SMALLER_FIX, :RESULT_DEFAULTS + + Member = Struct.new(:index, :to, :idempotency_key, :wire, keyword_init: true) + + attr_reader :body + + # @param shared [Hash] The batch's email without its recipients. + # @param members [Array] Every recipient, with its JSON as the request carries it. The body takes it + # over, so each member's +wire+ is +nil+ afterwards. + # @param parse_warnings [#call] Turns a reply's warnings into {Emails::Warning}s. + # @param reply_error [#call] Turns a refused reply into an {EmailError}. + def initialize(shared, members, parse_warnings:, reply_error:) + @members = members + @parse_warnings = parse_warnings + @reply_error = reply_error + @warnings = [] + @maybe_queued = false + @attempt_error = nil + @template_form = shared.key?(:template_id) + head = JSON.generate(shared.merge(recipients: [])).delete_suffix(']}') + # A buffer of the exact size, and each recipient's JSON dropped once copied, so the request body is the only copy + # of the batch through every retry. + size = head.bytesize + members.sum { |member| member.wire.bytesize + 1 } + 1 + @body = String.new(head, capacity: size, encoding: Encoding::UTF_8) + members.each_with_index do |member, index| + @body << ',' unless index.zero? + @body << member.wire + member.wire = nil + end + @body << ']}' + end + + # @return [Emails::BatchResult] The result of an answer with a result for each recipient. + # @raise [EmailError] PostHog refused the request, or answered without a result for each recipient. + def answer((status, payload, retry_after)) + fields = payload.is_a?(Hash) ? payload : {} + raise response_error(fields, status, retry_after) unless status.between?(200, 299) + + @warnings = @parse_warnings.call(fields['warnings']).uniq + slots = fields['results'] + unless slots.is_a?(Array) && slots.size == @members.size + raise EmailError.new(code: 'api_error', status_code: status, fix: RESEND_FIX, + message: 'PostHog answered the batch without a result for each recipient.') + end + + results = @members.zip(slots).map { |member, slot| settle(member, slot.is_a?(Hash) ? slot : {}) } + Emails::BatchResult.new(results: results.freeze, warnings: @warnings.dup.freeze) + end + + # Remembers an attempt that failed, so a later attempt's refusal can't confirm what this one may have queued. + def attempt_failed(error) + @attempt_error = error + @maybe_queued = true if maybe_queued?(error) + end + + # Every recipient of a request that failed as a whole is `unconfirmed` when any attempt may have queued it, and + # `failed` otherwise. + def failure(error) + # Only an attempt's error says what PostHog may have queued; the client raises client_closed without a request. + refused = !(@attempt_error.equal?(error) && maybe_queued?(error)) + error = resend(error, earlier: refused) if @maybe_queued + status = @maybe_queued ? 'unconfirmed' : 'failed' + results = @members.map { |member| result(member, status, error: error) } + EmailBatchError.new(error, results: results.freeze, warnings: @warnings.dup.freeze) + end + + private + + # The status, not the code, says whether PostHog may have queued the emails: a 4xx refused them, except a 409 for + # keys still in flight. No answer, a 5xx and a 2xx without a result for each recipient leave them unknown. + def maybe_queued?(error) + status = error.status_code.to_i + return true unless status.between?(400, 499) + + # PostHog's only other 409 is batch_unavailable, so a 409 whose body didn't name it may hold keys in flight. + status == 409 && error.code != 'batch_unavailable' + end + + def settle(member, slot) + message_id = text(slot['message_id']) + if slot['error'].nil? && slot['status'] == 'queued' && message_id + return result(member, 'queued', message_id: message_id, replayed: slot['replayed'] == true) + end + + answer = slot_error(slot['error'], message_id) + if UNCONFIRMED_CODES.include?(answer.code) + return result(member, 'unconfirmed', message_id: message_id, error: answer) + elsif @maybe_queued + # A refusal can't confirm an email that an earlier attempt of the request may have queued. + return result(member, 'unconfirmed', message_id: message_id, error: resend(answer, earlier: true)) + end + + result(member, 'failed', message_id: message_id, error: answer) + end + + def result(member, status, **fields) + identity = { index: member.index, to: member.to, idempotency_key: member.idempotency_key, status: status } + Emails::BatchEmailResult.new(**RESULT_DEFAULTS, **identity, **fields) + end + + # A caller who follows PostHog's own advice without the key sends a second email. A refusal that follows an + # attempt that may have queued the email can't say no email was sent, so its message says so first. + def resend(error, earlier: false) + return error if error.fix == RESEND_FIX + + message = earlier ? "#{EARLIER_ATTEMPT} #{error.message}" : error.message + EmailError.new(code: error.code, message: message, status_code: error.status_code, why: error.why, + fix: RESEND_FIX, docs_url: error.docs_url, field: error.field, retry_after: error.retry_after) + end + + def response_error(fields, status, retry_after) + answered = fields.compact + fields = if status == 404 && unnamed_not_found?(answered) + # An unknown template, batch sends that are off and a server without the route answer alike, and + # after launch a wrong template ID is the likely one. + @template_form ? NO_TEMPLATE : NO_CODE_BATCH + elsif status == 413 + too_large(answered) + else + answered + end + fields = fields.merge('fix' => UNAVAILABLE_FIX) if fields['code'] == 'batch_unavailable' + @reply_error.call(fields, status, retry_after) + end + + def unnamed_not_found?(answered) + %w[not_found api_error].include?(text(answered['code']) || 'api_error') && text(answered['attr']).nil? + end + + def too_large(answered) + fields = TOO_LARGE.merge(answered.select { |_, value| text(value) }) + # One recipient can't be split, so only a smaller email gets through, whatever the reply advises. + @members.size > 1 ? fields : fields.merge('fix' => SMALLER_FIX) + end + + def slot_error(error, message_id) + unless error.is_a?(Hash) + return EmailError.new(code: 'api_error', message_id: message_id, fix: RESEND_FIX, + message: 'PostHog answered without a readable result for this email, so it may still ' \ + 'go out.') + end + + code = text(error['code']) || 'api_error' + status = error['status'].is_a?(Integer) ? error['status'] : nil + # EmailError#message_id means PostHog may have accepted the email, so a refusal leaves it on the result only. + unconfirmed = UNCONFIRMED_CODES.include?(code) + fallback = if unconfirmed + "PostHog couldn't confirm this email (#{code}), so it may still go out." + else + "PostHog didn't queue this email: #{code}." + end + EmailError.new(code: code, status_code: status, message_id: (message_id if unconfirmed), + fix: (RESEND_FIX if unconfirmed), message: text(error['detail']) || fallback) + end + + def text(value) + value if value.is_a?(String) && !value.empty? + end + end +end diff --git a/lib/posthog/email_error.rb b/lib/posthog/email_error.rb index 91ef326d..66d5c9f8 100644 --- a/lib/posthog/email_error.rb +++ b/lib/posthog/email_error.rb @@ -28,8 +28,9 @@ class EmailError < StandardError # @return [String, nil] The message ID of an email PostHog accepted although the call failed, such as an email # whose `schedule_not_confirmed` means it may go out at another time. Read its status with {Emails#get}. attr_reader :message_id - # @return [Array] PostHog's warnings about an email it accepted although the call failed. The - # client logs warnings only for a call that succeeds. + # @return [Array] PostHog's warnings about the emails it accepted although the call failed, each + # once, such as those of a batch's requests that went out. The client logs warnings only for a call that + # succeeds. attr_reader :warnings # @api private @@ -53,9 +54,13 @@ def initialize(code:, message:, status_code: nil, why: nil, fix: nil, docs_url: 'invalid_attachment' => 'validation_error', 'too_many_attachments' => 'validation_error', 'message_too_large' => 'validation_error', - 'scheduling_requires_cloud' => 'validation_error' + 'scheduling_requires_cloud' => 'validation_error', + 'delivery_unavailable' => 'service_unavailable', + 'content_too_large' => 'validation_error' }.freeze - private_constant :SDK_ERROR_NAMES + # A 409 PostHog answers before it takes the request, so no idempotency key is in flight. + VALIDATION_CONFLICTS = %w[template_outdated batch_unavailable].freeze + private_constant :SDK_ERROR_NAMES, :VALIDATION_CONFLICTS # @api private def self.name_for(status_code, code) @@ -67,7 +72,7 @@ def self.name_for(status_code, code) when 400 then 'validation_error' when 403 then 'invalid_permission' when 404 then 'not_found' - when 409 then code == 'template_outdated' ? 'validation_error' : 'concurrent_idempotent_requests' + when 409 then VALIDATION_CONFLICTS.include?(code) ? 'validation_error' : 'concurrent_idempotent_requests' when 422 then code == 'idempotency_key_reused' ? 'invalid_idempotent_request' : 'validation_error' when 429 then code == 'quota_limited' ? 'monthly_quota_exceeded' : 'rate_limit_exceeded' when 503 then 'service_unavailable' @@ -75,4 +80,21 @@ def self.name_for(status_code, code) end end end + + # The request of {Emails#batch} failed as a whole. + # + # The other fields describe its error. {#results} holds every recipient: `unconfirmed` where PostHog may have queued + # them in any attempt, such as after a lost answer or while it held their keys, and `failed` otherwise. + class EmailBatchError < EmailError + # @return [Array] One result per recipient, in the order of the batch's recipients. + attr_reader :results + + # @api private + def initialize(error, results:, warnings:) + super(code: error.code, message: error.message, status_code: error.status_code, why: error.why, fix: error.fix, + docs_url: error.docs_url, field: error.field, retry_after: error.retry_after, message_id: error.message_id, + warnings: warnings) + @results = results + end + end end diff --git a/lib/posthog/emails.rb b/lib/posthog/emails.rb index 233d3b94..01307b9f 100644 --- a/lib/posthog/emails.rb +++ b/lib/posthog/emails.rb @@ -10,6 +10,7 @@ require 'zlib' require 'posthog/email_attachments' +require 'posthog/email_batch' require 'posthog/email_error' require 'posthog/logging' require 'posthog/utils' @@ -55,6 +56,16 @@ module PostHog # ) # result.status # => "scheduled" # result.scheduled_at # => the time in UTC + # + # @example The same template for many recipients, one email each + # result = posthog.emails.batch( + # template_id: '0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b', + # recipients: [ + # { to: 'ada@example.com', idempotency_key: 'launch:ada', template_data: { name: 'Ada' } }, + # { to: 'alan@example.com', idempotency_key: 'launch:alan', template_data: { name: 'Alan' } } + # ] + # ) + # result.results.reject { |email| email.status == 'queued' } # => send these again with the same keys class Emails include PostHog::Logging include PostHog::Utils @@ -91,9 +102,50 @@ def status # of a bounced email: `hard`, `soft` or `unknown`. Status = Struct.new(:id, :status, :created_at, :status_at, :reason, keyword_init: true) + # What happened to one recipient of {Emails#batch}. + # + # @!attribute [r] index + # @return [Integer] The recipient's position in +recipients+. + # @!attribute [r] to + # @return [String] The recipient's email address. + # @!attribute [r] idempotency_key + # @return [String] The recipient's key, given or made by the client. + # @!attribute [r] status + # @return [String] One of: + # - `queued`: PostHog accepted the email. Read it with {Emails#get} to see whether it went out. + # - `failed`: PostHog didn't queue the email, and {#error} says why, such as a suppressed address. + # - `unconfirmed`: the client can't tell whether PostHog queued the email, such as after a lost answer, also + # when a retry's answer refused it. It may still go out. Send it again with the same +idempotency_key+ + # within 24 hours of the first request that used it, so it goes out once. + # @!attribute [r] message_id + # @return [String, nil] The email's message ID, when PostHog named it. + # @!attribute [r] replayed + # @return [Boolean] PostHog's marker that an earlier send with the same key had already queued the email, so + # no new email went out. A replay that follows the first send at once can read +false+ even then; the same + # {#message_id} is what shows it is the same email. + # @!attribute [r] error + # @return [EmailError, nil] Why the email is not `queued`. For an `unconfirmed` email, {EmailError#code} names + # what left it so, such as `idempotency_key_in_flight`, `delivery_unavailable`, `api_error` or + # `network_error`, and {EmailError#fix} says to send it again with the same key. + BatchEmailResult = Struct.new(:index, :to, :idempotency_key, :status, :message_id, :replayed, :error, + keyword_init: true) + + # The answer to {Emails#batch}. + # + # @!attribute [r] results + # @return [Array] One result per recipient, in the order of +recipients+. + # @!attribute [r] warnings + # @return [Array] Warnings PostHog returned about the batch, each once. + BatchResult = Struct.new(:results, :warnings, keyword_init: true) + SEND_PATH = '/api/messaging/send/email/' UPLOADS_PATH = '/api/messaging/attachments/uploads/' STATUS_PATH = '/api/messaging/emails/%s/' + BATCH_PATH = '/api/messaging/send/email_batch/' + # PostHog waits up to 30 seconds for its pipeline before it answers a batch. Connecting and writing keep the + # client's timeout. + BATCH_ATTEMPT_TIMEOUT_SECONDS = 45.0 + BATCH_RECIPIENT_FIELDS = %w[to distinct_id idempotency_key template_data].freeze US_APP_HOST = 'https://us.posthog.com' EU_APP_HOST = 'https://eu.posthog.com' SCHEDULING_APP_HOSTS = [US_APP_HOST, EU_APP_HOST].freeze @@ -130,7 +182,9 @@ def status Timeout::Error, SocketError, SystemCallError, IOError, EOFError, OpenSSL::SSL::SSLError, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError, Zlib::Error ].freeze - private_constant :SEND_PATH, :UPLOADS_PATH, :STATUS_PATH, :US_APP_HOST, :EU_APP_HOST, :CLOUD_APP_HOSTS, + private_constant :SEND_PATH, :UPLOADS_PATH, :STATUS_PATH, :BATCH_PATH, + :BATCH_ATTEMPT_TIMEOUT_SECONDS, :BATCH_RECIPIENT_FIELDS, :US_APP_HOST, :EU_APP_HOST, + :CLOUD_APP_HOSTS, :SCHEDULING_APP_HOSTS, :MAX_RETRY_DELAY_SECONDS, :UUID_PATTERN, :IDEMPOTENCY_KEY_PATTERN, :TEMPLATE_KEY_PATTERN, :HEADER_TOKEN_PATTERN, :SCHEDULED_AT_PATTERN, :SEND_NOW_TOLERANCE_SECONDS, :SCHEDULED_AT_NEEDED, @@ -269,7 +323,94 @@ def send( end raise unconfirmed if unconfirmed - result.warnings.each { |warning| logger.warn("PostHog email warning #{warning.code}: #{warning.message}") } + log_warnings(result.warnings) + + result + end + + # Queues the same email for many recipients, one email each, from a template made in PostHog or from content + # your code rendered. + # + # Pass the template form, with +template_id+, or the code form, with +template_key+, as {#send} takes them. The + # client sends at most 100 recipients in one request and waits at least 45 seconds for the answer. PostHog + # refuses a batch too large to take at once with a 413 `content_too_large`: split the recipients into smaller + # batches, or, for one recipient, make the email smaller. A 400 `content_too_large` means the shared content is + # over PostHog's limit, which splitting doesn't change: make it smaller. A recipient whose own +template_data+ is + # over it comes back `failed` with `content_too_large` in its result, while the others go out. A batch takes no + # +cc+, +bcc+, +attachments+ or +scheduled_at+. + # + # Each recipient has an +idempotency_key+, given or made by the client, that every retry reuses, so a retry never + # queues an email twice. Retries follow {#send}'s. Send each `unconfirmed` email again with its + # +idempotency_key+ within 24 hours of the first request that used it, so it goes out once. + # + # @param recipients [Array] 1 to 100 recipients, each a Hash with: + # - +to+ [String] the recipient's email address; + # - +distinct_id+ [String] optional: the recipient's distinct ID in your product; + # - +idempotency_key+ [String] optional: 1 to 255 visible ASCII characters, a different one for each recipient. + # Without it, the client makes one that covers its own retries but not a second call, so pass keys you store + # when a batch may be cut off and run again: a rerun within 24 hours replays the emails that went out instead + # of sending them twice. A send and a batch recipient with the same key and the same email replay each other; + # - +template_data+ [Hash] optional, only with +template_id+: values for this recipient, merged over the + # batch's +template_data+. A top-level key set here replaces the same key there. + # @param template_id [String] Template form: the UUID of a template made transactional in PostHog. + # @param template_data [Hash] Template form: values for the template, shared by every recipient. + # @param template_key [String] Code form: names the email, as {#send} takes it. Pass +subject+ and +html+, +text+ + # or both, and optionally +from+, +reply_to+, +sensitive+, +tracking+ and +capture_engagement+, the same for + # every recipient. A recipient can't carry +template_data+: send personalized content with a +template_id+ + # batch, or with {#send}. + # @param max_retries [Integer] Overrides the client's `email_request_max_retries` for the batch's request. +0+ + # turns retries off. + # @return [BatchResult] A result per recipient, in the order of +recipients+. Check each + # {BatchEmailResult#status}, and send an `unconfirmed` email again with the same key so it goes out once. A + # logger that raises a StandardError other than Timeout::Error while logging the warnings doesn't lose the + # result. + # @raise [EmailBatchError] The request failed as a whole, such as a rate limit past its retries. The error is the + # last attempt's. {EmailBatchError#results} holds every recipient: `unconfirmed` with a fix to send it again with + # the same key when any attempt may have queued it (a 409 other than `batch_unavailable`, a 5xx, or a lost + # answer), and `failed` when PostHog refused the request with a 4xx and no earlier attempt may have queued it. + # When any attempt may have queued them, the error's fix is the same-key one, and when only an earlier attempt may + # have, its message says so. The error is `client_closed` when the client shut down before a retry. + # {EmailError#code} is `content_too_large` with PostHog's fix: a 413 for a batch to split into smaller batches, or + # for one recipient an email to make smaller, and a 400 for shared content to make smaller. It is + # `batch_unavailable` when the project can't send batches yet: send each email the batch didn't queue with {#send} + # and its recipient's +idempotency_key+. It is `not_found` with no {EmailError#field} when PostHog found no + # template with the +template_id+ or batch sends aren't available for the project, which PostHog answers alike: + # check +template_id+, and if it's right, send each recipient on its own the same way. The warnings of an answer + # without a result for each recipient are on {EmailError#warnings}, and the client logs none of them. + # @raise [EmailError] The client sent nothing, such as when it is disabled or has no +secret_key+. + # @raise [ArgumentError] An argument has the wrong type or format, such as more than 100 recipients or two + # recipients with the same +idempotency_key+. No email was sent. + def batch( + recipients:, template_id: nil, template_data: nil, template_key: nil, subject: nil, html: nil, text: nil, + from: nil, reply_to: nil, sensitive: nil, tracking: nil, capture_engagement: nil, max_retries: nil + ) + unless max_retries.nil? || retry_count?(max_retries) + raise ArgumentError, + 'max_retries must be a nonnegative integer.' + end + + fields = { + template_data: template_data, subject: subject, html: html, text: text, from: from, reply_to: reply_to, + sensitive: sensitive, tracking: tracking, capture_engagement: capture_engagement + }.compact + shared = content(template_id, template_key, fields) + members = batch_members(recipients, template_key.nil?) + run = EmailBatch.new(shared, members, parse_warnings: method(:warnings), reply_error: method(:reply_error)) + + result, failure = call('no email was sent', SEND_KEY_NEEDED) do |secret_key| + send_batch(run, secret_key, max_retries || @max_retries) + end + raise failure if failure + + begin + log_warnings(result.warnings) + rescue Timeout::Error + # A caller's deadline, from Timeout.timeout with this class, still ends the call. + raise + rescue StandardError + # PostHog queued the emails and the result holds the warnings. Raising here loses the derived keys, and a + # resend without them sends each email twice. + end result end @@ -312,6 +453,100 @@ def close(timeout: nil) private + def batch_members(recipients, template_form) + unless recipients.is_a?(Array) + raise ArgumentError, + "recipients must be an Array of recipients, each a Hash with to, such as [{ to: 'user@example.com' }]." + end + raise ArgumentError, 'recipients must hold at least one recipient.' if recipients.empty? + if recipients.size > EmailBatch::MAX_RECIPIENTS + raise ArgumentError, "recipients must hold at most #{EmailBatch::MAX_RECIPIENTS} recipients, not " \ + "#{recipients.size}. Split them into smaller batches." + end + + first_with_key = {} + recipients.each_with_index.map do |recipient, index| + fields = batch_recipient_fields(recipient, index) + member = batch_member(fields, index, template_form) + first = first_with_key[member.idempotency_key] ||= index + unless first == index + raise ArgumentError, "recipients[#{index}] has the same idempotency_key as recipients[#{first}]. Give each " \ + 'recipient its own key.' + end + + member + end + end + + def batch_recipient_fields(recipient, index) + fields = recipient.is_a?(Hash) ? Utils.stringify_keys(recipient) : {} + unless fields.key?('to') + raise ArgumentError, "recipients[#{index}] must be a Hash with to, such as { to: 'user@example.com' }." + end + + unknown = fields.keys - BATCH_RECIPIENT_FIELDS + return fields if unknown.empty? + + raise ArgumentError, "recipients[#{index}] takes only to, distinct_id, idempotency_key and template_data, not " \ + "#{unknown.join(', ')}." + end + + def batch_member(fields, index, template_form) + to, distinct_id, key, data = fields.values_at('to', 'distinct_id', 'idempotency_key', 'template_data') + begin + check_recipient(to, distinct_id, key, nil) + rescue ArgumentError => e + raise ArgumentError, "recipients[#{index}]: #{e.message}" + end + key ||= SecureRandom.uuid + wire = { to: to, idempotency_key: key } + wire[:distinct_id] = distinct_id unless distinct_id.nil? + unless data.nil? + unless template_form + raise ArgumentError, "recipients[#{index}] has template_data, but a batch with template_key sends the same " \ + 'content to every recipient. Send personalized content with a template_id batch or ' \ + 'with emails.send.' + end + raise ArgumentError, "recipients[#{index}]: template_data must be a Hash." unless data.is_a?(Hash) + + wire[:message_data] = isoify_dates(data) + end + EmailBatch::Member.new(index: index, to: to, idempotency_key: key, wire: JSON.generate(wire)) + end + + def send_batch(run, secret_key, max_retries) + uri = URI(@app_host + BATCH_PATH) + read_timeout = [@timeout.to_f, BATCH_ATTEMPT_TIMEOUT_SECONDS].max + result = with_retries(max_retries) do |attempt| + if attempt.positive? && !still_admitted? + raise EmailError.new(code: 'client_closed', + message: "The PostHog client is shut down, so it didn't retry the batch.") + end + + begin + run.answer(request(Net::HTTP::Post.new(uri), uri, secret_key, JSON_CONTENT, run.body, + read_timeout: read_timeout)) + rescue EmailError => e + run.attempt_failed(e) + raise + end + end + [result, nil] + rescue EmailError => e + [nil, run.failure(e)] + end + + def log_warnings(warnings) + warnings.each { |warning| logger.warn("PostHog email warning #{warning.code}: #{warning.message}") } + end + + def still_admitted? + @mutex.synchronize do + forget_parent_requests + !@closed + end + end + def check_options(timeout, max_retries, migrated_from) raise ArgumentError, 'email_request_timeout_seconds must be a positive number.' unless positive?(timeout) raise ArgumentError, 'email_request_max_retries must be a nonnegative integer.' unless retry_count?(max_retries) @@ -547,7 +782,7 @@ def finish def with_retries(max_retries) attempt = 0 begin - yield + yield attempt rescue EmailError => e delay = retry_delay(e, attempt, max_retries) raise if delay.nil? @@ -652,21 +887,21 @@ def upload_failed(file, status, answer, retry_after) ) end - def request(request, uri, secret_key, headers, body = nil) + def request(request, uri, secret_key, headers, body = nil, read_timeout: @timeout) request['Authorization'] = "Bearer #{secret_key}" request['Accept'] = 'application/json' request['User-Agent'] = @user_agent if @user_agent request['X-PostHog-Migrated-From'] = @migrated_from if @migrated_from - status, answer, retry_after = exchange(request, uri, headers, body) + status, answer, retry_after = exchange(request, uri, headers, body, read_timeout: read_timeout) [status, parse_json(answer), retry_after] end - def exchange(request, uri, headers, body) + def exchange(request, uri, headers, body, read_timeout: @timeout) headers.each { |name, value| request[name] = value } request.body = body if body head = nil - response = Net::HTTP.start(uri.hostname, uri.port, connection_options(uri)) do |http| + response = Net::HTTP.start(uri.hostname, uri.port, connection_options(uri, read_timeout)) do |http| http.request(request) { |started| head = started } end [response.code.to_i, response.body, parse_retry_after(response['Retry-After'])] @@ -676,9 +911,9 @@ def exchange(request, uri, headers, body) retry_after: head && parse_retry_after(head['Retry-After'])) end - def connection_options(uri) + def connection_options(uri, read_timeout) options = { - use_ssl: uri.scheme == 'https', open_timeout: @timeout, read_timeout: @timeout, write_timeout: @timeout, + use_ssl: uri.scheme == 'https', open_timeout: @timeout, read_timeout: read_timeout, write_timeout: @timeout, # Net::HTTP returns a body cut off by a closed connection as if it were whole. Raise instead. max_retries: 0, ignore_eof: false } diff --git a/public_api_snapshot.txt b/public_api_snapshot.txt index 3feb4c17..04fa4d02 100644 --- a/public_api_snapshot.txt +++ b/public_api_snapshot.txt @@ -63,6 +63,8 @@ constant PostHog::Defaults::Request::PATH: String constant PostHog::Defaults::Request::PORT: Integer constant PostHog::Defaults::Request::RETRIES: Integer constant PostHog::Defaults::Request::SSL: Boolean +class PostHog::EmailBatchError < PostHog::EmailError +instance_method PostHog::EmailBatchError#results() class PostHog::EmailError < StandardError instance_method PostHog::EmailError#code() instance_method PostHog::EmailError#docs_url() @@ -75,9 +77,40 @@ instance_method PostHog::EmailError#status_code() instance_method PostHog::EmailError#warnings() instance_method PostHog::EmailError#why() class PostHog::Emails +instance_method PostHog::Emails#batch(recipients:, template_id: ..., template_data: ..., template_key: ..., subject: ..., html: ..., text: ..., from: ..., reply_to: ..., sensitive: ..., tracking: ..., capture_engagement: ..., max_retries: ...) instance_method PostHog::Emails#get(message_id) instance_method PostHog::Emails#send(to:, template_id: ..., template_data: ..., template_key: ..., subject: ..., html: ..., text: ..., from: ..., reply_to: ..., cc: ..., bcc: ..., attachments: ..., sensitive: ..., tracking: ..., capture_engagement: ..., distinct_id: ..., idempotency_key: ..., max_retries: ..., scheduled_at: ...) class_method PostHog::Emails.logger() +class PostHog::Emails::BatchEmailResult < Struct +instance_method PostHog::Emails::BatchEmailResult#error() +instance_method PostHog::Emails::BatchEmailResult#error=(_) +instance_method PostHog::Emails::BatchEmailResult#idempotency_key() +instance_method PostHog::Emails::BatchEmailResult#idempotency_key=(_) +instance_method PostHog::Emails::BatchEmailResult#index() +instance_method PostHog::Emails::BatchEmailResult#index=(_) +instance_method PostHog::Emails::BatchEmailResult#message_id() +instance_method PostHog::Emails::BatchEmailResult#message_id=(_) +instance_method PostHog::Emails::BatchEmailResult#replayed() +instance_method PostHog::Emails::BatchEmailResult#replayed=(_) +instance_method PostHog::Emails::BatchEmailResult#status() +instance_method PostHog::Emails::BatchEmailResult#status=(_) +instance_method PostHog::Emails::BatchEmailResult#to() +instance_method PostHog::Emails::BatchEmailResult#to=(_) +class_method PostHog::Emails::BatchEmailResult.[](*arg0) +class_method PostHog::Emails::BatchEmailResult.inspect() +class_method PostHog::Emails::BatchEmailResult.keyword_init?() +class_method PostHog::Emails::BatchEmailResult.members() +class_method PostHog::Emails::BatchEmailResult.new(*arg0) +class PostHog::Emails::BatchResult < Struct +instance_method PostHog::Emails::BatchResult#results() +instance_method PostHog::Emails::BatchResult#results=(_) +instance_method PostHog::Emails::BatchResult#warnings() +instance_method PostHog::Emails::BatchResult#warnings=(_) +class_method PostHog::Emails::BatchResult.[](*arg0) +class_method PostHog::Emails::BatchResult.inspect() +class_method PostHog::Emails::BatchResult.keyword_init?() +class_method PostHog::Emails::BatchResult.members() +class_method PostHog::Emails::BatchResult.new(*arg0) class PostHog::Emails::SendResult < Struct instance_method PostHog::Emails::SendResult#id() instance_method PostHog::Emails::SendResult#id=(_) diff --git a/spec/posthog/emails_batch_spec.rb b/spec/posthog/emails_batch_spec.rb new file mode 100644 index 00000000..a6225a68 --- /dev/null +++ b/spec/posthog/emails_batch_spec.rb @@ -0,0 +1,516 @@ +# frozen_string_literal: true + +require 'spec_helper' + +module PostHog + describe Emails do + let(:batch_url) { 'https://us.posthog.com/api/messaging/send/email_batch/' } + let(:template_id) { '0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b' } + let(:uuid_v4) { /\A\h{8}-\h{4}-4\h{3}-[89ab]\h{3}-\h{12}\z/ } + let(:options) { { api_key: API_KEY, secret_key: 'phs_test', test_mode: true } } + let(:client) { Client.new(options) } + let(:emails) { client.emails.tap { |emails| allow(emails).to receive(:sleep) { |seconds| delays << seconds } } } + let(:delays) { [] } + let(:ada) { { to: 'ada@example.com', idempotency_key: 'welcome:ada', template_data: { name: 'Ada' } } } + let(:alan) { { to: 'alan@example.com', distinct_id: 'user_2', idempotency_key: 'welcome:alan' } } + + before do + stub_request(:get, %r{/flags/definitions}).to_return(status: 200, body: '{"flags":[]}') + end + + after { client.shutdown(timeout: 1) } + + def queued(message_id, replayed: false) + { message_id: message_id, status: 'queued', replayed: replayed } + end + + def slot_error(code, status, message_id: 'msg_x') + { message_id: message_id, error: { code: code, detail: "PostHog didn't queue it: #{code}.", status: status } } + end + + def answer(*slots, warnings: nil) + { status: 200, body: JSON.generate({ results: slots, warnings: warnings }.compact) } + end + + def refuse(status, code, **fields) + { status: status, body: JSON.generate({ code: code }.merge(fields)) } + end + + def batch_bodies + bodies = [] + expect(a_request(:post, batch_url).with { |request| bodies << JSON.parse(request.body) }) + .to have_been_made.at_least_once + bodies + end + + def batch_template(recipients, **extra) + emails.batch(template_id: template_id, template_data: { product: 'Hog' }, recipients: recipients, **extra) + end + + def statuses(results) + results.map(&:status) + end + + def resend_with_key(result) + [result.status, result.idempotency_key, + result.error.fix.to_s.include?('same idempotency_key within 24 hours of the first request that used it')] + end + describe '#batch' do + it 'sends one request and returns a result per recipient, in order' do + stub_request(:post, batch_url).to_return(answer(queued('msg_1'), queued('msg_2', replayed: true))) + + result = batch_template([ada, alan]) + + expect(result.results.map(&:to_h)).to eq( + [{ index: 0, to: 'ada@example.com', idempotency_key: 'welcome:ada', status: 'queued', message_id: 'msg_1', + replayed: false, error: nil }, + { index: 1, to: 'alan@example.com', idempotency_key: 'welcome:alan', status: 'queued', + message_id: 'msg_2', replayed: true, error: nil }] + ) + expect(batch_bodies).to eq( + [{ 'template_id' => template_id, 'message_data' => { 'product' => 'Hog' }, + 'recipients' => [ + { 'to' => 'ada@example.com', 'idempotency_key' => 'welcome:ada', 'message_data' => { 'name' => 'Ada' } }, + { 'to' => 'alan@example.com', 'idempotency_key' => 'welcome:alan', 'distinct_id' => 'user_2' } + ] }] + ) + expect(a_request(:post, batch_url).with(headers: { 'Authorization' => 'Bearer phs_test' })).to have_been_made + end + + it 'makes a key for each recipient without one, and keeps it on every retry' do + stub_request(:post, batch_url).to_return(refuse(503, 'delivery_unavailable'), + answer(queued('msg_1'), queued('msg_2'))) + + result = batch_template([{ to: 'ada@example.com' }, { 'to' => 'alan@example.com' }]) + + keys = result.results.map(&:idempotency_key) + expect(keys).to all(match(uuid_v4)) + expect(keys.uniq.size).to eq(2) + expect(a_request(:post, batch_url)).to have_been_made.twice + # WebMock records identical requests once, so one body means both attempts sent the same keys. + expect(batch_bodies.map { |body| body['recipients'].map { |recipient| recipient['idempotency_key'] } }) + .to eq([keys]) + expect(statuses(result.results)).to eq(%w[queued queued]) + end + + it 'sends the code form with the same content for every recipient' do + stub_request(:post, batch_url).to_return(answer(queued('msg_1'))) + + emails.batch(template_key: 'launch-news', subject: 'We launched', html: '

Hi

', from: 'a@example.com', + recipients: [{ to: 'ada@example.com', idempotency_key: 'launch:ada' }]) + + expect(batch_bodies.first).to eq( + 'template_key' => 'launch-news', 'subject' => 'We launched', 'html' => '

Hi

', + 'from' => 'a@example.com', + 'recipients' => [{ 'to' => 'ada@example.com', 'idempotency_key' => 'launch:ada' }] + ) + end + + it 'sends 100 recipients in one request, and refuses 101 before any request' do + hundred = Array.new(100) { |index| { to: "user#{index}@example.com", idempotency_key: "key-#{index}" } } + stub_request(:post, batch_url).to_return(answer(*Array.new(100) { |index| queued("msg_#{index}") })) + + expect { batch_template(hundred + [{ to: 'user100@example.com' }]) } + .to raise_error(ArgumentError, /at most 100 recipients/) + expect(a_request(:post, batch_url)).not_to have_been_made + + result = batch_template(hundred) + + expect(batch_bodies.map { |body| body['recipients'].size }).to eq([100]) + expect(result.results.map(&:message_id)).to eq(Array.new(100) { |index| "msg_#{index}" }) + end + + it "returns each recipient PostHog refused as failed and one it didn't confirm as unconfirmed" do + stub_request(:post, batch_url).to_return( + answer(slot_error('recipient_suppressed', 422, message_id: 'msg_1'), + slot_error('delivery_unavailable', 503, message_id: 'msg_2'), 'not a result') + ) + + results = batch_template([ada, alan, { to: 'grace@example.com' }]).results + + expect(statuses(results)).to eq(%w[failed unconfirmed unconfirmed]) + expect(results.map { |result| [result.message_id, result.error.code, result.error.name] }).to eq( + [%w[msg_1 recipient_suppressed validation_error], %w[msg_2 delivery_unavailable service_unavailable], + [nil, 'api_error', 'application_error']] + ) + expect(results.first.error.status_code).to eq(422) + expect(results.map { |result| result.error.message_id }).to eq([nil, 'msg_2', nil]) + end + + it 'keeps a recipient the retry refused unconfirmed when a lost answer may have queued it' do + stub_request(:post, batch_url).to_raise(Errno::ECONNRESET).then.to_return( + answer(queued('msg_ada'), slot_error('recipient_suppressed', 422, message_id: nil)) + ) + + results = batch_template([ada, alan], max_retries: 1).results + + expect(results.map(&:status)).to eq(%w[queued unconfirmed]) + expect([results.last.error.code, resend_with_key(results.last)]) + .to eq(['recipient_suppressed', ['unconfirmed', 'welcome:alan', true]]) + expect(results.last.error.message).to start_with('An earlier attempt of this batch may have queued') + end + + it 'leaves an unconfirmed email PostHog answered without an ID to be sent again with its key' do + stub_request(:post, batch_url).to_return( + answer(slot_error('delivery_unavailable', 503, message_id: 'msg_ada'), + slot_error('delivery_unavailable', 503, message_id: nil), { status: 'queued' }) + ) + + results = batch_template([ada, alan, { to: 'grace@example.com', idempotency_key: 'welcome:grace' }]).results + + expect(results.map(&:message_id)).to eq(['msg_ada', nil, nil]) + expect(results.map { |result| resend_with_key(result) }).to eq( + [['unconfirmed', 'welcome:ada', true], ['unconfirmed', 'welcome:alan', true], + ['unconfirmed', 'welcome:grace', true]] + ) + expect(a_request(:get, %r{/api/messaging/emails/status/})).not_to have_been_made + end + + it "doesn't tell an unconfirmed email without PostHog's detail that it wasn't queued" do + stub_request(:post, batch_url).to_return( + answer({ message_id: 'msg_ada', error: { code: 'delivery_unavailable', status: 503 } }) + ) + + error = batch_template([ada]).results.first.error + + expect(error.message).to include('may still go out') + expect(error.message).not_to include("didn't queue") + end + + it "logs the reply's warnings once each" do + warning = { code: 'unverified_link', detail: 'A link points to an unverified domain.' } + stub_request(:post, batch_url).to_return(answer(queued('msg_1'), warnings: [warning, warning])) + log = StringIO.new + PostHog::Logging.logger = Logger.new(log, level: Logger::WARN) + + result = batch_template([ada]) + + expect(result.warnings.map(&:code)).to eq(['unverified_link']) + expect(log.string.scan('PostHog email warning unverified_link').size).to eq(1) + end + + it "carries a failed batch's warnings on its error and never logs them" do + stub_request(:post, batch_url).to_return(answer(warnings: [{ code: 'unverified_link' }])) + log = StringIO.new + PostHog::Logging.logger = Logger.new(log, level: Logger::WARN) + + expect { batch_template([ada]) }.to raise_error(EmailBatchError) { |error| + expect([error.code, error.cause, error.warnings.map(&:code)]).to eq(['api_error', nil, ['unverified_link']]) + } + expect(log.string).to be_empty + end + + it 'returns a batch that went through whatever error the logger raises, so no resend gets new keys' do + stub_request(:post, batch_url).to_return(answer(queued('msg_0'), warnings: [{ code: 'unverified_link' }])) + PostHog::Logging.logger = Logger.new(StringIO.new, level: Logger::WARN, + formatter: ->(*) { raise IOError, 'log device closed' }) + + result = batch_template([{ to: 'user@example.com' }]) + + expect(result.results.map { |email| [email.status, email.message_id] }).to eq([%w[queued msg_0]]) + expect(result.results.first.idempotency_key).to match(/\A\h{8}-/) + expect(result.warnings.map(&:code)).to eq(['unverified_link']) + end + + # Timeout.timeout with Timeout::Error as its class raises it in the thread, here in the logger. + [Interrupt, Timeout::Error].each do |deadline| + it "lets #{deadline} raised while logging stop a batch that went through" do + stub_request(:post, batch_url).to_return(answer(queued('msg_0'), warnings: [{ code: 'unverified_link' }])) + PostHog::Logging.logger = Logger.new(StringIO.new, level: Logger::WARN, formatter: ->(*) { raise deadline }) + + expect { batch_template([ada]) }.to raise_error(deadline) + end + end + + context 'when the request fails as a whole' do + it 'raises EmailBatchError with every recipient failed and the field PostHog named' do + stub_request(:post, batch_url).to_return( + refuse(400, 'invalid_recipient', detail: 'A recipient is invalid.', attr: 'recipients__1__to') + ) + + expect { batch_template([ada, alan]) }.to raise_error(EmailBatchError) { |error| + expect([error.code, error.status_code, error.field]).to eq(['invalid_recipient', 400, 'recipients__1__to']) + expect(error.results.map { |result| [result.status, result.error.code] }) + .to eq([%w[failed invalid_recipient], %w[failed invalid_recipient]]) + } + expect(a_request(:post, batch_url)).to have_been_made.once + end + + { + 'a 413 with its code and fix' => [ + { status: 413, body: JSON.generate(code: 'content_too_large', detail: 'Too large.', fix: 'Split them.') }, + 'Split them.' + ], + 'a 413 without a JSON body' => [{ status: 413, body: 'Request Entity Too Large' }, 'smaller'], + 'a 413 with an empty code and fix' => [{ status: 413, body: JSON.generate(code: '', fix: '') }, 'smaller'], + 'a 413 with fields that are not text' => [ + { status: 413, body: JSON.generate(code: 413, fix: false) }, 'smaller' + ] + }.each do |name, (reply, fix)| + it "surfaces #{name} as content_too_large, with PostHog's fix or the advice to split the recipients" do + stub_request(:post, batch_url).to_return(reply) + + expect { batch_template([ada, alan]) }.to raise_error(EmailBatchError) { |error| + expect([error.code, error.status_code]).to eq(['content_too_large', 413]) + expect(error.fix).to include(fix) + expect(statuses(error.results)).to eq(%w[failed failed]) + } + expect(a_request(:post, batch_url)).to have_been_made.once + end + end + + { + 'without a fix' => { status: 413, body: 'Request Entity Too Large' }, + "with PostHog's split fix" => { + status: 413, + body: JSON.generate(code: 'content_too_large', fix: 'Split the recipients into smaller batches.') + } + }.each do |name, reply| + it "tells a one-recipient batch refused by a 413 #{name} to make the email smaller, not to split it" do + stub_request(:post, batch_url).to_return(reply) + + expect { batch_template([ada]) }.to raise_error(EmailBatchError) { |error| + expect([error.code, error.status_code]).to eq(['content_too_large', 413]) + expect(error.fix).to include('smaller') + expect(error.fix).not_to include('Split') + } + end + end + + it "keeps a 400 content_too_large for content over PostHog's limit as PostHog sent it, without split advice" do + stub_request(:post, batch_url).to_return( + refuse(400, 'content_too_large', fix: 'Make template_data smaller.', attr: 'template_data') + ) + + expect { batch_template([ada]) }.to raise_error(EmailBatchError) { |error| + expect([error.code, error.status_code, error.fix]) + .to eq(['content_too_large', 400, 'Make template_data smaller.']) + expect(statuses(error.results)).to eq(%w[failed]) + } + end + + it 'raises batch_unavailable with the fix to send each email on its own' do + stub_request(:post, batch_url).to_return(refuse(409, 'batch_unavailable', detail: 'Not yet.')) + + expect { batch_template([ada]) }.to raise_error(EmailBatchError) { |error| + expect([error.code, error.name, error.status_code]).to eq(['batch_unavailable', 'validation_error', 409]) + expect(error.fix).to include('send', 'idempotency_key') + expect(error.results.map(&:status)).to eq(['failed']) + } + expect(a_request(:post, batch_url)).to have_been_made.once + end + + ['', 'Wait a few seconds and try again.'].each do |fix| + it "keeps every recipient unconfirmed while PostHog holds the keys, with fix #{fix.inspect}" do + stub_request(:post, batch_url).to_return(refuse(409, 'idempotency_key_in_flight', fix: fix)) + + expect { batch_template([ada, alan], max_retries: 0) }.to raise_error(EmailBatchError) { |error| + expect([error.code, error.results.map(&:message_id)]).to eq(['idempotency_key_in_flight', [nil, nil]]) + expect(error.fix).to eq(error.results.first.error.fix) + expect(error.results.map { |result| resend_with_key(result) }) + .to eq([['unconfirmed', 'welcome:ada', true], ['unconfirmed', 'welcome:alan', true]]) + } + expect(a_request(:post, batch_url)).to have_been_made.once + end + end + + # PostHog answers an unknown template_id, batch sends that are off and a server without the route alike. + { + 'an unknown template or batch sends off' => JSON.generate(code: 'not_found', attr: nil, detail: 'Not found.'), + 'a server without the route' => JSON.generate(code: 'not_found', detail: 'Endpoint not found.'), + 'no body' => '' + }.each do |name, body| + it "names the template ID first after a 404 for #{name}" do + stub_request(:post, batch_url).to_return(status: 404, body: body) + + expect { batch_template([ada, alan]) }.to raise_error(EmailBatchError) { |error| + expect([error.code, error.name, error.status_code, error.field]) + .to eq(['not_found', 'not_found', 404, nil]) + expect(error.message) + .to include('no template with this ID', "batch sends aren't available for this project") + expect(error.fix).to include('Check template_id', 'on its own') + expect("#{error.message} #{error.why} #{error.fix}").not_to match(/update|upgrade|server|version/i) + expect(error.results.map(&:status)).to eq(%w[failed failed]) + } + end + + it "names batch sends from code after a 404 for #{name}" do + stub_request(:post, batch_url).to_return(status: 404, body: body) + + code = { template_key: 'launch', subject: 'Hi', text: 'Hi', recipients: [{ to: 'ada@example.com' }] } + expect { emails.batch(**code) }.to raise_error(EmailBatchError) { |error| + expect([error.code, error.status_code]).to eq(['not_found', 404]) + expect(error.message).to include("aren't available for this project") + expect(error.fix).to include('If this project can send email from code', 'on its own') + expect("#{error.message} #{error.why} #{error.fix}") + .not_to match(/template_id|update|upgrade|server|version/i) + } + end + end + + it 'keeps the answer of a 404 that names a field' do + stub_request(:post, batch_url).to_return(refuse(404, 'not_found', detail: 'No such sender.', attr: 'from')) + + expect { batch_template([ada]) }.to raise_error(EmailBatchError) { |error| + expect([error.code, error.field, error.message]).to eq(['not_found', 'from', 'No such sender.']) + } + end + + it 'keeps the recipients a lost answer may have queued unconfirmed, to send again with their keys' do + stub_request(:post, batch_url).to_raise(Errno::ECONNRESET) + + expect { batch_template([ada, alan], max_retries: 1) }.to raise_error(EmailBatchError) { |error| + expect(error.code).to eq('network_error') + expect(error.results.map { |result| [result.message_id, result.error.code] }) + .to eq([[nil, 'network_error'], [nil, 'network_error']]) + expect(error.results.map { |result| resend_with_key(result) }) + .to eq([['unconfirmed', 'welcome:ada', true], ['unconfirmed', 'welcome:alan', true]]) + } + expect(a_request(:post, batch_url)).to have_been_made.twice + expect(a_request(:get, %r{/api/messaging/emails/status/})).not_to have_been_made + end + + { + 'a 429' => [{ status: 429, body: JSON.generate(code: 'rate_limited') }, 'rate_limited'], + 'a 404 without a field' => [ + { status: 404, body: JSON.generate(code: 'not_found', detail: 'Not found.') }, 'not_found' + ] + }.each do |name, (refusal, code)| + it "keeps the recipients a lost answer may have queued unconfirmed when the retry gets #{name}" do + stub_request(:post, batch_url).to_raise(Errno::ECONNRESET).then.to_return(refusal) + + expect { batch_template([ada, alan], max_retries: 1) }.to raise_error(EmailBatchError) { |error| + expect(error.code).to eq(code) + expect(error.message).to start_with('An earlier attempt of this batch may have queued') + expect(error.results.first.error.message) + .to start_with('An earlier attempt of this batch may have queued') + expect(error.results.map { |result| resend_with_key(result) }) + .to eq([['unconfirmed', 'welcome:ada', true], ['unconfirmed', 'welcome:alan', true]]) + } + expect(a_request(:post, batch_url)).to have_been_made.twice + end + end + + it "doesn't say no email was sent, or advise a split, when a size refusal follows a lost answer" do + stub_request(:post, batch_url).to_raise(Errno::ECONNRESET) + .then.to_return(status: 413, body: 'Request Entity Too Large') + + expect { batch_template([ada, alan], max_retries: 1) }.to raise_error(EmailBatchError) { |error| + expect([error.code, error.status_code]).to eq(['content_too_large', 413]) + expect(error.message).to start_with('An earlier attempt of this batch may have queued') + expect(error.fix).to include('same idempotency_key within 24 hours') + expect(statuses(error.results)).to eq(%w[unconfirmed unconfirmed]) + } + end + + it 'keeps every recipient unconfirmed when the answer has no result for each, and never retries it' do + stub_request(:post, batch_url).to_return(answer(queued('msg_1'))) + + expect { batch_template([ada, alan]) }.to raise_error(EmailBatchError) { |error| + expect(error.code).to eq('api_error') + expect(error.results.map { |result| resend_with_key(result) }) + .to eq([['unconfirmed', 'welcome:ada', true], ['unconfirmed', 'welcome:alan', true]]) + } + expect(a_request(:post, batch_url)).to have_been_made.once + end + + { + [503, 503] => %w[unconfirmed delivery_unavailable], + [503, 400] => %w[unconfirmed invalid_recipient], + [503, 429] => %w[unconfirmed rate_limited], + [429, 400] => %w[failed invalid_recipient] + }.each do |statuses, (status, code)| + it "reports the last attempt's error after #{statuses.join(', ')}, unconfirmed if one may have queued" do + codes = { 400 => 'invalid_recipient', 429 => 'rate_limited', 503 => 'delivery_unavailable' } + stub_request(:post, batch_url).to_return(*statuses.map { |answered| refuse(answered, codes[answered]) }) + + expect { batch_template([ada], max_retries: 1) }.to raise_error(EmailBatchError) { |error| + result = error.results.first + expect([error.code, result.status, result.error.code]).to eq([code, status, code]) + } + expect(a_request(:post, batch_url)).to have_been_made.twice + end + end + + { + 'a 502 without a code' => [{ status: 502, body: 'Bad gateway' }, 'unconfirmed'], + 'a 504 with a code' => [{ status: 504, body: JSON.generate(code: 'gateway_timeout') }, 'unconfirmed'], + 'a 503 with client_closed' => [{ status: 503, body: JSON.generate(code: 'client_closed') }, 'unconfirmed'], + 'a 409 without a readable body' => [{ status: 409, body: 'Conflict' }, 'unconfirmed'], + 'a 403 without a code' => [{ status: 403, body: 'Forbidden' }, 'failed'], + 'a 403 naming keys in flight' => [ + { status: 403, body: JSON.generate(code: 'idempotency_key_in_flight') }, 'failed' + ] + }.each do |name, (reply, status)| + it "leaves every recipient #{status} after #{name}, the status deciding whether it may have gone out" do + stub_request(:post, batch_url).to_return(reply) + + expect { batch_template([ada], max_retries: 0) }.to raise_error(EmailBatchError) { |error| + expect(error.status_code).to eq(reply[:status]) + expect(resend_with_key(error.results.first)).to eq([status, 'welcome:ada', status == 'unconfirmed']) + expect(error.results.first.error.message).to eq(error.message) + expect(error.message).not_to start_with('An earlier attempt') + } + end + end + + it 'leaves the recipients failed when the client shuts down after PostHog refused the only request' do + stub_request(:post, batch_url).to_return do + client.shutdown(timeout: 0) + refuse(429, 'rate_limited') + end + + expect { batch_template([ada], max_retries: 1) }.to raise_error(EmailBatchError) { |error| + expect([error.code, error.results.map(&:status)]).to eq(['client_closed', ['failed']]) + } + expect(a_request(:post, batch_url)).to have_been_made.once + end + + it "doesn't retry once the client shuts down, and leaves the recipients unconfirmed" do + stub_request(:post, batch_url).to_return do + client.shutdown(timeout: 0) + refuse(503, 'delivery_unavailable') + end + + expect { batch_template([ada]) }.to raise_error(EmailBatchError) { |error| + expect(error.code).to eq('client_closed') + expect(resend_with_key(error.results.first)).to eq(['unconfirmed', 'welcome:ada', true]) + expect(error.results.first.error.message).to start_with('An earlier attempt of this batch may have queued') + } + expect(a_request(:post, batch_url)).to have_been_made.once + end + end + + it "hands Net::HTTP a read wait of at least 45 seconds and the client's connect and write timeouts" do + stub_request(:post, batch_url).to_return(answer(queued('msg_1'))) + allow(Net::HTTP).to receive(:start).and_call_original + options[:email_request_timeout_seconds] = 3 + + batch_template([ada]) + + expect(Net::HTTP).to have_received(:start) + .with('us.posthog.com', 443, hash_including(read_timeout: 45.0, open_timeout: 3, write_timeout: 3)) + end + + it 'refuses a bad batch before any request' do + [ + [{ recipients: [] }, /at least one recipient/], + [{ recipients: ada }, /recipients must be an Array/], + [{ recipients: [ada, ada.merge(to: 'b@example.com')] }, + /recipients\[1\] has the same idempotency_key as recipients\[0\]/], + [{ recipients: [{ to: '' }] }, /recipients\[0\]: to must be/], + [{ recipients: [{ to: 'a@example.com', cc: 'b@example.com' }] }, /recipients\[0\] takes only/], + [{ recipients: [ada], scheduled_at: Time.now }, /unknown keyword: :scheduled_at/], + [{ recipients: [ada], cc: 'b@example.com' }, /unknown keyword: :cc/], + [{ recipients: [ada], template_id: 'nope' }, /template_id must be/] + ].each do |args, message| + expect { emails.batch(template_id: template_id, **args) }.to raise_error(ArgumentError, message) + end + expect do + emails.batch(template_key: 'launch', subject: 'Hi', text: 'Hi', recipients: [ada]) + end.to raise_error(ArgumentError, /recipients\[0\] has template_data/) + expect(a_request(:any, %r{/api/messaging/})).not_to have_been_made + end + end + end +end