-
Notifications
You must be signed in to change notification settings - Fork 60
/
funcs.go
55 lines (48 loc) · 1.42 KB
/
funcs.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
package event
import (
"context"
"fmt"
"github.com/dymensionxyz/dymint/types"
"github.com/tendermint/tendermint/libs/pubsub"
tmpubsub "github.com/tendermint/tendermint/libs/pubsub"
tmquery "github.com/tendermint/tendermint/libs/pubsub/query"
)
// MustSubscribe subscribes to events and sends back a callback
// clientID is essentially the subscriber id, see https://pkg.go.dev/github.com/tendermint/tendermint/libs/pubsub#pkg-overview
func MustSubscribe(
ctx context.Context,
pubsubServer *pubsub.Server,
clientID string,
eventQuery pubsub.Query,
callback func(event pubsub.Message),
logger types.Logger,
outCapacity ...int,
) {
subscription, err := pubsubServer.Subscribe(ctx, clientID, eventQuery, outCapacity...)
if err != nil {
logger.Error("subscribe to events")
panic(err)
}
for {
select {
case <-ctx.Done():
return
case event := <-subscription.Out():
callback(event)
case <-subscription.Cancelled():
logger.Info(clientID + " subscription canceled")
return
}
}
}
// MustPublish submits an event or panics
func MustPublish(ctx context.Context, pubsubServer *pubsub.Server, msg any, events map[string][]string) {
err := pubsubServer.PublishWithEvents(ctx, msg, events)
if err != nil {
panic(err)
}
}
// QueryFor returns a query for the given event.
func QueryFor(eventTypeKey, eventType string) tmpubsub.Query {
return tmquery.MustParse(fmt.Sprintf("%s='%s'", eventTypeKey, eventType))
}