Skip to content

Commit

Permalink
wip(cloud-function): clean up server-timing logic
Browse files Browse the repository at this point in the history
  • Loading branch information
LeoMcA committed Jul 30, 2024
1 parent db9360e commit 3f264cf
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 14 deletions.
3 changes: 1 addition & 2 deletions cloud-function/src/handlers/render-html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export async function renderIndexHTML(
next: NextFunction
) {
if (req.url.endsWith("/index.html")) {
req.startServerTiming("totalSSR");
const html = await renderHTMLForContext(
req,
res,
Expand Down Expand Up @@ -55,9 +56,7 @@ export async function renderHTMLForContext(
}

try {
req.startServerTiming("addHeaders");
withRenderedContentResponseHeaders(req, res);
req.endServerTiming("addHeaders");
req.startServerTiming("renderHTML");
const html = renderHTML(context);
req.endServerTiming("renderHTML");
Expand Down
23 changes: 11 additions & 12 deletions cloud-function/src/middlewares/server-timing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,28 +8,27 @@ export async function addServerTimingHeaders(
res: Response,
next: NextFunction
) {
const timers = new Map<
string,
{ finished: boolean; hrtime: [number, number] }
>();
const timers = new Map<string, { start: bigint; diff?: bigint }>();

req.startServerTiming = (id: string) => {
timers.set(id, { finished: false, hrtime: hrtime() });
timers.set(id, { start: hrtime.bigint() });
};

req.endServerTiming = (id: string) => {
timers.set(id, { finished: true, hrtime: hrtime(timers.get(id)?.hrtime) });
const start = timers.get(id)?.start;
if (start !== undefined) {
timers.set(id, { start, diff: hrtime.bigint() - start });
}
};

req.startServerTiming("total");

onHeaders(res, () => {
req.endServerTiming("total");
const header = [...timers]
.filter(([, { finished }]) => finished)
.map(
([id, { hrtime }]) =>
`${id};dur=${((hrtime[0] * 1e9 + hrtime[1]) / 1e6).toFixed(0)}`
)
.map(([id, { start, diff }]) => {
const time = diff !== undefined ? diff : hrtime.bigint() - start;
return `${id};dur=${time / BigInt(1e6)}`;
})
.join(", ");
res.setHeader("Server-Timing", header);
});
Expand Down

0 comments on commit 3f264cf

Please sign in to comment.