-
Notifications
You must be signed in to change notification settings - Fork 14
/
server.go
333 lines (272 loc) · 8.46 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
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
package web
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"os"
"path/filepath"
"strings"
"time"
"github.com/YuriyNasretdinov/chukcha/replication"
"github.com/YuriyNasretdinov/chukcha/server"
"github.com/valyala/fasthttp"
)
const maxReadSize = 16 * 1024 * 1024 // 16 MiB
// Server implements a web server
type Server struct {
logger *log.Logger
instanceName string
dirname string
listenAddr string
replStorage *replication.Storage
getOnDisk GetOnDiskFn
}
type GetOnDiskFn func(category string) (*server.OnDisk, error)
// NewServer creates *Server
func NewServer(logger *log.Logger, instanceName string, dirname string, listenAddr string, replStorage *replication.Storage, getOnDisk GetOnDiskFn) *Server {
return &Server{
logger: logger,
instanceName: instanceName,
dirname: dirname,
listenAddr: listenAddr,
replStorage: replStorage,
getOnDisk: getOnDisk,
}
}
type errWithCode struct {
code int
text string
}
// Error implements `error` type interface
func (e *errWithCode) Error() string {
return e.text
}
// Code returns an HTTP status code of the response.
func (e *errWithCode) Code() int {
return e.code
}
type withCode interface {
Code() int
}
func (s *Server) withCode(err error, code int) *errWithCode {
return &errWithCode{code: code, text: err.Error()}
}
func (s *Server) handler(ctx *fasthttp.RequestCtx) {
var err error
switch string(ctx.Path()) {
case "/write":
err = s.writeHandler(ctx)
case "/read":
err = s.readHandler(ctx)
case "/ack":
err = s.ackHandler(ctx)
case "/replication/ack":
err = s.replicationAckHandler(ctx)
case "/replication/events":
err = s.replicationEventsHandler(ctx)
case "/listChunks":
err = s.listChunksHandler(ctx)
case "/listCategories":
err = s.listCategoriesHandler(ctx)
default:
err = &errWithCode{code: fasthttp.StatusNotFound, text: "not found"}
}
if err == nil {
return
}
var ec withCode
if errors.As(err, &ec) {
ctx.Response.SetStatusCode(ec.Code())
} else {
ctx.Response.SetStatusCode(fasthttp.StatusInternalServerError)
}
ctx.WriteString(err.Error())
}
// TODO: check validity of a file name on Windows.
func isValidCategory(category string) bool {
if category == "" {
return false
}
cleanPath := filepath.Clean(category)
if cleanPath != category {
return false
}
if strings.ContainsAny(category, `/\.`) {
return false
}
return true
}
func (s *Server) getStorageForCategory(category string) (*server.OnDisk, error) {
if !isValidCategory(category) {
return nil, errors.New("invalid category name")
}
return s.getOnDisk(category)
}
func (s *Server) writeHandler(ctx *fasthttp.RequestCtx) error {
storage, err := s.getStorageForCategory(string(ctx.QueryArgs().Peek("category")))
if err != nil {
return s.withCode(err, fasthttp.StatusBadRequest)
}
chunkName, off, err := storage.Write(ctx, ctx.Request.Body())
if err != nil {
return err
}
minSyncReplicas, err := ctx.QueryArgs().GetUint("min_sync_replicas")
if err != nil && err != fasthttp.ErrNoArgValue {
return s.withCode(err, fasthttp.StatusBadRequest)
} else if minSyncReplicas > 0 {
waitCtx, cancel := context.WithTimeout(ctx, time.Minute)
defer cancel()
if err := storage.Wait(waitCtx, chunkName, uint64(off), uint(minSyncReplicas)); err != nil {
return err
}
}
return nil
}
func (s *Server) ackHandler(ctx *fasthttp.RequestCtx) error {
storage, err := s.getStorageForCategory(string(ctx.QueryArgs().Peek("category")))
if err != nil {
return s.withCode(err, fasthttp.StatusBadRequest)
}
chunk := ctx.QueryArgs().Peek("chunk")
if len(chunk) == 0 {
return &errWithCode{code: fasthttp.StatusBadRequest, text: "bad `chunk` GET param: chunk name must be provided"}
}
size, err := ctx.QueryArgs().GetUint("size")
if err != nil {
return &errWithCode{code: fasthttp.StatusBadRequest, text: fmt.Sprintf("bad `size` GET param: %v", err)}
}
if err := storage.Ack(ctx, string(chunk), uint64(size)); err != nil {
return err
}
return nil
}
// replicationAckHandler is used to let chunk owner (us) know that
// replica has successfully downloaded the chunk.
func (s *Server) replicationAckHandler(ctx *fasthttp.RequestCtx) error {
storage, err := s.getStorageForCategory(string(ctx.QueryArgs().Peek("category")))
if err != nil {
return s.withCode(err, fasthttp.StatusBadRequest)
}
chunk := ctx.QueryArgs().Peek("chunk")
if len(chunk) == 0 {
return &errWithCode{code: fasthttp.StatusBadRequest, text: "bad `chunk` GET param: chunk name must be provided"}
}
// instance is the name of instance that has successfully downloaded the
// respective chunk part.
instance := ctx.QueryArgs().Peek("instance")
if len(instance) == 0 {
return &errWithCode{code: fasthttp.StatusBadRequest, text: "bad `instance` GET param: chunk name must be provided"}
}
size, err := ctx.QueryArgs().GetUint("size")
if err != nil {
return &errWithCode{code: fasthttp.StatusBadRequest, text: "bad `size` GET param: chunk name must be provided"}
}
storage.ReplicationAck(ctx, string(chunk), string(instance), uint64(size))
return nil
}
// registerReplicationEvents is sending the events stream to the connected replica.
func (s *Server) replicationEventsHandler(ctx *fasthttp.RequestCtx) error {
// instance is the name of the connected replica.
instance := ctx.QueryArgs().Peek("instance")
if len(instance) == 0 {
return &errWithCode{code: fasthttp.StatusBadRequest, text: "bad `instance` GET param: replica name must be provided"}
}
eventsCh := make(chan replication.Message, 1000)
ctx.Response.SetBodyStreamWriter(func(w *bufio.Writer) {
wr := json.NewEncoder(w)
for {
select {
case ch, ok := <-eventsCh:
if !ok {
return
}
if err := wr.Encode(ch); err != nil {
s.logger.Printf("error encoding event: %v", err)
return
}
case <-time.After(10 * time.Second):
if err := wr.Encode(&replication.Chunk{}); err != nil {
s.logger.Printf("error encoding heartbeat event: %v", err)
return
}
}
if err := w.Flush(); err != nil {
s.logger.Printf("error flushing event: %v", err)
return
}
}
})
s.replStorage.RegisterReplica(string(instance), eventsCh)
return nil
}
func (s *Server) readHandler(ctx *fasthttp.RequestCtx) error {
chunk := ctx.QueryArgs().Peek("chunk")
if len(chunk) == 0 {
return &errWithCode{code: fasthttp.StatusBadRequest, text: "bad `chunk` GET param: chunk name must be provided"}
}
fromReplication, _ := ctx.QueryArgs().GetUint("from_replication")
if fromReplication == 1 {
// s.logger.Printf("sleeping for 8 seconds for request from replication for chunk %v", string(chunk))
// time.Sleep(time.Second * 8)
}
storage, err := s.getStorageForCategory(string(ctx.QueryArgs().Peek("category")))
if err != nil {
return s.withCode(err, fasthttp.StatusBadRequest)
}
off, err := ctx.QueryArgs().GetUint("off")
if err != nil {
return &errWithCode{code: fasthttp.StatusBadRequest, text: fmt.Sprintf("bad `off` GET param: %v", err)}
}
maxSize, err := ctx.QueryArgs().GetUint("max_size")
if err != nil {
return &errWithCode{code: fasthttp.StatusBadRequest, text: fmt.Sprintf("bad `max_size` GET param: %v", err)}
} else if maxSize > maxReadSize {
return &errWithCode{code: fasthttp.StatusBadRequest, text: fmt.Sprintf("bad `max_size` GET param: size can't exceed %d bytes", maxReadSize)}
}
err = storage.Read(string(chunk), uint64(off), uint64(maxSize), ctx)
if err != nil && err != io.EOF {
if errors.Is(err, os.ErrNotExist) {
return s.withCode(err, fasthttp.StatusNotFound)
}
return err
}
return nil
}
func (s *Server) listChunksHandler(ctx *fasthttp.RequestCtx) error {
storage, err := s.getStorageForCategory(string(ctx.QueryArgs().Peek("category")))
if err != nil {
return s.withCode(err, fasthttp.StatusBadRequest)
}
fromReplication, _ := ctx.QueryArgs().GetUint("from_replication")
if fromReplication == 1 {
// c.logger.Printf("sleeping for 8 seconds for request from replication for listing chunks")
// time.Sleep(time.Second * 8)
}
chunks, err := storage.ListChunks()
if err != nil {
return err
}
return json.NewEncoder(ctx).Encode(chunks)
}
func (s *Server) listCategoriesHandler(ctx *fasthttp.RequestCtx) error {
res := make([]string, 0)
dis, err := os.ReadDir(s.dirname)
if err != nil {
return err
}
for _, d := range dis {
if d.IsDir() {
res = append(res, d.Name())
}
}
return json.NewEncoder(ctx).Encode(res)
}
// Serve listens to HTTP connections
func (s *Server) Serve() error {
return fasthttp.ListenAndServe(s.listenAddr, s.handler)
}