Skip to content
This repository was archived by the owner on Feb 12, 2024. It is now read-only.

Commit bd9686d

Browse files
committed
fix: cache preloaded CIDs
We 'preload' most CIDs we interact with on the network. In some cases this can mean preloading the same CID over and over again which is not necessary. This PR adds a LRU cache to the preloader with a default size of 1000. The cache is used to avoid re-preloading the same CID over and over again until it drops out of the cache. We use a cache that will evict CIDs over time to have some sort of upper bound on memory usage. Fixes #3307
1 parent 5d394c2 commit bd9686d

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

packages/ipfs-core/src/preload.js

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@ const CID = require('cids')
66
const shuffle = require('array-shuffle')
77
const AbortController = require('native-abort-controller')
88
const preload = require('./runtime/preload-nodejs')
9+
/** @type {typeof import('hashlru').default} */
10+
// @ts-ignore - hashlru has incorrect typedefs
11+
const hashlru = require('hashlru')
912

1013
const log = Object.assign(
1114
debug('ipfs:preload'),
@@ -14,12 +17,14 @@ const log = Object.assign(
1417

1518
/**
1619
* @param {Object} [options]
17-
* @param {boolean} [options.enabled]
18-
* @param {string[]} [options.addresses]
20+
* @param {boolean} [options.enabled] - Whether to preload anything
21+
* @param {string[]} [options.addresses] - Which preload servers to use
22+
* @param {number} [options.cache] - How many CIDs to cache
1923
*/
2024
const createPreloader = (options = {}) => {
2125
options.enabled = Boolean(options.enabled)
2226
options.addresses = options.addresses || []
27+
options.cache = options.cache || 1000
2328

2429
if (!options.enabled || !options.addresses.length) {
2530
log('preload disabled')
@@ -34,6 +39,9 @@ const createPreloader = (options = {}) => {
3439
let requests = []
3540
const apiUris = options.addresses.map(toUri)
3641

42+
// Avoid preloading the same CID over and over again
43+
const cache = hashlru(options.cache)
44+
3745
/**
3846
* @param {string|CID} path
3947
* @returns {Promise<void>}
@@ -46,6 +54,13 @@ const createPreloader = (options = {}) => {
4654
path = new CID(path).toString()
4755
}
4856

57+
if (cache.has(path)) {
58+
return
59+
}
60+
61+
// don't
62+
cache.set(path, true)
63+
4964
const fallbackApiUris = shuffle(apiUris)
5065
let success = false
5166
const now = Date.now()

0 commit comments

Comments
 (0)