forked from perkeep/perkeep
/
handler.go
858 lines (749 loc) · 22.2 KB
/
handler.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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
/*
Copyright 2011 Google Inc.
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 search
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
"time"
"camlistore.org/pkg/blob"
"camlistore.org/pkg/blobserver"
"camlistore.org/pkg/httputil"
"camlistore.org/pkg/index"
"camlistore.org/pkg/jsonconfig"
"camlistore.org/pkg/types"
"camlistore.org/pkg/types/camtypes"
)
const buffered = 32 // arbitrary channel buffer size
const maxResults = 1000 // arbitrary limit on the number of search results returned
const defaultNumResults = 50
// MaxImageSize is the maximum width or height in pixels that we will serve image
// thumbnails at. It is used in the search result UI.
const MaxImageSize = 2000
var blobRefPattern = regexp.MustCompile(blob.Pattern)
func init() {
blobserver.RegisterHandlerConstructor("search", newHandlerFromConfig)
}
// Handler handles search queries.
type Handler struct {
index index.Interface
owner blob.Ref
// Corpus optionally specifies the full in-memory metadata corpus
// to use.
// TODO: this may be required in the future, or folded into the index
// interface.
corpus *index.Corpus
// WebSocket hub
wsHub *wsHub
}
// GetRecentPermanoder is the interface containing the GetRecentPermanodes method.
type GetRecentPermanoder interface {
// GetRecentPermanodes returns recently-modified permanodes.
// This is a higher-level query returning more metadata than the index.GetRecentPermanodes,
// which only scans the blobrefs but doesn't return anything about the permanodes.
GetRecentPermanodes(*RecentRequest) (*RecentResponse, error)
}
var _ GetRecentPermanoder = (*Handler)(nil)
func NewHandler(index index.Interface, owner blob.Ref) *Handler {
sh := &Handler{
index: index,
owner: owner,
}
sh.wsHub = newWebsocketHub(sh)
go sh.wsHub.run()
sh.subscribeToNewBlobs()
return sh
}
func (sh *Handler) subscribeToNewBlobs() {
ch := make(chan blob.Ref, buffered)
blobserver.GetHub(sh.index).RegisterListener(ch)
go func() {
for br := range ch {
bm, err := sh.index.GetBlobMeta(br)
if err == nil {
sh.wsHub.newBlobRecv <- bm.CamliType
}
}
}()
}
func (h *Handler) SetCorpus(c *index.Corpus) {
h.corpus = c
}
// SendStatusUpdate sends a JSON status map to any connected WebSocket clients.
func (h *Handler) SendStatusUpdate(status json.RawMessage) {
h.wsHub.statusUpdate <- status
}
func newHandlerFromConfig(ld blobserver.Loader, conf jsonconfig.Obj) (http.Handler, error) {
indexPrefix := conf.RequiredString("index") // TODO: add optional help tips here?
ownerBlobStr := conf.RequiredString("owner")
devBlockStartupPrefix := conf.OptionalString("devBlockStartupOn", "")
slurpToMemory := conf.OptionalBool("slurpToMemory", false)
if err := conf.Validate(); err != nil {
return nil, err
}
if devBlockStartupPrefix != "" {
_, err := ld.GetHandler(devBlockStartupPrefix)
if err != nil {
return nil, fmt.Errorf("search handler references bogus devBlockStartupOn handler %s: %v", devBlockStartupPrefix, err)
}
}
indexHandler, err := ld.GetHandler(indexPrefix)
if err != nil {
return nil, fmt.Errorf("search config references unknown handler %q", indexPrefix)
}
indexer, ok := indexHandler.(index.Interface)
if !ok {
return nil, fmt.Errorf("search config references invalid indexer %q (actually a %T)", indexPrefix, indexHandler)
}
ownerBlobRef, ok := blob.Parse(ownerBlobStr)
if !ok {
return nil, fmt.Errorf("search 'owner' has malformed blobref %q; expecting e.g. sha1-xxxxxxxxxxxx",
ownerBlobStr)
}
h := NewHandler(indexer, ownerBlobRef)
if slurpToMemory {
ii := indexer.(*index.Index)
corpus, err := ii.KeepInMemory()
if err != nil {
return nil, fmt.Errorf("error slurping index to memory: %v", err)
}
h.corpus = corpus
}
return h, nil
}
// Owner returns Handler owner's public key blobref.
func (h *Handler) Owner() blob.Ref {
// TODO: figure out a plan for an owner having multiple active public keys, or public
// key rotation
return h.owner
}
func (h *Handler) Index() index.Interface {
return h.index
}
func jsonMap() map[string]interface{} {
return make(map[string]interface{})
}
var getHandler = map[string]func(*Handler, http.ResponseWriter, *http.Request){
"ws": (*Handler).serveWebSocket,
"recent": (*Handler).serveRecentPermanodes,
"permanodeattr": (*Handler).servePermanodesWithAttr,
"describe": (*Handler).serveDescribe,
"claims": (*Handler).serveClaims,
"files": (*Handler).serveFiles,
"signerattrvalue": (*Handler).serveSignerAttrValue,
"signerpaths": (*Handler).serveSignerPaths,
"edgesto": (*Handler).serveEdgesTo,
}
var postHandler = map[string]func(*Handler, http.ResponseWriter, *http.Request){
"describe": (*Handler).serveDescribe,
"query": (*Handler).serveQuery,
}
func (sh *Handler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
suffix := httputil.PathSuffix(req)
handlers := getHandler
switch {
case httputil.IsGet(req):
// use default from above
case req.Method == "POST":
handlers = postHandler
default:
handlers = nil
}
fn := handlers[strings.TrimPrefix(suffix, "camli/search/")]
if fn != nil {
fn(sh, rw, req)
return
}
// TODO: discovery for the endpoints & better error message with link to discovery info
ret := jsonMap()
ret["error"] = "Unsupported search path or method"
ret["errorType"] = "input"
httputil.ReturnJSON(rw, ret)
}
// sanitizeNumResults takes n as a requested number of search results and sanitizes it.
func sanitizeNumResults(n int) int {
if n <= 0 || n > maxResults {
return defaultNumResults
}
return n
}
// RecentRequest is a request to get a RecentResponse.
type RecentRequest struct {
N int // if zero, default number of results
Before time.Time // if zero, now
ThumbnailSize int // if zero, no thumbnails
}
func (r *RecentRequest) URLSuffix() string {
var buf bytes.Buffer
fmt.Fprintf(&buf, "camli/search/recent?n=%d&thumbnails=%d", r.n(), r.thumbnailSize())
if !r.Before.IsZero() {
fmt.Fprintf(&buf, "&before=%s", types.Time3339(r.Before))
}
return buf.String()
}
// fromHTTP panics with an httputil value on failure
func (r *RecentRequest) fromHTTP(req *http.Request) {
r.N, _ = strconv.Atoi(req.FormValue("n"))
r.ThumbnailSize = thumbnailSize(req)
if before := req.FormValue("before"); before != "" {
r.Before = time.Time(types.ParseTime3339OrZero(before))
}
}
// n returns the sanitized maximum number of search results.
func (r *RecentRequest) n() int {
return sanitizeNumResults(r.N)
}
func (r *RecentRequest) thumbnailSize() int {
v := r.ThumbnailSize
if v == 0 {
return 0
}
if v < minThumbSize || v > maxThumbSize {
return defThumbSize
}
return v
}
// WithAttrRequest is a request to get a WithAttrResponse.
type WithAttrRequest struct {
N int // max number of results
Signer blob.Ref // if nil, will use the server's default owner (if configured)
// Requested attribute. If blank, all attributes are searched (for Value)
// as fulltext.
Attr string
// Value of the requested attribute. If blank, permanodes which have
// request.Attr as an attribute are searched.
Value string
Fuzzy bool // fulltext search (if supported).
ThumbnailSize int // if zero, no thumbnails
}
func (r *WithAttrRequest) URLSuffix() string {
return fmt.Sprintf("camli/search/permanodeattr?signer=%v&value=%v&fuzzy=%v&attr=%v&max=%v&thumbnails=%v",
r.Signer, url.QueryEscape(r.Value), r.Fuzzy, r.Attr, r.N, r.ThumbnailSize)
}
// fromHTTP panics with an httputil value on failure
func (r *WithAttrRequest) fromHTTP(req *http.Request) {
r.Signer = blob.ParseOrZero(req.FormValue("signer"))
r.Value = req.FormValue("value")
fuzzy := req.FormValue("fuzzy") // exact match if empty
fuzzyMatch := false
if fuzzy != "" {
lowered := strings.ToLower(fuzzy)
if lowered == "true" || lowered == "t" {
fuzzyMatch = true
}
}
r.Attr = req.FormValue("attr") // all attributes if empty
if r.Attr == "" { // and force fuzzy in that case.
fuzzyMatch = true
}
r.Fuzzy = fuzzyMatch
r.ThumbnailSize = thumbnailSize(req)
max := req.FormValue("max")
if max != "" {
maxR, err := strconv.Atoi(max)
if err != nil {
panic(httputil.InvalidParameterError("max"))
}
r.N = maxR
}
r.N = r.n()
}
// n returns the sanitized maximum number of search results.
func (r *WithAttrRequest) n() int {
return sanitizeNumResults(r.N)
}
func (r *WithAttrRequest) thumbnailSize() int {
v := r.ThumbnailSize
if v == 0 {
return 0
}
if v < minThumbSize {
return minThumbSize
}
if v > maxThumbSize {
return maxThumbSize
}
return v
}
// ClaimsRequest is a request to get a ClaimsResponse.
type ClaimsRequest struct {
Permanode blob.Ref
// AttrFilter optionally filters claims about the given attribute.
// If empty, all claims for the given Permanode are returned.
AttrFilter string
}
func (r *ClaimsRequest) URLSuffix() string {
return fmt.Sprintf("camli/search/claims?permanode=%v&attrFilter=%s",
r.Permanode, url.QueryEscape(r.AttrFilter))
}
// fromHTTP panics with an httputil value on failure
func (r *ClaimsRequest) fromHTTP(req *http.Request) {
r.Permanode = httputil.MustGetBlobRef(req, "permanode")
r.AttrFilter = req.FormValue("attrFilter")
}
// SignerPathsRequest is a request to get a SignerPathsResponse.
type SignerPathsRequest struct {
Signer blob.Ref
Target blob.Ref
}
// fromHTTP panics with an httputil value on failure
func (r *SignerPathsRequest) fromHTTP(req *http.Request) {
r.Signer = httputil.MustGetBlobRef(req, "signer")
r.Target = httputil.MustGetBlobRef(req, "target")
}
// EdgesRequest is a request to get an EdgesResponse.
type EdgesRequest struct {
// The blob we want to find as a reference.
ToRef blob.Ref
}
// fromHTTP panics with an httputil value on failure
func (r *EdgesRequest) fromHTTP(req *http.Request) {
r.ToRef = httputil.MustGetBlobRef(req, "blobref")
}
// TODO(mpl): it looks like we never populate RecentResponse.Error*, shouldn't we remove them?
// Same for WithAttrResponse. I suppose it doesn't matter much if we end up removing GetRecentPermanodes anyway...
// RecentResponse is the JSON response from $searchRoot/camli/search/recent.
type RecentResponse struct {
Recent []*RecentItem `json:"recent"`
Meta MetaMap `json:"meta"`
Error string `json:"error,omitempty"`
ErrorType string `json:"errorType,omitempty"`
}
func (r *RecentResponse) Err() error {
if r.Error != "" || r.ErrorType != "" {
if r.ErrorType != "" {
return fmt.Errorf("%s: %s", r.ErrorType, r.Error)
}
return errors.New(r.Error)
}
return nil
}
// WithAttrResponse is the JSON response from $searchRoot/camli/search/permanodeattr.
type WithAttrResponse struct {
WithAttr []*WithAttrItem `json:"withAttr"`
Meta MetaMap `json:"meta"`
Error string `json:"error,omitempty"`
ErrorType string `json:"errorType,omitempty"`
}
func (r *WithAttrResponse) Err() error {
if r.Error != "" || r.ErrorType != "" {
if r.ErrorType != "" {
return fmt.Errorf("%s: %s", r.ErrorType, r.Error)
}
return errors.New(r.Error)
}
return nil
}
// ClaimsResponse is the JSON response from $searchRoot/camli/search/claims.
type ClaimsResponse struct {
Claims []*ClaimsItem `json:"claims"`
}
// SignerPathsResponse is the JSON response from $searchRoot/camli/search/signerpaths.
type SignerPathsResponse struct {
Paths []*SignerPathsItem `json:"paths"`
Meta MetaMap `json:"meta"`
}
// A RecentItem is an item returned from $searchRoot/camli/search/recent in the "recent" list.
type RecentItem struct {
BlobRef blob.Ref `json:"blobref"`
ModTime types.Time3339 `json:"modtime"`
Owner blob.Ref `json:"owner"`
}
// A WithAttrItem is an item returned from $searchRoot/camli/search/permanodeattr.
type WithAttrItem struct {
Permanode blob.Ref `json:"permanode"`
}
// A ClaimsItem is an item returned from $searchRoot/camli/search/claims.
type ClaimsItem struct {
BlobRef blob.Ref `json:"blobref"`
Signer blob.Ref `json:"signer"`
Permanode blob.Ref `json:"permanode"`
Date types.Time3339 `json:"date"`
Type string `json:"type"`
Attr string `json:"attr,omitempty"`
Value string `json:"value,omitempty"`
}
// A SignerPathsItem is an item returned from $searchRoot/camli/search/signerpaths.
type SignerPathsItem struct {
ClaimRef blob.Ref `json:"claimRef"`
BaseRef blob.Ref `json:"baseRef"`
Suffix string `json:"suffix"`
}
// EdgesResponse is the JSON response from $searchRoot/camli/search/edgesto.
type EdgesResponse struct {
ToRef blob.Ref `json:"toRef"`
EdgesTo []*EdgeItem `json:"edgesTo"`
}
// An EdgeItem is an item returned from $searchRoot/camli/search/edgesto.
type EdgeItem struct {
From blob.Ref `json:"from"`
FromType string `json:"fromType"`
}
func thumbnailSize(r *http.Request) int {
return thumbnailSizeStr(r.FormValue("thumbnails"))
}
const (
minThumbSize = 25
defThumbSize = 50
maxThumbSize = 800
)
func thumbnailSizeStr(s string) int {
if s == "" {
return 0
}
if i, _ := strconv.Atoi(s); i >= minThumbSize && i <= maxThumbSize {
return i
}
return defThumbSize
}
var testHookBug121 = func() {}
// GetRecentPermanodes returns recently-modified permanodes.
func (sh *Handler) GetRecentPermanodes(req *RecentRequest) (*RecentResponse, error) {
ch := make(chan camtypes.RecentPermanode)
errch := make(chan error, 1)
before := time.Now()
if !req.Before.IsZero() {
before = req.Before
}
go func() {
errch <- sh.index.GetRecentPermanodes(ch, sh.owner, req.n(), before)
}()
dr := sh.NewDescribeRequest()
var recent []*RecentItem
for res := range ch {
dr.Describe(res.Permanode, 2)
recent = append(recent, &RecentItem{
BlobRef: res.Permanode,
Owner: res.Signer,
ModTime: types.Time3339(res.LastModTime),
})
testHookBug121() // http://camlistore.org/issue/121
}
if err := <-errch; err != nil {
return nil, err
}
metaMap, err := dr.metaMapThumbs(req.thumbnailSize())
if err != nil {
return nil, err
}
res := &RecentResponse{
Recent: recent,
Meta: metaMap,
}
return res, nil
}
func (sh *Handler) serveRecentPermanodes(rw http.ResponseWriter, req *http.Request) {
defer httputil.RecoverJSON(rw, req)
var rr RecentRequest
rr.fromHTTP(req)
res, err := sh.GetRecentPermanodes(&rr)
if err != nil {
httputil.ServeJSONError(rw, err)
return
}
httputil.ReturnJSON(rw, res)
}
// GetPermanodesWithAttr returns permanodes with attribute req.Attr
// having the req.Value as a value.
// See WithAttrRequest for more details about the query.
func (sh *Handler) GetPermanodesWithAttr(req *WithAttrRequest) (*WithAttrResponse, error) {
ch := make(chan blob.Ref, buffered)
errch := make(chan error, 1)
go func() {
signer := req.Signer
if !signer.Valid() {
signer = sh.owner
}
errch <- sh.index.SearchPermanodesWithAttr(ch,
&camtypes.PermanodeByAttrRequest{
Attribute: req.Attr,
Query: req.Value,
Signer: signer,
FuzzyMatch: req.Fuzzy,
MaxResults: req.N,
})
}()
dr := sh.NewDescribeRequest()
var withAttr []*WithAttrItem
for res := range ch {
dr.Describe(res, 2)
withAttr = append(withAttr, &WithAttrItem{
Permanode: res,
})
}
metaMap, err := dr.metaMapThumbs(req.thumbnailSize())
if err != nil {
return nil, err
}
if err := <-errch; err != nil {
return nil, err
}
res := &WithAttrResponse{
WithAttr: withAttr,
Meta: metaMap,
}
return res, nil
}
// servePermanodesWithAttr uses the indexer to search for the permanodes matching
// the request.
// The valid values for the "attr" key in the request (i.e the only attributes
// for a permanode which are actually indexed as such) are "tag" and "title".
func (sh *Handler) servePermanodesWithAttr(rw http.ResponseWriter, req *http.Request) {
defer httputil.RecoverJSON(rw, req)
var wr WithAttrRequest
wr.fromHTTP(req)
res, err := sh.GetPermanodesWithAttr(&wr)
if err != nil {
httputil.ServeJSONError(rw, err)
return
}
httputil.ReturnJSON(rw, res)
}
// GetClaims returns the claims on req.Permanode signed by sh.owner.
func (sh *Handler) GetClaims(req *ClaimsRequest) (*ClaimsResponse, error) {
if !req.Permanode.Valid() {
return nil, errors.New("Error getting claims: nil permanode.")
}
var claims []camtypes.Claim
claims, err := sh.index.AppendClaims(claims, req.Permanode, sh.owner, req.AttrFilter)
if err != nil {
return nil, fmt.Errorf("Error getting claims of %s: %v", req.Permanode.String(), err)
}
sort.Sort(camtypes.ClaimsByDate(claims))
var jclaims []*ClaimsItem
for _, claim := range claims {
jclaim := &ClaimsItem{
BlobRef: claim.BlobRef,
Signer: claim.Signer,
Permanode: claim.Permanode,
Date: types.Time3339(claim.Date),
Type: claim.Type,
Attr: claim.Attr,
Value: claim.Value,
}
jclaims = append(jclaims, jclaim)
}
res := &ClaimsResponse{
Claims: jclaims,
}
return res, nil
}
func (sh *Handler) serveClaims(rw http.ResponseWriter, req *http.Request) {
defer httputil.RecoverJSON(rw, req)
var cr ClaimsRequest
cr.fromHTTP(req)
res, err := sh.GetClaims(&cr)
if err != nil {
httputil.ServeJSONError(rw, err)
return
}
httputil.ReturnJSON(rw, res)
}
func (sh *Handler) serveFiles(rw http.ResponseWriter, req *http.Request) {
ret := jsonMap()
defer httputil.ReturnJSON(rw, ret)
br, ok := blob.Parse(req.FormValue("wholedigest"))
if !ok {
ret["error"] = "Missing or invalid 'wholedigest' param"
ret["errorType"] = "input"
return
}
files, err := sh.index.ExistingFileSchemas(br)
if err != nil {
ret["error"] = err.Error()
ret["errorType"] = "server"
return
}
strList := []string{}
for _, br := range files {
strList = append(strList, br.String())
}
ret["files"] = strList
return
}
// SignerAttrValueResponse is the JSON response to $search/camli/search/signerattrvalue
type SignerAttrValueResponse struct {
Permanode blob.Ref `json:"permanode"`
Meta MetaMap `json:"meta"`
}
func (sh *Handler) serveSignerAttrValue(rw http.ResponseWriter, req *http.Request) {
defer httputil.RecoverJSON(rw, req)
signer := httputil.MustGetBlobRef(req, "signer")
attr := httputil.MustGet(req, "attr")
value := httputil.MustGet(req, "value")
pn, err := sh.index.PermanodeOfSignerAttrValue(signer, attr, value)
if err != nil {
httputil.ServeJSONError(rw, err)
return
}
dr := sh.NewDescribeRequest()
dr.Describe(pn, 2)
metaMap, err := dr.metaMap()
if err != nil {
httputil.ServeJSONError(rw, err)
return
}
httputil.ReturnJSON(rw, &SignerAttrValueResponse{
Permanode: pn,
Meta: metaMap,
})
}
// EdgesTo returns edges that reference req.RefTo.
// It filters out since-deleted permanode edges.
func (sh *Handler) EdgesTo(req *EdgesRequest) (*EdgesResponse, error) {
toRef := req.ToRef
toRefStr := toRef.String()
var edgeItems []*EdgeItem
edges, err := sh.index.EdgesTo(toRef, nil)
if err != nil {
panic(err)
}
type edgeOrError struct {
edge *EdgeItem // or nil
err error
}
resc := make(chan edgeOrError)
verify := func(edge *camtypes.Edge) {
db, err := sh.NewDescribeRequest().DescribeSync(edge.From)
if err != nil {
resc <- edgeOrError{err: err}
return
}
found := false
if db.Permanode != nil {
for attr, vv := range db.Permanode.Attr {
if index.IsBlobReferenceAttribute(attr) {
for _, v := range vv {
if v == toRefStr {
found = true
}
}
}
}
}
var ei *EdgeItem
if found {
ei = &EdgeItem{
From: edge.From,
FromType: "permanode",
}
}
resc <- edgeOrError{edge: ei}
}
verifying := 0
for _, edge := range edges {
if edge.FromType == "permanode" {
verifying++
go verify(edge)
continue
}
ei := &EdgeItem{
From: edge.From,
FromType: edge.FromType,
}
edgeItems = append(edgeItems, ei)
}
for i := 0; i < verifying; i++ {
res := <-resc
if res.err != nil {
return nil, res.err
}
if res.edge != nil {
edgeItems = append(edgeItems, res.edge)
}
}
return &EdgesResponse{
ToRef: toRef,
EdgesTo: edgeItems,
}, nil
}
// Unlike the index interface's EdgesTo method, the "edgesto" Handler
// here additionally filters out since-deleted permanode edges.
func (sh *Handler) serveEdgesTo(rw http.ResponseWriter, req *http.Request) {
defer httputil.RecoverJSON(rw, req)
var er EdgesRequest
er.fromHTTP(req)
res, err := sh.EdgesTo(&er)
if err != nil {
httputil.ServeJSONError(rw, err)
return
}
httputil.ReturnJSON(rw, res)
}
func (sh *Handler) serveQuery(rw http.ResponseWriter, req *http.Request) {
defer httputil.RecoverJSON(rw, req)
var sq SearchQuery
if err := sq.fromHTTP(req); err != nil {
httputil.ServeJSONError(rw, err)
return
}
sr, err := sh.Query(&sq)
if err != nil {
httputil.ServeJSONError(rw, err)
return
}
httputil.ReturnJSON(rw, sr)
}
// GetSignerPaths returns paths with a target of req.Target.
func (sh *Handler) GetSignerPaths(req *SignerPathsRequest) (*SignerPathsResponse, error) {
if !req.Signer.Valid() {
return nil, errors.New("Error getting signer paths: nil signer.")
}
if !req.Target.Valid() {
return nil, errors.New("Error getting signer paths: nil target.")
}
paths, err := sh.index.PathsOfSignerTarget(req.Signer, req.Target)
if err != nil {
return nil, fmt.Errorf("Error getting paths of %s: %v", req.Target.String(), err)
}
var jpaths []*SignerPathsItem
for _, path := range paths {
jpaths = append(jpaths, &SignerPathsItem{
ClaimRef: path.Claim,
BaseRef: path.Base,
Suffix: path.Suffix,
})
}
dr := sh.NewDescribeRequest()
for _, path := range paths {
dr.Describe(path.Base, 2)
}
metaMap, err := dr.metaMap()
if err != nil {
return nil, err
}
res := &SignerPathsResponse{
Paths: jpaths,
Meta: metaMap,
}
return res, nil
}
func (sh *Handler) serveSignerPaths(rw http.ResponseWriter, req *http.Request) {
defer httputil.RecoverJSON(rw, req)
var sr SignerPathsRequest
sr.fromHTTP(req)
res, err := sh.GetSignerPaths(&sr)
if err != nil {
httputil.ServeJSONError(rw, err)
return
}
httputil.ReturnJSON(rw, res)
}
const camliTypePrefix = "application/json; camliType="