retrystore.go 2.11 KB
Newer Older
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
// Package retrystore provides a datastore wrapper which
// allows to retry operations.
package retrystore

import (
	"fmt"
	"time"

	ds "github.com/ipfs/go-datastore"
)

// Datastore wraps a Batching datastore with a
// user-provided TempErrorFunc -which determines if an error
// is a temporal error and thus, worth retrying-, an amount of Retries
// -which specify how many times to retry an operation after
// a temporal error- and a base Delay, which is multiplied by the
// current retry and performs a pause before attempting the operation again.
type Datastore struct {
	TempErrFunc func(error) bool
	Retries     int
	Delay       time.Duration

	ds.Batching
}

var errFmtString = "ran out of retries trying to get past temporary error: %s"

func (d *Datastore) runOp(op func() error) error {
	err := op()
	if err == nil || !d.TempErrFunc(err) {
		return err
	}

	for i := 0; i < d.Retries; i++ {
		time.Sleep(time.Duration(i+1) * d.Delay)

		err = op()
		if err == nil || !d.TempErrFunc(err) {
			return err
		}
	}

	return fmt.Errorf(errFmtString, err)
}

46 47 48 49 50 51 52 53 54 55 56
// DiskUsage implements the PersistentDatastore interface.
func (d *Datastore) DiskUsage() (uint64, error) {
	var size uint64
	err := d.runOp(func() error {
		var err error
		size, err = ds.DiskUsage(d.Batching)
		return err
	})
	return size, err
}

57
// Get retrieves a value given a key.
58 59
func (d *Datastore) Get(k ds.Key) ([]byte, error) {
	var val []byte
60 61 62 63 64 65 66 67 68 69
	err := d.runOp(func() error {
		var err error
		val, err = d.Batching.Get(k)
		return err
	})

	return val, err
}

// Put stores a key/value.
70
func (d *Datastore) Put(k ds.Key, val []byte) error {
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
	return d.runOp(func() error {
		return d.Batching.Put(k, val)
	})
}

// Has checks if a key is stored.
func (d *Datastore) Has(k ds.Key) (bool, error) {
	var has bool
	err := d.runOp(func() error {
		var err error
		has, err = d.Batching.Has(k)
		return err
	})
	return has, err
}
Steven Allen's avatar
Steven Allen committed
86 87 88 89 90 91 92 93 94 95 96

// GetSize returns the size of the value in the datastore, if present.
func (d *Datastore) GetSize(k ds.Key) (int, error) {
	var size int
	err := d.runOp(func() error {
		var err error
		size, err = d.Batching.GetSize(k)
		return err
	})
	return size, err
}