forked from 0xPolygonHermez/zkevm-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
51 lines (44 loc) · 1.32 KB
/
client.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
package merkletree
import (
"context"
"time"
"github.com/0xPolygonHermez/zkevm-node/log"
"github.com/0xPolygonHermez/zkevm-node/merkletree/hashdb"
"google.golang.org/grpc"
"google.golang.org/grpc/connectivity"
"google.golang.org/grpc/credentials/insecure"
)
// NewMTDBServiceClient creates a new MTDB client.
func NewMTDBServiceClient(ctx context.Context, c Config) (hashdb.HashDBServiceClient, *grpc.ClientConn, context.CancelFunc) {
opts := []grpc.DialOption{
grpc.WithTransportCredentials(insecure.NewCredentials()),
}
mtDBConn, err := grpc.NewClient(c.URI, opts...)
if err != nil {
log.Fatalf("fail to create grpc connection to merkletree: %v", err)
}
log.Infof("trying to connect to merkletree: %v", c.URI)
const maxWaitSeconds = 120
ctx, cancel := context.WithTimeout(ctx, maxWaitSeconds*time.Second)
mtDBConn.Connect()
err = waitForConnection(ctx, mtDBConn)
if err != nil {
log.Fatalf("fail to connect to merkletree: %v", err)
}
log.Infof("connected to merkletree")
mtDBClient := hashdb.NewHashDBServiceClient(mtDBConn)
return mtDBClient, mtDBConn, cancel
}
func waitForConnection(ctx context.Context, conn *grpc.ClientConn) error {
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(time.Second):
s := conn.GetState()
if s == connectivity.Ready {
return nil
}
}
}
}