forked from berty/berty
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
76 lines (58 loc) · 1.52 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package bertyprotocol
import (
"context"
"google.golang.org/grpc"
"berty.tech/berty/v2/go/internal/grpcutil"
"berty.tech/berty/v2/go/pkg/errcode"
"berty.tech/berty/v2/go/pkg/protocoltypes"
)
const ClientBufferSize = 256 * 1024
type Client interface {
protocoltypes.ProtocolServiceClient
Close() error
}
type client struct {
protocoltypes.ProtocolServiceClient
l *grpcutil.BufListener
cc *grpc.ClientConn
}
type embeddedClient struct {
Client
server *grpc.Server
}
func (c *client) Close() error {
c.cc.Close()
return c.l.Close()
}
func (c *embeddedClient) Close() error {
_ = c.Client.Close()
c.server.Stop()
return nil
}
func NewClient(ctx context.Context, svc Service, clientOpts []grpc.DialOption, serverOpts []grpc.ServerOption) (Client, error) {
s := grpc.NewServer(serverOpts...)
c, err := NewClientFromServer(ctx, s, svc, clientOpts...)
if err != nil {
return nil, errcode.ErrInternal.Wrap(err)
}
return &embeddedClient{
Client: c,
server: s,
}, nil
}
func NewClientFromServer(ctx context.Context, s *grpc.Server, svc Service, opts ...grpc.DialOption) (Client, error) {
bl := grpcutil.NewBufListener(ctx, ClientBufferSize)
cc, err := bl.NewClientConn(opts...)
if err != nil {
return nil, err
}
protocoltypes.RegisterProtocolServiceServer(s, svc)
go func() {
err := s.Serve(bl)
if err != nil && !(err == grpc.ErrServerStopped || err.Error() == "closed") {
panic(err)
}
}()
c := client{ProtocolServiceClient: protocoltypes.NewProtocolServiceClient(cc), cc: cc, l: bl}
return &c, nil
}