Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
3b58e48
feat(emails): send one email to many recipients with emails.batch
Silthus Nov 24, 2026
101881a
fix(emails): keep a failed status read unconfirmed and tighten batch …
Silthus Nov 24, 2026
2f1c6e1
fix(emails): keep a batch retry's answer and fail oversize content pe…
Silthus Nov 24, 2026
58c4aa3
fix(emails): tell a too-large batch recipient to shrink its content
Silthus Nov 24, 2026
00af371
Merge remote-tracking branch 'origin/feat/scheduled-email-send' into …
Silthus Nov 24, 2026
c109a62
test(emails): check the fix a too-large batch recipient gets
Silthus Nov 24, 2026
5500d50
fix(emails): match the batch contract of Node and the server
Silthus Nov 24, 2026
5569436
Merge remote-tracking branch 'origin/feat/scheduled-email-send' into …
Silthus Nov 24, 2026
1b68402
fix(emails): take only the ID from a batch status read by key
Silthus Nov 24, 2026
81aa4cc
fix(emails): keep a batch's in-flight refusal as the error, and a cal…
Silthus Nov 24, 2026
4a8b693
Merge remote-tracking branch 'origin/feat/scheduled-email-send' into …
Silthus Nov 24, 2026
6031427
fix(emails): stop reading a batch's unconfirmed emails back by key
Silthus Nov 24, 2026
e1338b5
Merge remote-tracking branch 'origin/feat/scheduled-email-send' into …
Silthus Nov 24, 2026
568dab6
fix(emails): keep a batch recipient's first unconfirmed reason and th…
Silthus Nov 24, 2026
e85ef0d
Merge origin/feat/scheduled-email-send into feat/email-batch
Silthus Nov 24, 2026
90225a2
fix(emails): never log a failed batch's warnings, keep a retry's last…
Silthus Nov 24, 2026
231777b
chore(emails): name a failed batch's warnings in the changeset
Silthus Nov 24, 2026
5db89d3
Merge branch 'feat/scheduled-email-send' into feat/email-batch
Silthus Nov 24, 2026
df77a2f
feat(emails): send a batch as one request of at most 100 recipients
Silthus Nov 24, 2026
1b64865
chore: merge feat/scheduled-email-send into feat/email-batch
Silthus Nov 24, 2026
3d96c42
fix(emails): let a failed batch's status decide whether it may have g…
Silthus Nov 24, 2026
ee472cc
fix(emails): keep a batch unconfirmed once any attempt may have queue…
Silthus Nov 24, 2026
78c2319
fix(emails): keep a refused batch failed when the client shuts down
Silthus Nov 24, 2026
517819e
test(emails): check a batch logs a repeated warning once
Silthus Nov 24, 2026
d661708
fix(emails): say an earlier attempt may have queued a refused batch
Silthus Nov 24, 2026
8697230
fix(emails): only the client's own shutdown leaves a batch failed
Silthus Nov 24, 2026
ea1cea6
refactor(emails): settle an in-flight slot before an earlier attempt'…
Silthus Nov 24, 2026
a7a777a
fix(emails): don't tell a one-recipient batch to split on a bare 413
Silthus Nov 24, 2026
f0d8628
fix(emails): carry an earlier attempt's doubt onto the batch error
Silthus Nov 24, 2026
3306f5a
fix(emails): don't call an unconfirmed email unqueued when PostHog gi…
Silthus Nov 24, 2026
453ae70
docs(emails): say replayed can read false right after the first send
Silthus Nov 24, 2026
c238fd7
Merge branch 'feat/scheduled-email-send' into feat/email-batch
Silthus Nov 25, 2026
c6ac363
fix(emails): keep batch results past a raising logger or a bare 409
Silthus Nov 25, 2026
cbbf15e
fix(emails): hold one serialized copy of a batch through its retries
Silthus Nov 25, 2026
81c152c
docs(emails): say a raising logger keeps an accepted batch's results
Silthus Nov 25, 2026
6823db2
fix(emails): let a caller's Timeout::Error end a batch while it logs
Silthus Nov 25, 2026
4d1805e
fix(emails): name the template ID first after a batch 404 without a f…
Silthus Nov 25, 2026
47629d6
docs(emails): drop log_warnings' stale note that a logger error propa…
Silthus Nov 25, 2026
75c0024
fix(emails): advise a code batch's 404 to send alone only where code …
Silthus Nov 25, 2026
08d5089
fix(emails): give a batch error the same-key fix when any attempt may…
Silthus Nov 25, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/email-batch-sends.md
Original file line number Diff line number Diff line change
@@ -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.
202 changes: 202 additions & 0 deletions lib/posthog/email_batch.rb
Original file line number Diff line number Diff line change
@@ -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<Member>] 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
32 changes: 27 additions & 5 deletions lib/posthog/email_error.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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<Emails::Warning>] PostHog's warnings about an email it accepted although the call failed. The
# client logs warnings only for a call that succeeds.
# @return [Array<Emails::Warning>] 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
Expand All @@ -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)
Expand All @@ -67,12 +72,29 @@ 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'
else 'application_error'
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<Emails::BatchEmailResult>] 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
Loading