/
api_v2.go
528 lines (491 loc) · 13.4 KB
/
api_v2.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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
// Copyright 2017 The Cayley Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cayleyhttp
import (
"compress/gzip"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"strings"
"time"
"github.com/julienschmidt/httprouter"
"github.com/cayleygraph/cayley/clog"
"github.com/cayleygraph/cayley/graph"
"github.com/cayleygraph/cayley/graph/shape"
"github.com/cayleygraph/cayley/query"
_ "github.com/cayleygraph/cayley/writer"
"github.com/cayleygraph/quad"
)
func NewAPIv2(h *graph.Handle, wrappers ...HandlerWrapper) *APIv2 {
return NewAPIv2Writer(h, "single", nil, wrappers...)
}
func NewAPIv2Writer(h *graph.Handle, wtype string, wopts graph.Options, wrappers ...HandlerWrapper) *APIv2 {
api := &APIv2{h: h, wtyp: wtype, wopt: wopts, limit: 100}
api.r = httprouter.New()
api.RegisterOn(api.r, wrappers...)
return api
}
type APIv2 struct {
h *graph.Handle
r *httprouter.Router
ro bool
batch int
// replication
wtyp string
wopt graph.Options
// query
timeout time.Duration
limit int
}
func (api *APIv2) SetReadOnly(ro bool) {
api.ro = ro
}
func (api *APIv2) SetBatchSize(n int) {
api.batch = n
}
func (api *APIv2) SetQueryTimeout(dt time.Duration) {
api.timeout = dt
}
func (api *APIv2) SetQueryLimit(n int) {
api.limit = n
}
func (api *APIv2) ServeHTTP(w http.ResponseWriter, r *http.Request) {
api.r.ServeHTTP(w, r)
}
type HandlerWrapper func(httprouter.Handle) httprouter.Handle
func wrap(h http.HandlerFunc, arr []HandlerWrapper) httprouter.Handle {
wh := func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
h(w, r)
}
for _, w := range arr {
wh = w(wh)
}
return wh
}
func (api *APIv2) RegisterDataOn(r *httprouter.Router, wrappers ...HandlerWrapper) {
if !api.ro {
r.POST("/api/v2/write", wrap(api.ServeWrite, wrappers))
r.POST("/api/v2/delete", wrap(api.ServeDelete, wrappers))
r.POST("/api/v2/node/delete", wrap(api.ServeNodeDelete, wrappers))
}
r.POST("/api/v2/read", wrap(api.ServeRead, wrappers))
r.GET("/api/v2/read", wrap(api.ServeRead, wrappers))
r.GET("/api/v2/formats", wrap(api.ServeFormats, wrappers))
}
func (api *APIv2) RegisterQueryOn(r *httprouter.Router, wrappers ...HandlerWrapper) {
r.POST("/api/v2/query", wrap(api.ServeQuery, wrappers))
r.GET("/api/v2/query", wrap(api.ServeQuery, wrappers))
}
func (api *APIv2) RegisterOn(r *httprouter.Router, wrappers ...HandlerWrapper) {
api.RegisterDataOn(r, wrappers...)
api.RegisterQueryOn(r, wrappers...)
}
const (
defaultFormat = "nquads"
hdrContentType = "Content-Type"
hdrContentEncoding = "Content-Encoding"
hdrAccept = "Accept"
hdrAcceptEncoding = "Accept-Encoding"
contentTypeJSON = "application/json"
contentTypeJSONLD = "application/ld+json"
)
func getFormat(r *http.Request, formKey string, acceptName string) *quad.Format {
var format *quad.Format
if formKey != "" {
if name := r.FormValue("format"); name != "" {
format = quad.FormatByName(name)
}
}
if acceptName != "" && format == nil {
specs := ParseAccept(r.Header, acceptName)
// TODO: sort by Q
if len(specs) != 0 {
format = quad.FormatByMime(specs[0].Value)
}
}
if format == nil {
format = quad.FormatByName(defaultFormat)
}
return format
}
func readerFrom(r *http.Request, acceptName string) (io.ReadCloser, error) {
if specs := ParseAccept(r.Header, acceptName); len(specs) != 0 {
if s := specs[0]; s.Value == "gzip" {
zr, err := gzip.NewReader(r.Body)
if err != nil {
return nil, err
}
return zr, nil
}
}
return r.Body, nil
}
type nopWriteCloser struct {
io.Writer
}
func (nopWriteCloser) Close() error { return nil }
func writerFrom(w http.ResponseWriter, r *http.Request, acceptName string) io.WriteCloser {
if specs := ParseAccept(r.Header, acceptName); len(specs) != 0 {
if s := specs[0]; s.Value == "gzip" {
w.Header().Set(hdrContentEncoding, s.Value)
zw := gzip.NewWriter(w)
return zw
}
}
return nopWriteCloser{Writer: w}
}
func (api *APIv2) handleForRequest(r *http.Request) (*graph.Handle, error) {
return HandleForRequest(api.h, api.wtyp, api.wopt, r)
}
func (api *APIv2) ServeWrite(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
if api.ro {
jsonResponse(w, http.StatusForbidden, errors.New("database is read-only"))
return
}
format := getFormat(r, "", hdrContentType)
if format == nil || format.Reader == nil {
jsonResponse(w, http.StatusBadRequest, errors.New("format is not supported for reading data"))
return
}
rd, err := readerFrom(r, hdrContentEncoding)
if err != nil {
jsonResponse(w, http.StatusBadRequest, err)
return
}
defer rd.Close()
qr := format.Reader(rd)
defer qr.Close()
h, err := api.handleForRequest(r)
if err != nil {
jsonResponse(w, http.StatusBadRequest, err)
return
}
qw := graph.NewWriter(h.QuadWriter)
defer qw.Close()
n, err := quad.CopyBatch(qw, qr, api.batch)
if err != nil {
jsonResponse(w, http.StatusInternalServerError, err)
return
}
err = qw.Close()
if err != nil {
jsonResponse(w, http.StatusInternalServerError, err)
return
}
w.Header().Set(hdrContentType, contentTypeJSON)
fmt.Fprintf(w, `{"result": "Successfully wrote %d quads.", "count": %d}`+"\n", n, n)
}
func (api *APIv2) ServeDelete(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
if api.ro {
jsonResponse(w, http.StatusForbidden, errors.New("database is read-only"))
return
}
format := getFormat(r, "", hdrContentType)
if format == nil || format.Reader == nil {
jsonResponse(w, http.StatusBadRequest, fmt.Errorf("format is not supported for reading quads"))
return
}
rd, err := readerFrom(r, hdrContentEncoding)
if err != nil {
jsonResponse(w, http.StatusBadRequest, err)
return
}
defer rd.Close()
qr := format.Reader(r.Body)
defer qr.Close()
h, err := api.handleForRequest(r)
if err != nil {
jsonResponse(w, http.StatusBadRequest, err)
return
}
qw := graph.NewRemover(h.QuadWriter)
defer qw.Close()
n, err := quad.CopyBatch(qw, qr, api.batch)
if err != nil {
jsonResponse(w, http.StatusInternalServerError, err)
return
}
w.Header().Set(hdrContentType, contentTypeJSON)
fmt.Fprintf(w, `{"result": "Successfully deleted %d quads.", "count": %d}`+"\n", n, n)
}
func (api *APIv2) ServeNodeDelete(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
if api.ro {
jsonResponse(w, http.StatusForbidden, errors.New("database is read-only"))
return
}
format := getFormat(r, "", hdrContentType)
if format == nil || format.UnmarshalValue == nil {
jsonResponse(w, http.StatusBadRequest, fmt.Errorf("format is not supported for reading nodes"))
return
}
const limit = 128*1024 + 1
rd := io.LimitReader(r.Body, limit)
data, err := ioutil.ReadAll(rd)
if err != nil {
jsonResponse(w, http.StatusBadRequest, err)
return
} else if len(data) == limit {
jsonResponse(w, http.StatusBadRequest, fmt.Errorf("request data is too large"))
return
}
v, err := format.UnmarshalValue(data)
if err != nil {
jsonResponse(w, http.StatusBadRequest, err)
return
} else if v == nil {
jsonResponse(w, http.StatusBadRequest, fmt.Errorf("cannot remove nil value"))
return
}
h, err := api.handleForRequest(r)
if err != nil {
jsonResponse(w, http.StatusBadRequest, err)
return
}
err = h.RemoveNode(v)
if err != nil {
jsonResponse(w, http.StatusInternalServerError, err)
return
}
w.Header().Set(hdrContentType, contentTypeJSON)
const n = 1
fmt.Fprintf(w, `{"result": "Successfully deleted %d nodes.", "count": %d}`+"\n", n, n)
}
type checkWriter struct {
w io.Writer
written bool
}
func (w *checkWriter) Write(p []byte) (int, error) {
w.written = true
return w.w.Write(p)
}
func valuesFromString(s string) []quad.Value {
if s == "" {
return nil
}
arr := strings.Split(s, ",")
out := make([]quad.Value, 0, len(arr))
for _, s := range arr {
out = append(out, quad.StringToValue(s))
}
return out
}
func (api *APIv2) ServeRead(w http.ResponseWriter, r *http.Request) {
format := getFormat(r, "format", hdrAccept)
if format == nil || format.Writer == nil {
jsonResponse(w, http.StatusBadRequest, fmt.Errorf("format is not supported for reading data"))
return
}
h, err := api.handleForRequest(r)
if err != nil {
jsonResponse(w, http.StatusBadRequest, err)
return
}
values := shape.FilterQuads(
valuesFromString(r.FormValue("sub")),
valuesFromString(r.FormValue("pred")),
valuesFromString(r.FormValue("obj")),
valuesFromString(r.FormValue("label")),
)
it := values.BuildIterator(h.QuadStore)
qr := graph.NewResultReader(h.QuadStore, it)
defer qr.Close()
wr := writerFrom(w, r, hdrAcceptEncoding)
defer wr.Close()
cw := &checkWriter{w: wr}
qwc := format.Writer(cw)
defer qwc.Close()
var qw quad.Writer = qwc
if len(format.Mime) != 0 {
w.Header().Set(hdrContentType, format.Mime[0])
}
if irif := r.FormValue("iri"); irif != "" {
opts := quad.IRIOptions{
Format: quad.IRIDefault,
}
switch irif {
case "short":
opts.Format = quad.IRIShort
case "full":
opts.Format = quad.IRIFull
}
qw = quad.IRIWriter(qw, opts)
}
if bw, ok := qw.(quad.BatchWriter); ok {
_, err = quad.CopyBatch(bw, qr, api.batch)
} else {
_, err = quad.Copy(qw, qr)
}
if err != nil && !cw.written {
jsonResponse(w, http.StatusInternalServerError, err)
return
} else if err != nil {
// can do nothing here, since first byte (and header) was written
// TODO: check if client just gone away
clog.Errorf("read quads error: %v", err)
}
}
func (api *APIv2) ServeFormats(w http.ResponseWriter, r *http.Request) {
type Format struct {
Id string `json:"id"`
Read bool `json:"read,omitempty"`
Write bool `json:"write,omitempty"`
Nodes bool `json:"nodes,omitempty"`
Ext []string `json:"ext,omitempty"`
Mime []string `json:"mime,omitempty"`
Binary bool `json:"binary,omitempty"`
}
formats := quad.Formats()
out := make([]Format, 0, len(formats))
for _, f := range formats {
out = append(out, Format{
Id: f.Name,
Ext: f.Ext, Mime: f.Mime,
Read: f.Reader != nil, Write: f.Writer != nil,
Nodes: f.UnmarshalValue != nil,
Binary: f.Binary,
})
}
w.Header().Set(hdrContentType, contentTypeJSON)
json.NewEncoder(w).Encode(out)
}
func (api *APIv2) queryContext(r *http.Request) (ctx context.Context, cancel func()) {
ctx = r.Context()
if api.timeout > 0 {
ctx, cancel = context.WithTimeout(ctx, api.timeout)
} else {
ctx, cancel = context.WithCancel(ctx)
}
return ctx, cancel
}
func defaultErrorFunc(w query.ResponseWriter, err error) {
data, _ := json.Marshal(err.Error())
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(`{"error": `))
w.Write(data)
w.Write([]byte("}\n"))
}
func writeResults(w io.Writer, r interface{}) {
enc := json.NewEncoder(w)
enc.SetEscapeHTML(false)
enc.Encode(map[string]interface{}{
"result": r,
})
}
const maxQuerySize = 1024 * 1024 // 1 MB
func readLimit(r io.Reader) ([]byte, error) {
lr := io.LimitReader(r, maxQuerySize).(*io.LimitedReader)
data, err := ioutil.ReadAll(lr)
if err != nil && lr.N <= 0 {
err = errors.New("request is too large")
}
return data, err
}
func (api *APIv2) ServeQuery(w http.ResponseWriter, r *http.Request) {
ctx, cancel := api.queryContext(r)
defer cancel()
vals := r.URL.Query()
lang := vals.Get("lang")
if lang == "" {
jsonResponse(w, http.StatusBadRequest, "query language not specified")
return
}
l := query.GetLanguage(lang)
if l == nil {
jsonResponse(w, http.StatusBadRequest, "unknown query language")
return
}
errFunc := defaultErrorFunc
if l.HTTPError != nil {
errFunc = l.HTTPError
}
select {
case <-ctx.Done():
errFunc(w, ctx.Err())
return
default:
}
h, err := api.handleForRequest(r)
if err != nil {
errFunc(w, err)
return
}
if l.HTTPQuery != nil {
defer r.Body.Close()
l.HTTPQuery(ctx, h.QuadStore, w, r.Body)
return
}
if l.HTTP == nil {
errFunc(w, errors.New("HTTP interface is not supported for this query language"))
return
}
ses := l.HTTP(h.QuadStore)
var qu string
if r.Method == "GET" {
qu = vals.Get("qu")
} else {
data, err := readLimit(r.Body)
if err != nil {
errFunc(w, err)
return
}
qu = string(data)
}
if qu == "" {
jsonResponse(w, http.StatusBadRequest, "query is empty")
return
}
if clog.V(1) {
clog.Infof("query: %s: %q", lang, qu)
}
opt := query.Options{
Collation: query.JSON, // TODO: switch to JSON-LD by default when the time comes
Limit: api.limit,
}
if specs := ParseAccept(r.Header, hdrAccept); len(specs) != 0 {
// TODO: sort by Q
switch specs[0].Value {
case contentTypeJSON:
opt.Collation = query.JSON
case contentTypeJSONLD:
opt.Collation = query.JSONLD
}
}
it, err := ses.Execute(ctx, qu, opt)
if err != nil {
errFunc(w, err)
return
}
defer it.Close()
var out []interface{}
for it.Next(ctx) {
out = append(out, it.Result())
}
if err = it.Err(); err != nil {
errFunc(w, err)
return
}
if opt.Collation == query.JSONLD {
w.Header().Set(hdrContentType, contentTypeJSONLD)
} else {
w.Header().Set(hdrContentType, contentTypeJSON)
}
writeResults(w, out)
}