posthog-ruby 3.43.1 → 3.44.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/lib/posthog/email_batch.rb +224 -0
- data/lib/posthog/email_error.rb +38 -5
- data/lib/posthog/emails.rb +386 -24
- data/lib/posthog/version.rb +1 -1
- metadata +2 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: bfe42553d00a920508a3dfe677de736f79b9dc594f57bd3af719adddd8ca2793
|
|
4
|
+
data.tar.gz: 2d72fe9b1afc7a722505b6a170c305c34b0e67bcf7ec22ae99b485847a2a7790
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: e137ae58446b49b781f0a0f063054127d68816e569e3411736fdc546f47dfb8ac1c8391315265b1fef12c7d0ddc29774136f1415f1102b29f14bc4e8b8ea9f2b
|
|
7
|
+
data.tar.gz: c86b34c57f559a571bdefca604dec860861ca973d79956e666f75a82058595ebf95eda11e049b91282c6bdb472229054fd99e7f502bd6c74f8fd890028cb128d
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'json'
|
|
4
|
+
|
|
5
|
+
require 'posthog/email_error'
|
|
6
|
+
|
|
7
|
+
module PostHog
|
|
8
|
+
# The recipients of one {Emails#batch} call, sent in one request, and what PostHog answered.
|
|
9
|
+
#
|
|
10
|
+
# @api private
|
|
11
|
+
class EmailBatch
|
|
12
|
+
MAX_RECIPIENTS = 100
|
|
13
|
+
UNCONFIRMED_CODES = %w[idempotency_key_in_flight delivery_unavailable api_error].freeze
|
|
14
|
+
RESEND_FIX = 'Send it again with the same idempotency_key within 24 hours of the first request that used it, so ' \
|
|
15
|
+
'it goes out once.'
|
|
16
|
+
BATCH_RESEND_FIX = 'Send each recipient again with the same idempotency_key within 24 hours of the first request ' \
|
|
17
|
+
'that used it, so each email goes out once.'
|
|
18
|
+
UNAVAILABLE_FIX = "Until batch sends are on for the project, send each email the batch didn't queue with " \
|
|
19
|
+
"emails.send and its recipient's idempotency_key."
|
|
20
|
+
NO_TEMPLATE = {
|
|
21
|
+
'code' => 'not_found',
|
|
22
|
+
'detail' => "PostHog found no template with this ID, or batch sends aren't available for this project, so it " \
|
|
23
|
+
'sent no email of this request.',
|
|
24
|
+
'fix' => "Check template_id. If it's right, send each recipient on its own with emails.send and its " \
|
|
25
|
+
'idempotency_key until batch sends are available.'
|
|
26
|
+
}.freeze
|
|
27
|
+
NO_CODE_BATCH = {
|
|
28
|
+
'code' => 'not_found',
|
|
29
|
+
'detail' => "Batch sends, or sends from code, aren't available for this project, so PostHog sent no email of " \
|
|
30
|
+
'this request.',
|
|
31
|
+
'fix' => 'If this project can send email from code, send each recipient on its own with emails.send and its ' \
|
|
32
|
+
'idempotency_key until batch sends are available.'
|
|
33
|
+
}.freeze
|
|
34
|
+
TOO_LARGE = {
|
|
35
|
+
'code' => 'content_too_large',
|
|
36
|
+
'detail' => 'PostHog refused the batch as too large, so no email was sent.',
|
|
37
|
+
'fix' => 'Split the recipients into smaller batches.'
|
|
38
|
+
}.freeze
|
|
39
|
+
SMALLER_FIX = 'Make the email smaller, such as its template_data.'
|
|
40
|
+
MAY_HAVE_GONE_OUT = "so some of its emails may have gone out: read each recipient's result."
|
|
41
|
+
EARLIER_REFUSED = 'PostHog refused a retry of this batch with %s. An earlier attempt may have queued it, ' \
|
|
42
|
+
"#{MAY_HAVE_GONE_OUT}".freeze
|
|
43
|
+
EARLIER_CLOSED = 'The PostHog client shut down before a retry of this batch. An earlier attempt may have queued ' \
|
|
44
|
+
"it, #{MAY_HAVE_GONE_OUT}".freeze
|
|
45
|
+
RESULT_DEFAULTS = { message_id: nil, replayed: false, error: nil }.freeze
|
|
46
|
+
private_constant :UNCONFIRMED_CODES, :RESEND_FIX, :BATCH_RESEND_FIX, :MAY_HAVE_GONE_OUT, :EARLIER_REFUSED,
|
|
47
|
+
:EARLIER_CLOSED, :UNAVAILABLE_FIX, :NO_TEMPLATE, :NO_CODE_BATCH,
|
|
48
|
+
:TOO_LARGE,
|
|
49
|
+
:SMALLER_FIX, :RESULT_DEFAULTS
|
|
50
|
+
|
|
51
|
+
Member = Struct.new(:index, :to, :idempotency_key, :wire, keyword_init: true)
|
|
52
|
+
|
|
53
|
+
attr_reader :body
|
|
54
|
+
|
|
55
|
+
# @param shared [Hash] The batch's email without its recipients.
|
|
56
|
+
# @param members [Array<Member>] Every recipient, with its JSON as the request carries it. The body takes it
|
|
57
|
+
# over, so each member's +wire+ is +nil+ afterwards.
|
|
58
|
+
# @param parse_warnings [#call] Turns a reply's warnings into {Emails::Warning}s.
|
|
59
|
+
# @param reply_error [#call] Turns a refused reply into an {EmailError}.
|
|
60
|
+
def initialize(shared, members, parse_warnings:, reply_error:)
|
|
61
|
+
@members = members
|
|
62
|
+
@parse_warnings = parse_warnings
|
|
63
|
+
@reply_error = reply_error
|
|
64
|
+
@warnings = []
|
|
65
|
+
@maybe_queued = false
|
|
66
|
+
@attempt_error = nil
|
|
67
|
+
@template_form = shared.key?(:template_id)
|
|
68
|
+
head = JSON.generate(shared.merge(recipients: [])).delete_suffix(']}')
|
|
69
|
+
# A buffer of the exact size, and each recipient's JSON dropped once copied, so the request body is the only copy
|
|
70
|
+
# of the batch through every retry.
|
|
71
|
+
size = head.bytesize + members.sum { |member| member.wire.bytesize + 1 } + 1
|
|
72
|
+
@body = String.new(head, capacity: size, encoding: Encoding::UTF_8)
|
|
73
|
+
members.each_with_index do |member, index|
|
|
74
|
+
@body << ',' unless index.zero?
|
|
75
|
+
@body << member.wire
|
|
76
|
+
member.wire = nil
|
|
77
|
+
end
|
|
78
|
+
@body << ']}'
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
# @return [Emails::BatchResult] The result of an answer with a result for each recipient.
|
|
82
|
+
# @raise [EmailError] PostHog refused the request, or answered without a result for each recipient.
|
|
83
|
+
def answer((status, payload, retry_after))
|
|
84
|
+
fields = payload.is_a?(Hash) ? payload : {}
|
|
85
|
+
raise response_error(fields, status, retry_after) unless status.between?(200, 299)
|
|
86
|
+
|
|
87
|
+
@warnings = @parse_warnings.call(fields['warnings']).uniq
|
|
88
|
+
slots = fields['results']
|
|
89
|
+
unless slots.is_a?(Array) && slots.size == @members.size
|
|
90
|
+
raise EmailError.new(code: 'api_error', status_code: status, fix: RESEND_FIX,
|
|
91
|
+
message: 'PostHog answered the batch without a result for each recipient.')
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
results = @members.zip(slots).map { |member, slot| settle(member, slot.is_a?(Hash) ? slot : {}) }
|
|
95
|
+
Emails::BatchResult.new(results: results.freeze, warnings: @warnings.dup.freeze)
|
|
96
|
+
end
|
|
97
|
+
|
|
98
|
+
# Remembers an attempt that failed, so a later attempt's refusal can't confirm what this one may have queued.
|
|
99
|
+
def attempt_failed(error)
|
|
100
|
+
@attempt_error = error
|
|
101
|
+
@maybe_queued = true if maybe_queued?(error)
|
|
102
|
+
end
|
|
103
|
+
|
|
104
|
+
# Every recipient of a request that failed as a whole is `unconfirmed` when any attempt may have queued it, and
|
|
105
|
+
# `failed` otherwise.
|
|
106
|
+
def failure(error)
|
|
107
|
+
if @maybe_queued
|
|
108
|
+
# A refusal's why speaks for its own attempt, and can say nothing was sent.
|
|
109
|
+
why = error.why if maybe_queued?(error)
|
|
110
|
+
recipient_error = restate(error, unconfirmed_message(error.code), RESEND_FIX, why)
|
|
111
|
+
error = restate(error, earlier_message(error), BATCH_RESEND_FIX, why)
|
|
112
|
+
end
|
|
113
|
+
status = @maybe_queued ? 'unconfirmed' : 'failed'
|
|
114
|
+
results = @members.map { |member| result(member, status, error: recipient_error || error) }
|
|
115
|
+
EmailBatchError.new(error, results: results.freeze, warnings: @warnings.dup.freeze)
|
|
116
|
+
end
|
|
117
|
+
|
|
118
|
+
private
|
|
119
|
+
|
|
120
|
+
# The status, not the code, says whether PostHog may have queued the emails: a 4xx refused them, except a 409 for
|
|
121
|
+
# keys still in flight. No answer, a 5xx and a 2xx without a result for each recipient leave them unknown.
|
|
122
|
+
def maybe_queued?(error)
|
|
123
|
+
status = error.status_code.to_i
|
|
124
|
+
return true unless status.between?(400, 499)
|
|
125
|
+
|
|
126
|
+
# PostHog's only other 409 is batch_unavailable, so a 409 whose body didn't name it may hold keys in flight.
|
|
127
|
+
status == 409 && error.code != 'batch_unavailable'
|
|
128
|
+
end
|
|
129
|
+
|
|
130
|
+
def settle(member, slot)
|
|
131
|
+
message_id = text(slot['message_id'])
|
|
132
|
+
if slot['error'].nil? && slot['status'] == 'queued' && message_id
|
|
133
|
+
return result(member, 'queued', message_id: message_id, replayed: slot['replayed'] == true)
|
|
134
|
+
end
|
|
135
|
+
|
|
136
|
+
answer = slot_error(slot['error'], message_id)
|
|
137
|
+
if UNCONFIRMED_CODES.include?(answer.code)
|
|
138
|
+
return result(member, 'unconfirmed', message_id: message_id, error: answer)
|
|
139
|
+
elsif @maybe_queued
|
|
140
|
+
# A refusal can't confirm an email that an earlier attempt of the request may have queued.
|
|
141
|
+
message = "PostHog didn't confirm this email: it refused a retry with #{answer.code}, but an earlier attempt " \
|
|
142
|
+
'of this batch may have queued it, so it may still go out.'
|
|
143
|
+
return result(member, 'unconfirmed', message_id: message_id, error: restate(answer, message, RESEND_FIX, nil))
|
|
144
|
+
end
|
|
145
|
+
|
|
146
|
+
result(member, 'failed', message_id: message_id, error: answer)
|
|
147
|
+
end
|
|
148
|
+
|
|
149
|
+
def result(member, status, **fields)
|
|
150
|
+
identity = { index: member.index, to: member.to, idempotency_key: member.idempotency_key, status: status }
|
|
151
|
+
Emails::BatchEmailResult.new(**RESULT_DEFAULTS, **identity, **fields)
|
|
152
|
+
end
|
|
153
|
+
|
|
154
|
+
# PostHog's text speaks for the last attempt only: it can say nothing was sent, or advise a split or new keys, while
|
|
155
|
+
# an earlier attempt may have queued every email. A caller who follows it without the keys sends a second email.
|
|
156
|
+
def earlier_message(error)
|
|
157
|
+
# The client raises client_closed itself, without a request.
|
|
158
|
+
return EARLIER_CLOSED unless @attempt_error.equal?(error)
|
|
159
|
+
|
|
160
|
+
maybe_queued?(error) ? error.message : format(EARLIER_REFUSED, error.code)
|
|
161
|
+
end
|
|
162
|
+
|
|
163
|
+
def unconfirmed_message(code)
|
|
164
|
+
"PostHog didn't confirm this email (#{code}), so it may still go out."
|
|
165
|
+
end
|
|
166
|
+
|
|
167
|
+
def restate(error, message, fix, why)
|
|
168
|
+
EmailError.new(code: error.code, message: message, status_code: error.status_code, why: why, fix: fix,
|
|
169
|
+
docs_url: error.docs_url, field: error.field, retry_after: error.retry_after,
|
|
170
|
+
message_id: error.message_id)
|
|
171
|
+
end
|
|
172
|
+
|
|
173
|
+
def response_error(fields, status, retry_after)
|
|
174
|
+
answered = fields.compact
|
|
175
|
+
fields = if status == 404 && unnamed_not_found?(answered)
|
|
176
|
+
# An unknown template, batch sends that are off and a server without the route answer alike, and
|
|
177
|
+
# after launch a wrong template ID is the likely one.
|
|
178
|
+
@template_form ? NO_TEMPLATE : NO_CODE_BATCH
|
|
179
|
+
elsif status == 413
|
|
180
|
+
too_large(answered)
|
|
181
|
+
else
|
|
182
|
+
answered
|
|
183
|
+
end
|
|
184
|
+
fields = fields.merge('fix' => UNAVAILABLE_FIX) if fields['code'] == 'batch_unavailable'
|
|
185
|
+
@reply_error.call(fields, status, retry_after)
|
|
186
|
+
end
|
|
187
|
+
|
|
188
|
+
def unnamed_not_found?(answered)
|
|
189
|
+
%w[not_found api_error].include?(text(answered['code']) || 'api_error') && text(answered['attr']).nil?
|
|
190
|
+
end
|
|
191
|
+
|
|
192
|
+
def too_large(answered)
|
|
193
|
+
fields = TOO_LARGE.merge(answered.select { |_, value| text(value) })
|
|
194
|
+
# One recipient can't be split, so only a smaller email gets through, whatever the reply advises.
|
|
195
|
+
@members.size > 1 ? fields : fields.merge('fix' => SMALLER_FIX)
|
|
196
|
+
end
|
|
197
|
+
|
|
198
|
+
def slot_error(error, message_id)
|
|
199
|
+
unless error.is_a?(Hash)
|
|
200
|
+
return EmailError.new(code: 'api_error', message_id: message_id, fix: RESEND_FIX,
|
|
201
|
+
message: "PostHog didn't confirm this email: its answer had no readable result for it, " \
|
|
202
|
+
'so it may still go out.')
|
|
203
|
+
end
|
|
204
|
+
|
|
205
|
+
code = text(error['code']) || 'api_error'
|
|
206
|
+
status = error['status'].is_a?(Integer) ? error['status'] : nil
|
|
207
|
+
# EmailError#message_id means PostHog may have accepted the email, so a refusal leaves it on the result only.
|
|
208
|
+
unconfirmed = UNCONFIRMED_CODES.include?(code)
|
|
209
|
+
# PostHog's detail for these codes can read as a refusal or advise a retry, while the email may still go out.
|
|
210
|
+
message = if unconfirmed
|
|
211
|
+
unconfirmed_message(code)
|
|
212
|
+
else
|
|
213
|
+
text(error['detail']) || "PostHog didn't queue this email: #{code}."
|
|
214
|
+
end
|
|
215
|
+
EmailError.new(code: code, status_code: status, message_id: (message_id if unconfirmed),
|
|
216
|
+
fix: (RESEND_FIX if unconfirmed), message: message)
|
|
217
|
+
end
|
|
218
|
+
|
|
219
|
+
# A blank string, or one that isn't valid UTF-8, names nothing.
|
|
220
|
+
def text(value)
|
|
221
|
+
value if value.is_a?(String) && value.valid_encoding? && !value.strip.empty?
|
|
222
|
+
end
|
|
223
|
+
end
|
|
224
|
+
end
|
data/lib/posthog/email_error.rb
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
3
|
module PostHog
|
|
4
|
-
# PostHog did not queue the email, or the client could not tell whether it did.
|
|
4
|
+
# PostHog did not queue the email, or the client could not tell whether it did. An error with a {#message_id}
|
|
5
|
+
# is the exception: PostHog accepted that email, which may still go out, so read it with {Emails#get} before you
|
|
6
|
+
# send again.
|
|
5
7
|
#
|
|
6
8
|
# Branch on {#code}, PostHog's stable error code, or on {#name}, a coarse category of the failure.
|
|
7
9
|
# The message never contains the secret key or the request body.
|
|
@@ -23,9 +25,17 @@ module PostHog
|
|
|
23
25
|
attr_reader :field
|
|
24
26
|
# @return [Float, nil] How long PostHog asked the client to wait before it sends again, in seconds.
|
|
25
27
|
attr_reader :retry_after
|
|
28
|
+
# @return [String, nil] The message ID of an email PostHog accepted although the call failed, such as an email
|
|
29
|
+
# whose `schedule_not_confirmed` means it may go out at another time. Read its status with {Emails#get}.
|
|
30
|
+
attr_reader :message_id
|
|
31
|
+
# @return [Array<Emails::Warning>] PostHog's warnings about the emails it accepted although the call failed, each
|
|
32
|
+
# once, such as those of a batch's requests that went out. The client logs warnings only for a call that
|
|
33
|
+
# succeeds.
|
|
34
|
+
attr_reader :warnings
|
|
26
35
|
|
|
27
36
|
# @api private
|
|
28
|
-
def initialize(code:, message:, status_code: nil, why: nil, fix: nil, docs_url: nil, field: nil, retry_after: nil
|
|
37
|
+
def initialize(code:, message:, status_code: nil, why: nil, fix: nil, docs_url: nil, field: nil, retry_after: nil,
|
|
38
|
+
message_id: nil, warnings: [])
|
|
29
39
|
super(message)
|
|
30
40
|
@name = self.class.name_for(status_code, code)
|
|
31
41
|
@code = code
|
|
@@ -35,15 +45,21 @@ module PostHog
|
|
|
35
45
|
@docs_url = docs_url
|
|
36
46
|
@field = field
|
|
37
47
|
@retry_after = retry_after
|
|
48
|
+
@message_id = message_id
|
|
49
|
+
@warnings = warnings.dup.freeze
|
|
38
50
|
end
|
|
39
51
|
|
|
40
52
|
SDK_ERROR_NAMES = {
|
|
41
53
|
'network_error' => 'service_unavailable',
|
|
42
54
|
'invalid_attachment' => 'validation_error',
|
|
43
55
|
'too_many_attachments' => 'validation_error',
|
|
44
|
-
'message_too_large' => 'validation_error'
|
|
56
|
+
'message_too_large' => 'validation_error',
|
|
57
|
+
'delivery_unavailable' => 'service_unavailable',
|
|
58
|
+
'content_too_large' => 'validation_error'
|
|
45
59
|
}.freeze
|
|
46
|
-
|
|
60
|
+
# A 409 PostHog answers before it takes the request, so no idempotency key is in flight.
|
|
61
|
+
VALIDATION_CONFLICTS = %w[template_outdated batch_unavailable].freeze
|
|
62
|
+
private_constant :SDK_ERROR_NAMES, :VALIDATION_CONFLICTS
|
|
47
63
|
|
|
48
64
|
# @api private
|
|
49
65
|
def self.name_for(status_code, code)
|
|
@@ -55,7 +71,7 @@ module PostHog
|
|
|
55
71
|
when 400 then 'validation_error'
|
|
56
72
|
when 403 then 'invalid_permission'
|
|
57
73
|
when 404 then 'not_found'
|
|
58
|
-
when 409 then code
|
|
74
|
+
when 409 then VALIDATION_CONFLICTS.include?(code) ? 'validation_error' : 'concurrent_idempotent_requests'
|
|
59
75
|
when 422 then code == 'idempotency_key_reused' ? 'invalid_idempotent_request' : 'validation_error'
|
|
60
76
|
when 429 then code == 'quota_limited' ? 'monthly_quota_exceeded' : 'rate_limit_exceeded'
|
|
61
77
|
when 503 then 'service_unavailable'
|
|
@@ -63,4 +79,21 @@ module PostHog
|
|
|
63
79
|
end
|
|
64
80
|
end
|
|
65
81
|
end
|
|
82
|
+
|
|
83
|
+
# The request of {Emails#batch} failed as a whole.
|
|
84
|
+
#
|
|
85
|
+
# The other fields describe its error. {#results} holds every recipient: `unconfirmed` where PostHog may have queued
|
|
86
|
+
# them in any attempt, such as after a lost answer or while it held their keys, and `failed` otherwise.
|
|
87
|
+
class EmailBatchError < EmailError
|
|
88
|
+
# @return [Array<Emails::BatchEmailResult>] One result per recipient, in the order of the batch's recipients.
|
|
89
|
+
attr_reader :results
|
|
90
|
+
|
|
91
|
+
# @api private
|
|
92
|
+
def initialize(error, results:, warnings:)
|
|
93
|
+
super(code: error.code, message: error.message, status_code: error.status_code, why: error.why, fix: error.fix,
|
|
94
|
+
docs_url: error.docs_url, field: error.field, retry_after: error.retry_after, message_id: error.message_id,
|
|
95
|
+
warnings: warnings)
|
|
96
|
+
@results = results
|
|
97
|
+
end
|
|
98
|
+
end
|
|
66
99
|
end
|
data/lib/posthog/emails.rb
CHANGED
|
@@ -3,12 +3,14 @@
|
|
|
3
3
|
require 'json'
|
|
4
4
|
require 'net/http'
|
|
5
5
|
require 'openssl'
|
|
6
|
+
require 'date'
|
|
6
7
|
require 'securerandom'
|
|
7
8
|
require 'time'
|
|
8
9
|
require 'uri'
|
|
9
10
|
require 'zlib'
|
|
10
11
|
|
|
11
12
|
require 'posthog/email_attachments'
|
|
13
|
+
require 'posthog/email_batch'
|
|
12
14
|
require 'posthog/email_error'
|
|
13
15
|
require 'posthog/logging'
|
|
14
16
|
require 'posthog/utils'
|
|
@@ -45,6 +47,26 @@ module PostHog
|
|
|
45
47
|
# distinct_id: 'user_123'
|
|
46
48
|
# )
|
|
47
49
|
#
|
|
50
|
+
# @example An email scheduled for tomorrow, on PostHog Cloud
|
|
51
|
+
# result = posthog.emails.send(
|
|
52
|
+
# to: 'user@example.com',
|
|
53
|
+
# template_id: '0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b',
|
|
54
|
+
# scheduled_at: Time.now + 86_400,
|
|
55
|
+
# idempotency_key: 'trial-ending:user_123'
|
|
56
|
+
# )
|
|
57
|
+
# result.status # => "scheduled"
|
|
58
|
+
# result.scheduled_at # => the time in UTC
|
|
59
|
+
#
|
|
60
|
+
# @example The same template for many recipients, one email each
|
|
61
|
+
# result = posthog.emails.batch(
|
|
62
|
+
# template_id: '0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b',
|
|
63
|
+
# recipients: [
|
|
64
|
+
# { to: 'ada@example.com', idempotency_key: 'launch:ada', template_data: { name: 'Ada' } },
|
|
65
|
+
# { to: 'alan@example.com', idempotency_key: 'launch:alan', template_data: { name: 'Alan' } }
|
|
66
|
+
# ]
|
|
67
|
+
# )
|
|
68
|
+
# result.results.reject { |email| email.status == 'queued' } # => send these again with the same keys
|
|
69
|
+
#
|
|
48
70
|
# @example Email headers and event tags on a code send
|
|
49
71
|
# posthog.emails.send(
|
|
50
72
|
# to: 'user@example.com',
|
|
@@ -58,15 +80,23 @@ module PostHog
|
|
|
58
80
|
include PostHog::Logging
|
|
59
81
|
include PostHog::Utils
|
|
60
82
|
|
|
61
|
-
# The
|
|
83
|
+
# The accepted email. A result means PostHog queued or scheduled the email, not that it was delivered.
|
|
62
84
|
#
|
|
63
85
|
# @!attribute [r] id
|
|
64
|
-
# @return [String] The
|
|
86
|
+
# @return [String] The accepted email's message ID.
|
|
65
87
|
# @!attribute [r] replayed
|
|
66
88
|
# @return [Boolean] Whether PostHog had already accepted this idempotency key and returned the first result.
|
|
67
89
|
# @!attribute [r] warnings
|
|
68
90
|
# @return [Array<Warning>]
|
|
69
|
-
|
|
91
|
+
# @!attribute [r] scheduled_at
|
|
92
|
+
# @return [Time, nil] When a scheduled email goes out, in UTC. +nil+ for an email that goes out now, also when
|
|
93
|
+
# its +scheduled_at+ had already passed when PostHog accepted it.
|
|
94
|
+
SendResult = Struct.new(:id, :replayed, :warnings, :scheduled_at, keyword_init: true) do
|
|
95
|
+
# @return [String] `scheduled` when the email waits for its {#scheduled_at}, `queued` when it goes out now.
|
|
96
|
+
def status
|
|
97
|
+
scheduled_at.nil? ? 'queued' : 'scheduled'
|
|
98
|
+
end
|
|
99
|
+
end
|
|
70
100
|
|
|
71
101
|
# A warning PostHog returned with a queued email.
|
|
72
102
|
Warning = Struct.new(:code, :message, :fix, keyword_init: true)
|
|
@@ -74,18 +104,61 @@ module PostHog
|
|
|
74
104
|
# What happened to an email that {Emails#send} queued.
|
|
75
105
|
#
|
|
76
106
|
# @!attribute [r] status
|
|
77
|
-
# @return [String] `queued`, `sent`, `failed`, `delivered`, `bounced` or `complained`.
|
|
78
|
-
# can see values this list does not
|
|
107
|
+
# @return [String] `scheduled`, `queued`, `sent`, `failed`, `delivered`, `bounced` or `complained`. A
|
|
108
|
+
# scheduled email reads `scheduled` until it goes out. Later SDK versions can see values this list does not
|
|
109
|
+
# have yet.
|
|
79
110
|
# @!attribute [r] reason
|
|
80
111
|
# @return [String, nil] Why a failed email was not sent, such as `recipient_suppressed`, or the bounce type
|
|
81
112
|
# of a bounced email: `hard`, `soft` or `unknown`.
|
|
82
113
|
Status = Struct.new(:id, :status, :created_at, :status_at, :reason, keyword_init: true)
|
|
83
114
|
|
|
115
|
+
# What happened to one recipient of {Emails#batch}.
|
|
116
|
+
#
|
|
117
|
+
# @!attribute [r] index
|
|
118
|
+
# @return [Integer] The recipient's position in +recipients+.
|
|
119
|
+
# @!attribute [r] to
|
|
120
|
+
# @return [String] The recipient's email address.
|
|
121
|
+
# @!attribute [r] idempotency_key
|
|
122
|
+
# @return [String] The recipient's key, given or made by the client.
|
|
123
|
+
# @!attribute [r] status
|
|
124
|
+
# @return [String] One of:
|
|
125
|
+
# - `queued`: PostHog accepted the email. Read it with {Emails#get} to see whether it went out.
|
|
126
|
+
# - `failed`: PostHog didn't queue the email, and {#error} says why, such as a suppressed address.
|
|
127
|
+
# - `unconfirmed`: the client can't tell whether PostHog queued the email, such as after a lost answer, also
|
|
128
|
+
# when a retry's answer refused it. It may still go out. Send it again with the same +idempotency_key+
|
|
129
|
+
# within 24 hours of the first request that used it, so it goes out once.
|
|
130
|
+
# @!attribute [r] message_id
|
|
131
|
+
# @return [String, nil] The email's message ID, when PostHog named it.
|
|
132
|
+
# @!attribute [r] replayed
|
|
133
|
+
# @return [Boolean] PostHog's marker that an earlier send with the same key had already queued the email, so
|
|
134
|
+
# no new email went out. A replay that follows the first send at once can read +false+ even then; the same
|
|
135
|
+
# {#message_id} is what shows it is the same email.
|
|
136
|
+
# @!attribute [r] error
|
|
137
|
+
# @return [EmailError, nil] Why the email is not `queued`. For an `unconfirmed` email, {EmailError#code} names
|
|
138
|
+
# what left it so, such as `idempotency_key_in_flight`, `delivery_unavailable`, `api_error` or
|
|
139
|
+
# `network_error`, and {EmailError#fix} says to send it again with the same key.
|
|
140
|
+
BatchEmailResult = Struct.new(:index, :to, :idempotency_key, :status, :message_id, :replayed, :error,
|
|
141
|
+
keyword_init: true)
|
|
142
|
+
|
|
143
|
+
# The answer to {Emails#batch}.
|
|
144
|
+
#
|
|
145
|
+
# @!attribute [r] results
|
|
146
|
+
# @return [Array<BatchEmailResult>] One result per recipient, in the order of +recipients+.
|
|
147
|
+
# @!attribute [r] warnings
|
|
148
|
+
# @return [Array<Warning>] Warnings PostHog returned about the batch, each once.
|
|
149
|
+
BatchResult = Struct.new(:results, :warnings, keyword_init: true)
|
|
150
|
+
|
|
84
151
|
SEND_PATH = '/api/messaging/send/email/'
|
|
85
152
|
UPLOADS_PATH = '/api/messaging/attachments/uploads/'
|
|
86
153
|
STATUS_PATH = '/api/messaging/emails/%<message_id>s/'
|
|
154
|
+
BATCH_PATH = '/api/messaging/send/email_batch/'
|
|
155
|
+
# PostHog waits up to 30 seconds for its pipeline before it answers a batch. Connecting and writing keep the
|
|
156
|
+
# client's timeout.
|
|
157
|
+
BATCH_ATTEMPT_TIMEOUT_SECONDS = 45.0
|
|
158
|
+
BATCH_RECIPIENT_FIELDS = %w[to distinct_id idempotency_key template_data].freeze
|
|
87
159
|
US_APP_HOST = 'https://us.posthog.com'
|
|
88
160
|
EU_APP_HOST = 'https://eu.posthog.com'
|
|
161
|
+
SCHEDULING_APP_HOSTS = [US_APP_HOST, EU_APP_HOST].freeze
|
|
89
162
|
CLOUD_APP_HOSTS = {
|
|
90
163
|
'https://us.i.posthog.com' => US_APP_HOST,
|
|
91
164
|
'https://us.posthog.com' => US_APP_HOST,
|
|
@@ -98,6 +171,13 @@ module PostHog
|
|
|
98
171
|
IDEMPOTENCY_KEY_PATTERN = /\A[\x21-\x7e]{1,255}\z/
|
|
99
172
|
TEMPLATE_KEY_PATTERN = /\A[a-zA-Z0-9_-]{1,400}\z/
|
|
100
173
|
HEADER_TOKEN_PATTERN = /\A[\x21-\x7e]+\z/
|
|
174
|
+
SCHEDULED_AT_PATTERN = /
|
|
175
|
+
\A(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?
|
|
176
|
+
(?:Z|([+-]\d{2}):?(\d{2}))\z
|
|
177
|
+
/x
|
|
178
|
+
SEND_NOW_TOLERANCE_SECONDS = 60
|
|
179
|
+
SCHEDULED_AT_NEEDED = 'scheduled_at must be a Time, or an ISO 8601 time with an offset, such as ' \
|
|
180
|
+
'2026-12-01T09:00:00Z or 2026-12-01T10:00:00+01:00, so no email was sent.'
|
|
101
181
|
JSON_CONTENT = { 'Content-Type' => 'application/json' }.freeze
|
|
102
182
|
SEND_KEY_NEEDED = 'Sending email needs secret_key, a project secret API key with the ' \
|
|
103
183
|
'transactional_email:write scope.'
|
|
@@ -114,10 +194,14 @@ module PostHog
|
|
|
114
194
|
Timeout::Error, SocketError, SystemCallError, IOError, EOFError, OpenSSL::SSL::SSLError,
|
|
115
195
|
Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError, Zlib::Error
|
|
116
196
|
].freeze
|
|
117
|
-
private_constant :SEND_PATH, :UPLOADS_PATH, :STATUS_PATH, :
|
|
118
|
-
:
|
|
119
|
-
:
|
|
120
|
-
:
|
|
197
|
+
private_constant :SEND_PATH, :UPLOADS_PATH, :STATUS_PATH, :BATCH_PATH,
|
|
198
|
+
:BATCH_ATTEMPT_TIMEOUT_SECONDS, :BATCH_RECIPIENT_FIELDS, :US_APP_HOST, :EU_APP_HOST,
|
|
199
|
+
:CLOUD_APP_HOSTS,
|
|
200
|
+
:SCHEDULING_APP_HOSTS, :MAX_RETRY_DELAY_SECONDS, :UUID_PATTERN, :IDEMPOTENCY_KEY_PATTERN,
|
|
201
|
+
:TEMPLATE_KEY_PATTERN, :HEADER_TOKEN_PATTERN, :SCHEDULED_AT_PATTERN, :SEND_NOW_TOLERANCE_SECONDS,
|
|
202
|
+
:SCHEDULED_AT_NEEDED,
|
|
203
|
+
:JSON_CONTENT, :SEND_KEY_NEEDED, :READ_KEY_NEEDED, :TEMPLATE_FORM_WHY, :CODE_FORM_WHY,
|
|
204
|
+
:TEMPLATE_FIELDS, :CODE_FIELDS, :NETWORK_ERRORS
|
|
121
205
|
|
|
122
206
|
# @api private
|
|
123
207
|
def initialize(secret_key:, host:, app_host:, timeout:, max_retries:, migrated_from:, user_agent:, disabled:,
|
|
@@ -210,19 +294,36 @@ module PostHog
|
|
|
210
294
|
# retries the send.
|
|
211
295
|
# @param max_retries [Integer] Overrides the client's `email_request_max_retries` for this send. +0+ turns
|
|
212
296
|
# retries off.
|
|
213
|
-
# @
|
|
297
|
+
# @param scheduled_at [Time, DateTime, String] When to send the email, at most 7 days ahead: a +Time+, such as
|
|
298
|
+
# +Time.now + 3600+ or a Rails time with zone, a +DateTime+, or an ISO 8601 time with an offset, such as
|
|
299
|
+
# `2026-12-01T10:00:00+01:00`. A time that has passed sends the email now. PostHog keeps the time to the
|
|
300
|
+
# millisecond, and the client rounds a finer time up to the next millisecond and sends that time on every retry.
|
|
301
|
+
# When PostHog sends the email now, the client accepts that for a time up to a minute ahead by this machine's
|
|
302
|
+
# clock, to allow for clock skew, so such an email can go out up to a minute early. Work out a relative time
|
|
303
|
+
# once and pass the same time when you send again with the same +idempotency_key+: another time with that key
|
|
304
|
+
# raises `idempotency_key_reused`. Only PostHog Cloud schedules emails. To stop scheduled emails, disable the
|
|
305
|
+
# email's workflow in PostHog until they have reached a final status, which refuses every new send of it
|
|
306
|
+
# meanwhile.
|
|
307
|
+
# @return [SendResult] The accepted email.
|
|
214
308
|
# @raise [EmailError] PostHog did not queue the email, or the client could not tell whether it did.
|
|
309
|
+
# With +scheduled_at+, {EmailError#code} is `scheduling_requires_cloud` before any request when the client's
|
|
310
|
+
# app host isn't PostHog Cloud US or EU, such as a self-hosted PostHog, a reverse proxy or a custom domain, which
|
|
311
|
+
# could send the email at once. It is `schedule_not_confirmed` when PostHog accepted the email without confirming
|
|
312
|
+
# its time, also when PostHog sends now an email due more than a minute ahead by this machine's clock: the email
|
|
313
|
+
# exists and may go out at another time, and {EmailError#message_id} names it. Read it with {#get} before you
|
|
314
|
+
# send again. The reply's warnings are on {EmailError#warnings}, and the client logs none of them.
|
|
215
315
|
# Before any request, {EmailError#code} is `invalid_attachment` for a file the client can't send,
|
|
216
316
|
# `too_many_attachments` for more than 10 files, and `message_too_large` for files too large for one email.
|
|
217
317
|
# It is `attachment_upload_failed` when file storage refused an upload, and `not_found` with
|
|
218
318
|
# {EmailError#field} `attachments` when PostHog has no upload route for this project. Unless `app_host` is
|
|
219
319
|
# an http URL, an upload URL without https raises `api_error` on the file's field, such as
|
|
220
320
|
# `attachments__0`, before any file goes out. No email was sent.
|
|
221
|
-
# @raise [ArgumentError] An argument has the wrong type or format,
|
|
321
|
+
# @raise [ArgumentError] An argument has the wrong type or format, such as a +scheduled_at+ without an offset, or
|
|
322
|
+
# the call mixes the two forms.
|
|
222
323
|
def send(
|
|
223
324
|
to:, template_id: nil, template_data: nil, template_key: nil, subject: nil, html: nil, text: nil, from: nil,
|
|
224
325
|
reply_to: nil, cc: nil, bcc: nil, attachments: nil, sensitive: nil, tracking: nil, capture_engagement: nil,
|
|
225
|
-
headers: nil, tags: nil, distinct_id: nil, idempotency_key: nil, max_retries: nil
|
|
326
|
+
headers: nil, tags: nil, distinct_id: nil, idempotency_key: nil, max_retries: nil, scheduled_at: nil
|
|
226
327
|
)
|
|
227
328
|
fields = {
|
|
228
329
|
template_data: template_data, subject: subject, html: html, text: text, from: from, reply_to: reply_to,
|
|
@@ -231,21 +332,117 @@ module PostHog
|
|
|
231
332
|
}.compact
|
|
232
333
|
check_recipient(to, distinct_id, idempotency_key, max_retries)
|
|
233
334
|
payload = content(template_id, template_key, fields).merge(to: to)
|
|
335
|
+
due = scheduled_time(scheduled_at)
|
|
234
336
|
files = EmailAttachments.from(fields.fetch(:attachments, []), bodies_with_derived_text(fields), fields[:subject])
|
|
235
337
|
payload[:attachments] = files.references unless files.empty?
|
|
236
338
|
payload[:distinct_id] = distinct_id unless distinct_id.nil?
|
|
339
|
+
payload[:scheduled_at] = time_in_iso8601(due) if due
|
|
237
340
|
body = JSON.generate(payload)
|
|
238
341
|
request_headers = { 'Content-Type' => 'application/json',
|
|
239
342
|
'Idempotency-Key' => idempotency_key || SecureRandom.uuid }
|
|
240
343
|
|
|
241
|
-
result = call('no email was sent', SEND_KEY_NEEDED) do |secret_key|
|
|
344
|
+
result, unconfirmed = call('no email was sent', SEND_KEY_NEEDED) do |secret_key|
|
|
345
|
+
check_schedulable if due
|
|
242
346
|
upload(files, secret_key, max_retries || @max_retries) unless files.empty?
|
|
243
347
|
uri = URI(@app_host + SEND_PATH)
|
|
348
|
+
# A slow reply must not move a time that was more than a minute ahead into the send-now window.
|
|
349
|
+
sent_at = Time.now
|
|
244
350
|
with_retries(max_retries || @max_retries) do
|
|
245
|
-
parse_send_reply(request(Net::HTTP::Post.new(uri), uri, secret_key, request_headers, body))
|
|
351
|
+
parse_send_reply(request(Net::HTTP::Post.new(uri), uri, secret_key, request_headers, body), due, sent_at)
|
|
246
352
|
end
|
|
247
353
|
end
|
|
248
|
-
|
|
354
|
+
raise unconfirmed if unconfirmed
|
|
355
|
+
|
|
356
|
+
log_warnings(result.warnings)
|
|
357
|
+
|
|
358
|
+
result
|
|
359
|
+
end
|
|
360
|
+
|
|
361
|
+
# Queues the same email for many recipients, one email each, from a template made in PostHog or from content
|
|
362
|
+
# your code rendered.
|
|
363
|
+
#
|
|
364
|
+
# Pass the template form, with +template_id+, or the code form, with +template_key+, as {#send} takes them. The
|
|
365
|
+
# client sends at most 100 recipients in one request and waits at least 45 seconds for the answer. PostHog
|
|
366
|
+
# refuses a batch too large to take at once with a 413 `content_too_large`: split the recipients into smaller
|
|
367
|
+
# batches, or, for one recipient, make the email smaller. A 400 `content_too_large` means the shared content is
|
|
368
|
+
# over PostHog's limit, which splitting doesn't change: make it smaller. A recipient whose own +template_data+ is
|
|
369
|
+
# over it comes back `failed` with `content_too_large` in its result, while the others go out. A batch takes no
|
|
370
|
+
# +cc+, +bcc+, +attachments+ or +scheduled_at+.
|
|
371
|
+
#
|
|
372
|
+
# Each recipient has an +idempotency_key+, given or made by the client, that every retry reuses, so a retry never
|
|
373
|
+
# queues an email twice. Retries follow {#send}'s. Send each `unconfirmed` email again with its
|
|
374
|
+
# +idempotency_key+ within 24 hours of the first request that used it, so it goes out once.
|
|
375
|
+
#
|
|
376
|
+
# @param recipients [Array<Hash>] 1 to 100 recipients, each a Hash with:
|
|
377
|
+
# - +to+ [String] the recipient's email address;
|
|
378
|
+
# - +distinct_id+ [String] optional: the recipient's distinct ID in your product;
|
|
379
|
+
# - +idempotency_key+ [String] optional: 1 to 255 visible ASCII characters, a different one for each recipient.
|
|
380
|
+
# Without it, the client makes one that covers its own retries but not a second call, so pass keys you store
|
|
381
|
+
# when a batch may be cut off and run again: a rerun within 24 hours replays the emails that went out instead
|
|
382
|
+
# of sending them twice. A send and a batch recipient with the same key and the same email replay each other;
|
|
383
|
+
# - +template_data+ [Hash] optional, only with +template_id+: values for this recipient, merged over the
|
|
384
|
+
# batch's +template_data+. A top-level key set here replaces the same key there.
|
|
385
|
+
# @param template_id [String] Template form: the UUID of a template made transactional in PostHog.
|
|
386
|
+
# @param template_data [Hash] Template form: values for the template, shared by every recipient.
|
|
387
|
+
# @param template_key [String] Code form: names the email, as {#send} takes it. Pass +subject+ and +html+, +text+
|
|
388
|
+
# or both, and optionally +from+, +reply_to+, +sensitive+, +tracking+ and +capture_engagement+, the same for
|
|
389
|
+
# every recipient. A recipient can't carry +template_data+: send personalized content with a +template_id+
|
|
390
|
+
# batch, or with {#send}.
|
|
391
|
+
# @param max_retries [Integer] Overrides the client's `email_request_max_retries` for the batch's request. +0+
|
|
392
|
+
# turns retries off.
|
|
393
|
+
# @return [BatchResult] A result per recipient, in the order of +recipients+. Check each
|
|
394
|
+
# {BatchEmailResult#status}, and send an `unconfirmed` email again with the same key so it goes out once. A
|
|
395
|
+
# logger that raises a StandardError other than Timeout::Error while logging the warnings doesn't lose the
|
|
396
|
+
# result.
|
|
397
|
+
# @raise [EmailBatchError] The request failed as a whole, such as a rate limit past its retries. The error is the
|
|
398
|
+
# last attempt's. {EmailBatchError#results} holds every recipient: `unconfirmed` with a fix to send it again with
|
|
399
|
+
# the same key when any attempt may have queued it (a 409 other than `batch_unavailable`, a 5xx, or a lost
|
|
400
|
+
# answer), and `failed` when PostHog refused the request with a 4xx and no earlier attempt may have queued it.
|
|
401
|
+
# When any attempt may have queued them, the error's fix is to send each recipient again with its key, each
|
|
402
|
+
# recipient's message says PostHog didn't confirm it and it may still go out, and when only an earlier attempt may
|
|
403
|
+
# have, the error's message says some emails may have gone out. The error is `client_closed` when the client shut
|
|
404
|
+
# down before a retry. {EmailError#code} is `content_too_large` with PostHog's fix: a 413 for a batch to split
|
|
405
|
+
# into smaller batches, or for one recipient an email to make smaller, and a 400 for shared content to make
|
|
406
|
+
# smaller. It is `batch_unavailable` when the project can't send batches yet: send each email the batch didn't
|
|
407
|
+
# queue with {#send} and its recipient's +idempotency_key+. It is `not_found` with no {EmailError#field} when
|
|
408
|
+
# PostHog found no template with the +template_id+ or batch sends aren't available for the project, which PostHog
|
|
409
|
+
# answers alike: check +template_id+, and if it's right, send each recipient on its own the same way. The warnings
|
|
410
|
+
# of an answer without a result for each recipient are on {EmailError#warnings}, and the client logs none of them.
|
|
411
|
+
# @raise [EmailError] The client sent nothing, such as when it is disabled or has no +secret_key+.
|
|
412
|
+
# @raise [ArgumentError] An argument has the wrong type or format, such as more than 100 recipients or two
|
|
413
|
+
# recipients with the same +idempotency_key+. No email was sent.
|
|
414
|
+
def batch(
|
|
415
|
+
recipients:, template_id: nil, template_data: nil, template_key: nil, subject: nil, html: nil, text: nil,
|
|
416
|
+
from: nil, reply_to: nil, sensitive: nil, tracking: nil, capture_engagement: nil, max_retries: nil
|
|
417
|
+
)
|
|
418
|
+
unless max_retries.nil? || retry_count?(max_retries)
|
|
419
|
+
raise ArgumentError,
|
|
420
|
+
'max_retries must be a nonnegative integer.'
|
|
421
|
+
end
|
|
422
|
+
|
|
423
|
+
fields = {
|
|
424
|
+
template_data: template_data, subject: subject, html: html, text: text, from: from, reply_to: reply_to,
|
|
425
|
+
sensitive: sensitive, tracking: tracking, capture_engagement: capture_engagement
|
|
426
|
+
}.compact
|
|
427
|
+
shared = content(template_id, template_key, fields)
|
|
428
|
+
members = batch_members(recipients, template_key.nil?)
|
|
429
|
+
run = EmailBatch.new(shared, members, parse_warnings: method(:warnings), reply_error: method(:reply_error))
|
|
430
|
+
|
|
431
|
+
result, failure = call('no email was sent', SEND_KEY_NEEDED) do |secret_key|
|
|
432
|
+
send_batch(run, secret_key, max_retries || @max_retries)
|
|
433
|
+
end
|
|
434
|
+
raise failure if failure
|
|
435
|
+
|
|
436
|
+
begin
|
|
437
|
+
log_warnings(result.warnings)
|
|
438
|
+
rescue Timeout::Error
|
|
439
|
+
# A caller's deadline, from Timeout.timeout with this class, still ends the call.
|
|
440
|
+
raise
|
|
441
|
+
rescue StandardError
|
|
442
|
+
# PostHog queued the emails and the result holds the warnings. Raising here loses the derived keys, and a
|
|
443
|
+
# resend without them sends each email twice.
|
|
444
|
+
end
|
|
445
|
+
|
|
249
446
|
result
|
|
250
447
|
end
|
|
251
448
|
|
|
@@ -287,6 +484,100 @@ module PostHog
|
|
|
287
484
|
|
|
288
485
|
private
|
|
289
486
|
|
|
487
|
+
def batch_members(recipients, template_form)
|
|
488
|
+
unless recipients.is_a?(Array)
|
|
489
|
+
raise ArgumentError,
|
|
490
|
+
"recipients must be an Array of recipients, each a Hash with to, such as [{ to: 'user@example.com' }]."
|
|
491
|
+
end
|
|
492
|
+
raise ArgumentError, 'recipients must hold at least one recipient.' if recipients.empty?
|
|
493
|
+
if recipients.size > EmailBatch::MAX_RECIPIENTS
|
|
494
|
+
raise ArgumentError, "recipients must hold at most #{EmailBatch::MAX_RECIPIENTS} recipients, not " \
|
|
495
|
+
"#{recipients.size}. Split them into smaller batches."
|
|
496
|
+
end
|
|
497
|
+
|
|
498
|
+
first_with_key = {}
|
|
499
|
+
recipients.each_with_index.map do |recipient, index|
|
|
500
|
+
fields = batch_recipient_fields(recipient, index)
|
|
501
|
+
member = batch_member(fields, index, template_form)
|
|
502
|
+
first = first_with_key[member.idempotency_key] ||= index
|
|
503
|
+
unless first == index
|
|
504
|
+
raise ArgumentError, "recipients[#{index}] has the same idempotency_key as recipients[#{first}]. Give each " \
|
|
505
|
+
'recipient its own key.'
|
|
506
|
+
end
|
|
507
|
+
|
|
508
|
+
member
|
|
509
|
+
end
|
|
510
|
+
end
|
|
511
|
+
|
|
512
|
+
def batch_recipient_fields(recipient, index)
|
|
513
|
+
fields = recipient.is_a?(Hash) ? Utils.stringify_keys(recipient) : {}
|
|
514
|
+
unless fields.key?('to')
|
|
515
|
+
raise ArgumentError, "recipients[#{index}] must be a Hash with to, such as { to: 'user@example.com' }."
|
|
516
|
+
end
|
|
517
|
+
|
|
518
|
+
unknown = fields.keys - BATCH_RECIPIENT_FIELDS
|
|
519
|
+
return fields if unknown.empty?
|
|
520
|
+
|
|
521
|
+
raise ArgumentError, "recipients[#{index}] takes only to, distinct_id, idempotency_key and template_data, not " \
|
|
522
|
+
"#{unknown.join(', ')}."
|
|
523
|
+
end
|
|
524
|
+
|
|
525
|
+
def batch_member(fields, index, template_form)
|
|
526
|
+
to, distinct_id, key, data = fields.values_at('to', 'distinct_id', 'idempotency_key', 'template_data')
|
|
527
|
+
begin
|
|
528
|
+
check_recipient(to, distinct_id, key, nil)
|
|
529
|
+
rescue ArgumentError => e
|
|
530
|
+
raise ArgumentError, "recipients[#{index}]: #{e.message}"
|
|
531
|
+
end
|
|
532
|
+
key ||= SecureRandom.uuid
|
|
533
|
+
wire = { to: to, idempotency_key: key }
|
|
534
|
+
wire[:distinct_id] = distinct_id unless distinct_id.nil?
|
|
535
|
+
unless data.nil?
|
|
536
|
+
unless template_form
|
|
537
|
+
raise ArgumentError, "recipients[#{index}] has template_data, but a batch with template_key sends the same " \
|
|
538
|
+
'content to every recipient. Send personalized content with a template_id batch or ' \
|
|
539
|
+
'with emails.send.'
|
|
540
|
+
end
|
|
541
|
+
raise ArgumentError, "recipients[#{index}]: template_data must be a Hash." unless data.is_a?(Hash)
|
|
542
|
+
|
|
543
|
+
wire[:message_data] = isoify_dates(data)
|
|
544
|
+
end
|
|
545
|
+
EmailBatch::Member.new(index: index, to: to, idempotency_key: key, wire: JSON.generate(wire))
|
|
546
|
+
end
|
|
547
|
+
|
|
548
|
+
def send_batch(run, secret_key, max_retries)
|
|
549
|
+
uri = URI(@app_host + BATCH_PATH)
|
|
550
|
+
read_timeout = [@timeout.to_f, BATCH_ATTEMPT_TIMEOUT_SECONDS].max
|
|
551
|
+
result = with_retries(max_retries) do |attempt|
|
|
552
|
+
if attempt.positive? && !still_admitted?
|
|
553
|
+
raise EmailError.new(code: 'client_closed',
|
|
554
|
+
message: "The PostHog client is shut down, so it didn't retry the batch.")
|
|
555
|
+
end
|
|
556
|
+
|
|
557
|
+
begin
|
|
558
|
+
run.answer(request(Net::HTTP::Post.new(uri), uri, secret_key, JSON_CONTENT, run.body,
|
|
559
|
+
read_timeout: read_timeout))
|
|
560
|
+
rescue EmailError => e
|
|
561
|
+
run.attempt_failed(e)
|
|
562
|
+
raise
|
|
563
|
+
end
|
|
564
|
+
end
|
|
565
|
+
[result, nil]
|
|
566
|
+
rescue EmailError => e
|
|
567
|
+
[nil, run.failure(e)]
|
|
568
|
+
end
|
|
569
|
+
|
|
570
|
+
def log_warnings(warnings)
|
|
571
|
+
warnings.each { |warning| logger.warn("PostHog email warning #{warning.code}: #{warning.message}") }
|
|
572
|
+
end
|
|
573
|
+
|
|
574
|
+
def still_admitted?
|
|
575
|
+
@mutex.synchronize do
|
|
576
|
+
forget_parent_requests
|
|
577
|
+
!@closed
|
|
578
|
+
end
|
|
579
|
+
end
|
|
580
|
+
|
|
290
581
|
def check_options(timeout, max_retries, migrated_from)
|
|
291
582
|
raise ArgumentError, 'email_request_timeout_seconds must be a positive number.' unless positive?(timeout)
|
|
292
583
|
raise ArgumentError, 'email_request_max_retries must be a nonnegative integer.' unless retry_count?(max_retries)
|
|
@@ -347,6 +638,50 @@ module PostHog
|
|
|
347
638
|
value.is_a?(String) && !value.strip.empty?
|
|
348
639
|
end
|
|
349
640
|
|
|
641
|
+
def scheduled_time(value)
|
|
642
|
+
return nil if value.nil?
|
|
643
|
+
|
|
644
|
+
instant = case value
|
|
645
|
+
when DateTime then Time.at((value - DateTime.new(1970, 1, 1)) * 86_400)
|
|
646
|
+
when Time then Time.at(value.to_r)
|
|
647
|
+
when String then offset_time(value)
|
|
648
|
+
end
|
|
649
|
+
raise ArgumentError, SCHEDULED_AT_NEEDED if instant.nil?
|
|
650
|
+
|
|
651
|
+
instant.utc.ceil(3)
|
|
652
|
+
end
|
|
653
|
+
|
|
654
|
+
def offset_time(value)
|
|
655
|
+
return nil unless value.valid_encoding? && value.encoding.ascii_compatible?
|
|
656
|
+
|
|
657
|
+
parts = SCHEDULED_AT_PATTERN.match(value)
|
|
658
|
+
return nil if parts.nil?
|
|
659
|
+
|
|
660
|
+
year, month, day, hour, minute, second, fraction, offset_hours, offset_minutes = parts.captures
|
|
661
|
+
return nil unless Date.valid_date?(year.to_i, month.to_i, day.to_i, Date::GREGORIAN)
|
|
662
|
+
return nil unless hour.to_i <= 23 && minute.to_i <= 59 && second.to_i <= 59
|
|
663
|
+
return nil unless offset_hours.to_s[1, 2].to_i <= 23 && offset_minutes.to_i <= 59
|
|
664
|
+
|
|
665
|
+
seconds = second.to_i + (fraction ? Rational(fraction.to_i, 10**fraction.size) : 0)
|
|
666
|
+
offset = offset_hours ? "#{offset_hours}:#{offset_minutes}" : '+00:00'
|
|
667
|
+
Time.new(year.to_i, month.to_i, day.to_i, hour.to_i, minute.to_i, seconds, offset)
|
|
668
|
+
end
|
|
669
|
+
|
|
670
|
+
def check_schedulable
|
|
671
|
+
return if SCHEDULING_APP_HOSTS.include?(@app_host)
|
|
672
|
+
|
|
673
|
+
uri = URI(@app_host)
|
|
674
|
+
host = uri.port == uri.default_port ? uri.host : "#{uri.host}:#{uri.port}"
|
|
675
|
+
raise EmailError.new(
|
|
676
|
+
code: 'scheduling_requires_cloud', field: 'scheduled_at',
|
|
677
|
+
message: 'Only PostHog Cloud (us.posthog.com or eu.posthog.com) schedules emails, and this client sends ' \
|
|
678
|
+
"email to #{host}, so no email was sent.",
|
|
679
|
+
why: "A PostHog that doesn't schedule emails would send this one at once.",
|
|
680
|
+
fix: "Send without scheduled_at, or set app_host to PostHog Cloud's app host. A reverse proxy or custom " \
|
|
681
|
+
"domain can't schedule emails yet."
|
|
682
|
+
)
|
|
683
|
+
end
|
|
684
|
+
|
|
350
685
|
def content(template_id, template_key, fields)
|
|
351
686
|
if template_id.nil? == template_key.nil?
|
|
352
687
|
raise ArgumentError, 'Send either template_id, or template_key with subject and html or text.'
|
|
@@ -482,7 +817,7 @@ module PostHog
|
|
|
482
817
|
def with_retries(max_retries)
|
|
483
818
|
attempt = 0
|
|
484
819
|
begin
|
|
485
|
-
yield
|
|
820
|
+
yield attempt
|
|
486
821
|
rescue EmailError => e
|
|
487
822
|
delay = retry_delay(e, attempt, max_retries)
|
|
488
823
|
raise if delay.nil?
|
|
@@ -587,21 +922,21 @@ module PostHog
|
|
|
587
922
|
)
|
|
588
923
|
end
|
|
589
924
|
|
|
590
|
-
def request(request, uri, secret_key, headers, body = nil)
|
|
925
|
+
def request(request, uri, secret_key, headers, body = nil, read_timeout: @timeout)
|
|
591
926
|
request['Authorization'] = "Bearer #{secret_key}"
|
|
592
927
|
request['Accept'] = 'application/json'
|
|
593
928
|
request['User-Agent'] = @user_agent if @user_agent
|
|
594
929
|
request['X-PostHog-Migrated-From'] = @migrated_from if @migrated_from
|
|
595
|
-
status, answer, retry_after = exchange(request, uri, headers, body)
|
|
930
|
+
status, answer, retry_after = exchange(request, uri, headers, body, read_timeout: read_timeout)
|
|
596
931
|
[status, parse_json(answer), retry_after]
|
|
597
932
|
end
|
|
598
933
|
|
|
599
|
-
def exchange(request, uri, headers, body)
|
|
934
|
+
def exchange(request, uri, headers, body, read_timeout: @timeout)
|
|
600
935
|
headers.each { |name, value| request[name] = value }
|
|
601
936
|
request.body = body if body
|
|
602
937
|
|
|
603
938
|
head = nil
|
|
604
|
-
response = Net::HTTP.start(uri.hostname, uri.port, connection_options(uri)) do |http|
|
|
939
|
+
response = Net::HTTP.start(uri.hostname, uri.port, connection_options(uri, read_timeout)) do |http|
|
|
605
940
|
http.request(request) { |started| head = started }
|
|
606
941
|
end
|
|
607
942
|
[response.code.to_i, response.body, parse_retry_after(response['Retry-After'])]
|
|
@@ -611,9 +946,9 @@ module PostHog
|
|
|
611
946
|
retry_after: head && parse_retry_after(head['Retry-After']))
|
|
612
947
|
end
|
|
613
948
|
|
|
614
|
-
def connection_options(uri)
|
|
949
|
+
def connection_options(uri, read_timeout)
|
|
615
950
|
options = {
|
|
616
|
-
use_ssl: uri.scheme == 'https', open_timeout: @timeout, read_timeout:
|
|
951
|
+
use_ssl: uri.scheme == 'https', open_timeout: @timeout, read_timeout: read_timeout, write_timeout: @timeout,
|
|
617
952
|
# Net::HTTP returns a body cut off by a closed connection as if it were whole. Raise instead.
|
|
618
953
|
max_retries: 0, ignore_eof: false
|
|
619
954
|
}
|
|
@@ -627,7 +962,7 @@ module PostHog
|
|
|
627
962
|
nil
|
|
628
963
|
end
|
|
629
964
|
|
|
630
|
-
def parse_send_reply((status, payload, retry_after))
|
|
965
|
+
def parse_send_reply((status, payload, retry_after), due, sent_at)
|
|
631
966
|
fields = payload.is_a?(Hash) ? payload : {}
|
|
632
967
|
raise reply_error(fields, status, retry_after) unless status.between?(200, 299)
|
|
633
968
|
|
|
@@ -637,7 +972,34 @@ module PostHog
|
|
|
637
972
|
status_code: status)
|
|
638
973
|
end
|
|
639
974
|
|
|
640
|
-
SendResult.new(id: id, replayed: fields['replayed'] == true, warnings: warnings(fields['warnings'])
|
|
975
|
+
result = SendResult.new(id: id, replayed: fields['replayed'] == true, warnings: warnings(fields['warnings']),
|
|
976
|
+
scheduled_at: nil)
|
|
977
|
+
return [result, nil] if due.nil? || time_had_passed?(fields, due, sent_at)
|
|
978
|
+
return [result, schedule_not_confirmed(id, status, result.warnings)] unless confirms?(fields, due)
|
|
979
|
+
|
|
980
|
+
result.scheduled_at = due
|
|
981
|
+
[result, nil]
|
|
982
|
+
end
|
|
983
|
+
|
|
984
|
+
def time_had_passed?(fields, due, sent_at)
|
|
985
|
+
fields['status'] == 'queued' && fields.key?('scheduled_at') && fields['scheduled_at'].nil? &&
|
|
986
|
+
due <= sent_at + SEND_NOW_TOLERANCE_SECONDS
|
|
987
|
+
end
|
|
988
|
+
|
|
989
|
+
def confirms?(fields, due)
|
|
990
|
+
answered = fields['scheduled_at']
|
|
991
|
+
fields['status'] == 'scheduled' && answered.is_a?(String) && offset_time(answered) == due
|
|
992
|
+
end
|
|
993
|
+
|
|
994
|
+
def schedule_not_confirmed(message_id, status, warnings)
|
|
995
|
+
EmailError.new(
|
|
996
|
+
code: 'schedule_not_confirmed', status_code: status, field: 'scheduled_at', message_id: message_id,
|
|
997
|
+
warnings: warnings,
|
|
998
|
+
message: "PostHog accepted email #{message_id} without confirming its scheduled_at, so it may go out at " \
|
|
999
|
+
'another time.',
|
|
1000
|
+
fix: "Read what happened to the email with emails.get('#{message_id}') before you send it again: a send " \
|
|
1001
|
+
'with another idempotency_key makes a second email.'
|
|
1002
|
+
)
|
|
641
1003
|
end
|
|
642
1004
|
|
|
643
1005
|
def warnings(entries)
|
data/lib/posthog/version.rb
CHANGED
metadata
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: posthog-ruby
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 3.
|
|
4
|
+
version: 3.44.0
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- PostHog
|
|
@@ -39,6 +39,7 @@ files:
|
|
|
39
39
|
- lib/posthog/client.rb
|
|
40
40
|
- lib/posthog/defaults.rb
|
|
41
41
|
- lib/posthog/email_attachments.rb
|
|
42
|
+
- lib/posthog/email_batch.rb
|
|
42
43
|
- lib/posthog/email_error.rb
|
|
43
44
|
- lib/posthog/emails.rb
|
|
44
45
|
- lib/posthog/exception_capture.rb
|