-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
56 lines (49 loc) · 1.11 KB
/
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
package paxoskv
import (
context "context"
fmt "fmt"
"os"
"time"
"github.com/LiuzhouChan/go-paxos"
)
type server struct {
nh *paxos.NodeHost
}
func (s *server) Put(ctx context.Context,
req *KVRequest) (*KVResponse, error) {
return s.propose(ctx, req)
}
func (s *server) Delete(ctx context.Context,
req *KVRequest) (*KVResponse, error) {
return s.propose(ctx, req)
}
func (s *server) GetLocal(ctx context.Context,
req *KVRequest) (*KVResponse, error) {
query, err := req.Marshal()
if err != nil {
panic(err)
}
res, err := s.nh.ReadLocalNode(128, query)
if err != nil {
panic(err)
}
var resp KVResponse
err = resp.Unmarshal(res)
return &resp, err
}
func (s *server) propose(ctx context.Context, req *KVRequest) (*KVResponse, error) {
query, err := req.Marshal()
if err != nil {
panic(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
code, err := s.nh.SyncPropose(ctx, 128, query)
cancel()
if err != nil {
fmt.Fprintf(os.Stderr, "SyncPropose returned error %v\n", err)
return nil, err
}
resp := &KVResponse{}
resp.Code = KVResponse_Code(code)
return resp, nil
}