-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdiscovery.go
81 lines (69 loc) · 1.75 KB
/
discovery.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
77
78
79
80
81
package discovery
import (
"context"
"github.com/RealFax/RedQueen/client"
"github.com/RealFax/red-discovery/internal/maputil"
"github.com/pkg/errors"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"sync/atomic"
)
var (
DefaultDialOpts = []grpc.DialOption{
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithDefaultCallOptions(grpc.WaitForReady(true)),
}
namespace atomic.Pointer[string]
)
func Namespace() string {
if ns := namespace.Load(); ns != nil {
return *ns
}
return ""
}
func SetNamespace(ns string) {
if ns != "" {
namespace.Store(&ns)
}
}
const (
MaxEndpointSize uint64 = 8192
)
type Client struct {
ctx context.Context
dialOpts []grpc.DialOption
client *client.Client
services *maputil.Map[string, Service]
DiscoveryAndRegister
}
func (c *Client) Service(naming string) (Service, bool) {
return c.services.Load(naming)
}
func (c *Client) Close() error {
c.services.Range(func(key string, value Service) bool {
c.services.Delete(key)
value.CloseAliveConn()
return true
})
return c.client.Close()
}
func NewWithClient(ctx context.Context, c *client.Client, dialOpts ...grpc.DialOption) *Client {
if dialOpts == nil {
dialOpts = DefaultDialOpts
}
services := maputil.New[string, Service]()
return &Client{
ctx: ctx,
dialOpts: dialOpts,
client: c,
services: services,
DiscoveryAndRegister: NewDiscoveryAndRegister(ctx, services, c, dialOpts...),
}
}
func New(ctx context.Context, endpoints []string, dialOpts ...grpc.DialOption) (*Client, error) {
c, err := client.New(ctx, endpoints, dialOpts...)
if err != nil {
return nil, errors.Wrap(err, "dial endpoints")
}
return NewWithClient(ctx, c, dialOpts...), nil
}