Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clean up cache properly if session ID changes #2267

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
5 changes: 5 additions & 0 deletions .changeset/quick-seas-help.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@lion/ajax': patch
---

Reset cache and pending requests when cache session ID changes
1 change: 1 addition & 0 deletions packages/ajax/src/PendingRequestStore.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ export default class PendingRequestStore {
}

reset() {
this.resolveMatching(/.*/);
this._pendingRequests = {};
}
}
11 changes: 10 additions & 1 deletion packages/ajax/src/cacheManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,15 @@ export const pendingRequestStore = new PendingRequestStore();
*/
export const isCurrentSessionId = cacheId => cacheId === cacheSessionId;

/**
* Sets the current cache session ID.
*
* @param {string} id The id that will be tied to the current session
*/
export const setCacheSessionId = id => {
cacheSessionId = id;
};

/**
* Resets the cache session when the cacheId changes.
*
Expand All @@ -43,7 +52,7 @@ export const resetCacheSession = cacheId => {
throw new Error('Invalid cache identifier');
}
if (!isCurrentSessionId(cacheId)) {
cacheSessionId = cacheId;
setCacheSessionId(cacheId);
ajaxCache.reset();
pendingRequestStore.reset();
}
Expand Down
6 changes: 6 additions & 0 deletions packages/ajax/src/interceptors/cacheInterceptors.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,12 @@ const createCacheRequestInterceptor =
if (pendingRequest) {
// there is another concurrent request, wait for it to finish
await pendingRequest;

// If session ID changes while waiting for the pending request to complete,
// then do not read the cache.
if (!isCurrentSessionId(request.cacheSessionId)) {
return request;
}
}

const cachedResponse = ajaxCache.get(requestId, { maxAge, maxResponseSize });
Expand Down
26 changes: 25 additions & 1 deletion packages/ajax/test/Ajax.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -503,7 +503,7 @@ describe('Ajax', () => {
expect(customAjax._responseInterceptors.length).to.equal(1);
});

describe('caching interceptors', async () => {
describe('Caching interceptors: synchronous getCacheIdentifier tests', async () => {
/**
* @type {Ajax}
*/
Expand All @@ -530,6 +530,30 @@ describe('Ajax', () => {
expect(secondResponse.headers.get('Content-Type')).to.equal('application/json');
});

it('resets the cache if the cache ID changes', async () => {
/* Three calls to the same endpoint should result in a
single fetchStubCall due to caching */
await customAjax.fetch('/foo');
await customAjax.fetch('/foo');
await customAjax.fetch('/foo');
expect(fetchStub.callCount).to.equal(1);

newCacheId();
await customAjax.fetch('/foo');

/* The newCacheId call should reset the cache, thereby adding an
extra call to the fetchStub call count. */
expect(fetchStub.callCount).to.equal(2);
});

it('Completes pending requests when the cache ID changes', async () => {
const requestOne = customAjax.fetch('/foo').then(() => 'completedRequestOne');
newCacheId();
const requestTwo = customAjax.fetch('/foo').then(() => 'completedRequestTwo');
expect(await requestOne).to.equal('completedRequestOne');
expect(await requestTwo).to.equal('completedRequestTwo');
});

it('works with fetchJson', async () => {
fetchStub.returns(Promise.resolve(new Response('{"a":1,"b":2}', responseInit())));

Expand Down
38 changes: 37 additions & 1 deletion packages/ajax/test/interceptors/cacheInterceptors.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@ import { Ajax, createCacheInterceptors } from '@lion/ajax';
import { isResponseContentTypeSupported } from '../../src/interceptors/cacheInterceptors.js';

// TODO: these are private API? should they be exposed? if not why do we test them?
import { extendCacheOptions, resetCacheSession, ajaxCache } from '../../src/cacheManager.js';
import {
extendCacheOptions,
resetCacheSession,
ajaxCache,
setCacheSessionId,
} from '../../src/cacheManager.js';

const MOCK_RESPONSE = 'mock response';

Expand Down Expand Up @@ -437,6 +442,37 @@ describe('cache interceptors', () => {
expect(fetchStub.callCount).to.equal(1);
});

it('Does not use cached request when session ID changes during processing a pending request', async () => {
addCacheInterceptors(ajax, {
useCache: true,
maxAge: 750,
});

// Reset cache
newCacheId();

/* Bump sessionID manually in an injected response interceptor.
This will simulate the cache session ID getting changed while
waiting for a pending request */

ajax._responseInterceptors.unshift(async (/** @type {Response} */ response) => {
newCacheId();
setCacheSessionId(getCacheIdentifier());
return response;
});

const requestOne = ajax.fetch('/foo').then(() => 'completedRequestOne');
const requestTwo = ajax.fetch('/foo').then(() => 'completedRequestTwo');
expect(await requestOne).to.equal('completedRequestOne');
// At this point the response interceptor of requestOne has called setCacheSessionId
expect(await requestTwo).to.equal('completedRequestTwo');

/* Neither call should use the cache. During the first call there is no cache entry for '/foo'.
During the second call there is, but since the first call's injected interceptor has bumped
the cache session ID, it shouldn't use the cached response. */
expect(fetchStub.callCount).to.equal(2);
});

it('does save to the cache when `maxResponseSize` is specified and the response size is within the threshold', async () => {
// Given
newCacheId();
Expand Down
Loading