-
-
Notifications
You must be signed in to change notification settings - Fork 931
/
courier.go
109 lines (92 loc) · 2.29 KB
/
courier.go
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
// Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package courier
import (
"context"
"time"
"github.com/ory/kratos/courier/template"
"github.com/ory/x/jsonnetsecure"
"github.com/cenkalti/backoff"
"github.com/gofrs/uuid"
"github.com/pkg/errors"
"github.com/ory/kratos/driver/config"
"github.com/ory/kratos/x"
gomail "github.com/ory/mail/v3"
)
type (
Dependencies interface {
PersistenceProvider
x.LoggingProvider
ConfigProvider
x.HTTPClientProvider
jsonnetsecure.VMProvider
}
Courier interface {
Work(ctx context.Context) error
QueueEmail(ctx context.Context, t EmailTemplate) (uuid.UUID, error)
QueueSMS(ctx context.Context, t SMSTemplate) (uuid.UUID, error)
SmtpDialer() *gomail.Dialer
DispatchQueue(ctx context.Context) error
DispatchMessage(ctx context.Context, msg Message) error
SetGetEmailTemplateType(f func(t EmailTemplate) (TemplateType, error))
SetNewEmailTemplateFromMessage(f func(d template.Dependencies, msg Message) (EmailTemplate, error))
UseBackoff(b backoff.BackOff)
}
Provider interface {
Courier(ctx context.Context) (Courier, error)
}
ConfigProvider interface {
CourierConfig() config.CourierConfigs
}
courier struct {
smsClient *smsClient
smtpClient *smtpClient
deps Dependencies
failOnError bool
backoff backoff.BackOff
}
)
func NewCourier(ctx context.Context, deps Dependencies) (Courier, error) {
smtp, err := newSMTP(ctx, deps)
if err != nil {
return nil, err
}
return &courier{
smsClient: newSMS(ctx, deps),
smtpClient: smtp,
deps: deps,
backoff: backoff.NewExponentialBackOff(),
}, nil
}
func (c *courier) FailOnDispatchError() {
c.failOnError = true
}
func (c *courier) Work(ctx context.Context) error {
errChan := make(chan error)
defer close(errChan)
go c.watchMessages(ctx, errChan)
select {
case <-ctx.Done():
if errors.Is(ctx.Err(), context.Canceled) {
return nil
}
return ctx.Err()
case err := <-errChan:
return err
}
}
func (c *courier) UseBackoff(b backoff.BackOff) {
c.backoff = b
}
func (c *courier) watchMessages(ctx context.Context, errChan chan error) {
c.backoff.Reset()
for {
if err := backoff.Retry(func() error {
return c.DispatchQueue(ctx)
}, c.backoff); err != nil {
errChan <- err
return
}
time.Sleep(time.Second)
}
}