forked from bluesky-social/indigo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevents.go
475 lines (414 loc) · 11.6 KB
/
events.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
464
465
466
467
468
469
470
471
472
473
474
475
package events
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"sync"
"time"
comatproto "github.com/bluesky-social/indigo/api/atproto"
lexutil "github.com/bluesky-social/indigo/lex/util"
"github.com/bluesky-social/indigo/models"
"github.com/prometheus/client_golang/prometheus"
logging "github.com/ipfs/go-log"
cbg "github.com/whyrusleeping/cbor-gen"
"go.opentelemetry.io/otel"
)
var log = logging.Logger("events")
type Scheduler interface {
AddWork(ctx context.Context, repo string, val *XRPCStreamEvent) error
Shutdown()
}
type EventManager struct {
subs []*Subscriber
subsLk sync.Mutex
bufferSize int
crossoverBufferSize int
persister EventPersistence
}
func NewEventManager(persister EventPersistence) *EventManager {
em := &EventManager{
bufferSize: 16 << 10,
crossoverBufferSize: 512,
persister: persister,
}
persister.SetEventBroadcaster(em.broadcastEvent)
return em
}
const (
opSubscribe = iota
opUnsubscribe
opSend
)
type Operation struct {
op int
sub *Subscriber
evt *XRPCStreamEvent
}
func (em *EventManager) Shutdown(ctx context.Context) error {
return em.persister.Shutdown(ctx)
}
func (em *EventManager) broadcastEvent(evt *XRPCStreamEvent) {
// the main thing we do is send it out, so MarshalCBOR once
if err := evt.Preserialize(); err != nil {
log.Errorf("broadcast serialize failed, %s", err)
// serialize isn't going to go better later, this event is cursed
return
}
em.subsLk.Lock()
defer em.subsLk.Unlock()
// TODO: for a larger fanout we should probably have dedicated goroutines
// for subsets of the subscriber set, and tiered channels to distribute
// events out to them, or some similar architecture
// Alternatively, we might just want to not allow too many subscribers
// directly to the bgs, and have rebroadcasting proxies instead
for _, s := range em.subs {
if s.filter(evt) {
s.enqueuedCounter.Inc()
select {
case s.outgoing <- evt:
case <-s.done:
default:
// filter out all future messages that would be
// sent to this subscriber, but wait for it to
// actually be removed by the correct bit of
// code
s.filter = func(*XRPCStreamEvent) bool { return false }
log.Warnw("dropping slow consumer due to event overflow", "bufferSize", len(s.outgoing), "ident", s.ident)
go func(torem *Subscriber) {
torem.lk.Lock()
if !torem.cleanedUp {
select {
case torem.outgoing <- &XRPCStreamEvent{
Error: &ErrorFrame{
Error: "ConsumerTooSlow",
},
}:
case <-time.After(time.Second * 5):
log.Warnw("failed to send error frame to backed up consumer", "ident", torem.ident)
}
}
torem.lk.Unlock()
torem.cleanup()
}(s)
}
s.broadcastCounter.Inc()
}
}
}
func (em *EventManager) persistAndSendEvent(ctx context.Context, evt *XRPCStreamEvent) {
// TODO: can cut 5-10% off of disk persister benchmarks by making this function
// accept a uid. The lookup inside the persister is notably expensive (despite
// being an lru cache?)
if err := em.persister.Persist(ctx, evt); err != nil {
log.Errorf("failed to persist outbound event: %s", err)
}
}
type Subscriber struct {
outgoing chan *XRPCStreamEvent
filter func(*XRPCStreamEvent) bool
done chan struct{}
cleanup func()
lk sync.Mutex
cleanedUp bool
ident string
enqueuedCounter prometheus.Counter
broadcastCounter prometheus.Counter
}
const (
EvtKindErrorFrame = -1
EvtKindMessage = 1
)
type EventHeader struct {
Op int64 `cborgen:"op"`
MsgType string `cborgen:"t"`
}
var (
AccountStatusActive = "active"
AccountStatusTakendown = "takendown"
AccountStatusSuspended = "suspended"
AccountStatusDeleted = "deleted"
AccountStatusDeactivated = "deactivated"
)
type XRPCStreamEvent struct {
Error *ErrorFrame
RepoCommit *comatproto.SyncSubscribeRepos_Commit
RepoHandle *comatproto.SyncSubscribeRepos_Handle
RepoIdentity *comatproto.SyncSubscribeRepos_Identity
RepoInfo *comatproto.SyncSubscribeRepos_Info
RepoMigrate *comatproto.SyncSubscribeRepos_Migrate
RepoTombstone *comatproto.SyncSubscribeRepos_Tombstone
RepoAccount *comatproto.SyncSubscribeRepos_Account
LabelLabels *comatproto.LabelSubscribeLabels_Labels
LabelInfo *comatproto.LabelSubscribeLabels_Info
// some private fields for internal routing perf
PrivUid models.Uid `json:"-" cborgen:"-"`
PrivPdsId uint `json:"-" cborgen:"-"`
PrivRelevantPds []uint `json:"-" cborgen:"-"`
Preserialized []byte `json:"-" cborgen:"-"`
}
func (evt *XRPCStreamEvent) Serialize(wc io.Writer) error {
header := EventHeader{Op: EvtKindMessage}
var obj lexutil.CBOR
switch {
case evt.Error != nil:
header.Op = EvtKindErrorFrame
obj = evt.Error
case evt.RepoCommit != nil:
header.MsgType = "#commit"
obj = evt.RepoCommit
case evt.RepoHandle != nil:
header.MsgType = "#handle"
obj = evt.RepoHandle
case evt.RepoIdentity != nil:
header.MsgType = "#identity"
obj = evt.RepoIdentity
case evt.RepoAccount != nil:
header.MsgType = "#account"
obj = evt.RepoAccount
case evt.RepoInfo != nil:
header.MsgType = "#info"
obj = evt.RepoInfo
case evt.RepoMigrate != nil:
header.MsgType = "#migrate"
obj = evt.RepoMigrate
case evt.RepoTombstone != nil:
header.MsgType = "#tombstone"
obj = evt.RepoTombstone
default:
return fmt.Errorf("unrecognized event kind")
}
cborWriter := cbg.NewCborWriter(wc)
if err := header.MarshalCBOR(cborWriter); err != nil {
return fmt.Errorf("failed to write header: %w", err)
}
return obj.MarshalCBOR(cborWriter)
}
func (xevt *XRPCStreamEvent) Deserialize(r io.Reader) error {
var header EventHeader
if err := header.UnmarshalCBOR(r); err != nil {
return fmt.Errorf("reading header: %w", err)
}
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)
}
xevt.RepoCommit = &evt
case "#handle":
var evt comatproto.SyncSubscribeRepos_Handle
if err := evt.UnmarshalCBOR(r); err != nil {
return err
}
xevt.RepoHandle = &evt
case "#identity":
var evt comatproto.SyncSubscribeRepos_Identity
if err := evt.UnmarshalCBOR(r); err != nil {
return err
}
xevt.RepoIdentity = &evt
case "#account":
var evt comatproto.SyncSubscribeRepos_Account
if err := evt.UnmarshalCBOR(r); err != nil {
return err
}
xevt.RepoAccount = &evt
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
}
xevt.RepoInfo = &evt
case "#migrate":
var evt comatproto.SyncSubscribeRepos_Migrate
if err := evt.UnmarshalCBOR(r); err != nil {
return err
}
xevt.RepoMigrate = &evt
case "#tombstone":
var evt comatproto.SyncSubscribeRepos_Tombstone
if err := evt.UnmarshalCBOR(r); err != nil {
return err
}
xevt.RepoTombstone = &evt
case "#labels":
var evt comatproto.LabelSubscribeLabels_Labels
if err := evt.UnmarshalCBOR(r); err != nil {
return fmt.Errorf("reading Labels event: %w", err)
}
xevt.LabelLabels = &evt
}
case EvtKindErrorFrame:
var errframe ErrorFrame
if err := errframe.UnmarshalCBOR(r); err != nil {
return err
}
xevt.Error = &errframe
default:
return fmt.Errorf("unrecognized event stream type: %d", header.Op)
}
return nil
}
var ErrNoSeq = errors.New("event has no sequence number")
// serialize content into Preserialized cache
func (evt *XRPCStreamEvent) Preserialize() error {
if evt.Preserialized != nil {
return nil
}
var buf bytes.Buffer
err := evt.Serialize(&buf)
if err != nil {
return err
}
evt.Preserialized = buf.Bytes()
return nil
}
type ErrorFrame struct {
Error string `cborgen:"error"`
Message string `cborgen:"message"`
}
func (em *EventManager) AddEvent(ctx context.Context, ev *XRPCStreamEvent) error {
ctx, span := otel.Tracer("events").Start(ctx, "AddEvent")
defer span.End()
em.persistAndSendEvent(ctx, ev)
return nil
}
var (
ErrPlaybackShutdown = fmt.Errorf("playback shutting down")
ErrCaughtUp = fmt.Errorf("caught up")
)
func (em *EventManager) Subscribe(ctx context.Context, ident string, filter func(*XRPCStreamEvent) bool, since *int64) (<-chan *XRPCStreamEvent, func(), error) {
if filter == nil {
filter = func(*XRPCStreamEvent) bool { return true }
}
done := make(chan struct{})
sub := &Subscriber{
ident: ident,
outgoing: make(chan *XRPCStreamEvent, em.bufferSize),
filter: filter,
done: done,
enqueuedCounter: eventsEnqueued.WithLabelValues(ident),
broadcastCounter: eventsBroadcast.WithLabelValues(ident),
}
sub.cleanup = sync.OnceFunc(func() {
sub.lk.Lock()
defer sub.lk.Unlock()
close(done)
em.rmSubscriber(sub)
close(sub.outgoing)
sub.cleanedUp = true
})
if since == nil {
em.addSubscriber(sub)
return sub.outgoing, sub.cleanup, nil
}
out := make(chan *XRPCStreamEvent, em.crossoverBufferSize)
go func() {
lastSeq := *since
// run playback to get through *most* of the events, getting our current cursor close to realtime
if err := em.persister.Playback(ctx, *since, func(e *XRPCStreamEvent) error {
select {
case <-done:
return ErrPlaybackShutdown
case out <- e:
seq := SequenceForEvent(e)
if seq > 0 {
lastSeq = seq
}
return nil
}
}); err != nil {
if errors.Is(err, ErrPlaybackShutdown) {
log.Warnf("events playback: %s", err)
} else {
log.Errorf("events playback: %s", err)
}
// TODO: send an error frame or something?
close(out)
return
}
// now, start buffering events from the live stream
em.addSubscriber(sub)
first := <-sub.outgoing
// run playback again to get us to the events that have started buffering
if err := em.persister.Playback(ctx, lastSeq, func(e *XRPCStreamEvent) error {
seq := SequenceForEvent(e)
if seq > SequenceForEvent(first) {
return ErrCaughtUp
}
select {
case <-done:
return ErrPlaybackShutdown
case out <- e:
return nil
}
}); err != nil {
if !errors.Is(err, ErrCaughtUp) {
log.Errorf("events playback: %s", err)
// TODO: send an error frame or something?
close(out)
em.rmSubscriber(sub)
return
}
}
// now that we are caught up, just copy events from the channel over
for evt := range sub.outgoing {
select {
case out <- evt:
case <-done:
em.rmSubscriber(sub)
return
}
}
}()
return out, sub.cleanup, nil
}
func SequenceForEvent(evt *XRPCStreamEvent) int64 {
return evt.Sequence()
}
func (evt *XRPCStreamEvent) Sequence() int64 {
switch {
case evt == nil:
return -1
case evt.RepoCommit != nil:
return evt.RepoCommit.Seq
case evt.RepoHandle != nil:
return evt.RepoHandle.Seq
case evt.RepoMigrate != nil:
return evt.RepoMigrate.Seq
case evt.RepoTombstone != nil:
return evt.RepoTombstone.Seq
case evt.RepoIdentity != nil:
return evt.RepoIdentity.Seq
case evt.RepoInfo != nil:
return -1
case evt.Error != nil:
return -1
default:
return -1
}
}
func (em *EventManager) rmSubscriber(sub *Subscriber) {
em.subsLk.Lock()
defer em.subsLk.Unlock()
for i, s := range em.subs {
if s == sub {
em.subs[i] = em.subs[len(em.subs)-1]
em.subs = em.subs[:len(em.subs)-1]
break
}
}
}
func (em *EventManager) addSubscriber(sub *Subscriber) {
em.subsLk.Lock()
defer em.subsLk.Unlock()
em.subs = append(em.subs, sub)
}
func (em *EventManager) TakeDownRepo(ctx context.Context, user models.Uid) error {
return em.persister.TakeDownRepo(ctx, user)
}