-
Notifications
You must be signed in to change notification settings - Fork 1
/
application.go
392 lines (306 loc) · 7.76 KB
/
application.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
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
package communication
import (
"bytes"
"context"
"fmt"
"html/template"
"time"
"github.com/pkg/errors"
"github.com/google/uuid"
"github.com/sirupsen/logrus"
)
const UserAgent = "InteractiveSolutions/GoCommunication-1.0"
type Application interface {
HttpHandler() *HttpHandler
SendEmail(id, locale, email, externalId string, params map[string]interface{}) error
SendSms(id, locale, number, externalId string, params map[string]interface{}) error
Shutdown(ctx context.Context)
}
type AppOption func(a *application)
type RenderFunc func(body string, params map[string]interface{}) (string, error)
func SetFallbackLocale(locale string) AppOption {
return func(a *application) {
a.fallbackLocale = locale
}
}
func SetDefaultSmsTransport(transport Transport) AppOption {
return func(a *application) {
a.defaultSmsTransport = transport
}
}
func SetDefaultEmailTransport(transport Transport) AppOption {
return func(a *application) {
a.defaultEmailTransport = transport
}
}
func SetTemplateRepo(repo TemplateRepository) AppOption {
return func(a *application) {
a.templateRepo = repo
}
}
func SetJobRepo(repo JobRepository) AppOption {
return func(a *application) {
a.jobRepo = repo
}
}
func SetWorkerCount(count int) AppOption {
return func(a *application) {
a.workerCount = count
}
}
func SetTemplateFuncMap(funcMap template.FuncMap) AppOption {
return func(a *application) {
a.templateFuncMap = funcMap
}
}
func SetHtmlToTextConverter(f func (string) string) AppOption {
return func (a *application) {
a.htmlToTextConverter = f
}
}
func SetLogger(logger logrus.FieldLogger) AppOption {
return func (a *application) {
a.logger = logger
}
}
func SetStaticParams(params map[string]interface{}) AppOption {
return func (a *application) {
a.staticParams = params
}
}
type application struct {
logger logrus.FieldLogger
workerCtx context.Context
workerCancel context.CancelFunc
workerQueue chan *Job
workerCount int
templateRepo TemplateRepository
jobRepo JobRepository
fallbackLocale string
defaultSmsTransport Transport
defaultEmailTransport Transport
templateFuncMap template.FuncMap
htmlToTextConverter func (string) string
staticParams map[string]interface{}
}
func NewApplication(options ...AppOption) (Application, error) {
app := &application{
logger: logrus.New(),
workerQueue: make(chan *Job, 1000),
workerCount: 5,
}
for _, option := range options {
option(app)
}
if err := app.ensureUsableConfiguration(); err != nil {
return app, err
}
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
app.workerCancel = cancel
for i := 0; i <= app.workerCount; i++ {
go app.worker(ctx)
}
jobs, err := app.jobRepo.GetPending()
if err != nil {
return app, err
}
for _, job := range jobs {
cpy := job
// Queue the copy of the join
app.queue(&cpy)
}
return app, nil
}
func (a *application) HttpHandler() *HttpHandler {
return &HttpHandler{
app: a,
}
}
func (a *application) SendEmail(id, locale, email, externalId string, params map[string]interface{}) error {
if a.defaultEmailTransport == nil {
return errors.New("No email transport configured")
}
job := &Job{
Uuid: uuid.New(),
ExternalId: externalId,
Type: JobEmail,
TemplateId: id,
Locale: locale,
Target: email,
Params: params,
CreatedAt: time.Now(),
}
if err := a.jobRepo.Create(job); err != nil {
return err
}
a.queue(job)
return nil
}
func (a *application) SendSms(id, locale, number, externalId string, params map[string]interface{}) error {
if a.defaultSmsTransport == nil {
return errors.New("No sms transport configured")
}
job := &Job{
Uuid: uuid.New(),
ExternalId: externalId,
Type: JobSms,
TemplateId: id,
Locale: locale,
Target: number,
Params: params,
CreatedAt: time.Now(),
}
if err := a.jobRepo.Create(job); err != nil {
return err
}
a.queue(job)
return nil
}
func (a *application) Shutdown(ctx context.Context) {
<-ctx.Done()
a.workerCancel()
}
func (a *application) ensureUsableConfiguration() error {
if a.templateRepo == nil {
return errors.New("Missing template repository")
}
if a.jobRepo == nil {
return errors.New("Missing transaction repository")
}
return nil
}
func (a *application) queue(job *Job) {
go func() {
a.workerQueue <- job
}()
}
func (a *application) worker(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
case job, ok := <-a.workerQueue:
if !ok {
return
}
if err := a.process(job); err != nil {
a.logger.
WithField("job", job).
WithError(err).
Error("failed to process job")
continue
}
now := time.Now()
job.SentAt = &now
if err := a.jobRepo.Update(job); err != nil {
a.logger.
WithField("job", job).
WithError(err).
Error("failed to update job in transaction repo")
}
}
}
}
func (a *application) createMockTemplate(templateId, locale string) (Template, error) {
tpl := Template{
TemplateId: templateId,
Locale: locale,
UpdateParameters: true,
Subject: "[InteractiveSolutions/Communications] template missing",
TextBody: fmt.Sprintf("A template is missing for template id: %s, locale: %s", templateId, locale),
HtmlBody: fmt.Sprintf("A template is missing for template id: %s, locale: %s", templateId, locale),
UpdatedAt: time.Now(),
CreatedAt: time.Now(),
}
if err := a.templateRepo.Create(&tpl); err != nil {
return tpl, err
}
return tpl, nil
}
func (a *application) getFallbackTemplate(templateId string) (Template, error) {
tpl, err := a.templateRepo.Get(templateId, a.fallbackLocale)
switch err {
case nil:
return tpl, nil
case TemplateNotFoundErr:
return a.createMockTemplate(templateId, a.fallbackLocale)
default:
return tpl, err
}
}
func (a *application) getTemplate(templateId, locale string) (Template, error) {
tpl, err := a.templateRepo.Get(templateId, locale)
switch err {
case nil:
if tpl.Enabled {
return tpl, nil
}
return a.getFallbackTemplate(templateId)
case TemplateNotFoundErr:
if _, err := a.createMockTemplate(templateId, locale); err != nil {
a.logger.
WithField("templateId", templateId).
WithField("locale", locale).
WithError(err).
Error("Failed to create mock template")
}
return a.getFallbackTemplate(templateId)
default:
return tpl, err
}
}
func (a *application) process(job *Job) error {
tpl, err := a.getTemplate(job.TemplateId, job.Locale)
if err != nil {
return err
}
if tpl.UpdateParameters {
tpl.Parameters = job.Params
tpl.UpdateParameters = false
if err := a.templateRepo.Update(&tpl); err != nil {
return err
}
}
switch job.Type {
case JobSms:
return a.defaultSmsTransport.Send(context.Background(), job, tpl, a.render)
case JobEmail:
return a.defaultEmailTransport.Send(context.Background(), job, tpl, a.render)
default:
return errors.Errorf("Unknown job type %s", job.Type)
}
}
func (a *application) Render(template Template, job *Job) (subject, text, html string, err error) {
subject, err = a.render(template.Subject, job.Params)
if err != nil {
return
}
text, err = a.render(template.TextBody, job.Params)
if err != nil {
return
}
html, err = a.render(template.HtmlBody, job.Params)
return
}
func (a *application) render(body string, params map[string]interface{}) (string, error) {
if params == nil {
params = map[string]interface{}{}
}
for key, value := range a.staticParams {
if _, ok := params[key]; ok {
// Allow dynamic parameters to overwrite static parameters
continue
}
params[key] = value
}
tpl, err := template.New("").Funcs(a.templateFuncMap).Parse(body)
if err != nil {
return "", err
}
out := &bytes.Buffer{}
if err := tpl.Execute(out, params); err != nil {
return "", err
}
return out.String(), nil
}