Repository navigation
Expand file tree
/
Copy pathnotification_service.go
More file actions
269 lines (219 loc) · 9.99 KB
/
Copy pathnotification_service.go
File metadata and controls
269 lines (219 loc) · 9.99 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
package services
import (
"context"
"errors"
"fmt"
"time"
"github.com/NdoleStudio/httpsms/pkg/events"
cloudevents "github.com/cloudevents/sdk-go/v2"
"firebase.google.com/go/messaging"
"github.com/NdoleStudio/httpsms/pkg/entities"
"github.com/NdoleStudio/httpsms/pkg/repositories"
"github.com/NdoleStudio/httpsms/pkg/telemetry"
"github.com/google/uuid"
"github.com/palantir/stacktrace"
)
// NotificationService sends out notifications to mobile phones
type NotificationService struct {
logger telemetry.Logger
tracer telemetry.Tracer
phoneNotificationRepository repositories.PhoneNotificationRepository
phoneRepository repositories.PhoneRepository
messagingClient *messaging.Client
eventDispatcher *EventDispatcher
}
// NewNotificationService creates a new NotificationService
func NewNotificationService(
logger telemetry.Logger,
tracer telemetry.Tracer,
messagingClient *messaging.Client,
phoneRepository repositories.PhoneRepository,
phoneNotificationRepository repositories.PhoneNotificationRepository,
dispatcher *EventDispatcher,
) (s *NotificationService) {
return &NotificationService{
logger: logger.WithService(fmt.Sprintf("%T", s)),
tracer: tracer,
messagingClient: messagingClient,
phoneNotificationRepository: phoneNotificationRepository,
phoneRepository: phoneRepository,
eventDispatcher: dispatcher,
}
}
// NotificationSendParams are parameters for sending a notification
type NotificationSendParams struct {
UserID entities.UserID
PhoneID uuid.UUID
PhoneNotificationID uuid.UUID
Source string
ScheduledAt time.Time
MessageID uuid.UUID
}
// Send sends a message when a message is sent
func (service *NotificationService) Send(ctx context.Context, params *NotificationSendParams) error {
ctx, span := service.tracer.Start(ctx)
defer span.End()
phone, err := service.phoneRepository.LoadByID(ctx, params.PhoneID)
if err != nil {
msg := fmt.Sprintf("cannot load phone with userID [%s] and phoneID [%s]", params.UserID, params.PhoneID)
return service.handleNotificationFailed(ctx, errors.New(msg), params)
}
if phone.FcmToken == nil {
msg := fmt.Sprintf("phone with id [%s] has no FCM token", phone.ID)
return service.handleNotificationFailed(ctx, errors.New(msg), params)
}
result, err := service.messagingClient.Send(ctx, &messaging.Message{
Data: map[string]string{
"KEY_MESSAGE_ID": params.MessageID.String(),
},
Token: *phone.FcmToken,
})
if err != nil {
return service.handleNotificationFailed(ctx, err, params)
}
return service.handleNotificationSent(ctx, phone, result, params)
}
// NotificationScheduleParams are parameters for sending a notification
type NotificationScheduleParams struct {
UserID entities.UserID
Owner string
Source string
MessageID uuid.UUID
}
// Schedule a notification to be sent to a phone
func (service *NotificationService) Schedule(ctx context.Context, params *NotificationScheduleParams) error {
ctx, span := service.tracer.Start(ctx)
defer span.End()
ctxLogger := service.tracer.CtxLogger(service.logger, span)
phone, err := service.phoneRepository.Load(ctx, params.UserID, params.Owner)
if err != nil {
msg := fmt.Sprintf("cannot load phone with userID [%s] and phone [%s]", params.UserID, params.Owner)
return service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
}
notification := &entities.PhoneNotification{
ID: uuid.New(),
MessageID: params.MessageID,
UserID: params.UserID,
PhoneID: phone.ID,
Status: entities.PhoneNotificationStatusPending,
ScheduledAt: time.Now().UTC(),
CreatedAt: time.Now().UTC(),
UpdatedAt: time.Now().UTC(),
}
if err = service.phoneNotificationRepository.Schedule(ctx, phone.MessagesPerMinute, notification); err != nil {
msg := fmt.Sprintf("cannot schedule notification for message [%s] to phone [%s]", params.MessageID, phone.ID)
return service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
}
event, err := service.createEvent(params.Source, notification)
if err != nil {
return stacktrace.Propagate(err, fmt.Sprintf("cannot create cloud event for notification [%s]", notification.ID))
}
if err = service.eventDispatcher.DispatchWithTimeout(ctx, event, notification.ScheduledAt.Sub(time.Now())); err != nil {
return stacktrace.Propagate(err, fmt.Sprintf("cannot dispatch event [%s] for notification [%s]", event.Type(), notification.ID))
}
ctxLogger.Info(fmt.Sprintf("message with id [%s] notification scheduled for [%s] with id [%s]", params.MessageID, notification.ScheduledAt, notification.ID))
return nil
}
func (service *NotificationService) handleNotificationFailed(ctx context.Context, err error, params *NotificationSendParams) error {
ctx, span := service.tracer.Start(ctx)
defer span.End()
ctxLogger := service.tracer.CtxLogger(service.logger, span)
msg := fmt.Sprintf("cannot send notification for message [%s] to phone [%s]", params.MessageID, params.PhoneNotificationID)
ctxLogger.Warn(stacktrace.Propagate(err, msg))
event, err := service.createMessageNotificationFailedEvent(params.Source, err.Error(), params)
if err != nil {
return stacktrace.Propagate(err, fmt.Sprintf("cannot create [%s] event for notification [%s]", events.EventTypeMessageNotificationFailed, params.PhoneNotificationID))
}
if err = service.eventDispatcher.Dispatch(ctx, event); err != nil {
return stacktrace.Propagate(err, fmt.Sprintf("cannot dispatch event [%s] for notification [%s]", event.Type(), params.PhoneNotificationID))
}
service.updateStatus(ctx, params.PhoneNotificationID, entities.PhoneNotificationStatusFailed)
return nil
}
func (service *NotificationService) handleNotificationSent(ctx context.Context, phone *entities.Phone, result string, params *NotificationSendParams) error {
ctx, span := service.tracer.Start(ctx)
defer span.End()
ctxLogger := service.tracer.CtxLogger(service.logger, span)
ctxLogger.Info(fmt.Sprintf("sent notification [%s] for message [%s] to phone [%s]", result, params.MessageID, params.PhoneID))
event, err := service.createMessageNotificationSentEvent(params.Source, phone, result, params)
if err != nil {
return stacktrace.Propagate(err, fmt.Sprintf("cannot create [%s] event for notification [%s]", events.EventTypeMessageNotificationSent, params.PhoneNotificationID))
}
if err = service.eventDispatcher.Dispatch(ctx, event); err != nil {
return stacktrace.Propagate(err, fmt.Sprintf("cannot dispatch event [%s] for notification [%s]", event.Type(), params.PhoneNotificationID))
}
service.updateStatus(ctx, params.PhoneNotificationID, entities.PhoneNotificationStatusSent)
return nil
}
func (service *NotificationService) createEvent(source string, notification *entities.PhoneNotification) (cloudevents.Event, error) {
event := cloudevents.NewEvent()
event.SetSource(source)
event.SetType(events.EventTypeMessageNotificationScheduled)
event.SetTime(time.Now().UTC())
event.SetID(uuid.New().String())
payload := events.MessageNotificationScheduledPayload{
MessageID: notification.MessageID,
UserID: notification.UserID,
PhoneID: notification.PhoneID,
ScheduledAt: notification.ScheduledAt,
NotificationID: notification.ID,
}
if err := event.SetData(cloudevents.ApplicationJSON, payload); err != nil {
msg := fmt.Sprintf("cannot encode %T [%#+v] as JSON", payload, payload)
return event, stacktrace.Propagate(err, msg)
}
return event, nil
}
func (service *NotificationService) createMessageNotificationSentEvent(source string, phone *entities.Phone, fcmMessageID string, params *NotificationSendParams) (cloudevents.Event, error) {
event := cloudevents.NewEvent()
event.SetSource(source)
event.SetType(events.EventTypeMessageNotificationSent)
event.SetTime(time.Now().UTC())
event.SetID(uuid.New().String())
payload := events.MessageNotificationSentPayload{
MessageID: params.MessageID,
UserID: params.UserID,
PhoneID: params.PhoneID,
ScheduledAt: params.ScheduledAt,
MessageExpirationTimeout: phone.MessageExpirationTimeout,
FcmMessageID: fcmMessageID,
NotificationSentAt: time.Now().UTC(),
NotificationID: params.PhoneNotificationID,
}
if err := event.SetData(cloudevents.ApplicationJSON, payload); err != nil {
msg := fmt.Sprintf("cannot encode %T [%#+v] as JSON", payload, payload)
return event, stacktrace.Propagate(err, msg)
}
return event, nil
}
func (service *NotificationService) createMessageNotificationFailedEvent(source string, errorMessage string, params *NotificationSendParams) (cloudevents.Event, error) {
event := cloudevents.NewEvent()
event.SetSource(source)
event.SetType(events.EventTypeMessageNotificationFailed)
event.SetTime(time.Now().UTC())
event.SetID(uuid.New().String())
payload := events.MessageNotificationFailedPayload{
MessageID: params.MessageID,
UserID: params.UserID,
PhoneID: params.PhoneID,
ErrorMessage: errorMessage,
NotificationFailedAt: time.Now().UTC(),
NotificationID: params.PhoneNotificationID,
}
if err := event.SetData(cloudevents.ApplicationJSON, payload); err != nil {
msg := fmt.Sprintf("cannot encode %T [%#+v] as JSON", payload, payload)
return event, stacktrace.Propagate(err, msg)
}
return event, nil
}
func (service *NotificationService) updateStatus(ctx context.Context, notificationID uuid.UUID, status entities.PhoneNotificationStatus) {
ctx, span := service.tracer.Start(ctx)
defer span.End()
ctxLogger := service.tracer.CtxLogger(service.logger, span)
err := service.phoneNotificationRepository.UpdateStatus(ctx, notificationID, status)
if err != nil {
msg := fmt.Sprintf("cannot update status of notificaiton with id [%s] to [%s]", notificationID, status)
ctxLogger.Error(stacktrace.Propagate(err, msg))
}
ctxLogger.Info(fmt.Sprintf("updated status of notificaiton with id [%s] to [%s]", notificationID, status))
}