-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkeys.go
80 lines (70 loc) · 2.03 KB
/
keys.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
package http2raft
import (
"context"
"io/ioutil"
"net/http"
"time"
"github.com/lni/dragonboat/v3"
"github.com/lni/dragonboat/v3/client"
)
// keysController implements endpoints to perform key-value operations
type keysController struct {
clusterID uint64
readTimeOut time.Duration
writeTimeOut time.Duration
raftNode *dragonboat.NodeHost
clientSession *client.Session
}
func (c *keysController) readKey(w http.ResponseWriter, r *http.Request) {
// perform linear read from cluster
query := []byte(r.Method + " " + r.URL.Path)
result, err := c.syncRead(query)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(result)
}
func (c *keysController) writeKey(w http.ResponseWriter, r *http.Request) {
// read payload
data, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer r.Body.Close()
// do SyncPropose change key
query := []byte(r.Method + " " + r.URL.Path)
if len(data) > 0 {
query = append(query, '\n')
query = append(query, data...)
}
ctx, cancel := context.WithTimeout(context.Background(), c.writeTimeOut)
// ignore result as for now
_, err = c.raftNode.SyncPropose(ctx, c.clientSession, query)
cancel()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// do sync read of just updated value because proposal based queries are not recommended
// (SyncPropose) could return new value in result
if r.Method != http.MethodDelete && r.URL.Query().Get("return_value") != "" {
query = []byte(http.MethodGet + " " + r.URL.Path)
result, err := c.syncRead(query)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(result)
}
}
func (c *keysController) syncRead(query []byte) ([]byte, error) {
ctx, cancel := context.WithTimeout(context.Background(), c.readTimeOut)
defer cancel()
result, err := c.raftNode.SyncRead(ctx, c.clusterID, query)
if err != nil {
return nil, err
}
return result.([]byte), nil
}