-
Notifications
You must be signed in to change notification settings - Fork 125
/
consumer.go
343 lines (293 loc) · 8.75 KB
/
consumer.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
package events
import (
"context"
"fmt"
"io"
"log/slog"
"net"
"time"
"github.com/RussellLuo/slidingwindow"
comatproto "github.com/bluesky-social/indigo/api/atproto"
"github.com/prometheus/client_golang/prometheus"
"github.com/gorilla/websocket"
)
type RepoStreamCallbacks struct {
RepoCommit func(evt *comatproto.SyncSubscribeRepos_Commit) error
RepoHandle func(evt *comatproto.SyncSubscribeRepos_Handle) error
RepoIdentity func(evt *comatproto.SyncSubscribeRepos_Identity) error
RepoAccount func(evt *comatproto.SyncSubscribeRepos_Account) error
RepoInfo func(evt *comatproto.SyncSubscribeRepos_Info) error
RepoMigrate func(evt *comatproto.SyncSubscribeRepos_Migrate) error
RepoTombstone func(evt *comatproto.SyncSubscribeRepos_Tombstone) error
LabelLabels func(evt *comatproto.LabelSubscribeLabels_Labels) error
LabelInfo func(evt *comatproto.LabelSubscribeLabels_Info) error
Error func(evt *ErrorFrame) error
}
func (rsc *RepoStreamCallbacks) EventHandler(ctx context.Context, xev *XRPCStreamEvent) error {
switch {
case xev.RepoCommit != nil && rsc.RepoCommit != nil:
return rsc.RepoCommit(xev.RepoCommit)
case xev.RepoHandle != nil && rsc.RepoHandle != nil:
return rsc.RepoHandle(xev.RepoHandle)
case xev.RepoInfo != nil && rsc.RepoInfo != nil:
return rsc.RepoInfo(xev.RepoInfo)
case xev.RepoMigrate != nil && rsc.RepoMigrate != nil:
return rsc.RepoMigrate(xev.RepoMigrate)
case xev.RepoIdentity != nil && rsc.RepoIdentity != nil:
return rsc.RepoIdentity(xev.RepoIdentity)
case xev.RepoAccount != nil && rsc.RepoAccount != nil:
return rsc.RepoAccount(xev.RepoAccount)
case xev.RepoTombstone != nil && rsc.RepoTombstone != nil:
return rsc.RepoTombstone(xev.RepoTombstone)
case xev.LabelLabels != nil && rsc.LabelLabels != nil:
return rsc.LabelLabels(xev.LabelLabels)
case xev.LabelInfo != nil && rsc.LabelInfo != nil:
return rsc.LabelInfo(xev.LabelInfo)
case xev.Error != nil && rsc.Error != nil:
return rsc.Error(xev.Error)
default:
return nil
}
}
type InstrumentedRepoStreamCallbacks struct {
limiters []*slidingwindow.Limiter
Next func(ctx context.Context, xev *XRPCStreamEvent) error
}
func NewInstrumentedRepoStreamCallbacks(limiters []*slidingwindow.Limiter, next func(ctx context.Context, xev *XRPCStreamEvent) error) *InstrumentedRepoStreamCallbacks {
return &InstrumentedRepoStreamCallbacks{
limiters: limiters,
Next: next,
}
}
func waitForLimiter(ctx context.Context, lim *slidingwindow.Limiter) error {
if lim.Allow() {
return nil
}
// wait until the limiter is ready (check every 100ms)
t := time.NewTicker(100 * time.Millisecond)
defer t.Stop()
for !lim.Allow() {
select {
case <-ctx.Done():
return ctx.Err()
case <-t.C:
}
}
return nil
}
func (rsc *InstrumentedRepoStreamCallbacks) EventHandler(ctx context.Context, xev *XRPCStreamEvent) error {
// Wait on all limiters before calling the next handler
for _, lim := range rsc.limiters {
if err := waitForLimiter(ctx, lim); err != nil {
return err
}
}
return rsc.Next(ctx, xev)
}
type instrumentedReader struct {
r io.Reader
addr string
bytesCounter prometheus.Counter
}
func (sr *instrumentedReader) Read(p []byte) (int, error) {
n, err := sr.r.Read(p)
sr.bytesCounter.Add(float64(n))
return n, err
}
// HandleRepoStream
// con is source of events
// sched gets AddWork for each event
// log may be nil for default logger
func HandleRepoStream(ctx context.Context, con *websocket.Conn, sched Scheduler, log *slog.Logger) error {
if log == nil {
log = slog.Default().With("system", "events")
}
ctx, cancel := context.WithCancel(ctx)
defer cancel()
defer sched.Shutdown()
remoteAddr := con.RemoteAddr().String()
go func() {
t := time.NewTicker(time.Second * 30)
defer t.Stop()
for {
select {
case <-t.C:
if err := con.WriteControl(websocket.PingMessage, []byte{}, time.Now().Add(time.Second*10)); err != nil {
log.Warn("failed to ping", "err", err)
}
case <-ctx.Done():
con.Close()
return
}
}
}()
con.SetPingHandler(func(message string) error {
err := con.WriteControl(websocket.PongMessage, []byte(message), time.Now().Add(time.Second*60))
if err == websocket.ErrCloseSent {
return nil
} else if e, ok := err.(net.Error); ok && e.Temporary() {
return nil
}
return err
})
con.SetPongHandler(func(_ string) error {
if err := con.SetReadDeadline(time.Now().Add(time.Minute)); err != nil {
log.Error("failed to set read deadline", "err", err)
}
return nil
})
lastSeq := int64(-1)
for {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
mt, rawReader, err := con.NextReader()
if err != nil {
return err
}
switch mt {
default:
return fmt.Errorf("expected binary message from subscription endpoint")
case websocket.BinaryMessage:
// ok
}
r := &instrumentedReader{
r: rawReader,
addr: remoteAddr,
bytesCounter: bytesFromStreamCounter.WithLabelValues(remoteAddr),
}
var header EventHeader
if err := header.UnmarshalCBOR(r); err != nil {
return fmt.Errorf("reading header: %w", err)
}
eventsFromStreamCounter.WithLabelValues(remoteAddr).Inc()
switch header.Op {
case EvtKindMessage:
switch header.MsgType {
case "#commit":
var evt comatproto.SyncSubscribeRepos_Commit
if err := evt.UnmarshalCBOR(r); err != nil {
return fmt.Errorf("reading repoCommit event: %w", err)
}
if evt.Seq < lastSeq {
log.Error("Got events out of order from stream", "seq", evt.Seq, "prev", lastSeq)
}
lastSeq = evt.Seq
if err := sched.AddWork(ctx, evt.Repo, &XRPCStreamEvent{
RepoCommit: &evt,
}); err != nil {
return err
}
case "#handle":
var evt comatproto.SyncSubscribeRepos_Handle
if err := evt.UnmarshalCBOR(r); err != nil {
return err
}
if evt.Seq < lastSeq {
log.Error("Got events out of order from stream", "seq", evt.Seq, "prev", lastSeq)
}
lastSeq = evt.Seq
if err := sched.AddWork(ctx, evt.Did, &XRPCStreamEvent{
RepoHandle: &evt,
}); err != nil {
return err
}
case "#identity":
var evt comatproto.SyncSubscribeRepos_Identity
if err := evt.UnmarshalCBOR(r); err != nil {
return err
}
if evt.Seq < lastSeq {
log.Error("Got events out of order from stream", "seq", evt.Seq, "prev", lastSeq)
}
lastSeq = evt.Seq
if err := sched.AddWork(ctx, evt.Did, &XRPCStreamEvent{
RepoIdentity: &evt,
}); err != nil {
return err
}
case "#account":
var evt comatproto.SyncSubscribeRepos_Account
if err := evt.UnmarshalCBOR(r); err != nil {
return err
}
if evt.Seq < lastSeq {
log.Error("Got events out of order from stream", "seq", evt.Seq, "prev", lastSeq)
}
lastSeq = evt.Seq
if err := sched.AddWork(ctx, evt.Did, &XRPCStreamEvent{
RepoAccount: &evt,
}); err != nil {
return err
}
case "#info":
// TODO: this might also be a LabelInfo (as opposed to RepoInfo)
var evt comatproto.SyncSubscribeRepos_Info
if err := evt.UnmarshalCBOR(r); err != nil {
return err
}
if err := sched.AddWork(ctx, "", &XRPCStreamEvent{
RepoInfo: &evt,
}); err != nil {
return err
}
case "#migrate":
var evt comatproto.SyncSubscribeRepos_Migrate
if err := evt.UnmarshalCBOR(r); err != nil {
return err
}
if evt.Seq < lastSeq {
log.Error("Got events out of order from stream", "seq", evt.Seq, "prev", lastSeq)
}
lastSeq = evt.Seq
if err := sched.AddWork(ctx, evt.Did, &XRPCStreamEvent{
RepoMigrate: &evt,
}); err != nil {
return err
}
case "#tombstone":
var evt comatproto.SyncSubscribeRepos_Tombstone
if err := evt.UnmarshalCBOR(r); err != nil {
return err
}
if evt.Seq < lastSeq {
log.Error("Got events out of order from stream", "seq", evt.Seq, "prev", lastSeq)
}
lastSeq = evt.Seq
if err := sched.AddWork(ctx, evt.Did, &XRPCStreamEvent{
RepoTombstone: &evt,
}); err != nil {
return err
}
case "#labels":
var evt comatproto.LabelSubscribeLabels_Labels
if err := evt.UnmarshalCBOR(r); err != nil {
return fmt.Errorf("reading Labels event: %w", err)
}
if evt.Seq < lastSeq {
log.Error("Got events out of order from stream", "seq", evt.Seq, "prev", lastSeq)
}
lastSeq = evt.Seq
if err := sched.AddWork(ctx, "", &XRPCStreamEvent{
LabelLabels: &evt,
}); err != nil {
return err
}
}
case EvtKindErrorFrame:
var errframe ErrorFrame
if err := errframe.UnmarshalCBOR(r); err != nil {
return err
}
if err := sched.AddWork(ctx, "", &XRPCStreamEvent{
Error: &errframe,
}); err != nil {
return err
}
default:
return fmt.Errorf("unrecognized event stream type: %d", header.Op)
}
}
}