11import type { ComposableCacheEntry , ComposableCacheHandler } from "types/cache" ;
2+ import { writeTags } from "utils/cache" ;
23import { fromReadableStream , toReadableStream } from "utils/stream" ;
34import { debug } from "./logger" ;
45
6+ const pendingWritePromiseMap = new Map < string , Promise < ComposableCacheEntry > > ( ) ;
7+
58export default {
69 async get ( cacheKey : string ) {
710 try {
11+ // We first check if we have a pending write for this cache key
12+ // If we do, we return the pending promise instead of fetching the cache
13+ if ( pendingWritePromiseMap . has ( cacheKey ) ) {
14+ return pendingWritePromiseMap . get ( cacheKey ) ;
15+ }
816 const result = await globalThis . incrementalCache . get (
917 cacheKey ,
1018 "composable" ,
@@ -48,7 +56,10 @@ export default {
4856 } ,
4957
5058 async set ( cacheKey : string , pendingEntry : Promise < ComposableCacheEntry > ) {
51- const entry = await pendingEntry ;
59+ pendingWritePromiseMap . set ( cacheKey , pendingEntry ) ;
60+ const entry = await pendingEntry . finally ( ( ) => {
61+ pendingWritePromiseMap . delete ( cacheKey ) ;
62+ } ) ;
5263 const valueToStore = await fromReadableStream ( entry . value ) ;
5364 await globalThis . incrementalCache . set (
5465 cacheKey ,
@@ -62,9 +73,7 @@ export default {
6273 const storedTags = await globalThis . tagCache . getByPath ( cacheKey ) ;
6374 const tagsToWrite = entry . tags . filter ( ( tag ) => ! storedTags . includes ( tag ) ) ;
6475 if ( tagsToWrite . length > 0 ) {
65- await globalThis . tagCache . writeTags (
66- tagsToWrite . map ( ( tag ) => ( { tag, path : cacheKey } ) ) ,
67- ) ;
76+ await writeTags ( tagsToWrite . map ( ( tag ) => ( { tag, path : cacheKey } ) ) ) ;
6877 }
6978 }
7079 } ,
@@ -83,7 +92,7 @@ export default {
8392 } ,
8493 async expireTags ( ...tags : string [ ] ) {
8594 if ( globalThis . tagCache . mode === "nextMode" ) {
86- return globalThis . tagCache . writeTags ( tags ) ;
95+ return writeTags ( tags ) ;
8796 }
8897 const tagCache = globalThis . tagCache ;
8998 const revalidatedAt = Date . now ( ) ;
@@ -104,7 +113,7 @@ export default {
104113 for ( const entry of pathsToUpdate . flat ( ) ) {
105114 setToWrite . add ( entry ) ;
106115 }
107- await globalThis . tagCache . writeTags ( Array . from ( setToWrite ) ) ;
116+ await writeTags ( Array . from ( setToWrite ) ) ;
108117 } ,
109118
110119 // This one is necessary for older versions of next
0 commit comments