Skip to content

Commit

Permalink
namecache: basic persistent version
Browse files Browse the repository at this point in the history
License: MIT
Signed-off-by: Łukasz Magiera <magik6k@gmail.com>
  • Loading branch information
magik6k committed Feb 5, 2019
1 parent 7d6de7e commit 4f56358
Show file tree
Hide file tree
Showing 3 changed files with 77 additions and 1 deletion.
4 changes: 4 additions & 0 deletions core/core.go
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,10 @@ func (n *IpfsNode) startOnlineServices(ctx context.Context, routingOption Routin

if follow {
n.Namecache = namecache.NewNameCache(ctx, n.Namesys, n.Pinning, n.DAG, n.Blockstore)
n.Namecache, err = namecache.NewPersistentCache(n.Namecache, n.Repo.Datastore())
if err != nil {
return err
}
}

// setup local discovery
Expand Down
2 changes: 1 addition & 1 deletion namecache/namecache.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ func (nc *nameCache) ListFollows() []string {
defer nc.mx.Unlock()

follows := make([]string, 0, len(nc.follows))
for name, _ := range nc.follows {
for name := range nc.follows {
follows = append(follows, name)
}

Expand Down
72 changes: 72 additions & 0 deletions namecache/persistent.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package namecache

import (
"encoding/json"
"time"

ds "gx/ipfs/Qmf4xQhNomPNhrtZc67qSnfJSjxjXs9LWvknJtSXwimPrM/go-datastore"
nsds "gx/ipfs/Qmf4xQhNomPNhrtZc67qSnfJSjxjXs9LWvknJtSXwimPrM/go-datastore/namespace"
dsq "gx/ipfs/Qmf4xQhNomPNhrtZc67qSnfJSjxjXs9LWvknJtSXwimPrM/go-datastore/query"
)

var dsPrefix = ds.NewKey("/namecache")

// persistent is a cache layer which persists followed names between node
// restarts
type persistent struct {
NameCache

ds ds.Datastore
}

type follow struct {
Pin bool
Deadline time.Time
}

func NewPersistentCache(base NameCache, d ds.Datastore) (NameCache, error) {
d = nsds.Wrap(d, dsPrefix)

q ,err := d.Query(dsq.Query{})
if err != nil {
return nil, err
}
defer q.Close()
for e := range q.Next() {
var f follow
if err := json.Unmarshal(e.Value, &f); err != nil {
return nil, err
}
if err := base.Follow(e.Key, f.Pin, time.Now().Sub(f.Deadline)); err != nil {
return nil, err
}
}


return &persistent{
NameCache: base,
ds: d,
}, nil
}

func (p *persistent) Follow(name string, dopin bool, followInterval time.Duration) error {
b, err := json.Marshal(&follow{
Pin: dopin,
Deadline: time.Now().Add(followInterval),
})
if err != nil {
return err
}

if err := p.NameCache.Follow(name, dopin, followInterval); err != nil {
return err
}
return p.ds.Put(ds.NewKey(name), b)
}

func (p *persistent) Unfollow(name string) error {
if err := p.NameCache.Unfollow(name); err != nil {
return err
}
return p.ds.Delete(ds.NewKey(name))
}

0 comments on commit 4f56358

Please sign in to comment.