tiered.go 1.87 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1 2 3 4 5 6
package tiered

import (
	"fmt"
	"sync"

Jeromy's avatar
Jeromy committed
7 8
	ds "github.com/ipfs/go-datastore"
	dsq "github.com/ipfs/go-datastore/query"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
9 10 11 12 13 14 15
)

type tiered []ds.Datastore

// New returns a tiered datastore. Puts and Deletes will write-through to
// all datastores, Has and Get will try each datastore sequentially, and
// Query will always try the last one (most complete) first.
Jeromy's avatar
Jeromy committed
16
func New(dses ...ds.Datastore) tiered {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
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
	return tiered(dses)
}

// Put stores the object `value` named by `key`.
func (d tiered) Put(key ds.Key, value interface{}) (err error) {
	errs := make(chan error, len(d))

	var wg sync.WaitGroup
	for _, cd := range d {
		wg.Add(1)
		go func(cd ds.Datastore) {
			defer wg.Done()
			if err := cd.Put(key, value); err != nil {
				errs <- err
			}
		}(cd)
	}
	wg.Wait()

	close(errs)
	for err := range errs {
		return err
	}
	return nil
}

// Get retrieves the object `value` named by `key`.
func (d tiered) Get(key ds.Key) (value interface{}, err error) {
	err = fmt.Errorf("no datastores")
	for _, cd := range d {
		value, err = cd.Get(key)
		if err == nil {
			break
		}
	}
	return
}

// Has returns whether the `key` is mapped to a `value`.
func (d tiered) Has(key ds.Key) (exists bool, err error) {
	err = fmt.Errorf("no datastores")
	for _, cd := range d {
		exists, err = cd.Has(key)
		if err == nil && exists {
			break
		}
	}
	return
}

// Delete removes the value for given `key`.
func (d tiered) Delete(key ds.Key) (err error) {
	errs := make(chan error, len(d))

	var wg sync.WaitGroup
	for _, cd := range d {
		wg.Add(1)
		go func(cd ds.Datastore) {
			defer wg.Done()
			if err := cd.Delete(key); err != nil {
				errs <- err
			}
		}(cd)
	}
	wg.Wait()

	close(errs)
	for err := range errs {
		return err
	}
	return nil
}

// Query returns a list of keys in the datastore
func (d tiered) Query(q dsq.Query) (dsq.Results, error) {
	// query always the last (most complete) one
	return d[len(d)-1].Query(q)
}