2016-08-31 15:48:50 +08:00
|
|
|
package storage
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/binary"
|
|
|
|
"path/filepath"
|
2018-01-09 20:11:34 +08:00
|
|
|
"time"
|
2016-08-31 15:48:50 +08:00
|
|
|
|
2018-04-12 09:34:24 +08:00
|
|
|
"github.com/anacrolix/missinggo/expect"
|
2016-08-31 15:48:50 +08:00
|
|
|
"github.com/boltdb/bolt"
|
|
|
|
|
|
|
|
"github.com/anacrolix/torrent/metainfo"
|
|
|
|
)
|
|
|
|
|
2016-08-31 19:00:44 +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 bolt DB.
|
|
|
|
chunkSize = 1 << 14
|
|
|
|
)
|
2016-08-31 16:04:11 +08:00
|
|
|
|
2016-08-31 15:48:50 +08:00
|
|
|
type boltDBClient struct {
|
|
|
|
db *bolt.DB
|
|
|
|
}
|
|
|
|
|
|
|
|
type boltDBTorrent struct {
|
|
|
|
cl *boltDBClient
|
|
|
|
ih metainfo.Hash
|
|
|
|
}
|
|
|
|
|
2016-09-02 13:10:57 +08:00
|
|
|
func NewBoltDB(filePath string) ClientImpl {
|
2018-01-09 20:11:34 +08:00
|
|
|
db, err := bolt.Open(filepath.Join(filePath, "bolt.db"), 0600, &bolt.Options{
|
|
|
|
Timeout: time.Second,
|
|
|
|
})
|
2018-04-12 09:34:24 +08:00
|
|
|
expect.Nil(err)
|
2018-01-09 20:11:34 +08:00
|
|
|
db.NoSync = true
|
|
|
|
return &boltDBClient{db}
|
2016-08-31 15:48:50 +08:00
|
|
|
}
|
|
|
|
|
2016-10-25 16:07:26 +08:00
|
|
|
func (me *boltDBClient) Close() error {
|
|
|
|
return me.db.Close()
|
|
|
|
}
|
|
|
|
|
2016-09-02 13:10:57 +08:00
|
|
|
func (me *boltDBClient) OpenTorrent(info *metainfo.Info, infoHash metainfo.Hash) (TorrentImpl, error) {
|
2016-08-31 15:48:50 +08:00
|
|
|
return &boltDBTorrent{me, infoHash}, nil
|
|
|
|
}
|
|
|
|
|
2016-09-02 13:10:57 +08:00
|
|
|
func (me *boltDBTorrent) Piece(p metainfo.Piece) PieceImpl {
|
2017-10-12 13:09:32 +08:00
|
|
|
ret := &boltDBPiece{
|
|
|
|
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 (boltDBTorrent) Close() error { return nil }
|