|
1 | 1 | import type { ComposableCacheEntry, ComposableCacheHandler } from "types/cache";
|
| 2 | +import type { CacheValue } from "types/overrides"; |
2 | 3 | import { writeTags } from "utils/cache";
|
3 | 4 | import { fromReadableStream, toReadableStream } from "utils/stream";
|
4 | 5 | import { debug } from "./logger";
|
5 | 6 |
|
6 |
| -const pendingWritePromiseMap = new Map<string, Promise<ComposableCacheEntry>>(); |
| 7 | +const pendingWritePromiseMap = new Map< |
| 8 | + string, |
| 9 | + Promise<CacheValue<"composable">> |
| 10 | +>(); |
7 | 11 |
|
8 | 12 | export default {
|
9 | 13 | async get(cacheKey: string) {
|
10 | 14 | try {
|
11 | 15 | // We first check if we have a pending write for this cache key
|
12 | 16 | // If we do, we return the pending promise instead of fetching the cache
|
13 | 17 | if (pendingWritePromiseMap.has(cacheKey)) {
|
14 |
| - return pendingWritePromiseMap.get(cacheKey); |
| 18 | + const stored = pendingWritePromiseMap.get(cacheKey); |
| 19 | + if (stored) { |
| 20 | + return stored.then((entry) => ({ |
| 21 | + ...entry, |
| 22 | + value: toReadableStream(entry.value), |
| 23 | + })); |
| 24 | + } |
15 | 25 | }
|
16 | 26 | const result = await globalThis.incrementalCache.get(
|
17 | 27 | cacheKey,
|
@@ -59,16 +69,20 @@ export default {
|
59 | 69 | },
|
60 | 70 |
|
61 | 71 | async set(cacheKey: string, pendingEntry: Promise<ComposableCacheEntry>) {
|
62 |
| - pendingWritePromiseMap.set(cacheKey, pendingEntry); |
63 |
| - const entry = await pendingEntry.finally(() => { |
| 72 | + const promiseEntry = pendingEntry.then(async (entry) => ({ |
| 73 | + ...entry, |
| 74 | + value: await fromReadableStream(entry.value), |
| 75 | + })); |
| 76 | + pendingWritePromiseMap.set(cacheKey, promiseEntry); |
| 77 | + |
| 78 | + const entry = await promiseEntry.finally(() => { |
64 | 79 | pendingWritePromiseMap.delete(cacheKey);
|
65 | 80 | });
|
66 |
| - const valueToStore = await fromReadableStream(entry.value); |
67 | 81 | await globalThis.incrementalCache.set(
|
68 | 82 | cacheKey,
|
69 | 83 | {
|
70 | 84 | ...entry,
|
71 |
| - value: valueToStore, |
| 85 | + value: entry.value, |
72 | 86 | },
|
73 | 87 | "composable",
|
74 | 88 | );
|
|
0 commit comments