FedP2P/storage/bolt.go

65 lines
1.2 KiB
Go
Raw Normal View History

2021-07-14 12:35:52 +08:00
//go:build !noboltdb && !wasm
// +build !noboltdb,!wasm
2016-08-31 15:48:50 +08:00
package storage
import (
"encoding/binary"
"path/filepath"
"time"
2016-08-31 15:48:50 +08:00
2018-04-12 09:34:24 +08:00
"github.com/anacrolix/missinggo/expect"
2020-03-24 09:54:57 +08:00
"go.etcd.io/bbolt"
2019-08-21 18:58:40 +08:00
"github.com/anacrolix/torrent/metainfo"
2016-08-31 15:48:50 +08:00
)
const (
// Chosen to match the usual chunk size in a torrent client. This way, most chunk writes are to
// exactly one full item in bbolt DB.
chunkSize = 1 << 14
)
2016-08-31 16:04:11 +08:00
type boltClient struct {
2020-03-24 09:54:57 +08:00
db *bbolt.DB
2016-08-31 15:48:50 +08:00
}
type boltTorrent struct {
cl *boltClient
2016-08-31 15:48:50 +08:00
ih metainfo.Hash
}
func NewBoltDB(filePath string) ClientImplCloser {
2021-11-08 11:47:01 +08:00
db, err := bbolt.Open(filepath.Join(filePath, "bolt.db"), 0o600, &bbolt.Options{
Timeout: time.Second,
})
2018-04-12 09:34:24 +08:00
expect.Nil(err)
db.NoSync = true
return &boltClient{db}
2016-08-31 15:48:50 +08:00
}
func (me *boltClient) Close() error {
return me.db.Close()
}
func (me *boltClient) OpenTorrent(_ *metainfo.Info, infoHash metainfo.Hash) (TorrentImpl, error) {
t := &boltTorrent{me, infoHash}
return TorrentImpl{
Piece: t.Piece,
Close: t.Close,
}, nil
2016-08-31 15:48:50 +08:00
}
func (me *boltTorrent) Piece(p metainfo.Piece) PieceImpl {
ret := &boltPiece{
p: p,
db: me.cl.db,
ih: me.ih,
}
2016-08-31 15:48:50 +08:00
copy(ret.key[:], me.ih[:])
binary.BigEndian.PutUint32(ret.key[20:], uint32(p.Index()))
return ret
}
func (boltTorrent) Close() error { return nil }