package store import ( "bytes" "fmt" "log/slog" "path/filepath" dlog "git.kmsign.ru/royalcat/tstor/src/log" "github.com/anacrolix/torrent/metainfo" "github.com/anacrolix/torrent/types/infohash" "github.com/dgraph-io/badger/v4" ) type InfoBytes struct { db *badger.DB } func NewInfoBytes(metaDir string) (*InfoBytes, error) { l := slog.With("component", "badger", "db", "info-bytes") opts := badger. DefaultOptions(filepath.Join(metaDir, "infobytes")). WithLogger(&dlog.Badger{L: l}) db, err := badger.Open(opts) if err != nil { return nil, err } return &InfoBytes{db}, nil } func (k *InfoBytes) GetBytes(ih infohash.T) ([]byte, error) { var data []byte err := k.db.View(func(tx *badger.Txn) error { item, err := tx.Get(ih.Bytes()) if err != nil { if err == badger.ErrKeyNotFound { return ErrNotFound } return fmt.Errorf("error getting value: %w", err) } data, err = item.ValueCopy(data) return err }) return data, err } func (k *InfoBytes) Get(ih infohash.T) (*metainfo.MetaInfo, error) { data, err := k.GetBytes(ih) if err != nil { return nil, err } return metainfo.Load(bytes.NewReader(data)) } func (me *InfoBytes) SetBytes(ih infohash.T, bytes []byte) error { return me.db.Update(func(txn *badger.Txn) error { return txn.Set(ih.Bytes(), bytes) }) } func (me *InfoBytes) Set(ih infohash.T, info metainfo.MetaInfo) error { return me.db.Update(func(txn *badger.Txn) error { return txn.Set(ih.Bytes(), info.InfoBytes) }) } func (k *InfoBytes) Delete(ih infohash.T) error { return k.db.Update(func(txn *badger.Txn) error { return txn.Delete(ih.Bytes()) }) } func (me *InfoBytes) Close() error { return me.db.Close() }