-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
msglistener.go
56 lines (47 loc) · 1.24 KB
/
msglistener.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 paychmgr
import (
"golang.org/x/xerrors"
"github.com/hannahhoward/go-pubsub"
"github.com/ipfs/go-cid"
)
type msgListeners struct {
ps *pubsub.PubSub
}
type msgCompleteEvt struct {
mcid cid.Cid
err error
}
type subscriberFn func(msgCompleteEvt)
func newMsgListeners() msgListeners {
ps := pubsub.New(func(event pubsub.Event, subFn pubsub.SubscriberFn) error {
evt, ok := event.(msgCompleteEvt)
if !ok {
return xerrors.Errorf("wrong type of event")
}
sub, ok := subFn.(subscriberFn)
if !ok {
return xerrors.Errorf("wrong type of subscriber")
}
sub(evt)
return nil
})
return msgListeners{ps: ps}
}
// onMsgComplete registers a callback for when the message with the given cid
// completes
func (ml *msgListeners) onMsgComplete(mcid cid.Cid, cb func(error)) pubsub.Unsubscribe {
var fn subscriberFn = func(evt msgCompleteEvt) {
if mcid.Equals(evt.mcid) {
cb(evt.err)
}
}
return ml.ps.Subscribe(fn)
}
// fireMsgComplete is called when a message completes
func (ml *msgListeners) fireMsgComplete(mcid cid.Cid, err error) {
e := ml.ps.Publish(msgCompleteEvt{mcid: mcid, err: err})
if e != nil {
// In theory we shouldn't ever get an error here
log.Errorf("unexpected error publishing message complete: %s", e)
}
}