From d540058ebd7f32e613d26c33e8a99b16d39a13d8 Mon Sep 17 00:00:00 2001 From: John Hiesey Date: Wed, 30 Jun 2021 13:19:18 -0700 Subject: feat: Use a cache on the chunk store (#2095) --- lib/torrent.js | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) (limited to 'lib') diff --git a/lib/torrent.js b/lib/torrent.js index 1f0be5b..b46cde3 100644 --- a/lib/torrent.js +++ b/lib/torrent.js @@ -2,6 +2,7 @@ const addrToIPPort = require('addr-to-ip-port') const BitField = require('bitfield').default +const CacheChunkStore = require('cache-chunk-store') const ChunkStoreWriteStream = require('chunk-store-stream/write') const cpus = require('cpus') const debug = require('debug')('webtorrent:torrent') @@ -12,6 +13,7 @@ const FSChunkStore = require('fs-chunk-store') // browser: `memory-chunk-store` const get = require('simple-get') const ImmediateChunkStore = require('immediate-chunk-store') const ltDontHave = require('lt_donthave') +const MemoryChunkStore = require('memory-chunk-store') const MultiStream = require('multistream') const net = require('net') // browser exclude const os = require('os') // browser exclude @@ -75,6 +77,7 @@ class Torrent extends EventEmitter { this.skipVerify = !!opts.skipVerify this._store = opts.store || FSChunkStore this._preloadedStore = opts.preloadedStore || null + this._storeCacheSlots = opts.storeCacheSlots !== undefined ? opts.storeCacheSlots : 20 this._destroyStoreOnDestroy = opts.destroyStoreOnDestroy || false this._getAnnounceOpts = opts.getAnnounceOpts @@ -470,8 +473,11 @@ class Torrent extends EventEmitter { this._rarityMap = new RarityMap(this) - this.store = new ImmediateChunkStore( - this._preloadedStore || new this._store(this.pieceLength, { + let rawStore = this._preloadedStore + if (!rawStore) { + rawStore = new this._store(this.pieceLength, { + // opts.torrent is deprecated (replaced by the name property). + // it doesn't appear to be used by current versions of any stores on npm. torrent: { infoHash: this.infoHash }, @@ -483,6 +489,17 @@ class Torrent extends EventEmitter { length: this.length, name: this.infoHash }) + } + + // don't use the cache if the store is already in memory + if (this._storeCacheSlots > 0 && !(rawStore instanceof MemoryChunkStore)) { + rawStore = new CacheChunkStore(rawStore, { + max: this._storeCacheSlots + }) + } + + this.store = new ImmediateChunkStore( + rawStore ) this.files = this.files.map(file => new File(this, file)) -- cgit v1.2.3