Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions packages/snap-client/src/Client/NetworkCache/NetworkCache.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,35 @@ describe('Network Cache', () => {
consoleWarnSpy.mockRestore();
});

it('skips caching when entry cannot fit after purging non-purgeable items', async () => {
const consoleWarnSpy = jest.spyOn(console, 'warn').mockImplementation();

// First cache a non-purgeable item that takes up space
const nonPurgeableCache = new NetworkCache({
ttl: 10000,
enabled: true,
maxSize: 4, // KB - small enough that we'll hit the limit
purgeable: false,
});

nonPurgeableCache.set('nonPurgeableKey', typedResponse);

// Now try to add another item with the same cache instance
// The non-purgeable item can't be evicted, so the new item won't fit
nonPurgeableCache.set('newKey', typedResponse);

// The non-purgeable entry should still exist
expect(nonPurgeableCache.get('nonPurgeableKey')).toEqual(typedResponse);

// The new entry should not be cached since it couldn't fit
expect(nonPurgeableCache.get('newKey')).toBeUndefined();

// Verify warning was logged about being unable to cache
expect(consoleWarnSpy).toHaveBeenCalledWith(expect.stringContaining('Unable to cache entry'));

consoleWarnSpy.mockRestore();
});

it('can pass in cache to set', async () => {
const key = 'key';
const cacheConfig = {
Expand Down
6 changes: 6 additions & 0 deletions packages/snap-client/src/Client/NetworkCache/NetworkCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,12 @@ export class NetworkCache {
currentSize = new Blob([JSON.stringify(this.memoryCache)], { endings: 'native' }).size / 1024;
}

// if we still can't fit the new object after purging, skip caching
if (currentSize + newObjectSize > this.config.maxSize) {
console.warn(`Unable to cache entry for key "${key}" without exceeding maxSize (${this.config.maxSize}KB), skipping cache`);
Comment thread
chrisFrazier77 marked this conversation as resolved.
return;
}
Comment thread
korgon marked this conversation as resolved.

// store cache in memory
this.memoryCache[key] = cacheObject;

Expand Down
Loading