-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnode_server.go
78 lines (66 loc) · 1.79 KB
/
node_server.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
package leaderless_key_value_store
import (
"context"
"fmt"
"time"
"github.com/46bit/leaderless-key-value-store/api"
"google.golang.org/protobuf/types/known/durationpb"
)
type NodeServer struct {
api.UnimplementedNodeServer
nodeId string
storage *Storage
startTime *time.Time
}
var _ api.NodeServer = (*NodeServer)(nil)
func NewNodeServer(nodeId string, storage *Storage) *NodeServer {
now := time.Now()
return &NodeServer{
nodeId: nodeId,
storage: storage,
startTime: &now,
}
}
func (s *NodeServer) Health(ctx context.Context, _ *api.HealthRequest) (*api.HealthResponse, error) {
return &api.HealthResponse{
NodeId: s.nodeId,
Status: api.Health_ONLINE,
Uptime: durationpb.New(s.uptime()),
}, nil
}
func (s *NodeServer) Info(_ *api.InfoRequest, stream api.Node_InfoServer) error {
keys, err := s.storage.Keys()
if err != nil {
err = fmt.Errorf("error listing keys: %w", err)
fmt.Println(err)
return err
}
return stream.Send(&api.InfoResponse{
NodeId: s.nodeId,
Uptime: durationpb.New(s.uptime()),
Keys: keys,
})
}
func (s *NodeServer) Get(ctx context.Context, req *api.GetRequest) (*api.NodeGetResponse, error) {
clockedEntry, err := s.storage.Get(req.Key)
if err != nil {
fmt.Println(fmt.Errorf("error getting value from node: %w", err))
return nil, err
}
return &api.NodeGetResponse{ClockedEntry: clockedEntry}, nil
}
func (s *NodeServer) Set(ctx context.Context, req *api.NodeSetRequest) (*api.SetResponse, error) {
err := s.storage.Set(req.ClockedEntry)
if err != nil {
fmt.Println(fmt.Errorf("error setting value on node: %w", err))
return nil, err
}
return &api.SetResponse{}, nil
}
func (s *NodeServer) uptime() time.Duration {
uptime := time.Duration(0)
if s.startTime != nil {
uptime = time.Now().Sub(*s.startTime)
}
return uptime
}