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

Use a singleton to store the memory cache in an internal WeakMap for the current request #2356

Merged
merged 4 commits into from
Jun 24, 2024
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
16 changes: 5 additions & 11 deletions src/lib/cache/memory.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { CacheBackend, CacheEntry } from './types';
import { CacheBackend } from './types';
import { NON_IMMUTABLE_LOCAL_CACHE_MAX_AGE_SECONDS, isCacheEntryImmutable } from './utils';
import { getGlobalContext } from '../waitUntil';
import { singleton } from '../async';

export const memoryCache: CacheBackend = {
name: 'memory',
Expand Down Expand Up @@ -66,13 +66,7 @@ export const memoryCache: CacheBackend = {
/**
* With next-on-pages, the code seems to be isolated between the middleware and the handler.
* To share the cache between the two, we use a global variable.
* By using a singleton, we ensure that the cache is only created once and stored in the
* current request context.
*/
async function getMemoryCache(): Promise<Map<string, CacheEntry>> {
let globalThisForMemoryCache: any = await getGlobalContext();

if (!globalThisForMemoryCache.gitbookMemoryCache) {
globalThisForMemoryCache.gitbookMemoryCache = new Map();
}

return globalThisForMemoryCache.gitbookMemoryCache;
}
const getMemoryCache = singleton(async () => new Map());
2 changes: 1 addition & 1 deletion src/lib/waitUntil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export async function getGlobalContext(): Promise<object> {

// We lazy-load the next-on-pages package to avoid errors when running tests because of 'server-only'.
const { getOptionalRequestContext } = await import('@cloudflare/next-on-pages');
return getOptionalRequestContext()?.ctx ?? globalThis;
return getOptionalRequestContext()?.cf ?? globalThis;
}

/**
Expand Down
Loading