/
service.go
463 lines (380 loc) · 12.8 KB
/
service.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
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
// Copyright (c) 2024 Proton AG
//
// This file is part of Proton Mail Bridge.
//
// Proton Mail Bridge is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Proton Mail Bridge is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Proton Mail Bridge. If not, see <https://www.gnu.org/licenses/>.
package userevents
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"sync"
"sync/atomic"
"time"
"github.com/ProtonMail/gluon/async"
"github.com/ProtonMail/gluon/watcher"
"github.com/ProtonMail/go-proton-api"
"github.com/ProtonMail/proton-bridge/v3/internal"
"github.com/ProtonMail/proton-bridge/v3/internal/events"
"github.com/ProtonMail/proton-bridge/v3/internal/network"
"github.com/ProtonMail/proton-bridge/v3/internal/services/orderedtasks"
"github.com/ProtonMail/proton-bridge/v3/pkg/cpc"
"github.com/bradenaw/juniper/xmaps"
"github.com/sirupsen/logrus"
)
// Service polls from the given event source and ensures that all the respective subscribers get notified
// before proceeding to the next event. The events are published in the following order:
// * Refresh
// * User
// * Address
// * Label
// * Message
// * UserUsedSpace
// By default this service starts paused, you need to call `Service.Resume` at least one time to begin event polling.
type Service struct {
cpc *cpc.CPC
userID string
eventSource EventSource
eventIDStore EventIDStore
log *logrus.Entry
eventPublisher events.EventPublisher
timer *proton.Ticker
eventTimeout time.Duration
paused uint32
panicHandler async.PanicHandler
subscriberList eventSubscriberList
pendingSubscriptionsLock sync.Mutex
pendingSubscriptions []pendingSubscription
eventPollWaiters []*EventPollWaiter
eventPollWaitersLock sync.Mutex
eventSubscription events.Subscription
eventWatcher *watcher.Watcher[events.Event]
}
func NewService(
userID string,
eventSource EventSource,
store EventIDStore,
eventPublisher events.EventPublisher,
pollPeriod time.Duration,
jitter time.Duration,
eventTimeout time.Duration,
panicHandler async.PanicHandler,
eventSubscription events.Subscription,
) *Service {
return &Service{
cpc: cpc.NewCPC(),
userID: userID,
eventSource: eventSource,
eventIDStore: store,
log: logrus.WithFields(logrus.Fields{
"service": "user-events",
"user": userID,
}),
eventPublisher: eventPublisher,
timer: proton.NewTicker(pollPeriod, jitter, panicHandler),
paused: 1,
eventTimeout: eventTimeout,
panicHandler: panicHandler,
eventSubscription: eventSubscription,
eventWatcher: eventSubscription.Add(events.ConnStatusDown{}, events.ConnStatusUp{}),
}
}
// Subscribe adds new subscribers to the service.
// This method can safely be called during event handling.
func (s *Service) Subscribe(subscription EventSubscriber) {
s.pendingSubscriptionsLock.Lock()
defer s.pendingSubscriptionsLock.Unlock()
s.pendingSubscriptions = append(s.pendingSubscriptions, pendingSubscription{op: pendingOpAdd, sub: subscription})
}
// Unsubscribe removes subscribers from the service.
// This method can safely be called during event handling.
func (s *Service) Unsubscribe(subscription EventSubscriber) {
subscription.cancel()
s.pendingSubscriptionsLock.Lock()
defer s.pendingSubscriptionsLock.Unlock()
s.pendingSubscriptions = append(s.pendingSubscriptions, pendingSubscription{op: pendingOpRemove, sub: subscription})
}
// Pause pauses the event polling.
func (s *Service) Pause() {
s.log.Info("Pausing")
atomic.StoreUint32(&s.paused, 1)
}
// PauseWithWaiter pauses the event polling and returns a waiter to notify when the last event has been published
// after the pause request.
func (s *Service) PauseWithWaiter() *EventPollWaiter {
s.log.Info("Pausing")
atomic.StoreUint32(&s.paused, 1)
waiter := newEventPollWaiter()
s.eventPollWaitersLock.Lock()
s.eventPollWaiters = append(s.eventPollWaiters, waiter)
s.eventPollWaitersLock.Unlock()
return waiter
}
// Resume resumes the event polling.
func (s *Service) Resume() {
s.log.Info("Resuming")
atomic.StoreUint32(&s.paused, 0)
}
// IsPaused return true if the service is paused.
func (s *Service) IsPaused() bool {
return atomic.LoadUint32(&s.paused) == 1
}
// RewindEventID sets the event id as the next event to be polled.
func (s *Service) RewindEventID(ctx context.Context, id string) error {
_, err := s.cpc.Send(ctx, &rewindEventIDReq{eventID: id})
return err
}
// Start the event service and return the last EventID that was processed.
func (s *Service) Start(ctx context.Context, group *orderedtasks.OrderedCancelGroup) (string, error) {
lastEventID, err := s.eventIDStore.Load(ctx)
if err != nil {
return "", fmt.Errorf("failed to load last event id: %w", err)
}
if lastEventID == "" {
s.log.Debugf("No event ID present in storage, retrieving latest")
client := network.NewClientRetryWrapper(s.eventSource, &network.ExpCoolDown{})
eventID, err := network.RetryWithClient(ctx, client, func(ctx context.Context, eventSource EventSource) (string, error) {
return eventSource.GetLatestEventID(ctx)
})
if err != nil {
return "", fmt.Errorf("failed to get latest event id: %w", err)
}
if err := s.eventIDStore.Store(ctx, eventID); err != nil {
return "", fmt.Errorf("failed to store event in event id store: %v", err)
}
lastEventID = eventID
}
group.Go(ctx, s.userID, "event-service", func(ctx context.Context) {
s.run(ctx, lastEventID)
})
return lastEventID, nil
}
func (s *Service) run(ctx context.Context, lastEventID string) {
s.log.Infof("Starting service Last EventID=%v", lastEventID)
defer s.cpc.Close()
defer s.timer.Stop()
defer s.log.Info("Exiting service")
client := network.NewClientRetryWrapper(s.eventSource, &network.ExpCoolDown{})
for {
select {
case <-ctx.Done():
return
case <-s.timer.C:
if s.IsPaused() {
s.closePollWaiters()
continue
}
case r, ok := <-s.cpc.ReceiveCh():
if !ok {
return
}
rewind, ok := r.Value().(*rewindEventIDReq)
if !ok {
s.log.Errorf("Received unknown request")
continue
}
err := s.rewindEventLoop(ctx, rewind.eventID)
r.Reply(ctx, nil, err)
if err == nil {
lastEventID = rewind.eventID
}
continue
case e, ok := <-s.eventWatcher.GetChannel():
if !ok {
continue
}
switch e.(type) {
case events.ConnStatusDown:
s.log.Info("Connection Lost, pausing")
s.Pause()
case events.ConnStatusUp:
s.log.Info("Connection Restored, resuming")
s.Resume()
}
}
// Apply any pending subscription changes.
func() {
s.pendingSubscriptionsLock.Lock()
defer s.pendingSubscriptionsLock.Unlock()
for _, p := range s.pendingSubscriptions {
if p.op == pendingOpAdd {
s.addSubscription(p.sub)
} else {
s.removeSubscription(p.sub)
}
}
s.pendingSubscriptions = nil
}()
newEvents, err := network.RetryWithClient(ctx, client, func(ctx context.Context, eventSource EventSource) ([]proton.Event, error) {
newEvents, _, err := eventSource.GetEvent(ctx, lastEventID)
return newEvents, err
})
if err != nil {
s.log.WithError(err).Errorf("Failed to get event (caused by %T)", internal.ErrCause(err))
continue
}
// If the event ID hasn't changed, there are no new events.
if newEvents[len(newEvents)-1].EventID == lastEventID {
s.log.Debugf("No new API Events")
continue
}
if event, eventErr := func() (proton.Event, error) {
for _, event := range newEvents {
if err := s.handleEvent(ctx, lastEventID, event); err != nil {
return event, err
}
}
return proton.Event{}, nil
}(); eventErr != nil {
subscriberName, err := s.handleEventError(ctx, lastEventID, event, eventErr)
if subscriberName == "" {
subscriberName = "?"
}
s.log.WithField("subscriber", subscriberName).WithError(err).Errorf("Failed to apply event")
continue
}
newEventID := newEvents[len(newEvents)-1].EventID
if err := s.eventIDStore.Store(ctx, newEventID); err != nil {
s.log.WithError(err).Errorf("Failed to store new event ID: %v", err)
s.onBadEvent(ctx, events.UserBadEvent{
Error: fmt.Errorf("failed to store new event ID: %w", err),
UserID: s.userID,
})
continue
}
lastEventID = newEventID
if s.IsPaused() {
s.closePollWaiters()
}
}
}
// Close should be called after the service has been cancelled to clean up any remaining pending operations.
func (s *Service) Close() {
if s.eventSubscription != nil {
s.eventSubscription.Remove(s.eventWatcher)
s.eventSubscription = nil
}
s.pendingSubscriptionsLock.Lock()
defer s.pendingSubscriptionsLock.Unlock()
processed := xmaps.Set[EventSubscriber]{}
// Cleanup pending removes.
for _, s := range s.pendingSubscriptions {
if !processed.Contains(s.sub) {
processed.Add(s.sub)
if s.op == pendingOpRemove {
s.sub.close()
} else {
s.sub.cancel()
s.sub.close()
}
}
}
s.pendingSubscriptions = nil
}
func (s *Service) closePollWaiters() {
s.eventPollWaitersLock.Lock()
defer s.eventPollWaitersLock.Unlock()
for _, v := range s.eventPollWaiters {
v.close()
}
s.eventPollWaiters = nil
}
func (s *Service) handleEvent(ctx context.Context, lastEventID string, event proton.Event) error {
s.log.WithFields(logrus.Fields{
"old": lastEventID,
"new": event,
}).Info("Received new API event")
if event.Refresh&proton.RefreshMail != 0 {
s.log.Info("Received refresh event")
}
return s.subscriberList.PublishParallel(ctx, event, s.panicHandler)
}
func unpackPublisherError(err error) (string, error) {
var publishErr *eventPublishError
if errors.As(err, &publishErr) {
return publishErr.subscriber.name(), publishErr.error
}
return "", err
}
func (s *Service) handleEventError(ctx context.Context, lastEventID string, event proton.Event, err error) (string, error) {
// Unpack the error so we can proceed to handle the real issue.
subscriberName, err := unpackPublisherError(err)
// If the error is a context cancellation, return error to retry later.
if errors.Is(err, context.Canceled) {
return subscriberName, fmt.Errorf("failed to handle event due to context cancellation: %w", err)
}
// If the error is a network error, return error to retry later.
if netErr := new(proton.NetError); errors.As(err, &netErr) {
return subscriberName, fmt.Errorf("failed to handle event due to network issue: %w", err)
}
// Catch all for uncategorized net errors that may slip through.
if netErr := new(net.OpError); errors.As(err, &netErr) {
return subscriberName, fmt.Errorf("failed to handle event due to network issues (uncategorized): %w", err)
}
// In case a json decode error slips through.
if jsonErr := new(json.UnmarshalTypeError); errors.As(err, &jsonErr) {
s.eventPublisher.PublishEvent(ctx, events.UncategorizedEventError{
UserID: s.userID,
Error: err,
})
return subscriberName, fmt.Errorf("failed to handle event due to JSON issue: %w", err)
}
// If the error is an unexpected EOF, return error to retry later.
if errors.Is(err, io.ErrUnexpectedEOF) {
return subscriberName, fmt.Errorf("failed to handle event due to EOF: %w", err)
}
// If the error is a server-side issue, return error to retry later.
if apiErr := new(proton.APIError); errors.As(err, &apiErr) && (apiErr.Status == 429 || apiErr.Status >= 500) {
return subscriberName, fmt.Errorf("failed to handle event due to server error: %w", err)
}
// Otherwise, the error is a client-side issue; notify bridge to handle it.
s.log.WithField("event", event).Warn("Failed to handle API event")
s.onBadEvent(ctx, events.UserBadEvent{
UserID: s.userID,
OldEventID: lastEventID,
NewEventID: event.EventID,
EventInfo: event.String(),
Error: err,
})
return subscriberName, fmt.Errorf("failed to handle event due to client error: %w", err)
}
func (s *Service) onBadEvent(ctx context.Context, event events.UserBadEvent) {
s.Pause()
s.eventPublisher.PublishEvent(ctx, event)
}
func (s *Service) addSubscription(subscription EventSubscriber) {
s.subscriberList.Add(subscription)
}
func (s *Service) removeSubscription(subscription EventSubscriber) {
s.subscriberList.Remove(subscription)
}
func (s *Service) rewindEventLoop(ctx context.Context, id string) error {
s.log.WithField("eventID", id).Info("Event loop reset")
return s.eventIDStore.Store(ctx, id)
}
type pendingOp int
const (
pendingOpAdd pendingOp = iota
pendingOpRemove
)
type pendingSubscription struct {
op pendingOp
sub EventSubscriber
}
type rewindEventIDReq struct {
eventID string
}