Repository navigation
Expand file tree
/
Copy pathemails.go
More file actions
832 lines (771 loc) · 30 KB
/
Copy pathemails.go
File metadata and controls
832 lines (771 loc) · 30 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
package posthog
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/url"
"reflect"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/google/uuid"
)
const (
emailSendPath = "/api/messaging/send/email/"
emailStatusPath = "/api/messaging/emails/"
maxEmailRetryDelay = 30 * time.Second
maxEmailRetries = 9
maxEmailReplyBytes = 1 << 20
emailNotSent = "no email was sent"
emailStatusNotRead = "no email status was read"
)
var (
idempotencyKeyPattern = regexp.MustCompile(`^[\x21-\x7e]{1,255}$`)
templateKeyPattern = regexp.MustCompile(`^[a-zA-Z0-9_-]{1,400}$`)
cloudAppHosts = map[string]string{
"https://us.i.posthog.com": "https://us.posthog.com",
"https://us.posthog.com": "https://us.posthog.com",
"https://app.posthog.com": "https://us.posthog.com",
"https://eu.i.posthog.com": "https://eu.posthog.com",
"https://eu.posthog.com": "https://eu.posthog.com",
}
)
// Emails sends transactional email, such as a password reset or a receipt, to
// one recipient per call, and reads the status of an email it sent. Every v2
// release takes every field. On v1, Emails needs 1.40.0 or later,
// CodeEmail.Sensitive and CodeEmail.Tracking need 1.43.0, and CodeEmail.Cc,
// CodeEmail.Bcc and CodeEmail.Attachments need 1.44.0. Every v1 release and
// v2 releases before 2.1.1 call /api/projects/@current/messaging/, which is
// going away; update to 2.1.1 or later. From 2.1.1, a self-hosted PostHog
// older than 2026-11-18 answers with a 404.
//
// It needs Config.SecretKey, a project secret API key (phs_...) with the
// transactional_email:write scope, the "Send transactional email" preset in
// your project settings. A key with only transactional_email:read can read
// statuses but not send. Keys made with hog_flow:write still work. Requests go
// to Config.AppHost, or to the PostHog Cloud app host of Config.Endpoint.
//
// Every error is an *EmailError. The client retries a network error or
// timeout, a 409 with the code idempotency_key_in_flight, a 429 other than
// a quota error, a 503, and an attachment upload that file storage throttled
// or could not serve. It retries up to Config.EmailRequestMaxRetries times, 2
// by default. Before retry n, counting from 0, it waits about 2^n seconds
// with 20% jitter, at most 30 seconds, or the Retry-After that PostHog sent
// when that is longer. A Retry-After over 30 seconds returns the error at
// once. Every attempt of a send carries the same idempotency key, so a retry
// never queues a second email.
type Emails interface {
// Send queues one email, from a TemplateEmail made in PostHog or from a
// CodeEmail your code rendered. A result means PostHog queued the email,
// not that it was delivered. An argument the client checks, such as a
// TemplateID that isn't a UUID, fails before any request. A network_error
// or a 503 doesn't mean that PostHog didn't queue the email: retry with
// the same IdempotencyKey. Only a key you set can be reused; without one,
// each Send makes a new key, so a second Send can queue the email twice.
Send(ctx context.Context, email Email) (*SendEmailResult, error)
// Get reads the status of an email that Send queued, for 30 days after the
// send. The error code is "not_found" when no email of the project has the
// ID, when the email is older than 30 days, or for a few seconds after the
// send. The client doesn't retry not_found, so right after a send, try
// again after a short wait before you treat the email as missing.
Get(ctx context.Context, messageID string) (*EmailStatus, error)
}
// Email is the content of one send: a TemplateEmail or a CodeEmail.
type Email interface {
prepare() (emailSend, *EmailError)
}
// TemplateEmail sends an email template made transactional in PostHog, by its
// ID. The template sets its own sender, subject and content, and follows the
// project's engagement setting.
type TemplateEmail struct {
// To is one recipient email address.
To string
// TemplateID is the UUID of the template.
TemplateID string
// TemplateData fills the template's {{ variables.* }} placeholders.
TemplateData map[string]interface{}
// DistinctID is the recipient's distinct ID in your product. The email's
// events go to this person. Without it, they go to a person whose distinct
// ID is the email address.
DistinctID string
// IdempotencyKey is 1 to 255 visible ASCII characters. A send with a key
// that PostHog already accepted queues nothing and returns the first send's
// result. Without it, the client makes a UUID that covers its own retries.
// Pass a key derived from what the email is for, such as
// "welcome:user_123", to cover retries outside this call too. PostHog
// keeps a key for 7 days after it queues the email, so finish every retry
// within 7 days, or a later one can send the email twice.
IdempotencyKey string
// MaxRetries overrides Config.EmailRequestMaxRetries for this send, 0 to
// 9. Ptr(0) turns retries off.
MaxRetries *int
}
// CodeEmail sends content your code rendered, named by a key. PostHog sends
// the subject and bodies as is and never stores them; it keeps attachments,
// as Attachments says. To send a React email, render it to HTML in your app
// and pass the HTML.
type CodeEmail struct {
// To is one recipient email address.
To string
// TemplateKey names the email, such as "password-reset", so its metrics,
// logs and status group under it in PostHog. Letters, digits, hyphens and
// underscores, at most 400.
TemplateKey string
Subject string
// HTML is the HTML body. Set HTML, Text or both.
HTML string
// Text is the plain-text body. Without it, PostHog derives it from HTML.
Text string
// From is a verified sender, such as "Acme <security@example.com>".
// Without it, PostHog sends from the project's default sender.
From string
ReplyTo []string
// Cc are bare addresses, such as "finance@example.com", that get a copy
// the other recipients see. At most 10.
Cc []string
// Bcc are bare addresses that get a copy the other recipients never see.
// At most 10.
Bcc []string
// Attachments are files sent with the email: at most 10, and at most 40 MB
// for the whole message after Base64 encoding, which leaves about 29 MB
// for the files. Send checks both before any request. It then hashes each
// file, uploads the files PostHog doesn't have yet straight to PostHog's
// file storage, and sends the email naming them, so the network must
// allow uploads to the storage host the upload URL names. A file PostHog
// already has isn't uploaded again. PostHog refuses file types that
// mailbox providers block, such as .exe. PostHog can't fetch a file from a
// path or URL: read the file and pass its bytes. PostHog keeps each
// uploaded file in its file storage for its retention period, and a later
// send of the same bytes, from any of the project's code, reuses it.
Attachments []EmailAttachment
// Sensitive marks an email that carries a login link, a reset token or a
// code. PostHog keeps a sensitive email's links unchanged, leaves its
// subject off engagement events and keeps its content out of logs. Nil
// takes the setting of the saved template whose key is TemplateKey, or
// true when no template has that key.
Sensitive *bool
// Tracking says what PostHog tracks for this email. Nil keeps the
// defaults: PostHog counts opens and captures engagement events, and
// rewrites links to count clicks only when the email isn't Sensitive. Use
// EmailTrackingOn, EmailTrackingOff or EmailTrackingWith.
Tracking *EmailTracking
// CaptureEngagement says whether PostHog captures the email's engagement
// events as events of the recipient. Nil means true. A project whose
// admin turned engagement capture off captures nothing, whatever the send
// asks. PostHog refuses a send that sets both CaptureEngagement and
// Tracking.
//
// Deprecated: Use Tracking with EmailTrackingOptions.Engagement.
CaptureEngagement *bool
// DistinctID is the recipient's distinct ID in your product. The email's
// events go to this person. Without it, they go to a person whose distinct
// ID is the email address.
DistinctID string
// IdempotencyKey is 1 to 255 visible ASCII characters. See
// TemplateEmail.IdempotencyKey.
IdempotencyKey string
// MaxRetries overrides Config.EmailRequestMaxRetries for this send and its
// attachment uploads, 0 to 9. Ptr(0) turns retries off.
MaxRetries *int
}
// EmailAttachment is a file sent with a CodeEmail.
type EmailAttachment struct {
// Filename is the name the recipient sees, such as "invoice.pdf", with no
// path.
Filename string
// Content is the file's bytes.
Content []byte
// ContentType is a MIME type, such as "application/pdf". Without it, the
// type follows from Filename.
ContentType string
// ContentID shows the file inline: the HTML references it as
// <img src="cid:logo"> when ContentID is "logo".
ContentID string
}
// EmailTracking says what PostHog tracks for a CodeEmail. Make one with
// EmailTrackingOn, EmailTrackingOff or EmailTrackingWith.
type EmailTracking struct {
all *bool
options EmailTrackingOptions
}
// EmailTrackingOptions turns each kind of tracking on or off. A nil field
// keeps its default.
type EmailTrackingOptions struct {
// Opens says whether PostHog adds its open pixel to count opens. Nil
// means true. With Opens false, PostHog counts no clicks, and refuses
// Clicks true.
Opens *bool `json:"opens,omitempty"`
// Clicks says whether PostHog rewrites the email's links to count clicks.
// Nil means true when the email isn't Sensitive and false when it is.
// Turn it on only when the links are safe to send through a redirect, so
// not for a login or password reset link. A link with a data-ph-no-track
// attribute is never rewritten.
Clicks *bool `json:"clicks,omitempty"`
// Engagement says whether PostHog captures the email's engagement events,
// such as opens and clicks, as events of the recipient. Nil means true.
Engagement *bool `json:"engagement,omitempty"`
}
// EmailTrackingOn tracks opens and clicks and captures engagement events.
// Use it only when the email's links are safe to send through a redirect.
func EmailTrackingOn() *EmailTracking {
return &EmailTracking{all: Ptr(true)}
}
// EmailTrackingOff turns off every kind of tracking, including kinds PostHog
// adds later. PostHog then can't count the email's opens and clicks, and
// captures no engagement events.
func EmailTrackingOff() *EmailTracking {
return &EmailTracking{all: Ptr(false)}
}
// EmailTrackingWith sets each kind of tracking on its own.
func EmailTrackingWith(options EmailTrackingOptions) *EmailTracking {
return &EmailTracking{options: options}
}
// MarshalJSON encodes the tracking as true, false or an object of the kinds
// that are set.
func (t EmailTracking) MarshalJSON() ([]byte, error) {
if t.all != nil {
return json.Marshal(*t.all)
}
return json.Marshal(t.options)
}
// SendEmailResult is an email that PostHog queued.
type SendEmailResult struct {
// ID is the queued email's message ID.
ID string
// Replayed is true when PostHog had already accepted this idempotency key
// and returned the first send's result.
Replayed bool
// Warnings are logged through Config.Logger as well.
Warnings []EmailWarning
}
// EmailWarning is a warning PostHog returned with a queued email.
type EmailWarning struct {
Code string
Message string
Fix string
}
// EmailStatus is what happened to an email that Emails.Send queued.
type EmailStatus struct {
// ID is the message ID that Send returned.
ID string
// Status is "queued", "sent", "failed", "delivered", "bounced" or
// "complained" today. Later SDK versions can see values this list does not
// have yet.
Status string
// CreatedAt is when PostHog queued the email.
CreatedAt time.Time
// StatusAt is when the email reached its current status.
StatusAt time.Time
// Reason says why a failed email was not sent, such as "provider_error" or
// "recipient_suppressed", or gives the bounce type of a bounced email:
// "hard", "soft" or "unknown". It is empty otherwise.
Reason string
}
type emailSend struct {
body []byte
attachments []attachment
idempotencyKey string
maxRetries *int
}
type templateEmailBody struct {
TemplateID string `json:"template_id"`
To string `json:"to"`
MessageData map[string]interface{} `json:"message_data"`
DistinctID string `json:"distinct_id,omitempty"`
}
type codeEmailBody struct {
To string `json:"to"`
TemplateKey string `json:"template_key"`
Subject string `json:"subject"`
HTML string `json:"html,omitempty"`
Text string `json:"text,omitempty"`
From string `json:"from,omitempty"`
ReplyTo []string `json:"reply_to,omitempty"`
Cc []string `json:"cc,omitempty"`
Bcc []string `json:"bcc,omitempty"`
Attachments []attachment `json:"attachments,omitempty"`
Sensitive *bool `json:"sensitive,omitempty"`
Tracking *EmailTracking `json:"tracking,omitempty"`
CaptureEngagement *bool `json:"capture_engagement,omitempty"`
DistinctID string `json:"distinct_id,omitempty"`
}
func (e TemplateEmail) prepare() (emailSend, *EmailError) {
if err := checkRecipient(e.To); err != nil {
return emailSend{}, err
}
if !isHyphenatedUUID(e.TemplateID) {
return emailSend{}, invalidEmail("invalid_template_id", "TemplateID", "TemplateID must be the template's UUID.")
}
messageData := e.TemplateData
if messageData == nil {
messageData = map[string]interface{}{}
}
body, err := encodeEmailBody(templateEmailBody{
TemplateID: strings.ToLower(e.TemplateID),
To: e.To,
MessageData: messageData,
DistinctID: e.DistinctID,
})
if err != nil {
return emailSend{}, invalidEmail("invalid_template_data", "TemplateData", "TemplateData must encode as JSON.")
}
return newEmailSend(body, e.IdempotencyKey, e.MaxRetries)
}
func (e CodeEmail) prepare() (emailSend, *EmailError) {
if err := checkRecipient(e.To); err != nil {
return emailSend{}, err
}
if !templateKeyPattern.MatchString(e.TemplateKey) {
return emailSend{}, invalidEmail("invalid_template_key", "TemplateKey", "TemplateKey can only have letters, digits, hyphens (-) and underscores (_), at most 400.")
}
if e.Subject == "" {
return emailSend{}, invalidEmail("invalid_form", "Subject", "A CodeEmail needs a Subject.")
}
if e.HTML == "" && e.Text == "" {
return emailSend{}, invalidEmail("invalid_form", "HTML", "A CodeEmail needs HTML, Text or both.")
}
for _, list := range []struct {
field, code string
addresses []string
}{
{"ReplyTo", "invalid_reply_to", e.ReplyTo},
{"Cc", "invalid_cc", e.Cc},
{"Bcc", "invalid_bcc", e.Bcc},
} {
for _, address := range list.addresses {
if strings.TrimSpace(address) == "" {
return emailSend{}, invalidEmail(list.code, list.field, list.field+" must not hold a blank address.")
}
}
}
attachments, attachmentsErr := checkAttachments(e.Attachments, e.Subject, e.HTML, e.Text)
if attachmentsErr != nil {
return emailSend{}, attachmentsErr
}
body, err := encodeEmailBody(codeEmailBody{
To: e.To,
TemplateKey: e.TemplateKey,
Subject: e.Subject,
HTML: e.HTML,
Text: e.Text,
From: e.From,
ReplyTo: e.ReplyTo,
Cc: e.Cc,
Bcc: e.Bcc,
Attachments: attachments,
Sensitive: e.Sensitive,
Tracking: e.Tracking,
CaptureEngagement: e.CaptureEngagement,
DistinctID: e.DistinctID,
})
if err != nil {
return emailSend{}, newEmailError("unexpected_error", "The client could not encode the email.", err)
}
send, sendErr := newEmailSend(body, e.IdempotencyKey, e.MaxRetries)
send.attachments = attachments
return send, sendErr
}
func checkRecipient(to string) *EmailError {
if strings.TrimSpace(to) == "" {
return invalidEmail("invalid_recipient", "To", "To must be one email address.")
}
return nil
}
func newEmailSend(body []byte, idempotencyKey string, maxRetries *int) (emailSend, *EmailError) {
if idempotencyKey == "" {
idempotencyKey = uuid.NewString()
} else if !idempotencyKeyPattern.MatchString(idempotencyKey) {
return emailSend{}, invalidEmail("invalid_idempotency_key", "IdempotencyKey", "IdempotencyKey must be 1 to 255 visible ASCII characters without spaces.")
}
if maxRetries != nil && (*maxRetries < 0 || *maxRetries > maxEmailRetries) {
return emailSend{}, invalidEmail("invalid_max_retries", "MaxRetries", "MaxRetries must be 0 to 9.")
}
return emailSend{body: body, idempotencyKey: idempotencyKey, maxRetries: maxRetries}, nil
}
// emailSender implements Emails. It owns the attempt loop, so every attempt of
// a send carries the same idempotency key, and it tracks requests in flight so
// that Close waits for them.
type emailSender struct {
disabled bool
appHost string
secretKey string
timeout time.Duration
maxRetries int
migratedFrom string
http http.Client
logger Logger
backoff func(attempt int) time.Duration
// now is the client's clock, which times how long an upload URL lives.
now func() time.Time
// allowInsecureUploads lets attachments upload to an http URL.
allowInsecureUploads bool
// ctx ends when Close runs out of time, which aborts requests and retry waits.
ctx context.Context
cancel context.CancelFunc
mu sync.Mutex
closed bool
inFlight sync.WaitGroup
}
func newEmailSender(config Config, transport http.RoundTripper) *emailSender {
ctx, cancel := context.WithCancel(context.Background())
return &emailSender{
appHost: resolveEmailAppHost(config.Endpoint, config.AppHost),
secretKey: config.effectiveSecretKey(),
timeout: config.EmailRequestTimeout,
maxRetries: *config.EmailRequestMaxRetries,
migratedFrom: config.MigratedFrom,
http: http.Client{
Transport: transport,
CheckRedirect: keepSecretKeyAndMethodOnRedirect,
},
logger: config.Logger,
backoff: NewBackoff(time.Second, 2, 0.2, maxEmailRetryDelay).Duration,
now: config.now,
allowInsecureUploads: config.AllowInsecureAppHost,
ctx: ctx,
cancel: cancel,
}
}
// keepSecretKeyAndMethodOnRedirect answers a redirect with the redirect itself,
// since following it would move the secret key or turn a send into a GET.
func keepSecretKeyAndMethodOnRedirect(*http.Request, []*http.Request) error {
return http.ErrUseLastResponse
}
func newDisabledEmailSender() *emailSender {
return &emailSender{disabled: true}
}
// resolveEmailAppHost returns the app host for email requests, or "" when the
// client can't tell it. PostHog Cloud ingestion hosts don't serve the app API,
// so they map to their region's app host.
func resolveEmailAppHost(endpoint, appHost string) string {
if appHost = strings.TrimRight(appHost, "/"); appHost != "" {
if cloud, ok := cloudAppHosts[canonicalHTTPSOrigin(appHost)]; ok {
return cloud
}
return appHost
}
return cloudAppHosts[canonicalHTTPSOrigin(endpoint)]
}
// canonicalHTTPSOrigin spells an https origin the way cloudAppHosts does:
// a lower-case host without the default port or a trailing slash.
func canonicalHTTPSOrigin(rawURL string) string {
parsed, err := url.Parse(strings.TrimSpace(rawURL))
if err != nil || !strings.EqualFold(parsed.Scheme, "https") || strings.Trim(parsed.Path, "/") != "" {
return rawURL
}
if port := parsed.Port(); port != "" && port != "443" {
return rawURL
}
return "https://" + strings.ToLower(parsed.Hostname())
}
func isHyphenatedUUID(id string) bool {
return len(id) == 36 && uuid.Validate(id) == nil
}
func (s *emailSender) Send(ctx context.Context, email Email) (*SendEmailResult, error) {
if isNilEmail(email) {
return nil, newEmailError("invalid_form", "Send needs a TemplateEmail or a CodeEmail.", nil)
}
send, err := email.prepare()
if err != nil {
return nil, err
}
finish, err := s.start(emailNotSent, "Sending email needs Config.SecretKey, a project secret API key with the transactional_email:write scope.")
if err != nil {
return nil, err
}
defer finish()
maxRetries := s.maxRetries
if send.maxRetries != nil {
maxRetries = *send.maxRetries
}
if len(send.attachments) > 0 {
if err := s.uploadAttachments(ctx, maxRetries, send.attachments); err != nil {
return nil, err
}
}
header := s.header()
header.Set("Content-Type", "application/json")
header.Set("Idempotency-Key", send.idempotencyKey)
reply, err := s.request(ctx, maxRetries, http.MethodPost, s.appHost+emailSendPath, header, send.body)
if err != nil {
return nil, err
}
result, err := reply.sendResult()
if err != nil {
return nil, err
}
for _, warning := range result.Warnings {
s.logger.Warnf("PostHog email warning %s: %s", warning.Code, warning.Message)
}
return result, nil
}
func (s *emailSender) Get(ctx context.Context, messageID string) (*EmailStatus, error) {
if !isHyphenatedUUID(messageID) {
return nil, newEmailError("invalid_message_id", "messageID must be the message ID that Send returned.", nil)
}
finish, err := s.start(emailStatusNotRead, "Reading an email status needs Config.SecretKey, a project secret API key with the transactional_email:read or transactional_email:write scope.")
if err != nil {
return nil, err
}
defer finish()
url := s.appHost + emailStatusPath + strings.ToLower(messageID) + "/"
reply, err := s.request(ctx, s.maxRetries, http.MethodGet, url, s.header(), nil)
if err != nil {
return nil, err
}
status, err := reply.emailStatus()
if err != nil {
return nil, err
}
return status, nil
}
// encodeEmailBody encodes a request body with the standard library, keeping
// HTML as written. goccy/go-json's MarshalNoEscape hides its argument from
// escape analysis, so a body built on the stack can move while it encodes;
// the Go 1.21 race tests caught it reading such a body as garbage.
func encodeEmailBody(body interface{}) ([]byte, error) {
var buf bytes.Buffer
encoder := json.NewEncoder(&buf)
encoder.SetEscapeHTML(false)
if err := encoder.Encode(body); err != nil {
return nil, err
}
return bytes.TrimSuffix(buf.Bytes(), []byte("\n")), nil
}
// isNilEmail reports a nil Email, including a nil *TemplateEmail or *CodeEmail.
func isNilEmail(email Email) bool {
if email == nil {
return true
}
value := reflect.ValueOf(email)
return value.Kind() == reflect.Pointer && value.IsNil()
}
// start admits one request into the in-flight set, or says why it can't run.
// The caller calls finish when the request has settled.
func (s *emailSender) start(nothingDone, keyNeeded string) (finish func(), err *EmailError) {
if s.disabled {
return nil, newEmailError("client_disabled", "The PostHog client is disabled, so "+nothingDone+".", ErrSDKDisabled)
}
s.mu.Lock()
defer s.mu.Unlock()
if s.closed {
return nil, newEmailError("client_closed", "The PostHog client is shut down, so "+nothingDone+".", ErrClosed)
}
if s.appHost == "" {
return nil, newEmailError("missing_app_host", "The client's Endpoint is not PostHog Cloud, so the client can't tell where to send email. Set Config.AppHost to your PostHog app host.", nil)
}
if s.secretKey == "" {
return nil, newEmailError("missing_secret_key", keyNeeded, nil)
}
s.inFlight.Add(1)
return s.inFlight.Done, nil
}
func (s *emailSender) header() http.Header {
header := http.Header{}
header.Set("Authorization", "Bearer "+s.secretKey)
header.Set("Accept", "application/json")
header.Set("User-Agent", SDKName+"/"+getVersion())
if s.migratedFrom != "" {
header.Set("X-PostHog-Migrated-From", s.migratedFrom)
}
return header
}
// request sends the request until PostHog accepts it, retrying what waiting
// can fix. Every attempt carries the same header, so a send's idempotency key
// holds across retries. A reply it returns is always a 2xx.
func (s *emailSender) request(ctx context.Context, maxRetries int, method, url string, header http.Header, body []byte) (emailReply, *EmailError) {
var reply emailReply
err := s.retry(ctx, maxRetries, func(ctx context.Context) *EmailError {
var err *EmailError
reply, err = s.do(ctx, method, url, header, body)
if err == nil && !reply.accepted() {
err = reply.error()
}
return err
})
if err != nil {
return emailReply{}, err
}
return reply, nil
}
// retry runs attempt until it succeeds, retrying what waiting can fix. Close
// running out of time ends the attempt and the wait before the next one.
func (s *emailSender) retry(ctx context.Context, maxRetries int, attempt func(context.Context) *EmailError) *EmailError {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
defer context.AfterFunc(s.ctx, cancel)()
for n := 0; ; n++ {
err := attempt(ctx)
if err == nil {
return nil
}
delay, retry := s.retryDelay(err, n, maxRetries)
if !retry {
return err
}
timer := time.NewTimer(delay)
select {
case <-timer.C:
case <-ctx.Done():
timer.Stop()
return err.interruptedBy(ctx.Err())
}
}
}
func (s *emailSender) retryDelay(err *EmailError, attempt, maxRetries int) (time.Duration, bool) {
if attempt >= maxRetries || !err.isRetryable() || asksForALongerWaitThanWeRetry(err) {
return 0, false
}
delay := s.backoff(attempt)
if err.RetryAfter > delay {
delay = err.RetryAfter
}
return delay, true
}
// asksForALongerWaitThanWeRetry is a Retry-After past the longest retry wait.
// Retrying sooner would break the server's rate limit, so the error goes back
// to the caller at once.
func asksForALongerWaitThanWeRetry(err *EmailError) bool {
return err.RetryAfter > maxEmailRetryDelay
}
func (s *emailSender) do(ctx context.Context, method, url string, header http.Header, body []byte) (emailReply, *EmailError) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
var reader io.Reader
if body != nil {
reader = bytes.NewReader(body)
}
req, err := http.NewRequestWithContext(ctx, method, url, reader)
if err != nil {
return emailReply{}, newEmailError("unexpected_error", "The client could not build the request.", err)
}
req.Header = header
res, err := s.http.Do(req)
if err != nil {
return emailReply{}, newEmailError("network_error", "The request to PostHog failed.", err)
}
defer res.Body.Close()
reply := emailReply{status: res.StatusCode}
reply.retryAfter, _ = parseRetryAfter(res.Header.Get("Retry-After"), time.Now())
raw, err := io.ReadAll(io.LimitReader(res.Body, maxEmailReplyBytes))
if err != nil {
return emailReply{}, cutOffAnswer(err, reply.status, reply.retryAfter)
}
reply.fields = jsonObjectOrNothing(raw)
return reply, nil
}
// cutOffAnswer is an answer that broke off mid-body. It can't say what PostHog
// decided: a send may already be queued, or a refusal may have been
// retryable. So it is a retryable network error, which the idempotency key
// keeps safe. Its status line and a Retry-After in its headers still hold.
func cutOffAnswer(cause error, status int, retryAfter time.Duration) *EmailError {
err := newEmailError("network_error", "Reading PostHog's answer failed.", cause)
err.StatusCode = status
err.RetryAfter = retryAfter
return err
}
// jsonObjectOrNothing decodes a whole JSON object. A body that isn't one as a
// whole says nothing, even when its start parsed.
func jsonObjectOrNothing(raw []byte) map[string]interface{} {
var fields map[string]interface{}
if json.Unmarshal(raw, &fields) != nil {
return nil
}
return fields
}
// close stops new requests. Requests already admitted keep running.
func (s *emailSender) close() {
s.mu.Lock()
defer s.mu.Unlock()
s.closed = true
}
// drain waits for every request in flight, retries included, to settle. When
// ctx ends first, it aborts them and returns ctx's error once they settled.
func (s *emailSender) drain(ctx context.Context) error {
settled := make(chan struct{})
go func() {
s.inFlight.Wait()
close(settled)
}()
select {
case <-settled:
return nil
case <-ctx.Done():
s.cancel()
<-settled
return ctx.Err()
}
}
type emailReply struct {
status int
fields map[string]interface{}
retryAfter time.Duration
}
func (r emailReply) accepted() bool { return r.status >= 200 && r.status < 300 }
func (r emailReply) text(field string) string {
value, _ := r.fields[field].(string)
return value
}
func (r emailReply) error() *EmailError {
code := r.text("code")
if code == "" {
code = "api_error"
}
message := r.text("detail")
if message == "" {
message = "PostHog answered HTTP " + strconv.Itoa(r.status) + "."
}
return &EmailError{
Name: emailErrorName(r.status, code),
Code: code,
Message: message,
StatusCode: r.status,
Why: r.text("why"),
Fix: r.text("fix"),
DocsURL: r.text("docs_url"),
Field: r.text("attr"),
RetryAfter: r.retryAfter,
}
}
func (r emailReply) apiError(message string) *EmailError {
return &EmailError{Name: emailErrorName(r.status, "api_error"), Code: "api_error", Message: message, StatusCode: r.status, RetryAfter: r.retryAfter}
}
func (r emailReply) sendResult() (*SendEmailResult, *EmailError) {
id := r.text("message_id")
if id == "" {
return nil, r.apiError("PostHog answered without a message ID.")
}
replayed, _ := r.fields["replayed"].(bool)
result := &SendEmailResult{ID: id, Replayed: replayed, Warnings: []EmailWarning{}}
warnings, _ := r.fields["warnings"].([]interface{})
for _, item := range warnings {
fields, ok := item.(map[string]interface{})
if !ok {
continue
}
warning := emailReply{fields: fields}
message := warning.text("detail")
if message == "" {
message = warning.text("message")
}
code := warning.text("code")
if code == "" {
code = "warning"
}
result.Warnings = append(result.Warnings, EmailWarning{Code: code, Message: message, Fix: warning.text("fix")})
}
return result, nil
}
func (r emailReply) emailStatus() (*EmailStatus, *EmailError) {
createdAt, createdErr := time.Parse(time.RFC3339Nano, r.text("created_at"))
statusAt, statusErr := time.Parse(time.RFC3339Nano, r.text("status_at"))
status := &EmailStatus{ID: r.text("id"), Status: r.text("status"), CreatedAt: createdAt, StatusAt: statusAt, Reason: r.text("reason")}
if status.ID == "" || status.Status == "" || createdErr != nil || statusErr != nil {
return nil, r.apiError("PostHog answered without an email status.")
}
return status, nil
}