Skip to content

Commit

Permalink
feat: use server-timing API to report duration
Browse files Browse the repository at this point in the history
  • Loading branch information
esroyo committed Feb 13, 2024
1 parent a677574 commit 611798b
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 23 deletions.
12 changes: 8 additions & 4 deletions src/esm-proxy-request-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,14 @@ export async function esmProxyRequestHandler(
} = await resolveConfig();
const buildTarget = getBuildTargetFromUA(req.headers.get('user-agent'));
if (Number(CACHE_MAXAGE)) {
performance.mark('cache-read');
const value = await retrieveCache(Deno.openKv(), [
req.url,
buildTarget,
]);
performance.measure('cache-read', 'cache-read');
if (value) {
performance.measure('cache-hit', { start: performance.now() });
return createFinalResponse(
{
...value,
Expand All @@ -40,6 +43,7 @@ export async function esmProxyRequestHandler(
);
}
}
performance.measure('cache-miss', { start: performance.now() });
const selfUrl = new URL(req.url);
const basePath = `/${BASE_PATH}/`.replace(/\/+/g, '/');
const esmOrigin = `${ESM_ORIGIN}/`.replace(/\/+$/, '/');
Expand Down Expand Up @@ -77,17 +81,17 @@ export async function esmProxyRequestHandler(
pair[0],
typeof pair[1] === 'string' ? replaceOrigin(pair[1]) : pair[1],
] as [string, string]);
performance.mark('fetch');
performance.mark('upstream');
const esmResponse = await _internals.fetch(esmUrl.toString(), {
headers: cloneHeaders(req.headers, denyHeaders),
redirect: 'manual',
});
performance.measure('fetch', 'fetch');
performance.measure('upstream', 'upstream');
let body = await esmResponse.text();
if (isJsResponse(esmResponse)) {
performance.mark('tosystemjs');
performance.mark('build');
body = replaceOrigin(await toSystemjs(body, { banner: OUTPUT_BANNER }));
performance.measure('tosystemjs', 'tosystemjs');
performance.measure('build', 'build');
}
return createFinalResponse(
{
Expand Down
40 changes: 21 additions & 19 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,12 @@ export const isJsResponse = (response: Response): boolean => {
));
};

export const isRedirectResponse = (response: Response): boolean => {
return response.status >= 300 && response.status < 400;
export const isRedirect = (status: number): boolean => {
return status >= 300 && status < 400;
};

export const isOk = (status: number): boolean => {
return status >= 200 && status < 300;
};

export const retrieveCache = async (
Expand Down Expand Up @@ -118,16 +122,11 @@ export const saveCache = async (
settledKv.close();
};

const buildDebugPerformance = (performance: Performance) => {
return JSON.stringify([
...performance.getEntriesByType('measure').map((
{ name, duration },
) => ({
name,
duration,
})),
]);
};
const buildDebugPerformance = (performance: Performance): string => (
performance.getEntriesByType('measure')
.map(({ name, duration }) => `${name}${duration ? `;dur=${duration}` : ''}`)
.join(',')
);

export const createFinalResponse = async (
responseProps: ResponseProps,
Expand All @@ -143,23 +142,26 @@ export const createFinalResponse = async (
status,
statusText,
} = responseProps;
headers.set('x-cache-status', isCached ? 'HIT' : 'MISS');
if (!headers.has('access-control-allow-origin')) {
headers.set('access-control-allow-origin', '*');
}
const isCacheable = isOk(status) || isRedirect(status);
const shouldCache = !isCached && isCacheable && Number(CACHE_MAXAGE);
if (shouldCache) {
performance.mark('cache-write');
await saveCache(Deno.openKv(), [url, buildTarget], responseProps);
performance.measure('cache-write', 'cache-write');
}

performance.measure('total', 'total');
headers.set('x-debug-performance', buildDebugPerformance(performance));
headers.set('server-timing', buildDebugPerformance(performance));

const response = new Response(body, {
headers,
status,
statusText,
});
const isCacheable = isJsResponse(response) || isRedirectResponse(response);
const shouldCache = !isCached && isCacheable && Number(CACHE_MAXAGE);
if (shouldCache) {
await saveCache(Deno.openKv(), [url, buildTarget], responseProps);
}

return response;
};

Expand Down

0 comments on commit 611798b

Please sign in to comment.