-
Notifications
You must be signed in to change notification settings - Fork 19
/
eventrpc.go
68 lines (59 loc) · 1.48 KB
/
eventrpc.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
package main
import (
"context"
"fmt"
"time"
pbevent "github.com/ethresearch/sharding-p2p-poc/pb/event"
peer "github.com/libp2p/go-libp2p-peer"
"google.golang.org/grpc"
)
type EventNotifier interface {
Receive(ctx context.Context, peerID peer.ID, msgType int, data []byte) ([]byte, error)
}
type mockEventNotifier struct {
}
type rpcEventNotifier struct {
client pbevent.EventClient
}
func NewMockEventNotifier() *mockEventNotifier {
return &mockEventNotifier{}
}
func (notifier *mockEventNotifier) Receive(
ctx context.Context,
peerID peer.ID,
msgType int,
data []byte) ([]byte, error) {
// Always return 1
return []byte{1}, nil
}
func NewRpcEventNotifier(ctx context.Context, rpcAddr string) (*rpcEventNotifier, error) {
conn, err := grpc.Dial(rpcAddr, grpc.WithInsecure(), grpc.WithBlock(), grpc.WithTimeout(time.Second*1))
if err != nil {
logger.Errorf("Failed to connect to the event notifier rpc server: %v", err)
return nil, err
}
client := pbevent.NewEventClient(conn)
n := &rpcEventNotifier{
client: client,
}
return n, nil
}
func (notifier *rpcEventNotifier) Receive(
ctx context.Context,
peerID peer.ID,
msgType int,
data []byte) ([]byte, error) {
req := &pbevent.ReceiveRequest{
PeerID: peerID.Pretty(),
MsgType: PBInt(msgType),
Data: data,
}
res, err := notifier.client.Receive(ctx, req)
if err != nil {
return nil, err
}
if res.Response.Status != pbevent.Response_SUCCESS {
return nil, fmt.Errorf("failure response")
}
return res.Data, nil
}