From ca4c9d46734d8882ad8659198212ef6eec0cbc36 Mon Sep 17 00:00:00 2001 From: Leonard Lyubich Date: Tue, 14 Sep 2021 18:09:36 +0300 Subject: [PATCH] [#791] writecache: Implement iterator over small objects There is a need to list addresses of the small objects stored in WriteCache database. Implement `IterateDB` function which accepts BoltDB instance and iterate over all saved objects and passes their addresses to the hander. Signed-off-by: Leonard Lyubich --- .../writecache/iterate.go | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 pkg/local_object_storage/writecache/iterate.go diff --git a/pkg/local_object_storage/writecache/iterate.go b/pkg/local_object_storage/writecache/iterate.go new file mode 100644 index 000000000..9273b9527 --- /dev/null +++ b/pkg/local_object_storage/writecache/iterate.go @@ -0,0 +1,42 @@ +package writecache + +import ( + "errors" + "fmt" + + "github.com/nspcc-dev/neofs-api-go/pkg/object" + "go.etcd.io/bbolt" +) + +// ErrNoDefaultBucket is returned by IterateDB when default bucket for objects is missing. +var ErrNoDefaultBucket = errors.New("no default bucket") + +// IterateDB iterates over all objects stored in bbolt.DB instance and passes them to f until error return. +// It is assumed that db is an underlying database of some WriteCache instance. +// +// Returns ErrNoDefaultBucket if there is no default bucket in db. +// +// DB must not be nil and should be opened. +func IterateDB(db *bbolt.DB, f func(*object.Address) error) error { + return db.View(func(tx *bbolt.Tx) error { + b := tx.Bucket(defaultBucket) + if b == nil { + return ErrNoDefaultBucket + } + + var addr *object.Address + + return b.ForEach(func(k, v []byte) error { + if addr == nil { + addr = object.NewAddress() + } + + err := addr.Parse(string(k)) + if err != nil { + return fmt.Errorf("could not parse object address: %w", err) + } + + return f(addr) + }) + }) +}