Add bolt store

This commit is contained in:
2021-12-04 09:58:16 +01:00
parent 6d904c724b
commit bf9f8d80cd
8 changed files with 166 additions and 20 deletions

90
store/bolt.go Normal file
View File

@@ -0,0 +1,90 @@
package store
import (
"fmt"
"gitea.benny.dog/torjus/ezshare/pb"
"github.com/google/uuid"
bolt "go.etcd.io/bbolt"
"google.golang.org/protobuf/proto"
)
type BoltStore struct {
db *bolt.DB
}
var bktKey = []byte("files")
func NewBoltStore(path string) (*BoltStore, error) {
s := &BoltStore{}
db, err := bolt.Open(path, 0660, &bolt.Options{})
if err != nil {
return nil, fmt.Errorf("unable to open store: %w", err)
}
s.db = db
err = db.Update(func(t *bolt.Tx) error {
if _, err := t.CreateBucketIfNotExists(bktKey); err != nil {
return err
}
return nil
})
if err != nil {
return nil, fmt.Errorf("unable to create bucket: %w", err)
}
return s, nil
}
func (s *BoltStore) Close() error {
return s.db.Close()
}
func (s *BoltStore) GetFile(id string) (*pb.File, error) {
var file pb.File
var data []byte
if err := s.db.View(func(t *bolt.Tx) error {
bkt := t.Bucket(bktKey)
data = bkt.Get([]byte(id))
return nil
}); err != nil {
return nil, fmt.Errorf("error getting file: %w", err)
}
if data == nil {
return nil, ErrNoSuchFile
}
err := proto.Unmarshal(data, &file)
if err != nil {
return nil, fmt.Errorf("unable to unmarshal file: %w", err)
}
return &file, nil
}
func (s *BoltStore) StoreFile(file *pb.File) (string, error) {
file.FileId = uuid.Must(uuid.NewRandom()).String()
data, err := proto.Marshal(file)
if err != nil {
return "", fmt.Errorf("unable to marshal file: %w", err)
}
err = s.db.Update(func(t *bolt.Tx) error {
bkt := t.Bucket(bktKey)
return bkt.Put([]byte(file.FileId), data)
})
if err != nil {
return "", fmt.Errorf("unable to store file: %w", err)
}
return file.FileId, nil
}
func (s *BoltStore) DeleteFile(id string) error {
return s.db.Update(func(t *bolt.Tx) error {
bkt := t.Bucket(bktKey)
data := bkt.Get([]byte(id))
if data == nil {
return ErrNoSuchFile
}
return bkt.Delete([]byte(id))
})
}

18
store/bolt_test.go Normal file
View File

@@ -0,0 +1,18 @@
package store_test
import (
"path/filepath"
"testing"
"gitea.benny.dog/torjus/ezshare/store"
)
func TestBoltStore(t *testing.T) {
path := filepath.Join(t.TempDir(), "boltstore.db")
s, err := store.NewBoltStore(path)
if err != nil {
t.Fatalf("Error opening store: %s", err)
}
doFileStoreTest(s, t)
s.Close()
}

View File

@@ -1,21 +1,13 @@
package store_test
import (
"io/ioutil"
"os"
"testing"
"gitea.benny.dog/torjus/ezshare/store"
)
func TestFileStore(t *testing.T) {
dir, err := ioutil.TempDir(os.TempDir(), "ezshare-test")
if err != nil {
t.Fatalf("unable to create temp-dir")
}
defer func() {
_ = os.RemoveAll(dir)
}()
dir := t.TempDir()
s := store.NewFileSystemStore(dir)
doFileStoreTest(s, t)