forked from storj/ipfs-go-ds-storj
-
Notifications
You must be signed in to change notification settings - Fork 0
/
storj.go
360 lines (282 loc) · 8.89 KB
/
storj.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
// Copyright (C) 2021 Storj Labs, Inc.
// See LICENSE for copying information.
package storjds
import (
"context"
"errors"
"strings"
"time"
ds "github.com/ipfs/go-datastore"
dsq "github.com/ipfs/go-datastore/query"
bs "github.com/ipfs/go-ipfs-blockstore"
logging "github.com/ipfs/go-log/v2"
"github.com/spacemonkeygo/monkit/v3"
"github.com/zeebo/errs"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"golang.org/x/sync/errgroup"
"storj.io/common/errs2"
"storj.io/common/rpc/rpcpool"
"storj.io/ipfs-go-ds-storj/block"
"storj.io/ipfs-go-ds-storj/db"
"storj.io/ipfs-go-ds-storj/pack"
"storj.io/uplink"
"storj.io/uplink/private/transport"
)
var mon = monkit.Package()
var log = logging.Logger("storjds")
// Error is the error class for Storj datastore.
var Error = errs.Class("storjds")
type Datastore struct {
Config
db *db.DB
project *uplink.Project
blocks *block.Store
packer *pack.Chore
cancel context.CancelFunc
group *errgroup.Group
}
type Config struct {
DBURI string
AccessGrant string
Bucket string
PackInterval time.Duration
MinPackSize int
MaxPackSize int
MaxPackBlocks int
DebugAddr string
UpdateBloomFilter bool
NodeConnectionPoolCapacity int
NodeConnectionPoolKeyCapacity int
NodeConnectionPoolIdleExpiration time.Duration
SatelliteConnectionPoolCapacity int
SatelliteConnectionPoolKeyCapacity int
SatelliteConnectionPoolIdleExpiration time.Duration
}
func OpenDatastore(ctx context.Context, db *db.DB, conf Config) (*Datastore, error) {
log.Desugar().Info("Open datastore")
ds := &Datastore{}
ctx, ds.cancel = context.WithCancel(ctx)
ds.group, ctx = errgroup.WithContext(ctx)
access, err := uplink.ParseAccess(conf.AccessGrant)
if err != nil {
return nil, Error.New("failed to parse access grant: %v", err)
}
uplinkCfg := uplink.Config{
UserAgent: "ipfs-go-ds-storj",
}
log.Desugar().Info("Initialize Storj node connection pool",
zap.Int("Capacity", conf.NodeConnectionPoolCapacity),
zap.Int("Key Capacity", conf.NodeConnectionPoolKeyCapacity),
zap.Duration("Idle Expiration", conf.NodeConnectionPoolIdleExpiration),
)
err = transport.SetConnectionPool(ctx, &uplinkCfg, rpcpool.New(rpcpool.Options{
Name: "default",
Capacity: conf.NodeConnectionPoolCapacity,
KeyCapacity: conf.NodeConnectionPoolKeyCapacity,
IdleExpiration: conf.NodeConnectionPoolIdleExpiration,
}))
if err != nil {
return nil, err
}
log.Desugar().Info("Initialize Storj satellite connection pool",
zap.Int("Capacity", conf.SatelliteConnectionPoolCapacity),
zap.Int("Key Capacity", conf.SatelliteConnectionPoolKeyCapacity),
zap.Duration("Idle Expiration", conf.SatelliteConnectionPoolIdleExpiration),
)
err = transport.SetSatelliteConnectionPool(ctx, &uplinkCfg, rpcpool.New(rpcpool.Options{
Name: "satellite",
Capacity: conf.SatelliteConnectionPoolCapacity,
KeyCapacity: conf.SatelliteConnectionPoolKeyCapacity,
IdleExpiration: conf.SatelliteConnectionPoolIdleExpiration,
}))
if err != nil {
return nil, err
}
project, err := uplinkCfg.OpenProject(ctx, access)
if err != nil {
return nil, Error.New("failed to open Storj project: %s", err)
}
packs := pack.NewStore(project, conf.Bucket)
blocks := block.NewStore(bs.BlockPrefix.String(), db, packs)
packer := pack.NewChore(db, packs).
WithInterval(conf.PackInterval).
WithPackSize(conf.MinPackSize, conf.MaxPackSize, conf.MaxPackBlocks)
ds.Config = conf
ds.db = db
ds.project = project
ds.blocks = blocks
ds.packer = packer
ds.group.Go(func() error {
packer.Run(ctx)
return nil
})
return ds, nil
}
func (storj *Datastore) Close() error {
log.Desugar().Debug("Close datastore")
storj.cancel()
return Error.Wrap(errs.Combine(
storj.group.Wait(),
storj.project.Close(),
storj.packer.Close(),
))
}
func (storj *Datastore) WithPackInterval(interval time.Duration) *Datastore {
storj.PackInterval = interval
storj.packer.WithInterval(interval)
return storj
}
func (storj *Datastore) WithPackSize(minSize, maxSize, maxBlocks int) *Datastore {
storj.MinPackSize = minSize
storj.MaxPackSize = maxSize
storj.MaxPackBlocks = maxBlocks
storj.packer.WithPackSize(minSize, maxSize, maxBlocks)
return storj
}
func (storj *Datastore) TriggerWaitPacker() {
storj.packer.TriggerWait()
}
func (storj *Datastore) DB() *db.DB {
return storj.db
}
func (storj *Datastore) Blockstore() *block.Store {
return storj.blocks
}
func (storj *Datastore) Put(ctx context.Context, key ds.Key, value []byte) (err error) {
defer mon.Task()(&ctx)(&err)
log.Desugar().Debug("Put requested", zap.Stringer("Key", key), zap.Int("Bytes", len(value)))
defer func() {
log.Desugar().Log(logLevel(ctx, err), "Put returned", zap.Stringer("Key", key), zap.Error(err))
}()
if isBlockKey(key) {
return storj.blocks.Put(ctx, trimFirstNamespace(key), value)
}
return storj.db.Put(ctx, key, value)
}
func (storj *Datastore) Sync(ctx context.Context, prefix ds.Key) (err error) {
return nil
}
func (storj *Datastore) Get(ctx context.Context, key ds.Key) (data []byte, err error) {
defer mon.Task()(&ctx)(&err)
log.Desugar().Debug("Get requested", zap.Stringer("Key", key))
defer func() {
log.Desugar().Log(logLevel(ctx, err), "Get returned", zap.Stringer("Key", key), zap.Int("Bytes", len(data)), zap.Error(err))
}()
if isBlockKey(key) {
return storj.blocks.Get(ctx, trimFirstNamespace(key))
}
return storj.db.Get(ctx, key)
}
func (storj *Datastore) Has(ctx context.Context, key ds.Key) (exists bool, err error) {
defer mon.Task()(&ctx)(&err)
log.Desugar().Debug("Has requested", zap.Stringer("Key", key))
defer func() {
log.Desugar().Log(logLevel(ctx, err), "Has returned", zap.Stringer("Key", key), zap.Bool("Exists", exists), zap.Error(err))
}()
if isBlockKey(key) {
return storj.blocks.Has(ctx, trimFirstNamespace(key))
}
return storj.db.Has(ctx, key)
}
func (storj *Datastore) GetSize(ctx context.Context, key ds.Key) (size int, err error) {
defer mon.Task()(&ctx)(&err)
// This may be too noisy if BloomFilterSize of IPFS config is set to 0.
// log.Desugar().Debug("GetSize requested", zap.Stringer("Key", key))
// defer func() {
// log.Desugar().Log(logLevel(ctx, err), "GetSize returned", zap.Stringer("Key", key), zap.Int("Size", size), zap.Error(err))
// }()
if isBlockKey(key) {
return storj.blocks.GetSize(ctx, trimFirstNamespace(key))
}
return storj.db.GetSize(ctx, key)
}
func (storj *Datastore) Delete(ctx context.Context, key ds.Key) (err error) {
defer mon.Task()(&ctx)(&err)
log.Desugar().Debug("Delete requested", zap.Stringer("Key", key))
defer func() {
log.Desugar().Log(logLevel(ctx, err), "Delete returned", zap.Stringer("Key", key), zap.Error(err))
}()
if isBlockKey(key) {
return storj.blocks.Delete(ctx, trimFirstNamespace(key))
}
return storj.db.Delete(ctx, key)
}
func (storj *Datastore) Query(ctx context.Context, q dsq.Query) (result dsq.Results, err error) {
defer mon.Task()(&ctx)(&err)
log.Desugar().Debug("Query requested", zap.Stringer("Query", q))
defer func() {
log.Desugar().Log(logLevel(ctx, err), "Query returned", zap.Stringer("Query", q), zap.Error(err))
}()
if strings.HasPrefix(q.Prefix, bs.BlockPrefix.String()) {
return storj.blocks.Query(ctx, q)
}
return storj.db.QueryDatastore(ctx, q)
}
func (storj *Datastore) Batch(ctx context.Context) (batch ds.Batch, err error) {
defer mon.Task()(&ctx)(&err)
log.Desugar().Debug("Batch")
return &storjBatch{
storj: storj,
ops: make(map[ds.Key]batchOp),
}, nil
}
func isBlockKey(key ds.Key) bool {
return bs.BlockPrefix == key || bs.BlockPrefix.IsAncestorOf(key)
}
func trimFirstNamespace(key ds.Key) ds.Key {
ns := key.Namespaces()
if len(ns) < 1 {
return key
}
return ds.KeyWithNamespaces(ns[1:])
}
func logLevel(ctx context.Context, err error) zapcore.Level {
if ctx.Err() != context.Canceled && errs2.IgnoreCanceled(err) != nil && !errors.Is(err, ds.ErrNotFound) {
return zapcore.ErrorLevel
}
return zapcore.DebugLevel
}
type storjBatch struct {
storj *Datastore
ops map[ds.Key]batchOp
}
type batchOp struct {
value []byte
delete bool
}
func (b *storjBatch) Put(ctx context.Context, key ds.Key, value []byte) (err error) {
defer mon.Task()(&ctx)(&err)
log.Desugar().Debug("BatchPut", zap.Stringer("Key", key), zap.Int("Bytes", len(value)))
b.ops[key] = batchOp{
value: value,
delete: false,
}
return nil
}
func (b *storjBatch) Delete(ctx context.Context, key ds.Key) (err error) {
defer mon.Task()(&ctx)(&err)
log.Desugar().Debug("BatchDelete", zap.Stringer("Key", key))
b.ops[key] = batchOp{
value: nil,
delete: true,
}
return nil
}
func (b *storjBatch) Commit(ctx context.Context) (err error) {
defer mon.Task()(&ctx)(&err)
log.Desugar().Debug("BatchCommit")
for key, op := range b.ops {
var err error
if op.delete {
err = b.storj.Delete(ctx, key)
} else {
err = b.storj.Put(ctx, key, op.value)
}
if err != nil {
return Error.Wrap(err)
}
}
return nil
}
var _ ds.Batching = (*Datastore)(nil)