-
Notifications
You must be signed in to change notification settings - Fork 212
/
events.go
56 lines (46 loc) · 1.38 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
package grpcserver
import (
"context"
"github.com/libp2p/go-libp2p/core/event"
"github.com/spacemeshos/go-spacemesh/log"
)
const subscriptionChanBufSize = 1 << 16
// Errors for cases with a full event buffer.
var (
errTxBufferFull = "tx buffer is full"
errLayerBufferFull = "layer buffer is full"
errAccountBufferFull = "account buffer is full"
errRewardsBufferFull = "rewards buffer is full"
errActivationsBufferFull = "activations buffer is full"
errStatusBufferFull = "status buffer is full"
errErrorsBufferFull = "errors buffer is full"
)
func consumeEvents[T any](ctx context.Context, subscription event.Subscription) (out <-chan T, bufFull <-chan struct{}) {
outCh := make(chan T, subscriptionChanBufSize)
bufFullCh := make(chan struct{})
go func() {
defer closeSubscription(subscription)
for e := range subscription.Out() {
event, ok := e.(T)
if !ok {
log.With().Warning("received invalid event type - dropping")
continue
}
select {
case <-ctx.Done():
return
case outCh <- event:
default:
log.With().Debug("subscriber's event buffer is full")
close(bufFullCh)
return
}
}
}()
return outCh, bufFullCh
}
func closeSubscription(accountSubscription event.Subscription) {
if err := accountSubscription.Close(); err != nil {
log.With().Panic("Failed to close account subscription", log.Err(err))
}
}