Block cache with LRU eviction
Bound the loaded blocks of a remote grid and watch old blocks get evicted.
Live example
Expected behavior
Loaded blocks are listed as loaded. Moving past the limit evicts the least recently used unprotected block and logs blockEvicted. Returning to it refetches it.
Source
const api = createGrid({
rows: [],
columns,
rowModel: 'remote',
blockSize: 100,
maxCachedBlocks: 5,
evictionPolicy: 'lru',
protectBlock: (block) => block.index === focusedBlock,
remoteSource: { fetchWindow },
});
api.on('blockEvicted', ({ index }) => log(`Block ${index} evicted`));
console.log(api.getCacheState().blocks);const api = createGrid({
rows: [],
columns,
rowModel: 'remote',
blockSize: 100,
maxCachedBlocks: 5,
evictionPolicy: 'lru',
protectBlock: (block) => block.index === focusedBlock,
remoteSource: { fetchWindow },
});
api.on('blockEvicted', ({ index }) => log(`Block ${index} evicted`));
console.log(api.getCacheState().blocks);const api = createGrid({
rows: [],
columns,
rowModel: 'remote',
blockSize: 100,
maxCachedBlocks: 5,
evictionPolicy: 'lru',
protectBlock: (block) => block.index === focusedBlock,
remoteSource: { fetchWindow },
});
api.on('blockEvicted', ({ index }) => log(`Block ${index} evicted`));
console.log(api.getCacheState().blocks);const api = createGrid({
rows: [],
columns,
rowModel: 'remote',
blockSize: 100,
maxCachedBlocks: 5,
evictionPolicy: 'lru',
protectBlock: (block) => block.index === focusedBlock,
remoteSource: { fetchWindow },
});
api.on('blockEvicted', ({ index }) => log(`Block ${index} evicted`));
console.log(api.getCacheState().blocks);// JavaScript interop module
const api = createGrid({
rows: [],
columns,
rowModel: 'remote',
blockSize: 100,
maxCachedBlocks: 5,
evictionPolicy: 'lru',
protectBlock: (block) => block.index === focusedBlock,
remoteSource: { fetchWindow },
});
api.on('blockEvicted', ({ index }) => log(`Block ${index} evicted`));
console.log(api.getCacheState().blocks);API reference
| Kind | Name | Type | Description |
|---|---|---|---|
| Option | maxCachedBlocks | — | Maximum unprotected loaded blocks. |
| Option | evictionPolicy | — | 'lru' or 'distance'. |
| Option | protectBlock | — | Returns true to keep a block cached. |
| Event | blockEvicted | — | Fires when a block is evicted. |
| Method | getCacheState | — | Lists blocks with index, state and lastAccess. |
Acceptance criteria
- The cache never holds more than maxCachedBlocks unprotected blocks. (met)
- Blocks intersecting the viewport are never evicted. (met)
- Blocks holding the focused row, rows being edited, or unsaved optimistic rows are never evicted. (met)
- An evicted block is refetched on demand with a new request. (met)
- getCacheState returns, for each block, its index, state and lastAccess. (met)