-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
744 lines (692 loc) · 20.7 KB
/
db.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
// Package db provides a DB which manage collections
package db
import (
"bytes"
"context"
"encoding/binary"
"encoding/gob"
"encoding/json"
"errors"
"fmt"
"io"
"regexp"
"sync"
"time"
"github.com/alecthomas/jsonschema"
threadcbor "github.com/dcnetio/gothreads-lib/cbor"
"github.com/dcnetio/gothreads-lib/core/app"
core "github.com/dcnetio/gothreads-lib/core/db"
lstore "github.com/dcnetio/gothreads-lib/core/logstore"
"github.com/dcnetio/gothreads-lib/core/net"
"github.com/dcnetio/gothreads-lib/core/thread"
kt "github.com/dcnetio/gothreads-lib/db/keytransform"
"github.com/dcnetio/gothreads-lib/util"
"github.com/dop251/goja"
ds "github.com/ipfs/go-datastore"
"github.com/ipfs/go-datastore/query"
format "github.com/ipfs/go-ipld-format"
logging "github.com/ipfs/go-log/v2"
ma "github.com/multiformats/go-multiaddr"
)
const (
idFieldName = "_id"
modFieldName = "_mod"
getBlockRetries = 3
getBlockInitialTimeout = time.Millisecond * 500
pullThreadBackgroundTimeout = time.Hour
createNetRecordTimeout = time.Second * 15
)
var (
log = logging.Logger("db")
// ErrThreadReadKeyRequired indicates the provided thread key does not contain a read key.
ErrThreadReadKeyRequired = errors.New("thread read key is required")
// ErrInvalidName indicates the provided name isn't valid for a Collection.
ErrInvalidName = errors.New("name may only contain alphanumeric characters or non-consecutive hyphens, " +
"and cannot begin or end with a hyphen")
// ErrInvalidCollectionSchema indicates the provided schema isn't valid for a Collection.
ErrInvalidCollectionSchema = errors.New("the collection schema _id property must be a string")
// ErrCannotIndexIDField indicates a custom index was specified on the ID field.
ErrCannotIndexIDField = errors.New("cannot create custom index on " + idFieldName)
nameRx *regexp.Regexp
dsPrefix = ds.NewKey("/db")
dsName = dsPrefix.ChildString("name")
dsSchemas = dsPrefix.ChildString("schema")
dsIndexes = dsPrefix.ChildString("index")
dsValidators = dsPrefix.ChildString("validator")
dsFilters = dsPrefix.ChildString("filter")
)
func init() {
nameRx = regexp.MustCompile(`^[A-Za-z0-9]+(?:[-][A-Za-z0-9]+)*$`)
// register empty map in order to gob-encode old-format events with non-encodable time.Time,
// which cbor decodes as map[string]interface{}
gob.Register(map[string]interface{}{})
}
// DB is the aggregate-root of events and state. External/remote events
// are dispatched to the DB, and are internally processed to impact collection
// states. Likewise, local changes in collections registered produce events dispatched
// externally.
type DB struct {
io.Closer
name string
connector *app.Connector
datastore kt.TxnDatastoreExtended
dispatcher *dispatcher
eventcodec core.EventCodec
lock sync.RWMutex
txnlock sync.RWMutex
collections map[string]*Collection
closed bool
localEventsBus *app.LocalEventsBus
stateChangedNotifee *stateChangedNotifee
}
// NewDB creates a new DB, which will *own* ds and dispatcher for internal use.
// Saying it differently, ds and dispatcher shouldn't be used externally.
func NewDB(
ctx context.Context,
store kt.TxnDatastoreExtended,
network app.Net,
id thread.ID,
opts ...NewOption,
) (*DB, error) {
log.Debugf("creating db %s", id)
args := &NewOptions{}
for _, opt := range opts {
opt(args)
}
if err := util.SetLogLevels(map[string]logging.LogLevel{
"db": util.LevelFromDebugFlag(args.Debug),
}); err != nil {
return nil, err
}
if args.Key.Defined() && !args.Key.CanRead() {
return nil, ErrThreadReadKeyRequired
}
if _, err := network.CreateThread(
ctx,
id,
net.WithThreadKey(args.Key),
net.WithLogKey(args.LogKey),
net.WithNewThreadToken(args.Token),
); err != nil && !errors.Is(err, lstore.ErrThreadExists) && !errors.Is(err, lstore.ErrLogExists) {
return nil, err
}
return newDB(store, network, id, args)
}
// NewDBFromAddr creates a new DB from a thread hosted by another peer at address,
// which will *own* ds and dispatcher for internal use.
// Saying it differently, ds and dispatcher shouldn't be used externally.
func NewDBFromAddr(
ctx context.Context,
store kt.TxnDatastoreExtended,
network app.Net,
addr ma.Multiaddr,
key thread.Key,
opts ...NewOption,
) (*DB, error) {
log.Debugf("creating db from address %s", addr)
args := &NewOptions{}
for _, opt := range opts {
opt(args)
}
if err := util.SetLogLevels(map[string]logging.LogLevel{
"db": util.LevelFromDebugFlag(args.Debug),
}); err != nil {
return nil, err
}
if key.Defined() && !key.CanRead() {
return nil, ErrThreadReadKeyRequired
}
info, err := network.AddThread(
ctx,
addr,
net.WithThreadKey(key),
net.WithLogKey(args.LogKey),
net.WithNewThreadToken(args.Token),
)
if err != nil {
return nil, err
}
d, err := newDB(store, network, info.ID, args)
if err != nil {
return nil, err
}
if args.Block {
if err = network.PullThread(ctx, info.ID, net.WithThreadToken(args.Token)); err != nil {
return nil, err
}
} else {
go func() {
ctx, cancel := context.WithTimeout(context.Background(), pullThreadBackgroundTimeout)
defer cancel()
if err := network.PullThread(ctx, info.ID, net.WithThreadToken(args.Token)); err != nil {
log.Errorf("error pulling thread %s", info.ID)
}
}()
}
return d, nil
}
// newDB is used directly by a db manager to create new dbs with the same config.
func newDB(s kt.TxnDatastoreExtended, n app.Net, id thread.ID, opts *NewOptions) (*DB, error) {
if opts.EventCodec == nil {
opts.EventCodec = newDefaultEventCodec()
}
d := &DB{
datastore: s,
dispatcher: newDispatcher(s),
eventcodec: opts.EventCodec,
collections: make(map[string]*Collection),
localEventsBus: app.NewLocalEventsBus(),
stateChangedNotifee: &stateChangedNotifee{},
}
if err := d.loadName(); err != nil {
return nil, err
}
prevName := d.name
if opts.Name != "" {
d.name = opts.Name
} else if prevName == "" {
d.name = "unnamed"
}
if err := d.saveName(prevName); err != nil {
return nil, err
}
if err := d.reCreateCollections(); err != nil {
return nil, err
}
d.dispatcher.Register(d)
connector, err := n.ConnectApp(d, id)
if err != nil {
return nil, err
}
d.connector = connector
for _, cc := range opts.Collections {
if _, err := d.NewCollection(cc); err != nil {
return nil, err
}
}
return d, nil
}
// saveName saves the db name.
func (d *DB) saveName(prevName string) error {
if d.name == prevName {
return nil
}
if !nameRx.MatchString(d.name) {
return ErrInvalidName
}
return d.datastore.Put(context.Background(), dsName, []byte(d.name))
}
// loadName loads db name if present.
func (d *DB) loadName() error {
bytes, err := d.datastore.Get(context.Background(), dsName)
if err != nil && !errors.Is(err, ds.ErrNotFound) {
return err
}
if bytes != nil {
d.name = string(bytes)
}
return nil
}
// reCreateCollections loads and registers schemas from the datastore.
func (d *DB) reCreateCollections() error {
d.lock.Lock()
defer d.lock.Unlock()
log.Debugf("recreating collections in %s", d.name)
results, err := d.datastore.Query(context.Background(), query.Query{
Prefix: dsSchemas.String(),
})
if err != nil {
return err
}
defer results.Close()
for res := range results.Next() {
name := ds.RawKey(res.Key).Name()
schema := &jsonschema.Schema{}
if err := json.Unmarshal(res.Value, schema); err != nil {
return err
}
wv, err := d.datastore.Get(context.Background(), dsValidators.ChildString(name))
if err != nil && !errors.Is(err, ds.ErrNotFound) {
return err
}
rf, err := d.datastore.Get(context.Background(), dsFilters.ChildString(name))
if err != nil && !errors.Is(err, ds.ErrNotFound) {
return err
}
c, err := newCollection(d, CollectionConfig{
Name: name,
Schema: schema,
WriteValidator: string(wv),
ReadFilter: string(rf),
})
if err != nil {
return err
}
var indexes map[string]Index
index, err := d.datastore.Get(context.Background(), dsIndexes.ChildString(name))
if err == nil && index != nil {
if err := json.Unmarshal(index, &indexes); err != nil {
return err
}
}
for _, index := range indexes {
if index.Path != "" { // Catch bad indexes from an old bug
c.indexes[index.Path] = index
}
}
d.collections[c.name] = c
}
return nil
}
// Info wraps info about a db.
type Info struct {
Name string
Addrs []ma.Multiaddr
Key thread.Key
}
// GetDBInfo returns the addresses and key that can be used to join the DB thread.
func (d *DB) GetDBInfo(opts ...Option) (info Info, err error) {
log.Debugf("getting db info in %s", d.name)
options := &Options{}
for _, opt := range opts {
opt(options)
}
thrd, err := d.connector.Net.GetThread(
context.Background(),
d.connector.ThreadID(),
net.WithThreadToken(options.Token),
)
if err != nil {
return info, err
}
return Info{
Name: d.name,
Addrs: thrd.Addrs,
Key: thrd.Key,
}, nil
}
// CollectionConfig describes a new Collection.
type CollectionConfig struct {
// Name is the name of the collection.
// Must only contain alphanumeric characters or non-consecutive hyphens, and cannot begin or end with a hyphen.
Name string
// Schema is JSON Schema used for instance validation.
Schema *jsonschema.Schema
// Indexes is a list of index configurations, which define how instances are indexed.
Indexes []Index
// An optional JavaScript (ECMAScript 5.1) function that is used to validate instances on write.
// The function receives three arguments:
// - writer: The multibase-encoded public key identity of the writer.
// - event: An object describing the update event (see core.Event).
// - instance: The current instance as a JavaScript object before the update event is applied.
// A "falsy" return value indicates a failed validation (https://developer.mozilla.org/en-US/docs/Glossary/Falsy).
// Note: Only the function body should be defined here.
WriteValidator string
// An optional JavaScript (ECMAScript 5.1) function that is used to filter instances on read.
// The function receives two arguments:
// - reader: The multibase-encoded public key identity of the reader.
// - instance: The current instance as a JavaScript object.
// The function must return a JavaScript object.
// Most implementation will modify and return the current instance.
// Note: Only the function body should be defined here.
ReadFilter string
}
// NewCollection creates a new db collection with config.
func (d *DB) NewCollection(config CollectionConfig, opts ...Option) (*Collection, error) {
d.lock.Lock()
defer d.lock.Unlock()
log.Debugf("creating collection %s in %s", config.Name, d.name)
args := &Options{}
for _, opt := range opts {
opt(args)
}
if err := d.connector.Validate(args.Token, false); err != nil {
return nil, err
}
if _, ok := d.collections[config.Name]; ok {
return nil, ErrCollectionAlreadyRegistered
}
c, err := newCollection(d, config)
if err != nil {
return nil, err
}
if err := d.addIndexes(c, config.Schema, config.Indexes, opts...); err != nil {
return nil, err
}
if err := d.saveCollection(c); err != nil {
return nil, err
}
return c, nil
}
// UpdateCollection updates an existing db collection with a new config.
// Indexes to new paths will be created.
// Indexes to removed paths will be dropped.
func (d *DB) UpdateCollection(config CollectionConfig, opts ...Option) (*Collection, error) {
d.lock.Lock()
defer d.lock.Unlock()
log.Debugf("updating collection %s in %s", config.Name, d.name)
args := &Options{}
for _, opt := range opts {
opt(args)
}
if err := d.connector.Validate(args.Token, false); err != nil {
return nil, err
}
xc, ok := d.collections[config.Name]
if !ok {
return nil, ErrCollectionNotFound
}
c, err := newCollection(d, config)
if err != nil {
return nil, err
}
if err := d.addIndexes(c, config.Schema, config.Indexes, opts...); err != nil {
return nil, err
}
// Drop indexes that are no longer requested
for _, index := range xc.indexes {
if _, ok := c.indexes[index.Path]; !ok {
if err := c.dropIndex(index.Path); err != nil {
return nil, err
}
}
}
if err := d.saveCollection(c); err != nil {
return nil, err
}
return c, nil
}
func (d *DB) addIndexes(c *Collection, schema *jsonschema.Schema, indexes []Index, opts ...Option) error {
log.Debugf("adding indexes to collection %s in %s", c.name, d.name)
for _, index := range indexes {
if index.Path == idFieldName {
return ErrCannotIndexIDField
}
if err := c.addIndex(schema, index, opts...); err != nil {
return err
}
}
return c.addIndex(schema, Index{Path: idFieldName, Unique: true}, opts...)
}
func (d *DB) saveCollection(c *Collection) error {
log.Debugf("saving collection %s in %s", c.name, d.name)
if err := d.datastore.Put(context.Background(), dsSchemas.ChildString(c.name), c.GetSchema()); err != nil {
return err
}
if c.rawWriteValidator != nil {
if err := d.datastore.Put(context.Background(), dsValidators.ChildString(c.name), c.rawWriteValidator); err != nil {
return err
}
}
if c.rawReadFilter != nil {
if err := d.datastore.Put(context.Background(), dsFilters.ChildString(c.name), c.rawReadFilter); err != nil {
return err
}
}
d.collections[c.name] = c
return nil
}
// GetCollection returns a collection by name.
func (d *DB) GetCollection(name string, opts ...Option) *Collection {
d.lock.Lock()
defer d.lock.Unlock()
log.Debugf("getting collection %s in %s", name, d.name)
args := &Options{}
for _, opt := range opts {
opt(args)
}
if err := d.connector.Validate(args.Token, true); err != nil {
return nil
}
return d.collections[name]
}
// ListCollections returns all collections.
func (d *DB) ListCollections(opts ...Option) []*Collection {
d.lock.Lock()
defer d.lock.Unlock()
log.Debugf("listing collections in %s", d.name)
args := &Options{}
for _, opt := range opts {
opt(args)
}
if err := d.connector.Validate(args.Token, true); err != nil {
return nil
}
list := make([]*Collection, len(d.collections))
var i int
for _, c := range d.collections {
list[i] = c
i++
}
return list
}
// DeleteCollection deletes collection by name and drops all indexes.
func (d *DB) DeleteCollection(name string, opts ...Option) error {
ctx := context.Background()
d.lock.Lock()
defer d.lock.Unlock()
log.Debugf("deleting collection %s in %s", name, d.name)
args := &Options{}
for _, opt := range opts {
opt(args)
}
if err := d.connector.Validate(args.Token, false); err != nil {
return err
}
c, ok := d.collections[name]
if !ok {
return ErrCollectionNotFound
}
txn, err := d.datastore.NewTransaction(ctx, false)
if err != nil {
return err
}
if err := txn.Delete(ctx, dsIndexes.ChildString(c.name)); err != nil {
return err
}
if err := txn.Delete(ctx, dsSchemas.ChildString(c.name)); err != nil {
return err
}
if err := txn.Delete(ctx, dsValidators.ChildString(c.name)); err != nil {
return err
}
if err := txn.Delete(ctx, dsFilters.ChildString(c.name)); err != nil {
return err
}
if err := txn.Commit(ctx); err != nil {
return err
}
delete(d.collections, c.name)
return nil
}
func (d *DB) Close() error {
log.Debugf("closing %s", d.name)
d.lock.Lock()
defer d.lock.Unlock()
d.txnlock.Lock()
defer d.txnlock.Unlock()
if d.closed {
return nil
}
d.closed = true
d.localEventsBus.Discard()
d.stateChangedNotifee.close()
return nil
}
func (d *DB) Reduce(events []core.Event) error {
log.Debugf("reducing events in %s", d.name)
codecActions, err := d.eventcodec.Reduce(events, d.datastore, baseKey, defaultIndexFunc(d))
if err != nil {
return err
}
actions := make([]Action, len(codecActions))
for i, ca := range codecActions {
var actionType ActionType
switch codecActions[i].Type {
case core.Create:
actionType = ActionCreate
case core.Save:
actionType = ActionSave
case core.Delete:
actionType = ActionDelete
default:
panic("eventcodec action not recognized")
}
actions[i] = Action{Collection: ca.Collection, Type: actionType, ID: ca.InstanceID}
}
d.notifyStateChanged(actions)
return nil
}
func defaultIndexFunc(d *DB) func(collection string, key ds.Key, oldData, newData []byte, txn ds.Txn) error {
return func(collection string, key ds.Key, oldData, newData []byte, txn ds.Txn) error {
c := d.GetCollection(collection)
if c == nil {
return fmt.Errorf("collection (%s) not found", collection)
}
if err := c.indexDelete(txn, key, oldData); err != nil {
return err
}
if newData == nil {
return nil
}
return c.indexAdd(txn, key, newData)
}
}
func (d *DB) ValidateNetRecordBody(_ context.Context, body format.Node, identity thread.PubKey) error {
events, err := d.eventcodec.EventsFromBytes(body.RawData())
if err != nil {
return err
}
if len(events) == 0 {
return nil
}
for _, e := range events {
c, ok := d.collections[e.Collection()]
if !ok {
return ErrCollectionNotFound
}
if err := c.validWrite(identity, e); err != nil {
return err
}
}
return nil
}
func parseJSON(vm *goja.Runtime, val []byte) (goja.Value, error) {
return vm.RunString(fmt.Sprintf("JSON.parse(`%s`);", string(val)))
}
func (d *DB) HandleNetRecord(ctx context.Context, rec net.ThreadRecord, key thread.Key) error {
event, err := threadcbor.EventFromRecord(ctx, d.connector.Net, rec.Value())
if err != nil {
block, err := d.getBlockWithRetry(ctx, rec.Value())
if err != nil {
return fmt.Errorf("error when getting block from record: %v", err)
}
event, err = threadcbor.EventFromNode(block)
if err != nil {
return fmt.Errorf("error when decoding block to event: %v", err)
}
}
body, err := event.GetBody(ctx, d.connector.Net, key.Read())
if err != nil {
return fmt.Errorf("error when getting body of event on thread %s/%s: %v", d.connector.ThreadID(), rec.LogID(), err)
}
events, err := d.eventcodec.EventsFromBytes(body.RawData())
if err != nil {
return fmt.Errorf("error when unmarshaling event from bytes: %v", err)
}
log.Debugf("dispatching new record: %s/%s", rec.ThreadID(), rec.LogID())
return d.dispatch(events)
}
func (d *DB) GetNetRecordCreateTime(ctx context.Context, rec net.ThreadRecord, key thread.Key) (int64, error) {
event, err := threadcbor.EventFromRecord(ctx, d.connector.Net, rec.Value())
if err != nil {
block, err := d.getBlockWithRetry(ctx, rec.Value())
if err != nil {
return 0, fmt.Errorf("error when getting block from record: %v", err)
}
event, err = threadcbor.EventFromNode(block)
if err != nil {
return 0, fmt.Errorf("error when decoding block to event: %v", err)
}
}
body, err := event.GetBody(ctx, d.connector.Net, key.Read())
if err != nil {
return 0, fmt.Errorf("error when getting body of event on thread %s/%s: %v", d.connector.ThreadID(), rec.LogID(), err)
}
events, err := d.eventcodec.EventsFromBytes(body.RawData())
if err != nil {
return 0, fmt.Errorf("error when unmarshaling event from bytes: %v", err)
}
if len(events) == 0 {
return 0, fmt.Errorf("no events found in record")
}
core_event := events[0]
buf := bytes.NewBuffer(core_event.Time())
var unix int64
if err = binary.Read(buf, binary.BigEndian, &unix); err != nil {
return 0, err
}
return unix, nil
}
// getBlockWithRetry gets a record block with exponential backoff.
func (d *DB) getBlockWithRetry(ctx context.Context, rec net.Record) (format.Node, error) {
backoff := getBlockInitialTimeout
var err error
for i := 1; i <= getBlockRetries; i++ {
n, err := rec.GetBlock(ctx, d.connector.Net)
if err == nil {
return n, nil
}
log.Warnf("error when fetching block %s in retry %d", rec.Cid(), i)
time.Sleep(backoff)
backoff *= 2
}
return nil, err
}
// dispatch applies external events to the db. This function guarantee
// no interference with registered collection states, and viceversa.
func (d *DB) dispatch(events []core.Event) error {
log.Debugf("dispatching events in %s", d.name)
d.txnlock.Lock()
defer d.txnlock.Unlock()
if err := d.dispatcher.Dispatch(events); err != nil {
return err
}
log.Debugf("dispatched events in %s", d.name)
return nil
}
func (d *DB) readTxn(c *Collection, f func(txn *Txn) error, opts ...TxnOption) error {
log.Debugf("starting read txn in %s", d.name)
d.txnlock.RLock()
defer d.txnlock.RUnlock()
args := &TxnOptions{}
for _, opt := range opts {
opt(args)
}
txn := &Txn{collection: c, token: args.Token, readonly: true}
defer txn.Discard()
if err := f(txn); err != nil {
return err
}
log.Debugf("ending read txn in %s", d.name)
return nil
}
func (d *DB) writeTxn(c *Collection, f func(txn *Txn) error, opts ...TxnOption) error {
log.Debugf("starting write txn in %s", d.name)
d.txnlock.Lock()
defer d.txnlock.Unlock()
args := &TxnOptions{}
for _, opt := range opts {
opt(args)
}
txn := &Txn{collection: c, token: args.Token}
defer txn.Discard()
if err := f(txn); err != nil {
return err
}
if err := txn.Commit(); err != nil {
return err
}
log.Debugf("ending write txn in %s", d.name)
return nil
}