-
Notifications
You must be signed in to change notification settings - Fork 0
/
datastore.go
311 lines (273 loc) · 8.48 KB
/
datastore.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
package grpcds
import (
"context"
"fmt"
"reflect"
"time"
pb "github.com/guseggert/go-ds-grpc/proto"
ds "github.com/ipfs/go-datastore"
"github.com/ipfs/go-datastore/query"
"github.com/ipfs/go-datastore/scoped"
"google.golang.org/protobuf/types/known/durationpb"
)
// Datastore forwards all requests to a gRPC server.
type Datastore struct {
QueryFilterCodecs map[reflect.Type]QueryFilterCodec
QueryOrderCodecs map[reflect.Type]QueryOrderCodec
Client pb.DatastoreClient
}
type Options struct {
QueryFilterCodecs map[reflect.Type]QueryFilterCodec
QueryOrderCodecs map[reflect.Type]QueryOrderCodec
}
// WithQueryFilterEncoders sets the given query filter encoders. These map from a concrete type that implements
func WithQueryFilterCodec(codec QueryFilterCodec) func(o *Options) {
return func(o *Options) {
typ := codec.Type()
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
o.QueryFilterCodecs[typ] = codec
}
}
func WithQueryOrderCodec(codec QueryOrderCodec) func(o *Options) {
return func(o *Options) {
typ := codec.Type()
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
o.QueryOrderCodecs[typ] = codec
}
}
// New constructs a new shim client that implements the Datastore interface.
// This negotiates the datastore features that the remote datastore supports,
// and constructs an underlying representation that only implements those features,
// so that type assertions on feature interfaces work as expected.
func New(ctx context.Context, client pb.DatastoreClient, optFns ...func(o *Options)) (ds.Datastore, error) {
opts := &Options{
QueryFilterCodecs: map[reflect.Type]QueryFilterCodec{},
QueryOrderCodecs: map[reflect.Type]QueryOrderCodec{},
}
// always register the built-ins
WithQueryFilterCodec(&FilterKeyCompareCodec{})(opts)
WithQueryFilterCodec(&FilterValueCompareCodec{})(opts)
WithQueryFilterCodec(&FilterKeyPrefixCodec{})(opts)
WithQueryOrderCodec(&OrderByKeyCodec{})(opts)
WithQueryOrderCodec(&OrderByKeyDescCodec{})(opts)
WithQueryOrderCodec(&OrderByValueCodec{})(opts)
WithQueryOrderCodec(&OrderByValueDescCodec{})(opts)
for _, optFn := range optFns {
optFn(opts)
}
grpcDS := &Datastore{
Client: client,
QueryFilterCodecs: opts.QueryFilterCodecs,
QueryOrderCodecs: opts.QueryOrderCodecs,
}
resp, err := client.Features(ctx, &pb.FeaturesRequest{})
if err != nil {
return nil, fmt.Errorf("negotiating datastore features: %w", err)
}
// scope down the concrete type to implement only the methods that the
// remote datastore supports
var features []ds.Feature
for _, f := range resp.Features {
var featureName string
switch f {
case pb.FeaturesResponse_BATCHING:
featureName = ds.FeatureNameBatching
case pb.FeaturesResponse_CHECKED:
featureName = ds.FeatureNameChecked
case pb.FeaturesResponse_GC:
featureName = ds.FeatureNameGC
case pb.FeaturesResponse_SCRUBBED:
featureName = ds.FeatureNameScrubbed
case pb.FeaturesResponse_PERSISTENT:
featureName = ds.FeatureNamePersistent
case pb.FeaturesResponse_TTL:
featureName = ds.FeatureNameTTL
case pb.FeaturesResponse_TRANSACTION:
featureName = ds.FeatureNameTransaction
default:
return nil, fmt.Errorf("unknown feature %q", f.String())
}
dsFeat, ok := ds.FeatureByName(featureName)
if !ok {
return nil, fmt.Errorf("unknown datastore feature %q", f)
}
features = append(features, dsFeat)
}
scopedDS := scoped.WithFeatures(grpcDS, features)
return scopedDS, nil
}
func (d *Datastore) Get(ctx context.Context, key ds.Key) (value []byte, err error) {
res, err := d.Client.Get(ctx, &pb.GetRequest{Key: key.String()})
if err != nil {
return nil, GRPCToDSError(err)
}
return res.Value, nil
}
func (d *Datastore) Has(ctx context.Context, key ds.Key) (exists bool, err error) {
res, err := d.Client.Has(ctx, &pb.HasRequest{Key: key.String()})
if err != nil {
return false, GRPCToDSError(err)
}
return res.Has, nil
}
func (d *Datastore) GetSize(ctx context.Context, key ds.Key) (size int, err error) {
res, err := d.Client.GetSize(ctx, &pb.GetSizeRequest{Key: key.String()})
if err != nil {
return 0, GRPCToDSError(err)
}
return int(res.Size), nil
}
func (d *Datastore) Put(ctx context.Context, key ds.Key, value []byte) error {
_, err := d.Client.Put(ctx, &pb.PutRequest{Key: key.String(), Value: value})
return GRPCToDSError(err)
}
func (d *Datastore) Delete(ctx context.Context, key ds.Key) error {
_, err := d.Client.Delete(ctx, &pb.DeleteRequest{Key: key.String()})
return GRPCToDSError(err)
}
func (d *Datastore) Sync(ctx context.Context, prefix ds.Key) error {
_, err := d.Client.Sync(ctx, &pb.SyncRequest{Prefix: prefix.String()})
return GRPCToDSError(err)
}
func (d *Datastore) Close() error {
return nil
}
func (d *Datastore) Query(ctx context.Context, q query.Query) (query.Results, error) {
filters := map[string][]byte{}
for _, f := range q.Filters {
typ := reflect.TypeOf(f)
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
codec, ok := d.QueryFilterCodecs[typ]
if !ok {
return nil, fmt.Errorf("no codec registered for query filter '%s'", typ)
}
b, err := codec.Encode(f)
if err != nil {
return nil, fmt.Errorf("encoding query filter: %w", err)
}
filters[codec.Name()] = b
}
orders := map[string][]byte{}
for _, o := range q.Orders {
typ := reflect.TypeOf(o)
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
codec, ok := d.QueryOrderCodecs[typ]
if !ok {
return nil, fmt.Errorf("no codec registered for query order '%s'", typ)
}
b, err := codec.Encode(o)
if err != nil {
return nil, fmt.Errorf("encoding query filter: %w", err)
}
orders[codec.Name()] = b
}
res, err := d.Client.Query(ctx, &pb.QueryRequest{
Prefix: q.Prefix,
Filters: filters,
Orders: orders,
Limit: uint64(q.Limit),
Offset: uint64(q.Offset),
KeysOnly: q.KeysOnly,
ReturnExpirations: q.ReturnExpirations,
ReturnSizes: q.ReturnsSizes,
})
if err != nil {
return nil, GRPCToDSError(err)
}
iter := &queryIterator{stream: res}
return query.ResultsFromIterator(q, query.Iterator{
Next: iter.Next,
Close: iter.Close,
}), nil
}
func (d *Datastore) Batch(ctx context.Context) (ds.Batch, error) {
return &batch{
ds: d,
ops: map[ds.Key]batchOp{},
}, nil
}
type batchOp struct {
delete bool
value []byte
}
type batch struct {
ds *Datastore
ops map[ds.Key]batchOp
}
func (b *batch) Put(ctx context.Context, key ds.Key, value []byte) error {
b.ops[key] = batchOp{value: value}
return nil
}
func (b *batch) Delete(ctx context.Context, key ds.Key) error {
b.ops[key] = batchOp{delete: true}
return nil
}
func (b *batch) Commit(ctx context.Context) error {
batchReq := pb.BatchRequest{}
var err error
for k, op := range b.ops {
if op.delete {
batchReq.Ops = append(batchReq.Ops, &pb.BatchRequest_Op{
OpCode: pb.BatchRequest_DELETE,
Key: k.String(),
})
} else {
batchReq.Ops = append(batchReq.Ops, &pb.BatchRequest_Op{
OpCode: pb.BatchRequest_PUT,
Key: k.String(),
Value: op.value,
})
}
}
_, err = b.ds.Client.Batch(ctx, &batchReq)
return GRPCToDSError(err)
}
func (d *Datastore) Check(ctx context.Context) error {
_, err := d.Client.Check(ctx, &pb.CheckRequest{})
return GRPCToDSError(err)
}
func (d *Datastore) Scrub(ctx context.Context) error {
_, err := d.Client.Scrub(ctx, &pb.ScrubRequest{})
return GRPCToDSError(err)
}
func (d *Datastore) CollectGarbage(ctx context.Context) error {
_, err := d.Client.CollectGarbage(ctx, &pb.CollectGarbageRequest{})
return GRPCToDSError(err)
}
func (d *Datastore) DiskUsage(ctx context.Context) (uint64, error) {
res, err := d.Client.DiskUsage(ctx, &pb.DiskUsageRequest{})
return res.Size, GRPCToDSError(err)
}
func (d *Datastore) PutWithTTL(ctx context.Context, key ds.Key, value []byte, ttl time.Duration) error {
_, err := d.Client.PutWithTTL(ctx, &pb.PutWithTTLRequest{
Key: key.String(),
Value: value,
TTL: durationpb.New(ttl),
})
return GRPCToDSError(err)
}
func (d *Datastore) SetTTL(ctx context.Context, key ds.Key, ttl time.Duration) error {
_, err := d.Client.SetTTL(ctx, &pb.SetTTLRequest{
Key: key.String(),
TTL: durationpb.New(ttl),
})
return GRPCToDSError(err)
}
func (d *Datastore) GetExpiration(ctx context.Context, key ds.Key) (time.Time, error) {
res, err := d.Client.GetExpiration(ctx, &pb.GetExpirationRequest{
Key: key.String(),
})
return res.Expiration.AsTime(), GRPCToDSError(err)
}
func (d *Datastore) NewTransaction(ctx context.Context, readOnly bool) (ds.Txn, error) {
// TODO: implement
return nil, nil
}