Skip to content

Commit

Permalink
feat: add cache changes for versioned assets
Browse files Browse the repository at this point in the history
  • Loading branch information
shafiqihtsham committed Sep 19, 2024
1 parent 3cd9714 commit 78e534e
Show file tree
Hide file tree
Showing 5 changed files with 32 additions and 14 deletions.
3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,6 @@
CLOUDFLARE_ACCOUNT_ID=5e0333335a21846798fafca9e55e044f
# Cloudflare API TOKEN
CLOUDFLARE_API_TOKEN=
# Development Enivronment Key
# Change this to 'production' when in production
POLYKEY_DOCS_ENV=development
3 changes: 3 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ jobs:
deployment_tier: 'development'
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
POLYKEY_DOCS_ENV: ${{ secrets.POLYKEY_DOCS_ENV }}
run: |
echo 'Perform service deployment for feature'
nix develop .#ci --command bash -c $'
Expand Down Expand Up @@ -124,6 +125,7 @@ jobs:
deployment_tier: 'staging'
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
POLYKEY_DOCS_ENV: ${{ secrets.POLYKEY_DOCS_ENV }}
run: |
nix develop .#ci --command bash -c $'
npm run deploy -- --env staging
Expand Down Expand Up @@ -186,6 +188,7 @@ jobs:
deployment_tier: 'production'
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
POLYKEY_DOCS_ENV: ${{ secrets.POLYKEY_DOCS_ENV }}
run: |
nix develop .#ci --command bash -c $'
npm run deploy -- --env production
Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
"scripts": {
"lint": "eslint '{src,server,scripts}/**/*.{js,ts,jsx,tsx,json}' 'docusaurus.config.ts'",
"lintfix": "eslint '{src,server,scripts}/**/*.{js,ts,jsx,tsx,json}' 'docusaurus.config.ts' --fix",
"lintcontent": "prettier --check '{blog,docs}/**/*.{md,mdx}'",
"lintcontentfix": "prettier --write '{blog,docs}/**/*.{md,mdx}'",
"start": "docusaurus start",
"swizzle": "docusaurus swizzle",
"build": "docusaurus build --out-dir=./public",
Expand Down
4 changes: 3 additions & 1 deletion scripts/deploy.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,9 @@ async function main(argv = process.argv) {
];
console.error(['wrangler', ...secretBulkArgs].join(' '));
childProcess.execFileSync('wrangler', secretBulkArgs, {
input: JSON.stringify({}),
input: JSON.stringify({
POLYKEY_DOCS_ENV: process.env.POLYKEY_DOCS_ENV,
}),
});
const deployArgs = ['deploy', '--config', './wrangler.toml', ...restArgs];
console.error(['wrangler', ...deployArgs].join(' '));
Expand Down
34 changes: 21 additions & 13 deletions server/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import assetManifestJSON from '__STATIC_CONTENT_MANIFEST';
export interface Env {
// CF Worker Sites automatically injects this to point to the KV namespace
__STATIC_CONTENT: string;
POLYKEY_DOCS_ENV: string;
}

const router = ittyRouter.Router();
Expand All @@ -28,23 +29,16 @@ function mapRequestToDocs(req: Request): Request {
return new Request(assetUrl.toString(), assetRequest);
}

router.all('*', async (req: Request, env: Env, ctx: ExecutionContext) => {
router.all("*", async (req: Request, env: Env, ctx: ExecutionContext) => {
const cacheControl = {
browserTTL: 30 * 24 * 60 * 60,
edgeTTL: 2 * 24 * 60 * 60,
bypassCache: false,
bypassCache: env.POLYKEY_DOCS_ENV === "development" ? true : false,
};
const url = new URL(req.url);
// Check if the URL pathname is exactly '/docs'
if (url.pathname === '/docs') {
console.log('Redirecting /docs to /docs/');
return Response.redirect(url.origin + '/docs/', 301);
}
// This is a mapping from request paths to content-hashed keys generated by
// wrangler as a cache busting measure.
const assetManifest = JSON.parse(assetManifestJSON);
try {
return await cloudflareKVAssetHandler.getAssetFromKV(
const response = await cloudflareKVAssetHandler.getAssetFromKV(
{
request: req,
waitUntil: ctx.waitUntil.bind(ctx),
Expand All @@ -56,9 +50,17 @@ router.all('*', async (req: Request, env: Env, ctx: ExecutionContext) => {
ASSET_MANIFEST: assetManifest,
},
);

if (req.url.includes("assets")) {
response.headers.set("Cache-Control", "max-age=31536000, immutable");
} else {
response.headers.set("Cache-Control", "max-age=86400");
}

return response;
} catch (e) {
if (e instanceof cloudflareKVAssetHandler.NotFoundError) {
console.log('Requested resource not found', e.message);
console.log("Requested resource not found", e.message);
const response404 = await cloudflareKVAssetHandler.getAssetFromKV(
{
request: req,
Expand All @@ -74,14 +76,20 @@ router.all('*', async (req: Request, env: Env, ctx: ExecutionContext) => {
ASSET_MANIFEST: assetManifest,
},
);

const headers = new Headers(response404.headers);

headers.set("Cache-Control", "max-age=86400");

return new Response(response404.body, {
...response404,
headers,
status: 404,
});
} else if (e instanceof cloudflareKVAssetHandler.MethodNotAllowedError) {
return new Response('Method Not Allowed', { status: 405 });
return new Response("Method Not Allowed", { status: 405 });
} else {
return new Response('Server Error', { status: 500 });
return new Response("Server Error", { status: 500 });
}
}
});
Expand Down

0 comments on commit 78e534e

Please sign in to comment.