-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
117 lines (94 loc) · 2.17 KB
/
server.go
File metadata and controls
117 lines (94 loc) · 2.17 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package main
import (
pb "KVStore/API"
"KVStore/SkipList"
"KVStore/Util"
"KVStore/WAL"
RecordPb "KVStore/WAL/pb"
"KVStore/errors"
"fmt"
"golang.org/x/net/context"
"google.golang.org/grpc"
"log"
"net"
)
const (
port = ":50051"
)
type server struct {
skiplist *SkipList.ConcurrentSkipList
log *wal.Log
}
func (s *server) Get(ctx context.Context, in *pb.GetRequest) (*pb.GetReply, error) {
key, err := util.StingTounin64(in.Key)
if err != nil {
return nil, err
}
node, result := s.skiplist.Search(key)
if !result {
return nil, errors.NewKeyNotFoundError()
}
return &pb.GetReply{Value: node.Value()}, nil
}
func (s *server) Put(ctx context.Context, in *pb.PutRequest) (*pb.PutReply, error) {
key, err := util.StingTounin64(in.Key)
if err != nil {
return nil, err
}
value, err := util.StringToArray(in.Value)
if err != nil {
return nil, err
}
s.skiplist.Insert(key, value)
record := &RecordPb.Record{
Type: 1,
Key: in.Key,
Value: in.Value,
}
s.log.AppendLog(record)
return &pb.PutReply{IsSuccess: true}, nil
}
func (s *server) Delete(ctx context.Context, in *pb.DeleteRequest) (*pb.DeleteReply, error) {
key, err := util.StingTounin64(in.Key)
if err != nil {
return nil, err
}
s.skiplist.Delete(key)
record := &RecordPb.Record{
Type: 2,
Key: in.Key,
}
s.log.AppendLog(record)
return &pb.DeleteReply{IsSuccess: true}, nil
}
func (s *server) Scan(ctx context.Context, in *pb.ScanRequest) (*pb.ScanReply, error) {
if in.Start < 0 || in.Limit < 1 {
return nil, errors.NewScanParameterInvaildError()
}
nodes := s.skiplist.Sub(in.Start, in.Limit)
var strs []string
for _, node := range nodes {
strs = append(strs, node.Value())
}
return &pb.ScanReply{Result: strs}, nil
}
func main() {
lis, err := net.Listen("tcp", port)
if err != nil {
log.Fatal("failed to listen: %v", err)
}
s := grpc.NewServer()
skipList, err := SkipList.NewConcurrentSkipList(16)
if err != nil {
fmt.Println(err)
}
server := &server{}
server.skiplist = skipList
server.log = wal.NewLog("data.dat")
play := wal.NewWalReplay("data.dat")
if play != nil {
play.ReadAll(server.skiplist)
}
pb.RegisterStoreServiceServer(s, server)
s.Serve(lis)
}