Unverified Commit a17f2d2c authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

feat: added compression to resume data cache using deflate (#73227)

Previously the resume data cache was simply a JSON encoded string. This
adds deflate compression to it to help reduce the bandwidth between the
edge and the file system.

---------
Co-authored-by: 's avatarJanka Uryga <lolzatu2@gmail.com>
parent fa240f92
import { createPrerenderResumeDataCache } from '../resume-data-cache/resume-data-cache' import { createPrerenderResumeDataCache } from '../resume-data-cache/resume-data-cache'
import { streamFromString } from '../stream-utils/node-web-streams-helper' import {
streamFromString,
streamToString,
} from '../stream-utils/node-web-streams-helper'
import { import {
DynamicState, DynamicState,
getDynamicDataPostponedState, getDynamicDataPostponedState,
...@@ -31,9 +34,30 @@ describe('getDynamicHTMLPostponedState', () => { ...@@ -31,9 +34,30 @@ describe('getDynamicHTMLPostponedState', () => {
prerenderResumeDataCache prerenderResumeDataCache
) )
expect(state).toMatchInlineSnapshot( const parsed = parsePostponedState(state, { slug: '123' })
`"169:39[["slug","%%drp:slug:e9615126684e5%%"]]{"%%drp:slug:e9615126684e5%%":"%%drp:slug:e9615126684e5%%","nested":{"%%drp:slug:e9615126684e5%%":"%%drp:slug:e9615126684e5%%"}}{"store":{"fetch":{},"cache":{"1":{"value":"aGVsbG8=","tags":[],"stale":0,"timestamp":0,"expire":0,"revalidate":0}}}}"` expect(parsed).toMatchInlineSnapshot(`
) {
"data": {
"123": "123",
"nested": {
"123": "123",
},
},
"renderResumeDataCache": {
"cache": Map {
"1" => Promise {},
},
"fetch": Map {},
},
"type": 2,
}
`)
const value = await parsed.renderResumeDataCache.cache.get('1')
expect(value).toBeDefined()
await expect(streamToString(value!.value)).resolves.toEqual('hello')
}) })
it('serializes a HTML postponed state without fallback params', async () => { it('serializes a HTML postponed state without fallback params', async () => {
......
...@@ -4,14 +4,9 @@ import { ...@@ -4,14 +4,9 @@ import {
} from './resume-data-cache' } from './resume-data-cache'
import { createPrerenderResumeDataCache } from './resume-data-cache' import { createPrerenderResumeDataCache } from './resume-data-cache'
import { streamFromString } from '../stream-utils/node-web-streams-helper' import { streamFromString } from '../stream-utils/node-web-streams-helper'
import { inflateSync } from 'node:zlib'
describe('stringifyResumeDataCache', () => { function createCacheWithSingleEntry() {
it('serializes an empty cache', async () => {
const cache = createPrerenderResumeDataCache()
expect(await stringifyResumeDataCache(cache)).toBe('null')
})
it('serializes a cache with a single entry', async () => {
const cache = createPrerenderResumeDataCache() const cache = createPrerenderResumeDataCache()
cache.cache.set( cache.cache.set(
'key', 'key',
...@@ -25,7 +20,27 @@ describe('stringifyResumeDataCache', () => { ...@@ -25,7 +20,27 @@ describe('stringifyResumeDataCache', () => {
}) })
) )
expect(await stringifyResumeDataCache(cache)).toMatchInlineSnapshot( return cache
}
describe('stringifyResumeDataCache', () => {
it('serializes an empty cache', async () => {
const cache = createPrerenderResumeDataCache()
expect(await stringifyResumeDataCache(cache)).toBe('null')
})
it('serializes a cache with a single entry', async () => {
const cache = createCacheWithSingleEntry()
const compressed = await stringifyResumeDataCache(cache)
// We have to decompress the output because the compressed string is not
// deterministic. If it fails here it's because the compressed string is
// different.
const decompressed = inflateSync(
Buffer.from(compressed, 'base64')
).toString('utf-8')
expect(decompressed).toMatchInlineSnapshot(
`"{"store":{"fetch":{},"cache":{"key":{"value":"dmFsdWU=","tags":[],"stale":0,"timestamp":0,"expire":0,"revalidate":0}}}}"` `"{"store":{"fetch":{},"cache":{"key":{"value":"dmFsdWU=","tags":[],"stale":0,"timestamp":0,"expire":0,"revalidate":0}}}}"`
) )
}) })
...@@ -37,4 +52,14 @@ describe('parseResumeDataCache', () => { ...@@ -37,4 +52,14 @@ describe('parseResumeDataCache', () => {
createPrerenderResumeDataCache() createPrerenderResumeDataCache()
) )
}) })
it('parses a cache with a single entry', async () => {
const cache = createCacheWithSingleEntry()
const serialized = await stringifyResumeDataCache(cache)
const parsed = createRenderResumeDataCache(serialized)
expect(parsed.cache.size).toBe(1)
expect(parsed.fetch.size).toBe(0)
})
}) })
import { InvariantError } from '../../shared/lib/invariant-error'
import { import {
type UseCacheCacheStore, type UseCacheCacheStore,
type FetchCacheStore, type FetchCacheStore,
...@@ -64,6 +65,11 @@ type ResumeStoreSerialized = { ...@@ -64,6 +65,11 @@ type ResumeStoreSerialized = {
export async function stringifyResumeDataCache( export async function stringifyResumeDataCache(
resumeDataCache: RenderResumeDataCache | PrerenderResumeDataCache resumeDataCache: RenderResumeDataCache | PrerenderResumeDataCache
): Promise<string> { ): Promise<string> {
if (process.env.NEXT_RUNTIME === 'edge') {
throw new InvariantError(
'`stringifyResumeDataCache` should not be called in edge runtime.'
)
} else {
if (resumeDataCache.fetch.size === 0 && resumeDataCache.cache.size === 0) { if (resumeDataCache.fetch.size === 0 && resumeDataCache.cache.size === 0) {
return 'null' return 'null'
} }
...@@ -79,7 +85,12 @@ export async function stringifyResumeDataCache( ...@@ -79,7 +85,12 @@ export async function stringifyResumeDataCache(
}, },
} }
return JSON.stringify(json) // Compress the JSON string using zlib. As the data we already want to
// decompress is in memory, we use the synchronous deflateSync function.
const { deflateSync } = require('node:zlib') as typeof import('node:zlib')
return deflateSync(JSON.stringify(json)).toString('base64')
}
} }
/** /**
...@@ -114,6 +125,11 @@ export function createRenderResumeDataCache( ...@@ -114,6 +125,11 @@ export function createRenderResumeDataCache(
export function createRenderResumeDataCache( export function createRenderResumeDataCache(
prerenderResumeDataCacheOrPersistedCache: PrerenderResumeDataCache | string prerenderResumeDataCacheOrPersistedCache: PrerenderResumeDataCache | string
): RenderResumeDataCache { ): RenderResumeDataCache {
if (process.env.NEXT_RUNTIME === 'edge') {
throw new InvariantError(
'`createRenderResumeDataCache` should not be called in edge runtime.'
)
} else {
if (typeof prerenderResumeDataCacheOrPersistedCache !== 'string') { if (typeof prerenderResumeDataCacheOrPersistedCache !== 'string') {
// If the cache is already a prerender cache, we can return it directly, // If the cache is already a prerender cache, we can return it directly,
// we're just performing a type change. // we're just performing a type change.
...@@ -127,11 +143,20 @@ export function createRenderResumeDataCache( ...@@ -127,11 +143,20 @@ export function createRenderResumeDataCache(
} }
} }
// This should be a compressed string. Let's decompress it using zlib.
// As the data we already want to decompress is in memory, we use the
// synchronous inflateSync function.
const { inflateSync } = require('node:zlib') as typeof import('node:zlib')
const json: ResumeStoreSerialized = JSON.parse( const json: ResumeStoreSerialized = JSON.parse(
prerenderResumeDataCacheOrPersistedCache inflateSync(
Buffer.from(prerenderResumeDataCacheOrPersistedCache, 'base64')
).toString('utf-8')
) )
return { return {
cache: parseUseCacheCacheStore(Object.entries(json.store.cache)), cache: parseUseCacheCacheStore(Object.entries(json.store.cache)),
fetch: parseFetchCacheStore(Object.entries(json.store.fetch)), fetch: parseFetchCacheStore(Object.entries(json.store.fetch)),
} }
}
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment