-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode.go
More file actions
83 lines (67 loc) · 1.58 KB
/
node.go
File metadata and controls
83 lines (67 loc) · 1.58 KB
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
package cluster
import (
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"net"
"time"
"github.com/cespare/xxhash/v2"
)
// NodeState represents membership state of a node.
type NodeState int
// Node state enumeration.
const (
NodeAlive NodeState = iota
NodeSuspect
NodeDead
)
// internal constants.
const (
nodeIDBytes = 8
)
func (s NodeState) String() string {
switch s {
case NodeAlive:
return "alive"
case NodeSuspect:
return "suspect"
case NodeDead:
return "dead"
default: // explicit default for revive enforce-switch-style
return "unknown"
}
}
// NodeID is a stable identifier for a node.
type NodeID string
// Node holds identity & state.
type Node struct {
ID NodeID
Address string // host:port for intra-cluster RPC
State NodeState
Incarnation uint64
LastSeen time.Time
}
// ErrInvalidAddress is returned when the node address is invalid.
var ErrInvalidAddress = errors.New("invalid node address")
// NewNode creates a node from address (host:port). If id empty, derive a short hex id using xxhash64.
func NewNode(id, addr string) *Node {
if id == "" {
hv := xxhash.Sum64String(addr)
b := make([]byte, nodeIDBytes)
binary.LittleEndian.PutUint64(b, hv)
id = hex.EncodeToString(b)
}
return &Node{ID: NodeID(id), Address: addr, State: NodeAlive, Incarnation: 1, LastSeen: time.Now()}
}
// Validate basic fields.
func (n *Node) Validate() error {
if n.Address == "" {
return ErrInvalidAddress
}
_, _, err := net.SplitHostPort(n.Address)
if err != nil {
return fmt.Errorf("%w: %w", ErrInvalidAddress, err)
}
return nil
}