Commit 48b1551d authored by Hector Sanjuan's avatar Hector Sanjuan

Add "delayed" datastore.

This is a partial extraction from go-ipfs/thirdparty/datastore2.

I have added a test.
parent a1533102
// Package delayed wraps a datastore allowing to artificially
// delay all operations.
package delayed
import (
ds "github.com/ipfs/go-datastore"
dsq "github.com/ipfs/go-datastore/query"
delay "github.com/ipfs/go-ipfs-delay"
)
// New returns a new delayed datastore.
func New(ds ds.Datastore, delay delay.D) ds.Datastore {
return &delayed{ds: ds, delay: delay}
}
type delayed struct {
ds ds.Datastore
delay delay.D
}
func (dds *delayed) Put(key ds.Key, value interface{}) (err error) {
dds.delay.Wait()
return dds.ds.Put(key, value)
}
func (dds *delayed) Get(key ds.Key) (value interface{}, err error) {
dds.delay.Wait()
return dds.ds.Get(key)
}
func (dds *delayed) Has(key ds.Key) (exists bool, err error) {
dds.delay.Wait()
return dds.ds.Has(key)
}
func (dds *delayed) Delete(key ds.Key) (err error) {
dds.delay.Wait()
return dds.ds.Delete(key)
}
func (dds *delayed) Query(q dsq.Query) (dsq.Results, error) {
dds.delay.Wait()
return dds.ds.Query(q)
}
func (dds *delayed) Batch() (ds.Batch, error) {
return ds.NewBasicBatch(dds), nil
}
func (dds *delayed) DiskUsage() (uint64, error) {
dds.delay.Wait()
return ds.DiskUsage(dds.ds)
}
package delayed
import (
"testing"
"time"
datastore "github.com/ipfs/go-datastore"
delay "github.com/ipfs/go-ipfs-delay"
)
func TestDelayed(t *testing.T) {
d := New(datastore.NewMapDatastore(), delay.Fixed(time.Second))
now := time.Now()
k := datastore.NewKey("test")
err := d.Put(k, "value")
if err != nil {
t.Fatal(err)
}
_, err = d.Get(k)
if err != nil {
t.Fatal(err)
}
if time.Since(now) < 2*time.Second {
t.Fatal("There should have been a delay of 1 second in put and in get")
}
}
......@@ -24,6 +24,12 @@
"hash": "QmYBJ8BXPDTMnzLFdv4rS5kbR1fUFASDVDpK7ZbeWMx6hq",
"name": "go-check",
"version": "1.0.0"
},
{
"author": "hsanjuan",
"hash": "QmRJVNatYJwTAHgdSM1Xef9QVQ1Ch3XHdmcrykjP5Y4soL",
"name": "go-ipfs-delay",
"version": "0.0.1"
}
],
"gxVersion": "0.7.0",
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment