-
Notifications
You must be signed in to change notification settings - Fork 2
/
http.go
208 lines (179 loc) · 4.49 KB
/
http.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
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
// SPDX-License-Identifier: Apache-2.0
// Copyright Authors of Cilium
package statedb
import (
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"github.com/cilium/statedb/part"
)
func (db *DB) HTTPHandler() http.Handler {
h := dbHandler{db}
mux := http.NewServeMux()
mux.HandleFunc("GET /dump", h.dumpAll)
mux.HandleFunc("GET /dump/{table}", h.dumpTable)
mux.HandleFunc("GET /query", h.query)
mux.HandleFunc("GET /changes/{table}", h.changes)
return mux
}
type dbHandler struct {
db *DB
}
func (h dbHandler) dumpAll(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
h.db.ReadTxn().WriteJSON(w)
}
func (h dbHandler) dumpTable(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
var err error
if table := r.PathValue("table"); table != "" {
err = h.db.ReadTxn().WriteJSON(w, r.PathValue("table"))
} else {
err = h.db.ReadTxn().WriteJSON(w)
}
if err != nil {
panic(err)
}
}
func (h dbHandler) query(w http.ResponseWriter, r *http.Request) {
enc := json.NewEncoder(w)
var req QueryRequest
body, err := io.ReadAll(r.Body)
r.Body.Close()
if err != nil {
w.WriteHeader(http.StatusBadRequest)
enc.Encode(QueryResponse{Err: err.Error()})
return
}
if err := json.Unmarshal(body, &req); err != nil {
w.WriteHeader(http.StatusBadRequest)
enc.Encode(QueryResponse{Err: err.Error()})
return
}
queryKey, err := base64.StdEncoding.DecodeString(req.Key)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
enc.Encode(QueryResponse{Err: err.Error()})
return
}
txn := h.db.ReadTxn().getTxn()
// Look up the table
var table TableMeta
for _, e := range txn.root {
if e.meta.Name() == req.Table {
table = e.meta
break
}
}
if table == nil {
w.WriteHeader(http.StatusNotFound)
enc.Encode(QueryResponse{Err: fmt.Sprintf("Table %q not found", req.Table)})
return
}
indexPos := table.indexPos(req.Index)
indexTxn, err := txn.indexReadTxn(table, indexPos)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
enc.Encode(QueryResponse{Err: err.Error()})
return
}
w.WriteHeader(http.StatusOK)
onObject := func(obj object) error {
return enc.Encode(QueryResponse{
Rev: obj.revision,
Obj: obj.data,
})
}
runQuery(indexTxn, req.LowerBound, queryKey, onObject)
}
type QueryRequest struct {
Key string `json:"key"` // Base64 encoded query key
Table string `json:"table"`
Index string `json:"index"`
LowerBound bool `json:"lowerbound"`
}
type QueryResponse struct {
Rev uint64 `json:"rev"`
Obj any `json:"obj"`
Err string `json:"err,omitempty"`
}
func runQuery(indexTxn indexReadTxn, lowerbound bool, queryKey []byte, onObject func(object) error) {
var iter *part.Iterator[object]
if lowerbound {
iter = indexTxn.LowerBound(queryKey)
} else {
iter, _ = indexTxn.Prefix(queryKey)
}
var match func([]byte) bool
switch {
case lowerbound:
match = func([]byte) bool { return true }
case indexTxn.unique:
match = func(k []byte) bool { return len(k) == len(queryKey) }
default:
match = func(k []byte) bool {
secondary, _ := decodeNonUniqueKey(k)
return len(secondary) == len(queryKey)
}
}
for key, obj, ok := iter.Next(); ok; key, obj, ok = iter.Next() {
if !match(key) {
continue
}
if err := onObject(obj); err != nil {
panic(err)
}
}
}
func (h dbHandler) changes(w http.ResponseWriter, r *http.Request) {
const keepaliveInterval = 30 * time.Second
enc := json.NewEncoder(w)
tableName := r.PathValue("table")
// Look up the table
var tableMeta TableMeta
for _, e := range h.db.ReadTxn().getTxn().root {
if e.meta.Name() == tableName {
tableMeta = e.meta
break
}
}
if tableMeta == nil {
w.WriteHeader(http.StatusNotFound)
enc.Encode(QueryResponse{Err: fmt.Sprintf("Table %q not found", tableName)})
return
}
// Register for changes.
wtxn := h.db.WriteTxn(tableMeta)
changeIter, err := tableMeta.anyChanges(wtxn)
wtxn.Commit()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
ticker := time.NewTicker(keepaliveInterval)
defer ticker.Stop()
for {
changes, watch := changeIter.nextAny(h.db.ReadTxn())
for change := range changes {
err := enc.Encode(change)
if err != nil {
panic(err)
}
}
w.(http.Flusher).Flush()
select {
case <-r.Context().Done():
return
case <-ticker.C:
// Send an empty keep-alive
enc.Encode(Change[any]{})
case <-watch:
}
}
}