royalcat
ef6680b854
All checks were successful
docker / build-docker (linux/386) (push) Successful in 1m23s
docker / build-docker (linux/amd64) (push) Successful in 1m25s
docker / build-docker (linux/arm64) (push) Successful in 8m18s
docker / build-docker (linux/arm/v7) (push) Successful in 9m8s
docker / build-docker (linux/arm64/v8) (push) Successful in 8m7s
97 lines
1.7 KiB
Go
97 lines
1.7 KiB
Go
package torrent
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/gob"
|
|
"log/slog"
|
|
"time"
|
|
|
|
dlog "git.kmsign.ru/royalcat/tstor/src/log"
|
|
"github.com/anacrolix/dht/v2/bep44"
|
|
"github.com/dgraph-io/badger/v4"
|
|
)
|
|
|
|
var _ bep44.Store = &fileItemStore{}
|
|
|
|
type fileItemStore struct {
|
|
ttl time.Duration
|
|
db *badger.DB
|
|
}
|
|
|
|
func newFileItemStore(path string, itemsTTL time.Duration) (*fileItemStore, error) {
|
|
l := slog.With("component", "item-store")
|
|
|
|
opts := badger.DefaultOptions(path).
|
|
WithLogger(&dlog.Badger{L: l}).
|
|
WithValueLogFileSize(1<<26 - 1)
|
|
|
|
db, err := badger.Open(opts)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
err = db.RunValueLogGC(0.5)
|
|
if err != nil && err != badger.ErrNoRewrite {
|
|
return nil, err
|
|
}
|
|
|
|
return &fileItemStore{
|
|
db: db,
|
|
ttl: itemsTTL,
|
|
}, nil
|
|
}
|
|
|
|
func (fis *fileItemStore) Put(i *bep44.Item) error {
|
|
tx := fis.db.NewTransaction(true)
|
|
defer tx.Discard()
|
|
|
|
key := i.Target()
|
|
var value bytes.Buffer
|
|
|
|
enc := gob.NewEncoder(&value)
|
|
if err := enc.Encode(i); err != nil {
|
|
return err
|
|
}
|
|
|
|
e := badger.NewEntry(key[:], value.Bytes()).WithTTL(fis.ttl)
|
|
if err := tx.SetEntry(e); err != nil {
|
|
return err
|
|
}
|
|
|
|
return tx.Commit()
|
|
}
|
|
|
|
func (fis *fileItemStore) Get(t bep44.Target) (*bep44.Item, error) {
|
|
tx := fis.db.NewTransaction(false)
|
|
defer tx.Discard()
|
|
|
|
dbi, err := tx.Get(t[:])
|
|
if err == badger.ErrKeyNotFound {
|
|
return nil, bep44.ErrItemNotFound
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
valb, err := dbi.ValueCopy(nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
buf := bytes.NewBuffer(valb)
|
|
dec := gob.NewDecoder(buf)
|
|
var i *bep44.Item
|
|
if err := dec.Decode(&i); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return i, nil
|
|
}
|
|
|
|
func (fis *fileItemStore) Del(t bep44.Target) error {
|
|
// ignore this
|
|
return nil
|
|
}
|
|
|
|
func (fis *fileItemStore) Close() error {
|
|
return fis.db.Close()
|
|
}
|