This repository has been archived by the owner on Mar 28, 2023. It is now read-only.
generated from ipfs/ipfs-repository-template
-
Notifications
You must be signed in to change notification settings - Fork 9
/
store.go
89 lines (73 loc) · 2.03 KB
/
store.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
package client
import (
"context"
"fmt"
"github.com/ipfs/boxo/ipns"
record "github.com/libp2p/go-libp2p-record"
"github.com/libp2p/go-libp2p/core/routing"
)
var _ routing.ValueStore = &Client{}
// PutValue adds value corresponding to given Key.
func (c *Client) PutValue(ctx context.Context, key string, val []byte, opts ...routing.Option) error {
ns, path, err := record.SplitKey(key)
if err != nil {
return fmt.Errorf("invalid key: %w", err)
}
if ns != "ipns" {
return ipns.ErrKeyFormat
}
return c.PutIPNS(ctx, []byte(path), val)
}
// GetValue searches for the value corresponding to given Key.
func (c *Client) GetValue(ctx context.Context, key string, opts ...routing.Option) ([]byte, error) {
ns, path, err := record.SplitKey(key)
if err != nil {
return nil, fmt.Errorf("invalid key: %w", err)
}
if ns != "ipns" {
return nil, ipns.ErrKeyFormat
}
return c.GetIPNS(ctx, []byte(path))
}
// SearchValue searches for better and better values from this value
// store corresponding to the given Key. By default implementations must
// stop the search after a good value is found. A 'good' value is a value
// that would be returned from GetValue.
//
// Useful when you want a result *now* but still want to hear about
// better/newer results.
//
// Implementations of this methods won't return ErrNotFound. When a value
// couldn't be found, the channel will get closed without passing any results
func (c *Client) SearchValue(ctx context.Context, key string, opts ...routing.Option) (<-chan []byte, error) {
ns, path, err := record.SplitKey(key)
if err != nil {
return nil, fmt.Errorf("invalid key: %w", err)
}
if ns != "ipns" {
return nil, ipns.ErrKeyFormat
}
resChan, err := c.GetIPNSAsync(ctx, []byte(path))
if err != nil {
return nil, err
}
outCh := make(chan []byte, 1)
go func() {
defer close(outCh)
for {
select {
case <-ctx.Done():
return
case r, ok := <-resChan:
if !ok {
return
}
if r.Err != nil {
continue
}
outCh <- r.Record
}
}
}()
return outCh, nil
}