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

refactor: use Module Worker pattern instead of Service Worker, add error handling #4276

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
refactor: use Module Worker pattern instead of Service Worker, add er…
…ror handling
  • Loading branch information
dominikg committed Apr 14, 2022
commit 75b3280971ed472a497eac7bdaa0868837ec2a0f
8 changes: 3 additions & 5 deletions packages/adapter-cloudflare-workers/ambient.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,7 @@ declare module 'MANIFEST' {
export const prerendered: Set<string>;
}

declare abstract class FetchEvent extends Event {
readonly request: Request;
respondWith(promise: Response | Promise<Response>): void;
passThroughOnException(): void;
waitUntil(promise: Promise<any>): void;
declare module '__STATIC_CONTENT_MANIFEST' {
const json: string;
export default json;
}
122 changes: 81 additions & 41 deletions packages/adapter-cloudflare-workers/files/entry.js
Original file line number Diff line number Diff line change
@@ -1,61 +1,101 @@
import { Server } from 'SERVER';
import { manifest, prerendered } from 'MANIFEST';
import { getAssetFromKV } from '@cloudflare/kv-asset-handler';
import static_asset_manifest_json from '__STATIC_CONTENT_MANIFEST';
const static_asset_manifest = JSON.parse(static_asset_manifest_json);

const server = new Server(manifest);

const prefix = `/${manifest.appDir}/`;

addEventListener('fetch', (/** @type {FetchEvent} */ event) => {
event.respondWith(handle(event));
});
export default {
/**
* @param {Request} req
* @param {any} env
* @param {any} context
*/
async fetch(req, env, context) {
const url = new URL(req.url);

/**
* @param {FetchEvent} event
* @returns {Promise<Response>}
*/
async function handle(event) {
const { request } = event;

const url = new URL(request.url);

// generated assets
if (url.pathname.startsWith(prefix)) {
const res = await getAssetFromKV(event);
return new Response(res.body, {
headers: {
'cache-control': 'public, immutable, max-age=31536000',
'content-type': res.headers.get('content-type')
// static assets
if (url.pathname.startsWith(prefix)) {
/** @type {Response} */
const res = await get_asset_from_kv(req, env, context);
if (is_error(res.status)) {
return res;
}
});
}
return new Response(res.body, {
headers: {
// include original cache headers, minus cache-control which
// is overridden, and etag which is no longer useful
'cache-control': 'public, immutable, max-age=31536000',
'content-type': res.headers.get('content-type'),
'x-robots-tag': 'noindex'
}
});
}

// prerendered pages and index.html files
const pathname = url.pathname.replace(/\/$/, '');
let file = pathname.substring(1);
// prerendered pages and index.html files
const pathname = url.pathname.replace(/\/$/, '');
let file = pathname.substring(1);

try {
file = decodeURIComponent(file);
} catch (err) {
// ignore
}
try {
file = decodeURIComponent(file);
} catch (err) {
// ignore
}

if (
manifest.assets.has(file) ||
manifest.assets.has(file + '/index.html') ||
prerendered.has(pathname || '/')
) {
return get_asset_from_kv(req, env, context);
}

if (
manifest.assets.has(file) ||
manifest.assets.has(file + '/index.html') ||
prerendered.has(pathname || '/')
) {
return await getAssetFromKV(event);
// dynamically-generated pages
try {
return await server.respond(req, {
platform: { env, context },
getClientAddress() {
return req.headers.get('cf-connecting-ip');
}
});
} catch (e) {
return new Response('Error rendering route: ' + (e.message || e.toString()), { status: 500 });
}
}
};

// dynamically-generated pages
/**
* @param {Request} req
* @param {any} env
* @param {any} context
*/
async function get_asset_from_kv(req, env, context) {
try {
return await server.respond(request, {
getClientAddress() {
return request.headers.get('cf-connecting-ip');
return await getAssetFromKV(
{
request: req,
waitUntil(promise) {
return context.waitUntil(promise);
}
},
{
ASSET_NAMESPACE: env.__STATIC_CONTENT,
ASSET_MANIFEST: static_asset_manifest
}
});
);
} catch (e) {
return new Response('Error rendering route:' + (e.message || e.toString()), { status: 500 });
const status = is_error(e.status) ? e.status : 500;
return new Response(e.message || e.toString(), { status });
}
}

/**
* @param {number} status
* @returns {boolean}
*/
function is_error(status) {
return status > 399;
}