-
Notifications
You must be signed in to change notification settings - Fork 17
/
event.go
118 lines (89 loc) · 2.22 KB
/
event.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
package proton
import (
"context"
"time"
"github.com/ProtonMail/gluon/async"
"github.com/go-resty/resty/v2"
)
func (c *Client) GetLatestEventID(ctx context.Context) (string, error) {
var res struct {
Event
}
if err := c.do(ctx, func(r *resty.Request) (*resty.Response, error) {
return r.SetResult(&res).Get("/core/v4/events/latest")
}); err != nil {
return "", err
}
return res.EventID, nil
}
// maxCollectedEvents limits the number of events which are collected per one GetEvent
// call.
const maxCollectedEvents = 50
func (c *Client) GetEvent(ctx context.Context, eventID string) ([]Event, bool, error) {
var events []Event
event, more, err := c.getEvent(ctx, eventID)
if err != nil {
return nil, more, err
}
events = append(events, event)
nCollected := 0
for more {
nCollected++
if nCollected >= maxCollectedEvents {
break
}
event, more, err = c.getEvent(ctx, event.EventID)
if err != nil {
return nil, false, err
}
events = append(events, event)
}
return events, more, nil
}
// NewEventStreamer returns a new event stream.
// It polls the API for new events at random intervals between `period` and `period+jitter`.
func (c *Client) NewEventStream(ctx context.Context, period, jitter time.Duration, lastEventID string) <-chan Event {
eventCh := make(chan Event)
go func() {
defer async.HandlePanic(c.m.panicHandler)
defer close(eventCh)
ticker := NewTicker(period, jitter, c.m.panicHandler)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
// ...
}
events, _, err := c.GetEvent(ctx, lastEventID)
if err != nil {
continue
}
if events[len(events)-1].EventID == lastEventID {
continue
}
for _, evt := range events {
select {
case <-ctx.Done():
return
case eventCh <- evt:
lastEventID = evt.EventID
}
}
}
}()
return eventCh
}
func (c *Client) getEvent(ctx context.Context, eventID string) (Event, bool, error) {
var res struct {
Event
More Bool
}
if err := c.do(ctx, func(r *resty.Request) (*resty.Response, error) {
return r.SetResult(&res).Get("/core/v4/events/" + eventID)
}); err != nil {
return Event{}, false, err
}
return res.Event, bool(res.More), nil
}