Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Cancel function; add finalizer to cleanup abandoned batch #105

Merged
merged 2 commits into from
Oct 9, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 23 additions & 7 deletions datastore.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package badger
import (
"errors"
"fmt"
"runtime"
"strings"
"sync"
"time"
Expand Down Expand Up @@ -398,19 +399,19 @@ func (d *Datastore) Close() error {

// Batch creats a new Batch object. This provides a way to do many writes, when
// there may be too many to fit into a single transaction.
//
// After writing to a Batch, always call Commit whether or not writing to the
// batch was completed successfully or not. This is necessary to flush any
// remaining data and free any resources associated with an incomplete
// transaction.
func (d *Datastore) Batch() (ds.Batch, error) {
d.closeLk.RLock()
defer d.closeLk.RUnlock()
if d.closed {
return nil, ErrClosed
}

return &batch{d, d.DB.NewWriteBatch()}, nil
b := &batch{d, d.DB.NewWriteBatch()}
// Ensure that incomplete transaction resources are cleaned up in case
// batch is abandoned.
runtime.SetFinalizer(b, func(b *batch) { b.cancel() })

return b, nil
}

func (d *Datastore) CollectGarbage() (err error) {
Expand Down Expand Up @@ -479,11 +480,26 @@ func (b *batch) commit() error {
err := b.writeBatch.Flush()
if err != nil {
// Discard incomplete transaction held by b.writeBatch
b.writeBatch.Cancel()
b.cancel()
}
return err
}

func (b *batch) Cancel() error {
b.ds.closeLk.RLock()
defer b.ds.closeLk.RUnlock()
if b.ds.closed {
return ErrClosed
}

b.cancel()
return nil
}

func (b *batch) cancel() {
b.writeBatch.Cancel()
}

var _ ds.Datastore = (*txn)(nil)
var _ ds.TTLDatastore = (*txn)(nil)

Expand Down
24 changes: 24 additions & 0 deletions ds_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,30 @@ func TestBatching(t *testing.T) {
"/g",
}, rs)

//Test cancel

b, err = d.Batch()
if err != nil {
t.Fatal(err)
}

const key = "/xyz"

err = b.Put(ds.NewKey(key), []byte("/x/y/z"))
if err != nil {
t.Fatal(err)
}

// TODO: remove type assertion once datastore.Batch interface has Cancel
err = b.(*batch).Cancel()
if err != nil {
t.Fatal(err)
}

_, err = d.Get(ds.NewKey(key))
if err == nil {
t.Fatal("expected error trying to get uncommited data")
}
}

func TestBatchingRequired(t *testing.T) {
Expand Down