2016-08-31 07:48:50 +00:00
|
|
|
package storage
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/binary"
|
|
|
|
"path/filepath"
|
2018-01-09 12:11:34 +00:00
|
|
|
"time"
|
2016-08-31 07:48:50 +00:00
|
|
|
|
2018-04-12 01:34:24 +00:00
|
|
|
"github.com/anacrolix/missinggo/expect"
|
2020-03-24 01:54:57 +00:00
|
|
|
"go.etcd.io/bbolt"
|
2019-08-21 10:58:40 +00:00
|
|
|
|
|
|
|
"github.com/anacrolix/torrent/metainfo"
|
2016-08-31 07:48:50 +00:00
|
|
|
)
|
|
|
|
|
2016-08-31 11:00:44 +00:00
|
|
|
const (
|
|
|
|
// Chosen to match the usual chunk size in a torrent client. This way,
|
2020-03-24 01:54:57 +00:00
|
|
|
// most chunk writes are to exactly one full item in bbolt DB.
|
2016-08-31 11:00:44 +00:00
|
|
|
chunkSize = 1 << 14
|
|
|
|
)
|
2016-08-31 08:04:11 +00:00
|
|
|
|
2016-08-31 07:48:50 +00:00
|
|
|
type boltDBClient struct {
|
2020-03-24 01:54:57 +00:00
|
|
|
db *bbolt.DB
|
2016-08-31 07:48:50 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type boltDBTorrent struct {
|
|
|
|
cl *boltDBClient
|
|
|
|
ih metainfo.Hash
|
|
|
|
}
|
|
|
|
|
2020-02-21 03:12:44 +00:00
|
|
|
func NewBoltDB(filePath string) ClientImplCloser {
|
2020-03-24 01:54:57 +00:00
|
|
|
db, err := bbolt.Open(filepath.Join(filePath, "bolt.db"), 0600, &bbolt.Options{
|
2018-01-09 12:11:34 +00:00
|
|
|
Timeout: time.Second,
|
|
|
|
})
|
2018-04-12 01:34:24 +00:00
|
|
|
expect.Nil(err)
|
2018-01-09 12:11:34 +00:00
|
|
|
db.NoSync = true
|
|
|
|
return &boltDBClient{db}
|
2016-08-31 07:48:50 +00:00
|
|
|
}
|
|
|
|
|
2016-10-25 08:07:26 +00:00
|
|
|
func (me *boltDBClient) Close() error {
|
|
|
|
return me.db.Close()
|
|
|
|
}
|
|
|
|
|
2016-09-02 05:10:57 +00:00
|
|
|
func (me *boltDBClient) OpenTorrent(info *metainfo.Info, infoHash metainfo.Hash) (TorrentImpl, error) {
|
2016-08-31 07:48:50 +00:00
|
|
|
return &boltDBTorrent{me, infoHash}, nil
|
|
|
|
}
|
|
|
|
|
2016-09-02 05:10:57 +00:00
|
|
|
func (me *boltDBTorrent) Piece(p metainfo.Piece) PieceImpl {
|
2017-10-12 05:09:32 +00:00
|
|
|
ret := &boltDBPiece{
|
|
|
|
p: p,
|
|
|
|
db: me.cl.db,
|
|
|
|
ih: me.ih,
|
|
|
|
}
|
2016-08-31 07:48:50 +00:00
|
|
|
copy(ret.key[:], me.ih[:])
|
|
|
|
binary.BigEndian.PutUint32(ret.key[20:], uint32(p.Index()))
|
|
|
|
return ret
|
|
|
|
}
|
|
|
|
|
|
|
|
func (boltDBTorrent) Close() error { return nil }
|