-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathendpoint.go
103 lines (87 loc) · 2.15 KB
/
endpoint.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package discovery
import (
"context"
jsoniter "github.com/json-iterator/go"
"github.com/pkg/errors"
"strings"
"sync/atomic"
"time"
)
type Endpoint struct {
ttl uint32
lastUpdated int64
ID string `json:"id"`
PeerAddress string `json:"peer-addr"`
Metadata jsoniter.RawMessage `json:"metadata,omitempty"`
}
func (e *Endpoint) Key() string {
return e.ID
}
func (e *Endpoint) Value() *Endpoint {
return e
}
func (e *Endpoint) Marshal() ([]byte, error) {
return jsoniter.ConfigFastest.Marshal(e)
}
func (e *Endpoint) WithNaming(naming string) string {
return strings.Join([]string{
naming,
e.ID,
}, "::")
}
func (e *Endpoint) SetTTL(ttl uint32) {
atomic.StoreUint32(&e.ttl, ttl)
}
func (e *Endpoint) TTL() uint32 {
return atomic.LoadUint32(&e.ttl)
}
func (e *Endpoint) Expired() bool {
return time.Now().UnixMilli() > e.lastUpdated+(time.Second*time.Duration(e.TTL())).Milliseconds()
}
func (e *Endpoint) PutMetadata(md EndpointMetadata) (err error) {
e.Metadata, err = md.Entry()
return
}
func NewEndpoint(id string, peerAddr string, ttl uint32, md jsoniter.RawMessage) *Endpoint {
return &Endpoint{
ttl: ttl,
lastUpdated: time.Now().UnixMilli(),
ID: id,
PeerAddress: peerAddr,
Metadata: md,
}
}
func ParseEndpoint(b []byte) (*Endpoint, error) {
var endpoint Endpoint
if err := jsoniter.ConfigFastest.Unmarshal(b, &endpoint); err != nil {
return nil, err
}
return &endpoint, nil
}
func ParseEndpointPath(path string) (string, string, error) {
s := strings.Split(path, "::")
if len(s) != 2 {
return "", "", ErrInvalidEndpointPathFormat
}
return s[0], s[1], nil
}
func AutoKeepAlive(ctx context.Context, naming string, client *Client, endpoint *Endpoint) error {
err := client.Register(naming, endpoint)
if err != nil {
return errors.Wrap(err, "sdr: AutoKeepAlive")
}
go func() {
ticker := time.NewTicker(time.Second * time.Duration(endpoint.TTL()/4))
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
endpoint.lastUpdated = time.Now().UnixMilli()
_ = client.Register(naming, endpoint)
}
}
}()
return nil
}