@trieb.work/nextjs-turbo-redis-cache 1.3.0 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.github/workflows/ci.yml +3 -2
- package/.github/workflows/release.yml +1 -0
- package/CHANGELOG.md +29 -0
- package/README.md +28 -16
- package/dist/index.d.mts +12 -2
- package/dist/index.d.ts +12 -2
- package/dist/index.js +5 -7
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +5 -7
- package/dist/index.mjs.map +1 -1
- package/package.json +6 -4
- package/src/RedisStringsHandler.ts +65 -57
- package/src/ZodHandler.ts +45 -0
- package/test/integration/{next-app → next-app-15-0-3}/package.json +1 -1
- package/test/integration/next-app-15-3-2/README.md +36 -0
- package/test/integration/next-app-15-3-2/eslint.config.mjs +16 -0
- package/test/integration/next-app-15-3-2/next.config.js +6 -0
- package/test/integration/next-app-15-3-2/package-lock.json +5969 -0
- package/test/integration/next-app-15-3-2/package.json +33 -0
- package/test/integration/next-app-15-3-2/pnpm-lock.yaml +3688 -0
- package/test/integration/next-app-15-3-2/postcss.config.mjs +5 -0
- package/test/integration/next-app-15-3-2/public/file.svg +1 -0
- package/test/integration/next-app-15-3-2/public/globe.svg +1 -0
- package/test/integration/next-app-15-3-2/public/next.svg +1 -0
- package/test/integration/next-app-15-3-2/public/vercel.svg +1 -0
- package/test/integration/next-app-15-3-2/public/window.svg +1 -0
- package/test/integration/next-app-15-3-2/src/app/api/cached-static-fetch/route.ts +18 -0
- package/test/integration/next-app-15-3-2/src/app/api/nested-fetch-in-api-route/revalidated-fetch/route.ts +27 -0
- package/test/integration/next-app-15-3-2/src/app/api/revalidatePath/route.ts +15 -0
- package/test/integration/next-app-15-3-2/src/app/api/revalidateTag/route.ts +15 -0
- package/test/integration/next-app-15-3-2/src/app/api/revalidated-fetch/route.ts +17 -0
- package/test/integration/next-app-15-3-2/src/app/api/uncached-fetch/route.ts +15 -0
- package/test/integration/next-app-15-3-2/src/app/globals.css +26 -0
- package/test/integration/next-app-15-3-2/src/app/layout.tsx +59 -0
- package/test/integration/next-app-15-3-2/src/app/page.tsx +755 -0
- package/test/integration/next-app-15-3-2/src/app/pages/cached-static-fetch/default--force-dynamic-page/page.tsx +19 -0
- package/test/integration/next-app-15-3-2/src/app/pages/cached-static-fetch/revalidate15--default-page/page.tsx +34 -0
- package/test/integration/next-app-15-3-2/src/app/pages/cached-static-fetch/revalidate15--force-dynamic-page/page.tsx +25 -0
- package/test/integration/next-app-15-3-2/src/app/pages/no-fetch/default-page/page.tsx +55 -0
- package/test/integration/next-app-15-3-2/src/app/pages/revalidated-fetch/default--force-dynamic-page/page.tsx +19 -0
- package/test/integration/next-app-15-3-2/src/app/pages/revalidated-fetch/revalidate15--default-page/page.tsx +35 -0
- package/test/integration/next-app-15-3-2/src/app/pages/revalidated-fetch/revalidate15--force-dynamic-page/page.tsx +25 -0
- package/test/integration/next-app-15-3-2/src/app/pages/uncached-fetch/default--force-dynamic-page/page.tsx +19 -0
- package/test/integration/next-app-15-3-2/src/app/pages/uncached-fetch/revalidate15--default-page/page.tsx +32 -0
- package/test/integration/next-app-15-3-2/src/app/pages/uncached-fetch/revalidate15--force-dynamic-page/page.tsx +25 -0
- package/test/integration/next-app-15-3-2/src/app/revalidation-interface.tsx +267 -0
- package/test/integration/next-app-15-3-2/tsconfig.json +27 -0
- package/test/integration/nextjs-cache-handler.integration.test.ts +29 -10
- /package/test/integration/{next-app → next-app-15-0-3}/README.md +0 -0
- /package/test/integration/{next-app → next-app-15-0-3}/eslint.config.mjs +0 -0
- /package/test/integration/{next-app → next-app-15-0-3}/next.config.js +0 -0
- /package/test/integration/{next-app → next-app-15-0-3}/package-lock.json +0 -0
- /package/test/integration/{next-app → next-app-15-0-3}/pnpm-lock.yaml +0 -0
- /package/test/integration/{next-app → next-app-15-0-3}/postcss.config.mjs +0 -0
- /package/test/integration/{next-app → next-app-15-0-3}/public/file.svg +0 -0
- /package/test/integration/{next-app → next-app-15-0-3}/public/globe.svg +0 -0
- /package/test/integration/{next-app → next-app-15-0-3}/public/next.svg +0 -0
- /package/test/integration/{next-app → next-app-15-0-3}/public/vercel.svg +0 -0
- /package/test/integration/{next-app → next-app-15-0-3}/public/window.svg +0 -0
- /package/test/integration/{next-app → next-app-15-0-3}/src/app/api/cached-static-fetch/route.ts +0 -0
- /package/test/integration/{next-app → next-app-15-0-3}/src/app/api/nested-fetch-in-api-route/revalidated-fetch/route.ts +0 -0
- /package/test/integration/{next-app → next-app-15-0-3}/src/app/api/revalidatePath/route.ts +0 -0
- /package/test/integration/{next-app → next-app-15-0-3}/src/app/api/revalidateTag/route.ts +0 -0
- /package/test/integration/{next-app → next-app-15-0-3}/src/app/api/revalidated-fetch/route.ts +0 -0
- /package/test/integration/{next-app → next-app-15-0-3}/src/app/api/uncached-fetch/route.ts +0 -0
- /package/test/integration/{next-app → next-app-15-0-3}/src/app/globals.css +0 -0
- /package/test/integration/{next-app → next-app-15-0-3}/src/app/layout.tsx +0 -0
- /package/test/integration/{next-app → next-app-15-0-3}/src/app/page.tsx +0 -0
- /package/test/integration/{next-app → next-app-15-0-3}/src/app/pages/cached-static-fetch/default--force-dynamic-page/page.tsx +0 -0
- /package/test/integration/{next-app → next-app-15-0-3}/src/app/pages/cached-static-fetch/revalidate15--default-page/page.tsx +0 -0
- /package/test/integration/{next-app → next-app-15-0-3}/src/app/pages/cached-static-fetch/revalidate15--force-dynamic-page/page.tsx +0 -0
- /package/test/integration/{next-app → next-app-15-0-3}/src/app/pages/no-fetch/default-page/page.tsx +0 -0
- /package/test/integration/{next-app → next-app-15-0-3}/src/app/pages/revalidated-fetch/default--force-dynamic-page/page.tsx +0 -0
- /package/test/integration/{next-app → next-app-15-0-3}/src/app/pages/revalidated-fetch/revalidate15--default-page/page.tsx +0 -0
- /package/test/integration/{next-app → next-app-15-0-3}/src/app/pages/revalidated-fetch/revalidate15--force-dynamic-page/page.tsx +0 -0
- /package/test/integration/{next-app → next-app-15-0-3}/src/app/pages/uncached-fetch/default--force-dynamic-page/page.tsx +0 -0
- /package/test/integration/{next-app → next-app-15-0-3}/src/app/pages/uncached-fetch/revalidate15--default-page/page.tsx +0 -0
- /package/test/integration/{next-app → next-app-15-0-3}/src/app/pages/uncached-fetch/revalidate15--force-dynamic-page/page.tsx +0 -0
- /package/test/integration/{next-app → next-app-15-0-3}/src/app/revalidation-interface.tsx +0 -0
- /package/test/integration/{next-app → next-app-15-0-3}/tsconfig.json +0 -0
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/RedisStringsHandler.ts","../src/utils/debug.ts","../src/SyncedMap.ts","../src/DeduplicatedRequestHandler.ts","../src/utils/json.ts","../src/CachedHandler.ts","../src/index.ts"],"sourcesContent":["import { commandOptions, createClient } from 'redis';\nimport { SyncedMap } from './SyncedMap';\nimport { DeduplicatedRequestHandler } from './DeduplicatedRequestHandler';\nimport { debug } from './utils/debug';\nimport { bufferReviver, bufferReplacer } from './utils/json';\n\nexport type CommandOptions = ReturnType<typeof commandOptions>;\nexport type Client = ReturnType<typeof createClient>;\n\nexport type CacheEntry = {\n value: unknown;\n lastModified: number;\n tags: string[];\n};\n\nexport type CreateRedisStringsHandlerOptions = {\n /** Redis database number to use. Uses DB 0 for production, DB 1 otherwise\n * @default process.env.VERCEL_ENV === 'production' ? 0 : 1\n */\n database?: number;\n /** Prefix added to all Redis keys\n * @default process.env.VERCEL_URL || 'UNDEFINED_URL_'\n */\n keyPrefix?: string;\n /** Timeout in milliseconds for Redis operations\n * @default 5000\n */\n timeoutMs?: number;\n /** Number of entries to query in one batch during full sync of shared tags hash map\n * @default 250\n */\n revalidateTagQuerySize?: number;\n /** Key used to store shared tags hash map in Redis\n * @default '__sharedTags__'\n */\n sharedTagsKey?: string;\n /** Average interval in milliseconds between tag map full re-syncs\n * @default 3600000 (1 hour)\n */\n avgResyncIntervalMs?: number;\n /** Enable deduplication of Redis get requests via internal in-memory cache\n * @default true\n */\n redisGetDeduplication?: boolean;\n /** Time in milliseconds to cache Redis get results in memory. Set this to 0 to disable in-memory caching completely\n * @default 10000\n */\n inMemoryCachingTime?: number;\n /** Default stale age in seconds for cached items\n * @default 1209600 (14 days)\n */\n defaultStaleAge?: number;\n /** Function to calculate expire age (redis TTL value) from stale age\n * @default Production: staleAge * 2, Other: staleAge * 1.2\n */\n estimateExpireAge?: (staleAge: number) => number;\n};\n\n// Identifier prefix used by Next.js to mark automatically generated cache tags\n// These tags are created internally by Next.js for route-based invalidation\nconst NEXT_CACHE_IMPLICIT_TAG_ID = '_N_T_';\n\n// Redis key used to store a map of tags and their last revalidation timestamps\n// This helps track when specific tags were last invalidated\nconst REVALIDATED_TAGS_KEY = '__revalidated_tags__';\n\nexport function getTimeoutRedisCommandOptions(\n timeoutMs: number,\n): CommandOptions {\n return commandOptions({ signal: AbortSignal.timeout(timeoutMs) });\n}\n\nexport default class RedisStringsHandler {\n private client: Client;\n private sharedTagsMap: SyncedMap<string[]>;\n private revalidatedTagsMap: SyncedMap<number>;\n private inMemoryDeduplicationCache: SyncedMap<\n Promise<ReturnType<Client['get']>>\n >;\n private redisGet: Client['get'];\n private redisDeduplicationHandler: DeduplicatedRequestHandler<\n Client['get'],\n string | Buffer | null\n >;\n private deduplicatedRedisGet: (key: string) => Client['get'];\n private timeoutMs: number;\n private keyPrefix: string;\n private redisGetDeduplication: boolean;\n private inMemoryCachingTime: number;\n private defaultStaleAge: number;\n private estimateExpireAge: (staleAge: number) => number;\n\n constructor({\n database = process.env.VERCEL_ENV === 'production' ? 0 : 1,\n keyPrefix = process.env.VERCEL_URL || 'UNDEFINED_URL_',\n sharedTagsKey = '__sharedTags__',\n timeoutMs = 5_000,\n revalidateTagQuerySize = 250,\n avgResyncIntervalMs = 60 * 60 * 1_000,\n redisGetDeduplication = true,\n inMemoryCachingTime = 10_000,\n defaultStaleAge = 60 * 60 * 24 * 14,\n estimateExpireAge = (staleAge) =>\n process.env.VERCEL_ENV === 'production' ? staleAge * 2 : staleAge * 1.2,\n }: CreateRedisStringsHandlerOptions) {\n this.keyPrefix = keyPrefix;\n this.timeoutMs = timeoutMs;\n this.redisGetDeduplication = redisGetDeduplication;\n this.inMemoryCachingTime = inMemoryCachingTime;\n this.defaultStaleAge = defaultStaleAge;\n this.estimateExpireAge = estimateExpireAge;\n\n try {\n this.client = createClient({\n ...(database !== 0 ? { database } : {}),\n url: process.env.REDISHOST\n ? `redis://${process.env.REDISHOST}:${process.env.REDISPORT}`\n : 'redis://localhost:6379',\n });\n\n this.client.on('error', (error) => {\n console.error('Redis client error', error);\n });\n\n this.client\n .connect()\n .then(() => {\n console.info('Redis client connected.');\n })\n .catch(() => {\n this.client.connect().catch((error) => {\n console.error('Failed to connect Redis client:', error);\n this.client.disconnect();\n throw error;\n });\n });\n } catch (error: unknown) {\n console.error('Failed to initialize Redis client');\n throw error;\n }\n\n const filterKeys = (key: string): boolean =>\n key !== REVALIDATED_TAGS_KEY && key !== sharedTagsKey;\n\n this.sharedTagsMap = new SyncedMap<string[]>({\n client: this.client,\n keyPrefix,\n redisKey: sharedTagsKey,\n database,\n timeoutMs,\n querySize: revalidateTagQuerySize,\n filterKeys,\n resyncIntervalMs:\n avgResyncIntervalMs -\n avgResyncIntervalMs / 10 +\n Math.random() * (avgResyncIntervalMs / 10),\n });\n\n this.revalidatedTagsMap = new SyncedMap<number>({\n client: this.client,\n keyPrefix,\n redisKey: REVALIDATED_TAGS_KEY,\n database,\n timeoutMs,\n querySize: revalidateTagQuerySize,\n filterKeys,\n resyncIntervalMs:\n avgResyncIntervalMs +\n avgResyncIntervalMs / 10 +\n Math.random() * (avgResyncIntervalMs / 10),\n });\n\n this.inMemoryDeduplicationCache = new SyncedMap({\n client: this.client,\n keyPrefix,\n redisKey: 'inMemoryDeduplicationCache',\n database,\n timeoutMs,\n querySize: revalidateTagQuerySize,\n filterKeys,\n customizedSync: {\n withoutRedisHashmap: true,\n withoutSetSync: true,\n },\n });\n\n const redisGet: Client['get'] = this.client.get.bind(this.client);\n this.redisDeduplicationHandler = new DeduplicatedRequestHandler(\n redisGet,\n inMemoryCachingTime,\n this.inMemoryDeduplicationCache,\n );\n this.redisGet = redisGet;\n this.deduplicatedRedisGet =\n this.redisDeduplicationHandler.deduplicatedFunction;\n }\n\n resetRequestCache(): void { }\n\n private async assertClientIsReady(): Promise<void> {\n await Promise.all([\n this.sharedTagsMap.waitUntilReady(),\n this.revalidatedTagsMap.waitUntilReady(),\n ]);\n if (!this.client.isReady) {\n throw new Error('Redis client is not ready yet or connection is lost.');\n }\n }\n\n public async get(\n key: string,\n ctx:\n | {\n kind: 'APP_ROUTE' | 'APP_PAGE';\n isRoutePPREnabled: boolean;\n isFallback: boolean;\n }\n | {\n kind: 'FETCH';\n revalidate: number;\n fetchUrl: string;\n fetchIdx: number;\n tags: string[];\n softTags: string[];\n isFallback: boolean;\n },\n ): Promise<CacheEntry | null> {\n if (\n ctx.kind !== 'APP_ROUTE' &&\n ctx.kind !== 'APP_PAGE' &&\n ctx.kind !== 'FETCH'\n ) {\n console.warn(\n 'RedisStringsHandler.get() called with',\n key,\n ctx,\n ' this cache handler is only designed and tested for kind APP_ROUTE and APP_PAGE and not for kind ',\n (ctx as { kind: string })?.kind,\n );\n }\n\n debug('green', 'RedisStringsHandler.get() called with', key, ctx);\n await this.assertClientIsReady();\n\n const clientGet = this.redisGetDeduplication\n ? this.deduplicatedRedisGet(key)\n : this.redisGet;\n const serializedCacheEntry = await clientGet(\n getTimeoutRedisCommandOptions(this.timeoutMs),\n this.keyPrefix + key,\n );\n\n debug(\n 'green',\n 'RedisStringsHandler.get() finished with result (serializedCacheEntry)',\n serializedCacheEntry?.substring(0, 200),\n );\n\n if (!serializedCacheEntry) {\n return null;\n }\n\n const cacheEntry: CacheEntry | null = JSON.parse(\n serializedCacheEntry,\n bufferReviver,\n );\n\n debug(\n 'green',\n 'RedisStringsHandler.get() finished with result (cacheEntry)',\n JSON.stringify(cacheEntry).substring(0, 200),\n );\n\n if (!cacheEntry) {\n return null;\n }\n\n if (!cacheEntry?.tags) {\n console.warn(\n 'RedisStringsHandler.get() called with',\n key,\n ctx,\n 'cacheEntry is mall formed (missing tags)',\n );\n }\n if (!cacheEntry?.value) {\n console.warn(\n 'RedisStringsHandler.get() called with',\n key,\n ctx,\n 'cacheEntry is mall formed (missing value)',\n );\n }\n if (!cacheEntry?.lastModified) {\n console.warn(\n 'RedisStringsHandler.get() called with',\n key,\n ctx,\n 'cacheEntry is mall formed (missing lastModified)',\n );\n }\n\n if (ctx.kind === 'FETCH') {\n const combinedTags = new Set([\n ...(ctx?.softTags || []),\n ...(ctx?.tags || []),\n ]);\n\n if (combinedTags.size === 0) {\n return cacheEntry;\n }\n\n // INFO: implicit tags (revalidate of nested fetch in api route/page on revalidatePath call of the page/api route). See revalidateTag() for more information\n //\n // This code checks if any of the cache tags associated with this entry (normally the internal tag of the parent page/api route containing the fetch request)\n // have been revalidated since the entry was last modified. If any tag was revalidated more recently than the entry's\n // lastModified timestamp, then the cached content is considered stale (therefore return null) and should be removed.\n for (const tag of combinedTags) {\n // Get the last revalidation time for this tag from our revalidatedTagsMap\n const revalidationTime = this.revalidatedTagsMap.get(tag);\n\n // If we have a revalidation time for this tag and it's more recent than when\n // this cache entry was last modified, the entry is stale\n if (revalidationTime && revalidationTime > cacheEntry.lastModified) {\n const redisKey = this.keyPrefix + key;\n\n // We don't await this cleanup since it can happen asynchronously in the background.\n // The cache entry is already considered invalid at this point.\n this.client\n .unlink(getTimeoutRedisCommandOptions(this.timeoutMs), redisKey)\n .catch((err) => {\n // If the first unlink fails, log the error and try one more time\n console.error(\n 'Error occurred while unlinking stale data. Retrying now. Error was:',\n err,\n );\n this.client.unlink(\n getTimeoutRedisCommandOptions(this.timeoutMs),\n redisKey,\n );\n })\n .finally(async () => {\n // Clean up our tag tracking maps after the Redis key is removed\n await this.sharedTagsMap.delete(key);\n await this.revalidatedTagsMap.delete(tag);\n });\n\n debug(\n 'green',\n 'RedisStringsHandler.get() found revalidation time for tag. Cache entry is stale and will be deleted and \"null\" will be returned.',\n tag,\n redisKey,\n revalidationTime,\n cacheEntry,\n );\n\n // Return null to indicate no valid cache entry was found\n return null;\n }\n }\n }\n\n return cacheEntry;\n }\n public async set(\n key: string,\n data:\n | {\n kind: 'APP_PAGE';\n status: number;\n headers: {\n 'x-nextjs-stale-time': string; // timestamp in ms\n 'x-next-cache-tags': string; // comma separated paths (tags)\n };\n html: string;\n rscData: Buffer;\n segmentData: unknown;\n postboned: unknown;\n }\n | {\n kind: 'APP_ROUTE';\n status: number;\n headers: {\n 'cache-control'?: string;\n 'x-nextjs-stale-time': string; // timestamp in ms\n 'x-next-cache-tags': string; // comma separated paths (tags)\n };\n body: Buffer;\n }\n | {\n kind: 'FETCH';\n data: {\n headers: Record<string, string>;\n body: string; // base64 encoded\n status: number;\n url: string;\n };\n revalidate: number | false;\n },\n ctx: {\n revalidate: number | false;\n isRoutePPREnabled: boolean;\n isFallback: boolean;\n tags?: string[];\n },\n ) {\n if (\n data.kind !== 'APP_ROUTE' &&\n data.kind !== 'APP_PAGE' &&\n data.kind !== 'FETCH'\n ) {\n console.warn(\n 'RedisStringsHandler.set() called with',\n key,\n ctx,\n data,\n ' this cache handler is only designed and tested for kind APP_ROUTE and APP_PAGE and not for kind ',\n (data as { kind: string })?.kind,\n );\n }\n\n await this.assertClientIsReady();\n\n if (data.kind === 'APP_PAGE' || data.kind === 'APP_ROUTE') {\n const tags = data.headers['x-next-cache-tags']?.split(',');\n ctx.tags = [...(ctx.tags || []), ...(tags || [])];\n }\n\n // Constructing and serializing the value for storing it in redis\n const cacheEntry: CacheEntry = {\n lastModified: Date.now(),\n tags: ctx?.tags || [],\n value: data,\n };\n const serializedCacheEntry = JSON.stringify(cacheEntry, bufferReplacer);\n\n // pre seed data into deduplicated get client. This will reduce redis load by not requesting\n // the same value from redis which was just set.\n if (this.redisGetDeduplication) {\n this.redisDeduplicationHandler.seedRequestReturn(\n key,\n serializedCacheEntry,\n );\n }\n\n // Constructing the expire time for the cache entry\n const expireAt =\n ctx.revalidate &&\n Number.isSafeInteger(ctx.revalidate) &&\n ctx.revalidate > 0\n ? this.estimateExpireAge(ctx.revalidate)\n : this.estimateExpireAge(this.defaultStaleAge);\n\n // Setting the cache entry in redis\n const options = getTimeoutRedisCommandOptions(this.timeoutMs);\n const setOperation: Promise<string | null> = this.client.set(\n options,\n this.keyPrefix + key,\n serializedCacheEntry,\n {\n EX: expireAt,\n },\n );\n\n debug(\n 'blue',\n 'RedisStringsHandler.set() will set the following serializedCacheEntry',\n this.keyPrefix,\n key,\n data,\n ctx,\n serializedCacheEntry?.substring(0, 200),\n expireAt,\n );\n\n // Setting the tags for the cache entry in the sharedTagsMap (locally stored hashmap synced via redis)\n let setTagsOperation: Promise<void> | undefined;\n if (ctx.tags && ctx.tags.length > 0) {\n const currentTags = this.sharedTagsMap.get(key);\n const currentIsSameAsNew =\n currentTags?.length === ctx.tags.length &&\n currentTags.every((v) => ctx.tags!.includes(v)) &&\n ctx.tags.every((v) => currentTags.includes(v));\n\n if (!currentIsSameAsNew) {\n setTagsOperation = this.sharedTagsMap.set(\n key,\n structuredClone(ctx.tags) as string[],\n );\n }\n }\n\n debug(\n 'blue',\n 'RedisStringsHandler.set() will set the following sharedTagsMap',\n key,\n ctx.tags as string[],\n );\n\n await Promise.all([setOperation, setTagsOperation]);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public async revalidateTag(tagOrTags: string | string[], ...rest: any[]) {\n debug(\n 'red',\n 'RedisStringsHandler.revalidateTag() called with',\n tagOrTags,\n rest,\n );\n const tags = new Set([tagOrTags || []].flat());\n await this.assertClientIsReady();\n\n // find all keys that are related to this tag\n const keysToDelete: Set<string> = new Set();\n\n for (const tag of tags) {\n // INFO: implicit tags (revalidate of nested fetch in api route/page on revalidatePath call of the page/api route)\n //\n // Invalidation logic for fetch requests that are related to a invalidated page.\n // revalidateTag is called for the page tag (_N_T_...) and the fetch request needs to be invalidated as well\n // unfortunately this is not possible since the revalidateTag is not called with any data that would allow us to find the cache entry of the fetch request\n // in case of a fetch request get method call, the get method of the cache handler is called with some information about the pages/routes the fetch request is inside\n // therefore we only mark the page/route as stale here (with help of the revalidatedTagsMap) \n // and delete the cache entry of the fetch request on the next request to the get function\n if (tag.startsWith(NEXT_CACHE_IMPLICIT_TAG_ID)) {\n const now = Date.now();\n debug(\n 'red',\n 'RedisStringsHandler.revalidateTag() set revalidation time for tag',\n tag,\n 'to',\n now,\n );\n await this.revalidatedTagsMap.set(tag, now);\n }\n }\n\n // Scan the whole sharedTagsMap for keys that are dependent on any of the revalidated tags\n for (const [key, sharedTags] of this.sharedTagsMap.entries()) {\n if (sharedTags.some((tag) => tags.has(tag))) {\n keysToDelete.add(key);\n }\n }\n\n debug(\n 'red',\n 'RedisStringsHandler.revalidateTag() found',\n keysToDelete,\n 'keys to delete',\n );\n\n // exit early if no keys are related to this tag\n if (keysToDelete.size === 0) {\n return;\n }\n\n // prepare deletion of all keys in redis that are related to this tag\n const redisKeys = Array.from(keysToDelete);\n const fullRedisKeys = redisKeys.map((key) => this.keyPrefix + key);\n const options = getTimeoutRedisCommandOptions(this.timeoutMs);\n const deleteKeysOperation = this.client.unlink(options, fullRedisKeys);\n\n // also delete entries from in-memory deduplication cache if they get revalidated\n if (this.redisGetDeduplication && this.inMemoryCachingTime > 0) {\n for (const key of keysToDelete) {\n this.inMemoryDeduplicationCache.delete(key);\n }\n }\n\n // prepare deletion of entries from shared tags map if they get revalidated so that the map will not grow indefinitely\n const deleteTagsOperation = this.sharedTagsMap.delete(redisKeys);\n\n // execute keys and tag maps deletion\n await Promise.all([deleteKeysOperation, deleteTagsOperation]);\n debug(\n 'red',\n 'RedisStringsHandler.revalidateTag() finished delete operations',\n );\n }\n}\n","export function debug(\n color:\n | 'red'\n | 'blue'\n | 'green'\n | 'yellow'\n | 'cyan'\n | 'white'\n | 'none' = 'none',\n ...args: unknown[]\n): void {\n const colorCode = {\n red: '\\x1b[31m',\n blue: '\\x1b[34m',\n green: '\\x1b[32m',\n yellow: '\\x1b[33m',\n cyan: '\\x1b[36m',\n white: '\\x1b[37m',\n none: '',\n };\n if (process.env.DEBUG_CACHE_HANDLER) {\n console.log(colorCode[color], 'DEBUG CACHE HANDLER: ', ...args);\n }\n}\n\nexport function debugVerbose(color: string, ...args: unknown[]) {\n if (process.env.DEBUG_CACHE_HANDLER_VERBOSE_VERBOSE) {\n console.log('\\x1b[35m', 'DEBUG SYNCED MAP: ', ...args);\n }\n}\n","// SyncedMap.ts\nimport { Client, getTimeoutRedisCommandOptions } from './RedisStringsHandler';\nimport { debugVerbose, debug } from './utils/debug';\n\ntype CustomizedSync = {\n withoutRedisHashmap?: boolean;\n withoutSetSync?: boolean;\n};\n\ntype SyncedMapOptions = {\n client: Client;\n keyPrefix: string;\n redisKey: string; // Redis Hash key\n database: number;\n timeoutMs: number;\n querySize: number;\n filterKeys: (key: string) => boolean;\n resyncIntervalMs?: number;\n customizedSync?: CustomizedSync;\n};\n\nexport type SyncMessage<V> = {\n type: 'insert' | 'delete';\n key?: string;\n value?: V;\n keys?: string[];\n};\n\nconst SYNC_CHANNEL_SUFFIX = ':sync-channel:';\nexport class SyncedMap<V> {\n private client: Client;\n private subscriberClient: Client;\n private map: Map<string, V>;\n private keyPrefix: string;\n private syncChannel: string;\n private redisKey: string;\n private database: number;\n private timeoutMs: number;\n private querySize: number;\n private filterKeys: (key: string) => boolean;\n private resyncIntervalMs?: number;\n private customizedSync?: CustomizedSync;\n\n private setupLock: Promise<void>;\n private setupLockResolve!: () => void;\n\n constructor(options: SyncedMapOptions) {\n this.client = options.client;\n this.keyPrefix = options.keyPrefix;\n this.redisKey = options.redisKey;\n this.syncChannel = `${options.keyPrefix}${SYNC_CHANNEL_SUFFIX}${options.redisKey}`;\n this.database = options.database;\n this.timeoutMs = options.timeoutMs;\n this.querySize = options.querySize;\n this.filterKeys = options.filterKeys;\n this.resyncIntervalMs = options.resyncIntervalMs;\n this.customizedSync = options.customizedSync;\n\n this.map = new Map<string, V>();\n this.subscriberClient = this.client.duplicate();\n this.setupLock = new Promise<void>((resolve) => {\n this.setupLockResolve = resolve;\n });\n\n this.setup().catch((error) => {\n console.error('Failed to setup SyncedMap:', error);\n throw error;\n });\n }\n\n private async setup() {\n let setupPromises: Promise<void>[] = [];\n if (!this.customizedSync?.withoutRedisHashmap) {\n setupPromises.push(this.initialSync());\n this.setupPeriodicResync();\n }\n setupPromises.push(this.setupPubSub());\n await Promise.all(setupPromises);\n this.setupLockResolve();\n }\n\n private async initialSync() {\n let cursor = 0;\n const hScanOptions = { COUNT: this.querySize };\n\n try {\n do {\n const remoteItems = await this.client.hScan(\n getTimeoutRedisCommandOptions(this.timeoutMs),\n this.keyPrefix + this.redisKey,\n cursor,\n hScanOptions,\n );\n for (const { field, value } of remoteItems.tuples) {\n if (this.filterKeys(field)) {\n const parsedValue = JSON.parse(value);\n this.map.set(field, parsedValue);\n }\n }\n cursor = remoteItems.cursor;\n } while (cursor !== 0);\n\n // Clean up keys not in Redis\n await this.cleanupKeysNotInRedis();\n } catch (error) {\n console.error('Error during initial sync:', error);\n throw error;\n }\n }\n\n private async cleanupKeysNotInRedis() {\n let cursor = 0;\n const scanOptions = { COUNT: this.querySize, MATCH: `${this.keyPrefix}*` };\n let remoteKeys: string[] = [];\n try {\n do {\n const remoteKeysPortion = await this.client.scan(\n getTimeoutRedisCommandOptions(this.timeoutMs),\n cursor,\n scanOptions,\n );\n remoteKeys = remoteKeys.concat(remoteKeysPortion.keys);\n cursor = remoteKeysPortion.cursor;\n } while (cursor !== 0);\n\n const remoteKeysSet = new Set(\n remoteKeys.map((key) => key.substring(this.keyPrefix.length)),\n );\n\n const keysToDelete: string[] = [];\n for (const key of this.map.keys()) {\n const keyStr = key as unknown as string;\n if (!remoteKeysSet.has(keyStr) && this.filterKeys(keyStr)) {\n keysToDelete.push(keyStr);\n }\n }\n\n if (keysToDelete.length > 0) {\n await this.delete(keysToDelete);\n }\n } catch (error) {\n console.error('Error during cleanup of keys not in Redis:', error);\n throw error;\n }\n }\n\n private setupPeriodicResync() {\n if (this.resyncIntervalMs && this.resyncIntervalMs > 0) {\n setInterval(() => {\n this.initialSync().catch((error) => {\n console.error('Error during periodic resync:', error);\n });\n }, this.resyncIntervalMs);\n }\n }\n\n private async setupPubSub() {\n const syncHandler = async (message: string) => {\n const syncMessage: SyncMessage<V> = JSON.parse(message);\n if (syncMessage.type === 'insert') {\n if (syncMessage.key !== undefined && syncMessage.value !== undefined) {\n this.map.set(syncMessage.key, syncMessage.value);\n }\n } else if (syncMessage.type === 'delete') {\n if (syncMessage.keys) {\n for (const key of syncMessage.keys) {\n this.map.delete(key);\n }\n }\n }\n };\n\n const keyEventHandler = async (key: string, message: string) => {\n debug(\n 'yellow',\n 'SyncedMap.keyEventHandler() called with message',\n this.redisKey,\n message,\n key,\n );\n // const key = message;\n if (key.startsWith(this.keyPrefix)) {\n const keyInMap = key.substring(this.keyPrefix.length);\n if (this.filterKeys(keyInMap)) {\n debugVerbose(\n 'SyncedMap.keyEventHandler() key matches filter and will be deleted',\n this.redisKey,\n message,\n key,\n );\n await this.delete(keyInMap, true);\n }\n } else {\n debugVerbose(\n 'SyncedMap.keyEventHandler() key does not have prefix',\n this.redisKey,\n message,\n key,\n );\n }\n };\n\n try {\n await this.subscriberClient.connect().catch(async () => {\n await this.subscriberClient.connect();\n });\n\n // Check if keyspace event configuration is set correctly\n const keyspaceEventConfig = (\n await this.subscriberClient.configGet('notify-keyspace-events')\n )?.['notify-keyspace-events'];\n if (!keyspaceEventConfig.includes('E')) {\n throw new Error(\n \"Keyspace event configuration has to include 'E' for Keyevent events, published with __keyevent@<db>__ prefix. We recommend to set it to 'Exe' like so `redis-cli -h localhost config set notify-keyspace-events Exe`\",\n );\n }\n if (\n !keyspaceEventConfig.includes('A') &&\n !(\n keyspaceEventConfig.includes('x') && keyspaceEventConfig.includes('e')\n )\n ) {\n throw new Error(\n \"Keyspace event configuration has to include 'A' or 'x' and 'e' for expired and evicted events. We recommend to set it to 'Exe' like so `redis-cli -h localhost config set notify-keyspace-events Exe`\",\n );\n }\n\n await Promise.all([\n // We use a custom channel for insert/delete For the following reason:\n // With custom channel we can delete multiple entries in one message. If we would listen to unlink / del we\n // could get thousands of messages for one revalidateTag (For example revalidateTag(\"algolia\") would send an enormous amount of network packages)\n // Also we can send the value in the message for insert\n this.subscriberClient.subscribe(this.syncChannel, syncHandler),\n // Subscribe to Redis keyevent notifications for evicted and expired keys\n this.subscriberClient.subscribe(\n `__keyevent@${this.database}__:evicted`,\n keyEventHandler,\n ),\n this.subscriberClient.subscribe(\n `__keyevent@${this.database}__:expired`,\n keyEventHandler,\n ),\n ]);\n\n // Error handling for reconnection\n this.subscriberClient.on('error', async (err) => {\n console.error('Subscriber client error:', err);\n try {\n await this.subscriberClient.quit();\n this.subscriberClient = this.client.duplicate();\n await this.setupPubSub();\n } catch (reconnectError) {\n console.error(\n 'Failed to reconnect subscriber client:',\n reconnectError,\n );\n }\n });\n } catch (error) {\n console.error('Error setting up pub/sub client:', error);\n throw error;\n }\n }\n\n public async waitUntilReady() {\n await this.setupLock;\n }\n\n public get(key: string): V | undefined {\n debugVerbose(\n 'SyncedMap.get() called with key',\n key,\n JSON.stringify(this.map.get(key))?.substring(0, 100),\n );\n return this.map.get(key);\n }\n\n public async set(key: string, value: V): Promise<void> {\n debugVerbose(\n 'SyncedMap.set() called with key',\n key,\n JSON.stringify(value)?.substring(0, 100),\n );\n this.map.set(key, value);\n const operations = [];\n\n // This is needed if we only want to sync delete commands. This is especially useful for non serializable data like a promise map\n if (this.customizedSync?.withoutSetSync) {\n return;\n }\n if (!this.customizedSync?.withoutRedisHashmap) {\n const options = getTimeoutRedisCommandOptions(this.timeoutMs);\n operations.push(\n this.client.hSet(\n options,\n this.keyPrefix + this.redisKey,\n key as unknown as string,\n JSON.stringify(value),\n ),\n );\n }\n\n const insertMessage: SyncMessage<V> = {\n type: 'insert',\n key: key as unknown as string,\n value,\n };\n operations.push(\n this.client.publish(this.syncChannel, JSON.stringify(insertMessage)),\n );\n await Promise.all(operations);\n }\n\n // /api/revalidated-fetch\n // true\n\n public async delete(\n keys: string[] | string,\n withoutSyncMessage = false,\n ): Promise<void> {\n debugVerbose(\n 'SyncedMap.delete() called with keys',\n this.redisKey,\n keys,\n withoutSyncMessage,\n );\n\n const keysArray = Array.isArray(keys) ? keys : [keys];\n const operations = [];\n\n for (const key of keysArray) {\n this.map.delete(key);\n }\n\n if (!this.customizedSync?.withoutRedisHashmap) {\n const options = getTimeoutRedisCommandOptions(this.timeoutMs);\n operations.push(\n this.client.hDel(options, this.keyPrefix + this.redisKey, keysArray),\n );\n }\n\n if (!withoutSyncMessage) {\n const deletionMessage: SyncMessage<V> = {\n type: 'delete',\n keys: keysArray,\n };\n operations.push(\n this.client.publish(this.syncChannel, JSON.stringify(deletionMessage)),\n );\n }\n\n await Promise.all(operations);\n debugVerbose(\n 'SyncedMap.delete() finished operations',\n this.redisKey,\n keys,\n operations.length,\n );\n }\n\n public has(key: string): boolean {\n return this.map.has(key);\n }\n\n public entries(): IterableIterator<[string, V]> {\n return this.map.entries();\n }\n}\n","import { debugVerbose } from './utils/debug';\nimport { SyncedMap } from './SyncedMap';\nexport class DeduplicatedRequestHandler<\n T extends (...args: [never, never]) => Promise<K>,\n K,\n> {\n private inMemoryDeduplicationCache: SyncedMap<Promise<K>>;\n private cachingTimeMs: number;\n private fn: T;\n\n constructor(\n fn: T,\n cachingTimeMs: number,\n inMemoryDeduplicationCache: SyncedMap<Promise<K>>,\n ) {\n this.fn = fn;\n this.cachingTimeMs = cachingTimeMs;\n this.inMemoryDeduplicationCache = inMemoryDeduplicationCache;\n }\n\n // Method to manually seed a result into the cache\n seedRequestReturn(key: string, value: K): void {\n const resultPromise = new Promise<K>((res) => res(value));\n this.inMemoryDeduplicationCache.set(key, resultPromise);\n\n debugVerbose(\n 'DeduplicatedRequestHandler.seedRequestReturn() seeded result ',\n key,\n (value as string).substring(0, 200),\n );\n\n setTimeout(() => {\n this.inMemoryDeduplicationCache.delete(key);\n }, this.cachingTimeMs);\n }\n\n // Method to handle deduplicated requests\n deduplicatedFunction = (key: string): T => {\n debugVerbose(\n 'DeduplicatedRequestHandler.deduplicatedFunction() called with',\n key,\n );\n //eslint-disable-next-line @typescript-eslint/no-this-alias\n const self = this;\n const dedupedFn = async (...args: [never, never]): Promise<K> => {\n // If there's already a pending request with the same key, return it\n debugVerbose(\n 'DeduplicatedRequestHandler.deduplicatedFunction().dedupedFn called with',\n key,\n );\n if (\n self.inMemoryDeduplicationCache &&\n self.inMemoryDeduplicationCache.has(key)\n ) {\n debugVerbose(\n 'DeduplicatedRequestHandler.deduplicatedFunction().dedupedFn ',\n key,\n 'found key in inMemoryDeduplicationCache',\n );\n const res = await self.inMemoryDeduplicationCache\n .get(key)!\n .then((v) => structuredClone(v));\n debugVerbose(\n 'DeduplicatedRequestHandler.deduplicatedFunction().dedupedFn ',\n key,\n 'found key in inMemoryDeduplicationCache and served result from there',\n JSON.stringify(res).substring(0, 200),\n );\n return res;\n }\n\n // If no pending request, call the original function and store the promise\n const promise = self.fn(...args);\n self.inMemoryDeduplicationCache.set(key, promise);\n\n debugVerbose(\n 'DeduplicatedRequestHandler.deduplicatedFunction().dedupedFn ',\n key,\n 'did not found key in inMemoryDeduplicationCache. Setting it now and waiting for promise to resolve',\n );\n\n try {\n const ts = performance.now();\n const result = await promise;\n debugVerbose(\n 'DeduplicatedRequestHandler.deduplicatedFunction().dedupedFn ',\n key,\n 'promise resolved (in ',\n performance.now() - ts,\n 'ms). Returning result',\n JSON.stringify(result).substring(0, 200),\n );\n return structuredClone(result);\n } finally {\n // Once the promise is resolved/rejected and caching timeout is over, remove it from the map\n setTimeout(() => {\n debugVerbose(\n 'DeduplicatedRequestHandler.deduplicatedFunction().dedupedFn ',\n key,\n 'deleting key from inMemoryDeduplicationCache after ',\n self.cachingTimeMs,\n 'ms',\n );\n self.inMemoryDeduplicationCache.delete(key);\n }, self.cachingTimeMs);\n }\n };\n return dedupedFn as T;\n };\n}\n","// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function bufferReviver(_: string, value: any): any {\n if (value && typeof value === 'object' && typeof value.$binary === 'string') {\n return Buffer.from(value.$binary, 'base64');\n }\n return value;\n}\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function bufferReplacer(_: string, value: any): any {\n if (Buffer.isBuffer(value)) {\n return {\n $binary: value.toString('base64'),\n };\n }\n if (\n value &&\n typeof value === 'object' &&\n value?.type === 'Buffer' &&\n Array.isArray(value.data)\n ) {\n return {\n $binary: Buffer.from(value.data).toString('base64'),\n };\n }\n return value;\n}\n","import RedisStringsHandler, {\n CreateRedisStringsHandlerOptions,\n} from './RedisStringsHandler';\nimport { debugVerbose } from './utils/debug';\n\nlet cachedHandler: RedisStringsHandler;\n\nexport default class CachedHandler {\n constructor(options: CreateRedisStringsHandlerOptions) {\n if (!cachedHandler) {\n console.log('created cached handler');\n cachedHandler = new RedisStringsHandler(options);\n }\n }\n get(\n ...args: Parameters<RedisStringsHandler['get']>\n ): ReturnType<RedisStringsHandler['get']> {\n debugVerbose('CachedHandler.get called with', args);\n return cachedHandler.get(...args);\n }\n set(\n ...args: Parameters<RedisStringsHandler['set']>\n ): ReturnType<RedisStringsHandler['set']> {\n debugVerbose('CachedHandler.set called with', args);\n return cachedHandler.set(...args);\n }\n revalidateTag(\n ...args: Parameters<RedisStringsHandler['revalidateTag']>\n ): ReturnType<RedisStringsHandler['revalidateTag']> {\n debugVerbose('CachedHandler.revalidateTag called with', args);\n return cachedHandler.revalidateTag(...args);\n }\n resetRequestCache(\n ...args: Parameters<RedisStringsHandler['resetRequestCache']>\n ): ReturnType<RedisStringsHandler['resetRequestCache']> {\n // debug(\"CachedHandler.resetRequestCache called with\", args);\n return cachedHandler.resetRequestCache(...args);\n }\n}\n","import CachedHandler from './CachedHandler';\nexport default CachedHandler;\nimport RedisStringsHandler from './RedisStringsHandler';\nexport { RedisStringsHandler };\n"],"mappings":";AAAA,SAAS,gBAAgB,oBA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mB,CAAC;AAC5D;AAAA,MACE;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;;;AK/jBA,IAAI;AAEJ,IAAqB,gBAArB,MAAmC;AAAA,EACjC,YAAY,SAA2C;AACrD,QAAI,CAAC,eAAe;AAClB,cAAQ,IAAI,wBAAwB;AACpC,sBAAgB,IAAI,oBAAoB,OAAO;AAAA,IACjD;AAAA,EACF;AAAA,EACA,OACK,MACqC;AACxC,iBAAa,iCAAiC,IAAI;AAClD,WAAO,cAAc,IAAI,GAAG,IAAI;AAAA,EAClC;AAAA,EACA,OACK,MACqC;AACxC,iBAAa,iCAAiC,IAAI;AAClD,WAAO,cAAc,IAAI,GAAG,IAAI;AAAA,EAClC;AAAA,EACA,iBACK,MAC+C;AAClD,iBAAa,2CAA2C,IAAI;AAC5D,WAAO,cAAc,cAAc,GAAG,IAAI;AAAA,EAC5C;AAAA,EACA,qBACK,MACmD;AAEtD,WAAO,cAAc,kBAAkB,GAAG,IAAI;AAAA,EAChD;AACF;;;ACrCA,IAAO,gBAAQ;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/RedisStringsHandler.ts","../src/utils/debug.ts","../src/SyncedMap.ts","../src/DeduplicatedRequestHandler.ts","../src/utils/json.ts","../src/CachedHandler.ts","../src/index.ts"],"sourcesContent":["import { commandOptions, createClient } from 'redis';\nimport { SyncedMap } from './SyncedMap';\nimport { DeduplicatedRequestHandler } from './DeduplicatedRequestHandler';\nimport { debug } from './utils/debug';\nimport { bufferReviver, bufferReplacer } from './utils/json';\n\nexport type CommandOptions = ReturnType<typeof commandOptions>;\nexport type Client = ReturnType<typeof createClient>;\n\nexport type CacheEntry = {\n value: unknown;\n lastModified: number;\n tags: string[];\n};\n\nexport type CreateRedisStringsHandlerOptions = {\n /** Redis redis_url to use.\n * @default process.env.REDIS_URL? process.env.REDIS_URL : process.env.REDISHOST\n ? `redis://${process.env.REDISHOST}:${process.env.REDISPORT}`\n : 'redis://localhost:6379'\n */\n redis_url?: string;\n /** Redis database number to use. Uses DB 0 for production, DB 1 otherwise\n * @default process.env.VERCEL_ENV === 'production' ? 0 : 1\n */\n database?: number;\n /** Prefix added to all Redis keys\n * @default process.env.VERCEL_URL || 'UNDEFINED_URL_'\n */\n keyPrefix?: string;\n /** Timeout in milliseconds for Redis operations\n * @default 5000\n */\n timeoutMs?: number;\n /** Number of entries to query in one batch during full sync of shared tags hash map\n * @default 250\n */\n revalidateTagQuerySize?: number;\n /** Key used to store shared tags hash map in Redis\n * @default '__sharedTags__'\n */\n sharedTagsKey?: string;\n /** Average interval in milliseconds between tag map full re-syncs\n * @default 3600000 (1 hour)\n */\n avgResyncIntervalMs?: number;\n /** Enable deduplication of Redis get requests via internal in-memory cache\n * @default true\n */\n redisGetDeduplication?: boolean;\n /** Time in milliseconds to cache Redis get results in memory. Set this to 0 to disable in-memory caching completely\n * @default 10000\n */\n inMemoryCachingTime?: number;\n /** Default stale age in seconds for cached items\n * @default 1209600 (14 days)\n */\n defaultStaleAge?: number;\n /** Function to calculate expire age (redis TTL value) from stale age\n * @default Production: staleAge * 2, Other: staleAge * 1.2\n */\n estimateExpireAge?: (staleAge: number) => number;\n};\n\n// Identifier prefix used by Next.js to mark automatically generated cache tags\n// These tags are created internally by Next.js for route-based invalidation\nconst NEXT_CACHE_IMPLICIT_TAG_ID = '_N_T_';\n\n// Redis key used to store a map of tags and their last revalidation timestamps\n// This helps track when specific tags were last invalidated\nconst REVALIDATED_TAGS_KEY = '__revalidated_tags__';\n\nexport function getTimeoutRedisCommandOptions(\n timeoutMs: number,\n): CommandOptions {\n return commandOptions({ signal: AbortSignal.timeout(timeoutMs) });\n}\n\nexport default class RedisStringsHandler {\n private client: Client;\n private sharedTagsMap: SyncedMap<string[]>;\n private revalidatedTagsMap: SyncedMap<number>;\n private inMemoryDeduplicationCache: SyncedMap<\n Promise<ReturnType<Client['get']>>\n >;\n private redisGet: Client['get'];\n private redisDeduplicationHandler: DeduplicatedRequestHandler<\n Client['get'],\n string | Buffer | null\n >;\n private deduplicatedRedisGet: (key: string) => Client['get'];\n private timeoutMs: number;\n private keyPrefix: string;\n private redisGetDeduplication: boolean;\n private inMemoryCachingTime: number;\n private defaultStaleAge: number;\n private estimateExpireAge: (staleAge: number) => number;\n\n constructor({\n redis_url = process.env.REDIS_URL\n ? process.env.REDIS_URL\n : process.env.REDISHOST\n ? `redis://${process.env.REDISHOST}:${process.env.REDISPORT}`\n : 'redis://localhost:6379',\n database = process.env.VERCEL_ENV === 'production' ? 0 : 1,\n keyPrefix = process.env.VERCEL_URL || 'UNDEFINED_URL_',\n sharedTagsKey = '__sharedTags__',\n timeoutMs = 5_000,\n revalidateTagQuerySize = 250,\n avgResyncIntervalMs = 60 * 60 * 1_000,\n redisGetDeduplication = true,\n inMemoryCachingTime = 10_000,\n defaultStaleAge = 60 * 60 * 24 * 14,\n estimateExpireAge = (staleAge) =>\n process.env.VERCEL_ENV === 'production' ? staleAge * 2 : staleAge * 1.2,\n }: CreateRedisStringsHandlerOptions) {\n this.keyPrefix = keyPrefix;\n this.timeoutMs = timeoutMs;\n this.redisGetDeduplication = redisGetDeduplication;\n this.inMemoryCachingTime = inMemoryCachingTime;\n this.defaultStaleAge = defaultStaleAge;\n this.estimateExpireAge = estimateExpireAge;\n\n try {\n this.client = createClient({\n ...(database !== 0 ? { database } : {}),\n url: redis_url,\n });\n\n this.client.on('error', (error) => {\n console.error('Redis client error', error);\n });\n\n this.client\n .connect()\n .then(() => {\n console.info('Redis client connected.');\n })\n .catch(() => {\n this.client.connect().catch((error) => {\n console.error('Failed to connect Redis client:', error);\n this.client.disconnect();\n throw error;\n });\n });\n } catch (error: unknown) {\n console.error('Failed to initialize Redis client');\n throw error;\n }\n\n const filterKeys = (key: string): boolean =>\n key !== REVALIDATED_TAGS_KEY && key !== sharedTagsKey;\n\n this.sharedTagsMap = new SyncedMap<string[]>({\n client: this.client,\n keyPrefix,\n redisKey: sharedTagsKey,\n database,\n timeoutMs,\n querySize: revalidateTagQuerySize,\n filterKeys,\n resyncIntervalMs:\n avgResyncIntervalMs -\n avgResyncIntervalMs / 10 +\n Math.random() * (avgResyncIntervalMs / 10),\n });\n\n this.revalidatedTagsMap = new SyncedMap<number>({\n client: this.client,\n keyPrefix,\n redisKey: REVALIDATED_TAGS_KEY,\n database,\n timeoutMs,\n querySize: revalidateTagQuerySize,\n filterKeys,\n resyncIntervalMs:\n avgResyncIntervalMs +\n avgResyncIntervalMs / 10 +\n Math.random() * (avgResyncIntervalMs / 10),\n });\n\n this.inMemoryDeduplicationCache = new SyncedMap({\n client: this.client,\n keyPrefix,\n redisKey: 'inMemoryDeduplicationCache',\n database,\n timeoutMs,\n querySize: revalidateTagQuerySize,\n filterKeys,\n customizedSync: {\n withoutRedisHashmap: true,\n withoutSetSync: true,\n },\n });\n\n const redisGet: Client['get'] = this.client.get.bind(this.client);\n this.redisDeduplicationHandler = new DeduplicatedRequestHandler(\n redisGet,\n inMemoryCachingTime,\n this.inMemoryDeduplicationCache,\n );\n this.redisGet = redisGet;\n this.deduplicatedRedisGet =\n this.redisDeduplicationHandler.deduplicatedFunction;\n }\n\n resetRequestCache(): void {}\n\n private async assertClientIsReady(): Promise<void> {\n await Promise.all([\n this.sharedTagsMap.waitUntilReady(),\n this.revalidatedTagsMap.waitUntilReady(),\n ]);\n if (!this.client.isReady) {\n throw new Error('Redis client is not ready yet or connection is lost.');\n }\n }\n\n public async get(\n key: string,\n ctx:\n | {\n kind: 'APP_ROUTE' | 'APP_PAGE';\n isRoutePPREnabled: boolean;\n isFallback: boolean;\n }\n | {\n kind: 'FETCH';\n revalidate: number;\n fetchUrl: string;\n fetchIdx: number;\n tags: string[];\n softTags: string[];\n isFallback: boolean;\n },\n ): Promise<CacheEntry | null> {\n if (\n ctx.kind !== 'APP_ROUTE' &&\n ctx.kind !== 'APP_PAGE' &&\n ctx.kind !== 'FETCH'\n ) {\n console.warn(\n 'RedisStringsHandler.get() called with',\n key,\n ctx,\n ' this cache handler is only designed and tested for kind APP_ROUTE and APP_PAGE and not for kind ',\n (ctx as { kind: string })?.kind,\n );\n }\n\n debug('green', 'RedisStringsHandler.get() called with', key, ctx);\n await this.assertClientIsReady();\n\n const clientGet = this.redisGetDeduplication\n ? this.deduplicatedRedisGet(key)\n : this.redisGet;\n const serializedCacheEntry = await clientGet(\n getTimeoutRedisCommandOptions(this.timeoutMs),\n this.keyPrefix + key,\n );\n\n debug(\n 'green',\n 'RedisStringsHandler.get() finished with result (serializedCacheEntry)',\n serializedCacheEntry?.substring(0, 200),\n );\n\n if (!serializedCacheEntry) {\n return null;\n }\n\n const cacheEntry: CacheEntry | null = JSON.parse(\n serializedCacheEntry,\n bufferReviver,\n );\n\n debug(\n 'green',\n 'RedisStringsHandler.get() finished with result (cacheEntry)',\n JSON.stringify(cacheEntry).substring(0, 200),\n );\n\n if (!cacheEntry) {\n return null;\n }\n\n if (!cacheEntry?.tags) {\n console.warn(\n 'RedisStringsHandler.get() called with',\n key,\n ctx,\n 'cacheEntry is mall formed (missing tags)',\n );\n }\n if (!cacheEntry?.value) {\n console.warn(\n 'RedisStringsHandler.get() called with',\n key,\n ctx,\n 'cacheEntry is mall formed (missing value)',\n );\n }\n if (!cacheEntry?.lastModified) {\n console.warn(\n 'RedisStringsHandler.get() called with',\n key,\n ctx,\n 'cacheEntry is mall formed (missing lastModified)',\n );\n }\n\n if (ctx.kind === 'FETCH') {\n const combinedTags = new Set([\n ...(ctx?.softTags || []),\n ...(ctx?.tags || []),\n ]);\n\n if (combinedTags.size === 0) {\n return cacheEntry;\n }\n\n // INFO: implicit tags (revalidate of nested fetch in api route/page on revalidatePath call of the page/api route). See revalidateTag() for more information\n //\n // This code checks if any of the cache tags associated with this entry (normally the internal tag of the parent page/api route containing the fetch request)\n // have been revalidated since the entry was last modified. If any tag was revalidated more recently than the entry's\n // lastModified timestamp, then the cached content is considered stale (therefore return null) and should be removed.\n for (const tag of combinedTags) {\n // Get the last revalidation time for this tag from our revalidatedTagsMap\n const revalidationTime = this.revalidatedTagsMap.get(tag);\n\n // If we have a revalidation time for this tag and it's more recent than when\n // this cache entry was last modified, the entry is stale\n if (revalidationTime && revalidationTime > cacheEntry.lastModified) {\n const redisKey = this.keyPrefix + key;\n\n // We don't await this cleanup since it can happen asynchronously in the background.\n // The cache entry is already considered invalid at this point.\n this.client\n .unlink(getTimeoutRedisCommandOptions(this.timeoutMs), redisKey)\n .catch((err) => {\n // If the first unlink fails, only log the error\n // Never implement a retry here as the cache entry will be updated directly after this get request\n console.error(\n 'Error occurred while unlinking stale data. Error was:',\n err,\n );\n })\n .finally(async () => {\n // Clean up our tag tracking maps after the Redis key is removed\n await this.sharedTagsMap.delete(key);\n await this.revalidatedTagsMap.delete(tag);\n });\n\n debug(\n 'green',\n 'RedisStringsHandler.get() found revalidation time for tag. Cache entry is stale and will be deleted and \"null\" will be returned.',\n tag,\n redisKey,\n revalidationTime,\n cacheEntry,\n );\n\n // Return null to indicate no valid cache entry was found\n return null;\n }\n }\n }\n\n return cacheEntry;\n }\n public async set(\n key: string,\n data:\n | {\n kind: 'APP_PAGE';\n status: number;\n headers: {\n 'x-nextjs-stale-time': string; // timestamp in ms\n 'x-next-cache-tags': string; // comma separated paths (tags)\n };\n html: string;\n rscData: Buffer;\n segmentData: unknown;\n postboned: unknown;\n }\n | {\n kind: 'APP_ROUTE';\n status: number;\n headers: {\n 'cache-control'?: string;\n 'x-nextjs-stale-time': string; // timestamp in ms\n 'x-next-cache-tags': string; // comma separated paths (tags)\n };\n body: Buffer;\n }\n | {\n kind: 'FETCH';\n data: {\n headers: Record<string, string>;\n body: string; // base64 encoded\n status: number;\n url: string;\n };\n revalidate: number | false;\n },\n ctx: {\n isRoutePPREnabled: boolean;\n isFallback: boolean;\n tags?: string[];\n // Different versions of Next.js use different arguments for the same functionality\n revalidate?: number | false; // Version 15.0.3\n cacheControl?: { revalidate: 5; expire: undefined }; // Version 15.0.3\n },\n ) {\n if (\n data.kind !== 'APP_ROUTE' &&\n data.kind !== 'APP_PAGE' &&\n data.kind !== 'FETCH'\n ) {\n console.warn(\n 'RedisStringsHandler.set() called with',\n key,\n ctx,\n data,\n ' this cache handler is only designed and tested for kind APP_ROUTE and APP_PAGE and not for kind ',\n (data as { kind: string })?.kind,\n );\n }\n\n await this.assertClientIsReady();\n\n if (data.kind === 'APP_PAGE' || data.kind === 'APP_ROUTE') {\n const tags = data.headers['x-next-cache-tags']?.split(',');\n ctx.tags = [...(ctx.tags || []), ...(tags || [])];\n }\n\n // Constructing and serializing the value for storing it in redis\n const cacheEntry: CacheEntry = {\n lastModified: Date.now(),\n tags: ctx?.tags || [],\n value: data,\n };\n const serializedCacheEntry = JSON.stringify(cacheEntry, bufferReplacer);\n\n // pre seed data into deduplicated get client. This will reduce redis load by not requesting\n // the same value from redis which was just set.\n if (this.redisGetDeduplication) {\n this.redisDeduplicationHandler.seedRequestReturn(\n key,\n serializedCacheEntry,\n );\n }\n\n // TODO: implement expiration based on cacheControl.expire argument, -> probably relevant for cacheLife and \"use cache\" etc.: https://nextjs.org/docs/app/api-reference/functions/cacheLife\n // Constructing the expire time for the cache entry\n const revalidate = ctx.revalidate || ctx.cacheControl?.revalidate;\n const expireAt =\n revalidate && Number.isSafeInteger(revalidate) && revalidate > 0\n ? this.estimateExpireAge(revalidate)\n : this.estimateExpireAge(this.defaultStaleAge);\n\n // Setting the cache entry in redis\n const options = getTimeoutRedisCommandOptions(this.timeoutMs);\n const setOperation: Promise<string | null> = this.client.set(\n options,\n this.keyPrefix + key,\n serializedCacheEntry,\n {\n EX: expireAt,\n },\n );\n\n debug(\n 'blue',\n 'RedisStringsHandler.set() will set the following serializedCacheEntry',\n this.keyPrefix,\n key,\n data,\n ctx,\n serializedCacheEntry?.substring(0, 200),\n expireAt,\n );\n\n // Setting the tags for the cache entry in the sharedTagsMap (locally stored hashmap synced via redis)\n let setTagsOperation: Promise<void> | undefined;\n if (ctx.tags && ctx.tags.length > 0) {\n const currentTags = this.sharedTagsMap.get(key);\n const currentIsSameAsNew =\n currentTags?.length === ctx.tags.length &&\n currentTags.every((v) => ctx.tags!.includes(v)) &&\n ctx.tags.every((v) => currentTags.includes(v));\n\n if (!currentIsSameAsNew) {\n setTagsOperation = this.sharedTagsMap.set(\n key,\n structuredClone(ctx.tags) as string[],\n );\n }\n }\n\n debug(\n 'blue',\n 'RedisStringsHandler.set() will set the following sharedTagsMap',\n key,\n ctx.tags as string[],\n );\n\n await Promise.all([setOperation, setTagsOperation]);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public async revalidateTag(tagOrTags: string | string[], ...rest: any[]) {\n debug(\n 'red',\n 'RedisStringsHandler.revalidateTag() called with',\n tagOrTags,\n rest,\n );\n const tags = new Set([tagOrTags || []].flat());\n await this.assertClientIsReady();\n\n // find all keys that are related to this tag\n const keysToDelete: Set<string> = new Set();\n\n for (const tag of tags) {\n // INFO: implicit tags (revalidate of nested fetch in api route/page on revalidatePath call of the page/api route)\n //\n // Invalidation logic for fetch requests that are related to a invalidated page.\n // revalidateTag is called for the page tag (_N_T_...) and the fetch request needs to be invalidated as well\n // unfortunately this is not possible since the revalidateTag is not called with any data that would allow us to find the cache entry of the fetch request\n // in case of a fetch request get method call, the get method of the cache handler is called with some information about the pages/routes the fetch request is inside\n // therefore we only mark the page/route as stale here (with help of the revalidatedTagsMap)\n // and delete the cache entry of the fetch request on the next request to the get function\n if (tag.startsWith(NEXT_CACHE_IMPLICIT_TAG_ID)) {\n const now = Date.now();\n debug(\n 'red',\n 'RedisStringsHandler.revalidateTag() set revalidation time for tag',\n tag,\n 'to',\n now,\n );\n await this.revalidatedTagsMap.set(tag, now);\n }\n }\n\n // Scan the whole sharedTagsMap for keys that are dependent on any of the revalidated tags\n for (const [key, sharedTags] of this.sharedTagsMap.entries()) {\n if (sharedTags.some((tag) => tags.has(tag))) {\n keysToDelete.add(key);\n }\n }\n\n debug(\n 'red',\n 'RedisStringsHandler.revalidateTag() found',\n keysToDelete,\n 'keys to delete',\n );\n\n // exit early if no keys are related to this tag\n if (keysToDelete.size === 0) {\n return;\n }\n\n // prepare deletion of all keys in redis that are related to this tag\n const redisKeys = Array.from(keysToDelete);\n const fullRedisKeys = redisKeys.map((key) => this.keyPrefix + key);\n const options = getTimeoutRedisCommandOptions(this.timeoutMs);\n const deleteKeysOperation = this.client.unlink(options, fullRedisKeys);\n\n // also delete entries from in-memory deduplication cache if they get revalidated\n if (this.redisGetDeduplication && this.inMemoryCachingTime > 0) {\n for (const key of keysToDelete) {\n this.inMemoryDeduplicationCache.delete(key);\n }\n }\n\n // prepare deletion of entries from shared tags map if they get revalidated so that the map will not grow indefinitely\n const deleteTagsOperation = this.sharedTagsMap.delete(redisKeys);\n\n // execute keys and tag maps deletion\n await Promise.all([deleteKeysOperation, deleteTagsOperation]);\n debug(\n 'red',\n 'RedisStringsHandler.revalidateTag() finished delete operations',\n );\n }\n}\n","export function debug(\n color:\n | 'red'\n | 'blue'\n | 'green'\n | 'yellow'\n | 'cyan'\n | 'white'\n | 'none' = 'none',\n ...args: unknown[]\n): void {\n const colorCode = {\n red: '\\x1b[31m',\n blue: '\\x1b[34m',\n green: '\\x1b[32m',\n yellow: '\\x1b[33m',\n cyan: '\\x1b[36m',\n white: '\\x1b[37m',\n none: '',\n };\n if (process.env.DEBUG_CACHE_HANDLER) {\n console.log(colorCode[color], 'DEBUG CACHE HANDLER: ', ...args);\n }\n}\n\nexport function debugVerbose(color: string, ...args: unknown[]) {\n if (process.env.DEBUG_CACHE_HANDLER_VERBOSE_VERBOSE) {\n console.log('\\x1b[35m', 'DEBUG SYNCED MAP: ', ...args);\n }\n}\n","// SyncedMap.ts\nimport { Client, getTimeoutRedisCommandOptions } from './RedisStringsHandler';\nimport { debugVerbose, debug } from './utils/debug';\n\ntype CustomizedSync = {\n withoutRedisHashmap?: boolean;\n withoutSetSync?: boolean;\n};\n\ntype SyncedMapOptions = {\n client: Client;\n keyPrefix: string;\n redisKey: string; // Redis Hash key\n database: number;\n timeoutMs: number;\n querySize: number;\n filterKeys: (key: string) => boolean;\n resyncIntervalMs?: number;\n customizedSync?: CustomizedSync;\n};\n\nexport type SyncMessage<V> = {\n type: 'insert' | 'delete';\n key?: string;\n value?: V;\n keys?: string[];\n};\n\nconst SYNC_CHANNEL_SUFFIX = ':sync-channel:';\nexport class SyncedMap<V> {\n private client: Client;\n private subscriberClient: Client;\n private map: Map<string, V>;\n private keyPrefix: string;\n private syncChannel: string;\n private redisKey: string;\n private database: number;\n private timeoutMs: number;\n private querySize: number;\n private filterKeys: (key: string) => boolean;\n private resyncIntervalMs?: number;\n private customizedSync?: CustomizedSync;\n\n private setupLock: Promise<void>;\n private setupLockResolve!: () => void;\n\n constructor(options: SyncedMapOptions) {\n this.client = options.client;\n this.keyPrefix = options.keyPrefix;\n this.redisKey = options.redisKey;\n this.syncChannel = `${options.keyPrefix}${SYNC_CHANNEL_SUFFIX}${options.redisKey}`;\n this.database = options.database;\n this.timeoutMs = options.timeoutMs;\n this.querySize = options.querySize;\n this.filterKeys = options.filterKeys;\n this.resyncIntervalMs = options.resyncIntervalMs;\n this.customizedSync = options.customizedSync;\n\n this.map = new Map<string, V>();\n this.subscriberClient = this.client.duplicate();\n this.setupLock = new Promise<void>((resolve) => {\n this.setupLockResolve = resolve;\n });\n\n this.setup().catch((error) => {\n console.error('Failed to setup SyncedMap:', error);\n throw error;\n });\n }\n\n private async setup() {\n let setupPromises: Promise<void>[] = [];\n if (!this.customizedSync?.withoutRedisHashmap) {\n setupPromises.push(this.initialSync());\n this.setupPeriodicResync();\n }\n setupPromises.push(this.setupPubSub());\n await Promise.all(setupPromises);\n this.setupLockResolve();\n }\n\n private async initialSync() {\n let cursor = 0;\n const hScanOptions = { COUNT: this.querySize };\n\n try {\n do {\n const remoteItems = await this.client.hScan(\n getTimeoutRedisCommandOptions(this.timeoutMs),\n this.keyPrefix + this.redisKey,\n cursor,\n hScanOptions,\n );\n for (const { field, value } of remoteItems.tuples) {\n if (this.filterKeys(field)) {\n const parsedValue = JSON.parse(value);\n this.map.set(field, parsedValue);\n }\n }\n cursor = remoteItems.cursor;\n } while (cursor !== 0);\n\n // Clean up keys not in Redis\n await this.cleanupKeysNotInRedis();\n } catch (error) {\n console.error('Error during initial sync:', error);\n throw error;\n }\n }\n\n private async cleanupKeysNotInRedis() {\n let cursor = 0;\n const scanOptions = { COUNT: this.querySize, MATCH: `${this.keyPrefix}*` };\n let remoteKeys: string[] = [];\n try {\n do {\n const remoteKeysPortion = await this.client.scan(\n getTimeoutRedisCommandOptions(this.timeoutMs),\n cursor,\n scanOptions,\n );\n remoteKeys = remoteKeys.concat(remoteKeysPortion.keys);\n cursor = remoteKeysPortion.cursor;\n } while (cursor !== 0);\n\n const remoteKeysSet = new Set(\n remoteKeys.map((key) => key.substring(this.keyPrefix.length)),\n );\n\n const keysToDelete: string[] = [];\n for (const key of this.map.keys()) {\n const keyStr = key as unknown as string;\n if (!remoteKeysSet.has(keyStr) && this.filterKeys(keyStr)) {\n keysToDelete.push(keyStr);\n }\n }\n\n if (keysToDelete.length > 0) {\n await this.delete(keysToDelete);\n }\n } catch (error) {\n console.error('Error during cleanup of keys not in Redis:', error);\n throw error;\n }\n }\n\n private setupPeriodicResync() {\n if (this.resyncIntervalMs && this.resyncIntervalMs > 0) {\n setInterval(() => {\n this.initialSync().catch((error) => {\n console.error('Error during periodic resync:', error);\n });\n }, this.resyncIntervalMs);\n }\n }\n\n private async setupPubSub() {\n const syncHandler = async (message: string) => {\n const syncMessage: SyncMessage<V> = JSON.parse(message);\n if (syncMessage.type === 'insert') {\n if (syncMessage.key !== undefined && syncMessage.value !== undefined) {\n this.map.set(syncMessage.key, syncMessage.value);\n }\n } else if (syncMessage.type === 'delete') {\n if (syncMessage.keys) {\n for (const key of syncMessage.keys) {\n this.map.delete(key);\n }\n }\n }\n };\n\n const keyEventHandler = async (key: string, message: string) => {\n debug(\n 'yellow',\n 'SyncedMap.keyEventHandler() called with message',\n this.redisKey,\n message,\n key,\n );\n // const key = message;\n if (key.startsWith(this.keyPrefix)) {\n const keyInMap = key.substring(this.keyPrefix.length);\n if (this.filterKeys(keyInMap)) {\n debugVerbose(\n 'SyncedMap.keyEventHandler() key matches filter and will be deleted',\n this.redisKey,\n message,\n key,\n );\n await this.delete(keyInMap, true);\n }\n } else {\n debugVerbose(\n 'SyncedMap.keyEventHandler() key does not have prefix',\n this.redisKey,\n message,\n key,\n );\n }\n };\n\n try {\n await this.subscriberClient.connect().catch(async () => {\n await this.subscriberClient.connect();\n });\n\n // Check if keyspace event configuration is set correctly\n const keyspaceEventConfig = (\n await this.subscriberClient.configGet('notify-keyspace-events')\n )?.['notify-keyspace-events'];\n if (!keyspaceEventConfig.includes('E')) {\n throw new Error(\n \"Keyspace event configuration has to include 'E' for Keyevent events, published with __keyevent@<db>__ prefix. We recommend to set it to 'Exe' like so `redis-cli -h localhost config set notify-keyspace-events Exe`\",\n );\n }\n if (\n !keyspaceEventConfig.includes('A') &&\n !(\n keyspaceEventConfig.includes('x') && keyspaceEventConfig.includes('e')\n )\n ) {\n throw new Error(\n \"Keyspace event configuration has to include 'A' or 'x' and 'e' for expired and evicted events. We recommend to set it to 'Exe' like so `redis-cli -h localhost config set notify-keyspace-events Exe`\",\n );\n }\n\n await Promise.all([\n // We use a custom channel for insert/delete For the following reason:\n // With custom channel we can delete multiple entries in one message. If we would listen to unlink / del we\n // could get thousands of messages for one revalidateTag (For example revalidateTag(\"algolia\") would send an enormous amount of network packages)\n // Also we can send the value in the message for insert\n this.subscriberClient.subscribe(this.syncChannel, syncHandler),\n // Subscribe to Redis keyevent notifications for evicted and expired keys\n this.subscriberClient.subscribe(\n `__keyevent@${this.database}__:evicted`,\n keyEventHandler,\n ),\n this.subscriberClient.subscribe(\n `__keyevent@${this.database}__:expired`,\n keyEventHandler,\n ),\n ]);\n\n // Error handling for reconnection\n this.subscriberClient.on('error', async (err) => {\n console.error('Subscriber client error:', err);\n try {\n await this.subscriberClient.quit();\n this.subscriberClient = this.client.duplicate();\n await this.setupPubSub();\n } catch (reconnectError) {\n console.error(\n 'Failed to reconnect subscriber client:',\n reconnectError,\n );\n }\n });\n } catch (error) {\n console.error('Error setting up pub/sub client:', error);\n throw error;\n }\n }\n\n public async waitUntilReady() {\n await this.setupLock;\n }\n\n public get(key: string): V | undefined {\n debugVerbose(\n 'SyncedMap.get() called with key',\n key,\n JSON.stringify(this.map.get(key))?.substring(0, 100),\n );\n return this.map.get(key);\n }\n\n public async set(key: string, value: V): Promise<void> {\n debugVerbose(\n 'SyncedMap.set() called with key',\n key,\n JSON.stringify(value)?.substring(0, 100),\n );\n this.map.set(key, value);\n const operations = [];\n\n // This is needed if we only want to sync delete commands. This is especially useful for non serializable data like a promise map\n if (this.customizedSync?.withoutSetSync) {\n return;\n }\n if (!this.customizedSync?.withoutRedisHashmap) {\n const options = getTimeoutRedisCommandOptions(this.timeoutMs);\n operations.push(\n this.client.hSet(\n options,\n this.keyPrefix + this.redisKey,\n key as unknown as string,\n JSON.stringify(value),\n ),\n );\n }\n\n const insertMessage: SyncMessage<V> = {\n type: 'insert',\n key: key as unknown as string,\n value,\n };\n operations.push(\n this.client.publish(this.syncChannel, JSON.stringify(insertMessage)),\n );\n await Promise.all(operations);\n }\n\n // /api/revalidated-fetch\n // true\n\n public async delete(\n keys: string[] | string,\n withoutSyncMessage = false,\n ): Promise<void> {\n debugVerbose(\n 'SyncedMap.delete() called with keys',\n this.redisKey,\n keys,\n withoutSyncMessage,\n );\n\n const keysArray = Array.isArray(keys) ? keys : [keys];\n const operations = [];\n\n for (const key of keysArray) {\n this.map.delete(key);\n }\n\n if (!this.customizedSync?.withoutRedisHashmap) {\n const options = getTimeoutRedisCommandOptions(this.timeoutMs);\n operations.push(\n this.client.hDel(options, this.keyPrefix + this.redisKey, keysArray),\n );\n }\n\n if (!withoutSyncMessage) {\n const deletionMessage: SyncMessage<V> = {\n type: 'delete',\n keys: keysArray,\n };\n operations.push(\n this.client.publish(this.syncChannel, JSON.stringify(deletionMessage)),\n );\n }\n\n await Promise.all(operations);\n debugVerbose(\n 'SyncedMap.delete() finished operations',\n this.redisKey,\n keys,\n operations.length,\n );\n }\n\n public has(key: string): boolean {\n return this.map.has(key);\n }\n\n public entries(): IterableIterator<[string, V]> {\n return this.map.entries();\n }\n}\n","import { debugVerbose } from './utils/debug';\nimport { SyncedMap } from './SyncedMap';\nexport class DeduplicatedRequestHandler<\n T extends (...args: [never, never]) => Promise<K>,\n K,\n> {\n private inMemoryDeduplicationCache: SyncedMap<Promise<K>>;\n private cachingTimeMs: number;\n private fn: T;\n\n constructor(\n fn: T,\n cachingTimeMs: number,\n inMemoryDeduplicationCache: SyncedMap<Promise<K>>,\n ) {\n this.fn = fn;\n this.cachingTimeMs = cachingTimeMs;\n this.inMemoryDeduplicationCache = inMemoryDeduplicationCache;\n }\n\n // Method to manually seed a result into the cache\n seedRequestReturn(key: string, value: K): void {\n const resultPromise = new Promise<K>((res) => res(value));\n this.inMemoryDeduplicationCache.set(key, resultPromise);\n\n debugVerbose(\n 'DeduplicatedRequestHandler.seedRequestReturn() seeded result ',\n key,\n (value as string).substring(0, 200),\n );\n\n setTimeout(() => {\n this.inMemoryDeduplicationCache.delete(key);\n }, this.cachingTimeMs);\n }\n\n // Method to handle deduplicated requests\n deduplicatedFunction = (key: string): T => {\n debugVerbose(\n 'DeduplicatedRequestHandler.deduplicatedFunction() called with',\n key,\n );\n //eslint-disable-next-line @typescript-eslint/no-this-alias\n const self = this;\n const dedupedFn = async (...args: [never, never]): Promise<K> => {\n // If there's already a pending request with the same key, return it\n debugVerbose(\n 'DeduplicatedRequestHandler.deduplicatedFunction().dedupedFn called with',\n key,\n );\n if (\n self.inMemoryDeduplicationCache &&\n self.inMemoryDeduplicationCache.has(key)\n ) {\n debugVerbose(\n 'DeduplicatedRequestHandler.deduplicatedFunction().dedupedFn ',\n key,\n 'found key in inMemoryDeduplicationCache',\n );\n const res = await self.inMemoryDeduplicationCache\n .get(key)!\n .then((v) => structuredClone(v));\n debugVerbose(\n 'DeduplicatedRequestHandler.deduplicatedFunction().dedupedFn ',\n key,\n 'found key in inMemoryDeduplicationCache and served result from there',\n JSON.stringify(res).substring(0, 200),\n );\n return res;\n }\n\n // If no pending request, call the original function and store the promise\n const promise = self.fn(...args);\n self.inMemoryDeduplicationCache.set(key, promise);\n\n debugVerbose(\n 'DeduplicatedRequestHandler.deduplicatedFunction().dedupedFn ',\n key,\n 'did not found key in inMemoryDeduplicationCache. Setting it now and waiting for promise to resolve',\n );\n\n try {\n const ts = performance.now();\n const result = await promise;\n debugVerbose(\n 'DeduplicatedRequestHandler.deduplicatedFunction().dedupedFn ',\n key,\n 'promise resolved (in ',\n performance.now() - ts,\n 'ms). Returning result',\n JSON.stringify(result).substring(0, 200),\n );\n return structuredClone(result);\n } finally {\n // Once the promise is resolved/rejected and caching timeout is over, remove it from the map\n setTimeout(() => {\n debugVerbose(\n 'DeduplicatedRequestHandler.deduplicatedFunction().dedupedFn ',\n key,\n 'deleting key from inMemoryDeduplicationCache after ',\n self.cachingTimeMs,\n 'ms',\n );\n self.inMemoryDeduplicationCache.delete(key);\n }, self.cachingTimeMs);\n }\n };\n return dedupedFn as T;\n };\n}\n","// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function bufferReviver(_: string, value: any): any {\n if (value && typeof value === 'object' && typeof value.$binary === 'string') {\n return Buffer.from(value.$binary, 'base64');\n }\n return value;\n}\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function bufferReplacer(_: string, value: any): any {\n if (Buffer.isBuffer(value)) {\n return {\n $binary: value.toString('base64'),\n };\n }\n if (\n value &&\n typeof value === 'object' &&\n value?.type === 'Buffer' &&\n Array.isArray(value.data)\n ) {\n return {\n $binary: Buffer.from(value.data).toString('base64'),\n };\n }\n return value;\n}\n","import RedisStringsHandler, {\n CreateRedisStringsHandlerOptions,\n} from './RedisStringsHandler';\nimport { debugVerbose } from './utils/debug';\n\nlet cachedHandler: RedisStringsHandler;\n\nexport default class CachedHandler {\n constructor(options: CreateRedisStringsHandlerOptions) {\n if (!cachedHandler) {\n console.log('created cached handler');\n cachedHandler = new RedisStringsHandler(options);\n }\n }\n get(\n ...args: Parameters<RedisStringsHandler['get']>\n ): ReturnType<RedisStringsHandler['get']> {\n debugVerbose('CachedHandler.get called with', args);\n return cachedHandler.get(...args);\n }\n set(\n ...args: Parameters<RedisStringsHandler['set']>\n ): ReturnType<RedisStringsHandler['set']> {\n debugVerbose('CachedHandler.set called with', args);\n return cachedHandler.set(...args);\n }\n revalidateTag(\n ...args: Parameters<RedisStringsHandler['revalidateTag']>\n ): ReturnType<RedisStringsHandler['revalidateTag']> {\n debugVerbose('CachedHandler.revalidateTag called with', args);\n return cachedHandler.revalidateTag(...args);\n }\n resetRequestCache(\n ...args: Parameters<RedisStringsHandler['resetRequestCache']>\n ): ReturnType<RedisStringsHandler['resetRequestCache']> {\n // debug(\"CachedHandler.resetRequestCache called with\", args);\n return cachedHandler.resetRequestCache(...args);\n }\n}\n","import CachedHandler from './CachedHandler';\nexport default CachedHandler;\nimport RedisStringsHandler from './RedisStringsHandler';\nexport { RedisStringsHandler };\n"],"mappings":";AAAA,SAAS,gBAAgB,oBAAoB;;;ACAtC,SAAS,MACd,QAOa,WACV,MACG;AACN,QAAM,YAAY;AAAA,IAChB,KAAK;AAAA,IACL,MAAM;AAAA,IACN,OAAO;AAAA,IACP,QAAQ;AAAA,IACR,MAAM;AAAA,IACN,OAAO;AAAA,IACP,MAAM;AAAA,EACR;AACA,MAAI,QAAQ,IAAI,qBAAqB;AACnC,YAAQ,IAAI,UAAU,KAAK,GAAG,yBAAyB,GAAG,IAAI;AAAA,EAChE;AACF;AAEO,SAAS,aAAa,UAAkB,MAAiB;AAC9D,MAAI,QAAQ,IAAI,qCAAqC;AACnD,YAAQ,IAAI,YAAY,sBAAsB,GAAG,IAAI;AAAA,EACvD;AACF;;;ACDA,IAAM,sBAAsB;AACrB,IAAM,YAAN,MAAmB;AAAA,EAiBxB,YAAY,SAA2B;AACrC,SAAK,SAAS,QAAQ;AACtB,SAAK,YAAY,QAAQ;AACzB,SAAK,WAAW,QA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tD,WAAO,cAAc,kBAAkB,GAAG,IAAI;AAAA,EAChD;AACF;;;ACrCA,IAAO,gBAAQ;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,16 +1,18 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@trieb.work/nextjs-turbo-redis-cache",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.5.0",
|
|
4
4
|
"repository": {
|
|
5
5
|
"type": "git",
|
|
6
6
|
"url": "https://github.com/trieb-work/nextjs-turbo-redis-cache.git"
|
|
7
7
|
},
|
|
8
8
|
"scripts": {
|
|
9
9
|
"dev": "pnpm test",
|
|
10
|
-
"run-dev-server": "
|
|
10
|
+
"run-dev-server": "pnpm run-dev-server-15-3-2",
|
|
11
|
+
"run-dev-server-15-3-2": "cd ./test/integration/next-app-15-3-2 && pnpm dev",
|
|
12
|
+
"run-dev-server-15-0-3": "cd ./test/integration/next-app-15-0-3 && pnpm dev",
|
|
11
13
|
"build": "tsup",
|
|
12
14
|
"lint": "eslint -c eslint.config.mjs --fix",
|
|
13
|
-
"
|
|
15
|
+
"format": "prettier --write 'src/**/*.ts' 'src/*.ts'",
|
|
14
16
|
"test": "vitest --coverage --config vite.config.ts",
|
|
15
17
|
"test:ui": "vitest --ui --config vite.config.ts",
|
|
16
18
|
"test:unit": "vitest --config vite.config.ts src/**/*.test.ts src/**/*.test.tsx",
|
|
@@ -84,7 +86,7 @@
|
|
|
84
86
|
"vitest": "^2.1.5"
|
|
85
87
|
},
|
|
86
88
|
"peerDependencies": {
|
|
87
|
-
"next": "15.0.3",
|
|
89
|
+
"next": ">=15.0.3 <= 15.3.2",
|
|
88
90
|
"redis": "4.7.0"
|
|
89
91
|
},
|
|
90
92
|
"packageManager": "pnpm@9.15.9+sha512.68046141893c66fad01c079231128e9afb89ef87e2691d69e4d40eee228988295fd4682181bae55b58418c3a253bde65a505ec7c5f9403ece5cc3cd37dcf2531"
|
|
@@ -14,6 +14,12 @@ export type CacheEntry = {
|
|
|
14
14
|
};
|
|
15
15
|
|
|
16
16
|
export type CreateRedisStringsHandlerOptions = {
|
|
17
|
+
/** Redis redis_url to use.
|
|
18
|
+
* @default process.env.REDIS_URL? process.env.REDIS_URL : process.env.REDISHOST
|
|
19
|
+
? `redis://${process.env.REDISHOST}:${process.env.REDISPORT}`
|
|
20
|
+
: 'redis://localhost:6379'
|
|
21
|
+
*/
|
|
22
|
+
redis_url?: string;
|
|
17
23
|
/** Redis database number to use. Uses DB 0 for production, DB 1 otherwise
|
|
18
24
|
* @default process.env.VERCEL_ENV === 'production' ? 0 : 1
|
|
19
25
|
*/
|
|
@@ -91,6 +97,11 @@ export default class RedisStringsHandler {
|
|
|
91
97
|
private estimateExpireAge: (staleAge: number) => number;
|
|
92
98
|
|
|
93
99
|
constructor({
|
|
100
|
+
redis_url = process.env.REDIS_URL
|
|
101
|
+
? process.env.REDIS_URL
|
|
102
|
+
: process.env.REDISHOST
|
|
103
|
+
? `redis://${process.env.REDISHOST}:${process.env.REDISPORT}`
|
|
104
|
+
: 'redis://localhost:6379',
|
|
94
105
|
database = process.env.VERCEL_ENV === 'production' ? 0 : 1,
|
|
95
106
|
keyPrefix = process.env.VERCEL_URL || 'UNDEFINED_URL_',
|
|
96
107
|
sharedTagsKey = '__sharedTags__',
|
|
@@ -113,9 +124,7 @@ export default class RedisStringsHandler {
|
|
|
113
124
|
try {
|
|
114
125
|
this.client = createClient({
|
|
115
126
|
...(database !== 0 ? { database } : {}),
|
|
116
|
-
url:
|
|
117
|
-
? `redis://${process.env.REDISHOST}:${process.env.REDISPORT}`
|
|
118
|
-
: 'redis://localhost:6379',
|
|
127
|
+
url: redis_url,
|
|
119
128
|
});
|
|
120
129
|
|
|
121
130
|
this.client.on('error', (error) => {
|
|
@@ -195,7 +204,7 @@ export default class RedisStringsHandler {
|
|
|
195
204
|
this.redisDeduplicationHandler.deduplicatedFunction;
|
|
196
205
|
}
|
|
197
206
|
|
|
198
|
-
resetRequestCache(): void {
|
|
207
|
+
resetRequestCache(): void {}
|
|
199
208
|
|
|
200
209
|
private async assertClientIsReady(): Promise<void> {
|
|
201
210
|
await Promise.all([
|
|
@@ -211,19 +220,19 @@ export default class RedisStringsHandler {
|
|
|
211
220
|
key: string,
|
|
212
221
|
ctx:
|
|
213
222
|
| {
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
223
|
+
kind: 'APP_ROUTE' | 'APP_PAGE';
|
|
224
|
+
isRoutePPREnabled: boolean;
|
|
225
|
+
isFallback: boolean;
|
|
226
|
+
}
|
|
218
227
|
| {
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
228
|
+
kind: 'FETCH';
|
|
229
|
+
revalidate: number;
|
|
230
|
+
fetchUrl: string;
|
|
231
|
+
fetchIdx: number;
|
|
232
|
+
tags: string[];
|
|
233
|
+
softTags: string[];
|
|
234
|
+
isFallback: boolean;
|
|
235
|
+
},
|
|
227
236
|
): Promise<CacheEntry | null> {
|
|
228
237
|
if (
|
|
229
238
|
ctx.kind !== 'APP_ROUTE' &&
|
|
@@ -329,15 +338,12 @@ export default class RedisStringsHandler {
|
|
|
329
338
|
this.client
|
|
330
339
|
.unlink(getTimeoutRedisCommandOptions(this.timeoutMs), redisKey)
|
|
331
340
|
.catch((err) => {
|
|
332
|
-
// If the first unlink fails, log the error
|
|
341
|
+
// If the first unlink fails, only log the error
|
|
342
|
+
// Never implement a retry here as the cache entry will be updated directly after this get request
|
|
333
343
|
console.error(
|
|
334
|
-
'Error occurred while unlinking stale data.
|
|
344
|
+
'Error occurred while unlinking stale data. Error was:',
|
|
335
345
|
err,
|
|
336
346
|
);
|
|
337
|
-
this.client.unlink(
|
|
338
|
-
getTimeoutRedisCommandOptions(this.timeoutMs),
|
|
339
|
-
redisKey,
|
|
340
|
-
);
|
|
341
347
|
})
|
|
342
348
|
.finally(async () => {
|
|
343
349
|
// Clean up our tag tracking maps after the Redis key is removed
|
|
@@ -366,42 +372,44 @@ export default class RedisStringsHandler {
|
|
|
366
372
|
key: string,
|
|
367
373
|
data:
|
|
368
374
|
| {
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
| {
|
|
381
|
-
kind: 'APP_ROUTE';
|
|
382
|
-
status: number;
|
|
383
|
-
headers: {
|
|
384
|
-
'cache-control'?: string;
|
|
385
|
-
'x-nextjs-stale-time': string; // timestamp in ms
|
|
386
|
-
'x-next-cache-tags': string; // comma separated paths (tags)
|
|
387
|
-
};
|
|
388
|
-
body: Buffer;
|
|
389
|
-
}
|
|
375
|
+
kind: 'APP_PAGE';
|
|
376
|
+
status: number;
|
|
377
|
+
headers: {
|
|
378
|
+
'x-nextjs-stale-time': string; // timestamp in ms
|
|
379
|
+
'x-next-cache-tags': string; // comma separated paths (tags)
|
|
380
|
+
};
|
|
381
|
+
html: string;
|
|
382
|
+
rscData: Buffer;
|
|
383
|
+
segmentData: unknown;
|
|
384
|
+
postboned: unknown;
|
|
385
|
+
}
|
|
390
386
|
| {
|
|
391
|
-
|
|
392
|
-
data: {
|
|
393
|
-
headers: Record<string, string>;
|
|
394
|
-
body: string; // base64 encoded
|
|
387
|
+
kind: 'APP_ROUTE';
|
|
395
388
|
status: number;
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
389
|
+
headers: {
|
|
390
|
+
'cache-control'?: string;
|
|
391
|
+
'x-nextjs-stale-time': string; // timestamp in ms
|
|
392
|
+
'x-next-cache-tags': string; // comma separated paths (tags)
|
|
393
|
+
};
|
|
394
|
+
body: Buffer;
|
|
395
|
+
}
|
|
396
|
+
| {
|
|
397
|
+
kind: 'FETCH';
|
|
398
|
+
data: {
|
|
399
|
+
headers: Record<string, string>;
|
|
400
|
+
body: string; // base64 encoded
|
|
401
|
+
status: number;
|
|
402
|
+
url: string;
|
|
403
|
+
};
|
|
404
|
+
revalidate: number | false;
|
|
405
|
+
},
|
|
400
406
|
ctx: {
|
|
401
|
-
revalidate: number | false;
|
|
402
407
|
isRoutePPREnabled: boolean;
|
|
403
408
|
isFallback: boolean;
|
|
404
409
|
tags?: string[];
|
|
410
|
+
// Different versions of Next.js use different arguments for the same functionality
|
|
411
|
+
revalidate?: number | false; // Version 15.0.3
|
|
412
|
+
cacheControl?: { revalidate: 5; expire: undefined }; // Version 15.0.3
|
|
405
413
|
},
|
|
406
414
|
) {
|
|
407
415
|
if (
|
|
@@ -443,12 +451,12 @@ export default class RedisStringsHandler {
|
|
|
443
451
|
);
|
|
444
452
|
}
|
|
445
453
|
|
|
454
|
+
// TODO: implement expiration based on cacheControl.expire argument, -> probably relevant for cacheLife and "use cache" etc.: https://nextjs.org/docs/app/api-reference/functions/cacheLife
|
|
446
455
|
// Constructing the expire time for the cache entry
|
|
456
|
+
const revalidate = ctx.revalidate || ctx.cacheControl?.revalidate;
|
|
447
457
|
const expireAt =
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
ctx.revalidate > 0
|
|
451
|
-
? this.estimateExpireAge(ctx.revalidate)
|
|
458
|
+
revalidate && Number.isSafeInteger(revalidate) && revalidate > 0
|
|
459
|
+
? this.estimateExpireAge(revalidate)
|
|
452
460
|
: this.estimateExpireAge(this.defaultStaleAge);
|
|
453
461
|
|
|
454
462
|
// Setting the cache entry in redis
|
|
@@ -521,7 +529,7 @@ export default class RedisStringsHandler {
|
|
|
521
529
|
// revalidateTag is called for the page tag (_N_T_...) and the fetch request needs to be invalidated as well
|
|
522
530
|
// unfortunately this is not possible since the revalidateTag is not called with any data that would allow us to find the cache entry of the fetch request
|
|
523
531
|
// in case of a fetch request get method call, the get method of the cache handler is called with some information about the pages/routes the fetch request is inside
|
|
524
|
-
// therefore we only mark the page/route as stale here (with help of the revalidatedTagsMap)
|
|
532
|
+
// therefore we only mark the page/route as stale here (with help of the revalidatedTagsMap)
|
|
525
533
|
// and delete the cache entry of the fetch request on the next request to the get function
|
|
526
534
|
if (tag.startsWith(NEXT_CACHE_IMPLICIT_TAG_ID)) {
|
|
527
535
|
const now = Date.now();
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* This handler is used to validate the arguments of the get, set, revalidateTag methods against a zod schema.
|
|
3
|
+
* This is mainly used to test new nextjs versions and to ensure that the arguments are still valid. As we
|
|
4
|
+
* saw in the past, that arguments against the cache handler changed between different nextjs versions very often (even between patch versions).
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import RedisStringsHandler, {
|
|
8
|
+
CreateRedisStringsHandlerOptions,
|
|
9
|
+
} from './RedisStringsHandler';
|
|
10
|
+
import { debugVerbose } from './utils/debug';
|
|
11
|
+
|
|
12
|
+
let cachedHandler: RedisStringsHandler;
|
|
13
|
+
|
|
14
|
+
export default class CachedHandler {
|
|
15
|
+
constructor(options: CreateRedisStringsHandlerOptions) {
|
|
16
|
+
if (!cachedHandler) {
|
|
17
|
+
console.log('created development cached handler');
|
|
18
|
+
cachedHandler = new RedisStringsHandler(options);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
get(
|
|
22
|
+
...args: Parameters<RedisStringsHandler['get']>
|
|
23
|
+
): ReturnType<RedisStringsHandler['get']> {
|
|
24
|
+
debugVerbose('CachedHandler.get called with', args);
|
|
25
|
+
return cachedHandler.get(...args);
|
|
26
|
+
}
|
|
27
|
+
set(
|
|
28
|
+
...args: Parameters<RedisStringsHandler['set']>
|
|
29
|
+
): ReturnType<RedisStringsHandler['set']> {
|
|
30
|
+
debugVerbose('CachedHandler.set called with', args);
|
|
31
|
+
return cachedHandler.set(...args);
|
|
32
|
+
}
|
|
33
|
+
revalidateTag(
|
|
34
|
+
...args: Parameters<RedisStringsHandler['revalidateTag']>
|
|
35
|
+
): ReturnType<RedisStringsHandler['revalidateTag']> {
|
|
36
|
+
debugVerbose('CachedHandler.revalidateTag called with', args);
|
|
37
|
+
return cachedHandler.revalidateTag(...args);
|
|
38
|
+
}
|
|
39
|
+
resetRequestCache(
|
|
40
|
+
...args: Parameters<RedisStringsHandler['resetRequestCache']>
|
|
41
|
+
): ReturnType<RedisStringsHandler['resetRequestCache']> {
|
|
42
|
+
// debug("CachedHandler.resetRequestCache called with", args);
|
|
43
|
+
return cachedHandler.resetRequestCache(...args);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"version": "0.1.0",
|
|
4
4
|
"private": true,
|
|
5
5
|
"scripts": {
|
|
6
|
-
"dev": "export VERCEL_URL=\"dev-test-$RANDOM\" && echo $VERCEL_URL && cd ../../.. && pnpm build && cd test/integration/next-app && pnpm i && pnpm build && VERCEL_ENV=production REDISHOST=localhost REDISPORT=6379 DEBUG_CACHE_HANDLER=true pnpm start",
|
|
6
|
+
"dev": "export VERCEL_URL=\"dev-test-$RANDOM\" && echo $VERCEL_URL && cd ../../.. && pnpm build && cd test/integration/next-app-15-0-3 && pnpm i && pnpm build && VERCEL_ENV=production REDISHOST=localhost REDISPORT=6379 DEBUG_CACHE_HANDLER=true pnpm start",
|
|
7
7
|
"build": "next build",
|
|
8
8
|
"start": "next start",
|
|
9
9
|
"lint": "next lint"
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
|
|
2
|
+
|
|
3
|
+
## Getting Started
|
|
4
|
+
|
|
5
|
+
First, run the development server:
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm run dev
|
|
9
|
+
# or
|
|
10
|
+
yarn dev
|
|
11
|
+
# or
|
|
12
|
+
pnpm dev
|
|
13
|
+
# or
|
|
14
|
+
bun dev
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
|
|
18
|
+
|
|
19
|
+
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
|
|
20
|
+
|
|
21
|
+
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
|
|
22
|
+
|
|
23
|
+
## Learn More
|
|
24
|
+
|
|
25
|
+
To learn more about Next.js, take a look at the following resources:
|
|
26
|
+
|
|
27
|
+
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
|
|
28
|
+
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
|
|
29
|
+
|
|
30
|
+
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
|
|
31
|
+
|
|
32
|
+
## Deploy on Vercel
|
|
33
|
+
|
|
34
|
+
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
|
|
35
|
+
|
|
36
|
+
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { dirname } from "path";
|
|
2
|
+
import { fileURLToPath } from "url";
|
|
3
|
+
import { FlatCompat } from "@eslint/eslintrc";
|
|
4
|
+
|
|
5
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
6
|
+
const __dirname = dirname(__filename);
|
|
7
|
+
|
|
8
|
+
const compat = new FlatCompat({
|
|
9
|
+
baseDirectory: __dirname,
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
const eslintConfig = [
|
|
13
|
+
...compat.extends("next/core-web-vitals", "next/typescript"),
|
|
14
|
+
];
|
|
15
|
+
|
|
16
|
+
export default eslintConfig;
|