Skip to content
This repository was archived by the owner on Feb 7, 2024. It is now read-only.

Commit f4de346

Browse files
committed
Add experimental findprovs
1 parent 458b0e6 commit f4de346

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

shell.go

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package shell
33

44
import (
55
"bytes"
6+
"context"
67
"encoding/json"
78
"errors"
89
"fmt"
@@ -13,6 +14,8 @@ import (
1314
"strings"
1415
"time"
1516

17+
pstore "github.com/libp2p/go-libp2p-peerstore"
18+
notif "github.com/libp2p/go-libp2p-routing/notifications"
1619
ma "github.com/multiformats/go-multiaddr"
1720
manet "github.com/multiformats/go-multiaddr-net"
1821
files "github.com/whyrusleeping/go-multipart-files"
@@ -371,6 +374,53 @@ func (s *Shell) FindPeer(peer string) (*PeerInfo, error) {
371374
return &str.Responses[0], nil
372375
}
373376

377+
func (s *Shell) FindProvs(ctx context.Context, cid string) (<-chan pstore.PeerInfo, error) {
378+
ctx, cancel := context.WithCancel(ctx)
379+
380+
resp, err := s.newRequest("dht/findprovs", cid).Send(s.httpcli)
381+
if err != nil {
382+
return nil, err
383+
}
384+
385+
if resp.Error != nil {
386+
return nil, resp.Error
387+
}
388+
389+
// 4 is arbitrary here just to make the channel buffered
390+
outchan := make(chan pstore.PeerInfo, 4)
391+
392+
go func() {
393+
defer close(outchan)
394+
defer cancel()
395+
396+
var n notif.QueryEvent
397+
decoder := json.NewDecoder(resp.Output)
398+
for {
399+
err := decoder.Decode(&n)
400+
if err != nil {
401+
return
402+
}
403+
404+
if n.Type == notif.Provider {
405+
for _, p := range n.Responses {
406+
select {
407+
case outchan <- *p:
408+
case <-ctx.Done():
409+
return
410+
}
411+
}
412+
}
413+
}
414+
}()
415+
416+
go func() {
417+
<-ctx.Done()
418+
resp.Close()
419+
}()
420+
421+
return outchan, nil
422+
}
423+
374424
func (s *Shell) Refs(hash string, recursive bool) (<-chan string, error) {
375425
req := s.newRequest("refs", hash)
376426
if recursive {

shell_test.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package shell
22

33
import (
44
"bytes"
5+
"context"
56
"crypto/md5"
67
"fmt"
78
"io"
@@ -212,3 +213,18 @@ func TestObjectStat(t *testing.T) {
212213
is.Equal(stat.LinksSize, 3)
213214
is.Equal(stat.CumulativeSize, 1688)
214215
}
216+
217+
func TestFindProvs(t *testing.T) {
218+
is := is.New(t)
219+
s := NewShell(shellUrl)
220+
ctx, cancel := context.WithCancel(context.Background())
221+
defer cancel()
222+
223+
c, err := s.FindProvs(ctx, "Qme1g4e3m2SmdiSGGU3vSWmUStwUjc5oECnEriaK9Xa1HU")
224+
is.Nil(err)
225+
226+
p := <-c
227+
t.Logf("prov: %s", p)
228+
is.NotNil(p)
229+
is.NotNil(p.ID)
230+
}

0 commit comments

Comments
 (0)