Thanks to visit codestin.com
Credit goes to github.com

Skip to content

feat(isr): nonBlockingRender & backgroundRevalidation #1762

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Sep 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions apps/ssr-isr/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,9 @@ export function app(): express.Express {
browserDistFolder,
bootstrap,
commonEngine,
modifyGeneratedHtml: defaultModifyGeneratedHtml,

backgroundRevalidation: true, // will revalidate in background and serve the cache page first
nonBlockingRender: true, // will serve page first and store in cache in background
modifyGeneratedHtml: customModifyGeneratedHtml,
// cache: fsCacheHandler,
});

Expand Down Expand Up @@ -66,12 +67,11 @@ export function app(): express.Express {
return server;
}

const defaultModifyGeneratedHtml: ModifyHtmlCallbackFn = (
const customModifyGeneratedHtml: ModifyHtmlCallbackFn = (
req: Request,
html: string,
): string => {
const time = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '');

let msg = '<!-- ';
msg += `\n🚀 ISR: Served from cache! \n⌛ Last updated: ${time}. `;
msg += ' \n-->';
Expand Down
11 changes: 11 additions & 0 deletions libs/isr/models/src/isr-handler-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,17 @@ export interface ISRHandlerConfig {
* which only add commented text to the html to indicate when it was generated.
*/
modifyGeneratedHtml?: ModifyHtmlCallbackFn;

/**
* If set to true, the server will not wait for storing the rendered page to the cache storage first and will return the rendered HTML as soon as possible.
* This can avoid client-side waiting times if the remote cache storage is down.
*/
nonBlockingRender?: boolean;

/**
* If set to true, the server will provide the cached HTML as soon as possible and will revalidate the cache in the background.
*/
backgroundRevalidation?: boolean;
}

export interface ServeFromCacheConfig {
Expand Down
26 changes: 22 additions & 4 deletions libs/isr/server/src/cache-generation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,19 +103,37 @@ export class CacheGeneration {
// don't do !revalidate because it will also catch "0"
return { html: finalHtml };
}

// add the regenerated page to cache
await this.cache.add(cacheKey, finalHtml, {
revalidate,
buildId: this.isrConfig.buildId,
});
const addToCache = () => {
return this.cache.add(cacheKey, finalHtml, {
revalidate,
buildId: this.isrConfig.buildId,
});
};

try {
if (this.isrConfig.nonBlockingRender) {
// If enabled, add to cache without waiting (fire-and-forget)
addToCache();
} else {
// If not enabled, wait for cache addition to complete before proceeding
await addToCache();
}
} catch (error) {
console.error('Error adding to cache:', error);
}

if (mode === 'regenerate') {
// remove from urlsOnHold because we are done
this.urlsOnHold = this.urlsOnHold.filter((x) => x !== cacheKey);
this.logger.log(`Url: ${cacheKey} was regenerated!`);
}

return { html: finalHtml };
} catch (error) {
this.logger.log(`Error regenerating url: ${cacheKey}`, error);

if (mode === 'regenerate') {
// Ensure removal from urlsOnHold in case of error
this.urlsOnHold = this.urlsOnHold.filter((x) => x !== cacheKey);
Expand Down
22 changes: 14 additions & 8 deletions libs/isr/server/src/cache-handlers/filesystem-cache-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,14 +76,20 @@ export class FileSystemCacheHandler extends CacheHandler {

if (cachedRoute) {
// on html field we have saved path to file
this.readFromFile(cachedRoute.htmlFilePath).then((html) => {
const cacheData: CacheData = {
html,
options: cachedRoute.options,
createdAt: cachedRoute.createdAt,
};
resolve(cacheData);
});
this.readFromFile(cachedRoute.htmlFilePath)
.then((html) => {
const cacheData: CacheData = {
html,
options: cachedRoute.options,
createdAt: cachedRoute.createdAt,
};
resolve(cacheData);
})
.catch((err) => {
reject(
`Error: 💥 Cannot read cache file for route ${route}: ${cachedRoute.htmlFilePath}, ${err}`,
);
});
} else {
reject('Error: 💥 Url is not cached.');
}
Expand Down
44 changes: 26 additions & 18 deletions libs/isr/server/src/isr-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,34 +188,42 @@ export class ISRHandler {
return;
}

// Apply the callback if given
let finalHtml = html;
if (config?.modifyCachedHtml) {
const timeStart = performance.now();
finalHtml = config.modifyCachedHtml(req, html);
const totalTime = (performance.now() - timeStart).toFixed(2);
finalHtml += `<!--\nℹ️ ISR: This cachedHtml has been modified with modifyCachedHtml()\n❗️
This resulted into more ${totalTime}ms of processing time.\n-->`;
}

// Cache exists. Send it.
this.logger.log(`Page was retrieved from cache: `, cacheKey);
let finalHtml = html;

// if the cache is expired, we will regenerate it
if (cacheConfig.revalidate && cacheConfig.revalidate > 0) {
const lastCacheDateDiff = (Date.now() - createdAt) / 1000; // in seconds

if (lastCacheDateDiff > cacheConfig.revalidate) {
// regenerate the page without awaiting, so the user gets the cached page immediately
this.cacheGeneration.generateWithCacheKey(
req,
res,
cacheKey,
config?.providers,
'regenerate',
);
const generate = () => {
return this.cacheGeneration.generateWithCacheKey(
req,
res,
cacheKey,
config?.providers,
'regenerate',
);
};

try {
// regenerate the page without awaiting, so the user gets the cached page immediately
if (this.isrConfig.backgroundRevalidation) {
generate();
} else {
const result = await generate();
if (result?.html) {
finalHtml = result.html;
}
}
} catch (error) {
console.error('Error generating html', error);
next();
}
}
}

return res.send(finalHtml);
} catch (error) {
// Cache does not exist. Serve user using SSR
Expand Down
Loading