Skip to content
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

fix(caching): 🔧 Changing the caching strategy #384

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
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
28 changes: 14 additions & 14 deletions sw/CacheChildrenStrategy.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
/* eslint-disable import/no-unused-modules */
import { Strategy, StrategyHandler } from 'workbox-strategies';
import Dexie from 'dexie';
import debug from 'debug';
import debug from 'debug'
import Dexie from 'dexie'
import { Strategy, StrategyHandler } from 'workbox-strategies'

const logger = debug('starmap:sw:CacheChildrenStrategy')
const log = {
debug: logger.extend('debug'),
info: logger.extend('info'),
warn: logger.extend('warn'),
warn: logger.extend('warn')
}

/**
Expand All @@ -27,8 +27,8 @@ const generateHashCode = str => [...str].reduce((hash, chr) => 0 | (31 * hash +

const contentHashDB: {hashes?: Dexie.Table} & Dexie = new Dexie('contentHashDB')
contentHashDB.version(1).stores({
hashes: `cacheKey, hashCode`
});
hashes: 'cacheKey, hashCode'
})

/**
* check if the cached response is valid:
Expand Down Expand Up @@ -60,13 +60,14 @@ function isCachedResponseStillValid (cachedResponse?: Response): cachedResponse
* The benefit of writing this as a workbox strategy is we can use other workbox plugins like expiration.
*/
export class CacheChildren extends Strategy implements Strategy {
fetchOptions?: RequestInit = {
fetchOptions?: RequestInit = {
method: 'GET',
headers: {
'cache-control': 's-maxage=30, stale-while-revalidate=86400'
}
}
async populateCacheAsync(cacheKey: string, responsePromise: Promise<Response>, handler: StrategyHandler): Promise<void> {

async populateCacheAsync (cacheKey: string, responsePromise: Promise<Response>, handler: StrategyHandler): Promise<void> {
const response = await responsePromise
log.debug(`response(actual) x-vercel-cache header: ${response.headers.get('x-vercel-cache')}`)
if (!response.ok) {
Expand All @@ -87,10 +88,9 @@ export class CacheChildren extends Strategy implements Strategy {
} else {
log.debug(`populateCacheAsync(${cacheKey}) - previous response matches latest response hash - not updating response`)
}
return
}

async _handle(request: Request, handler: StrategyHandler): Promise<Response> {
async _handle (request: Request, handler: StrategyHandler): Promise<Response> {
try {
const url = new URL(request.url)
const queryParams = new URLSearchParams(url.search)
Expand All @@ -111,9 +111,12 @@ export class CacheChildren extends Strategy implements Strategy {
// That will cause cache collisions.
const cacheKey = `${CACHE_VERSION}/${owner}/${repo}/${issue_number}/${node_id}`
// Checking if the cache already has the response.
let cachedResponse = await handler.cacheMatch(cacheKey)
const cachedResponse = await handler.cacheMatch(cacheKey)
log.debug(`response(cached) x-vercel-cache header: ${cachedResponse?.headers?.get('x-vercel-cache')}`)

const actualResponse = handler.fetch(request.clone())
const populateCachePromise = this.populateCacheAsync(cacheKey, actualResponse, handler)
void handler.waitUntil(populateCachePromise)
if (isCachedResponseStillValid(cachedResponse)) {
// We have a cached response with 200-299 (status.ok) or 304 ("Not Modified") response, return it immediately.
return cachedResponse
Expand All @@ -124,12 +127,9 @@ export class CacheChildren extends Strategy implements Strategy {
*/
log.debug('No valid cached response found. Waiting for populateCacheAsync to finish')

const actualResponse = handler.fetch(request.clone())
const populateCachePromise = this.populateCacheAsync(cacheKey, actualResponse, handler)
// WARNING: We're not awaiting this call deliberately. We want to populate the cache in the background.
// Essentially, poor-man's version of stale-while-revalidate.
// handler will wait till this promise resolves. This can be monitored using the `doneWaiting` method.
void handler.waitUntil(populateCachePromise)
await handler.doneWaiting()
log.debug('populateCacheAsync finished. Returning actual response')

Expand Down
Loading