Skip to content

Commit

Permalink
Add span for static file handler
Browse files Browse the repository at this point in the history
  • Loading branch information
lucacasonato committed Dec 10, 2024
1 parent 3054803 commit 28c45de
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 51 deletions.
115 changes: 66 additions & 49 deletions src/middlewares/static_files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import type { MiddlewareFn } from "./mod.ts";
import { ASSET_CACHE_BUST_KEY } from "../runtime/shared_internal.tsx";
import { BUILD_ID } from "../runtime/build_id.ts";
import { getBuildCache } from "../context.ts";
import { tracer } from "../otel.ts";
import { context, trace } from "@opentelemetry/api";

/**
* Fresh middleware to enable file-system based routing.
Expand All @@ -25,6 +27,7 @@ export function staticFiles<T>(): MiddlewareFn<T> {
}

// Fast path bail out
const startTime = performance.now() + performance.timeOrigin;
const file = await buildCache.readFile(pathname);
if (pathname === "/" || file === null) {
// Optimization: Prevent long responses for favicon.ico requests
Expand All @@ -39,60 +42,74 @@ export function staticFiles<T>(): MiddlewareFn<T> {
return new Response("Method Not Allowed", { status: 405 });
}

const cacheKey = url.searchParams.get(ASSET_CACHE_BUST_KEY);
if (cacheKey !== null && BUILD_ID !== cacheKey) {
url.searchParams.delete(ASSET_CACHE_BUST_KEY);
const location = url.pathname + url.search;
file.close();
return new Response(null, {
status: 307,
headers: {
location,
},
});
}
const span = tracer.startSpan("static file", {
attributes: { "fresh.span_type": "static_file" },
startTime,
});

const ext = path.extname(pathname);
const etag = file.hash;
try {
const cacheKey = url.searchParams.get(ASSET_CACHE_BUST_KEY);
if (cacheKey !== null && BUILD_ID !== cacheKey) {
url.searchParams.delete(ASSET_CACHE_BUST_KEY);
const location = url.pathname + url.search;
file.close();
span.setAttribute("fresh.cache", "invalid_bust_key");
span.setAttribute("fresh.cache_key", cacheKey);
return new Response(null, {
status: 307,
headers: {
location,
},
});
}

const contentType = getContentType(ext);
const headers = new Headers({
"Content-Type": contentType ?? "text/plain",
vary: "If-None-Match",
});
const ext = path.extname(pathname);
const etag = file.hash;

const ifNoneMatch = req.headers.get("If-None-Match");
if (
ifNoneMatch !== null &&
(ifNoneMatch === etag || ifNoneMatch === `W/"${etag}"`)
) {
file.close();
return new Response(null, { status: 304, headers });
} else if (etag !== null) {
headers.set("Etag", `W/"${etag}"`);
}
const contentType = getContentType(ext);
const headers = new Headers({
"Content-Type": contentType ?? "text/plain",
vary: "If-None-Match",
});

if (
ctx.config.mode !== "development" &&
(BUILD_ID === cacheKey ||
url.pathname.startsWith(
`${ctx.config.basePath}/_fresh/js/${BUILD_ID}/`,
))
) {
headers.append("Cache-Control", "public, max-age=31536000, immutable");
} else {
headers.append(
"Cache-Control",
"no-cache, no-store, max-age=0, must-revalidate",
);
}
const ifNoneMatch = req.headers.get("If-None-Match");
if (
ifNoneMatch !== null &&
(ifNoneMatch === etag || ifNoneMatch === `W/"${etag}"`)
) {
file.close();
span.setAttribute("fresh.cache", "not_modified");
return new Response(null, { status: 304, headers });
} else if (etag !== null) {
headers.set("Etag", `W/"${etag}"`);
}

headers.set("Content-Length", String(file.size));
if (req.method === "HEAD") {
file.close();
return new Response(null, { status: 200, headers });
}
if (
ctx.config.mode !== "development" &&
(BUILD_ID === cacheKey ||
url.pathname.startsWith(
`${ctx.config.basePath}/_fresh/js/${BUILD_ID}/`,
))
) {
span.setAttribute("fresh.cache", "immutable");
headers.append("Cache-Control", "public, max-age=31536000, immutable");
} else {
span.setAttribute("fresh.cache", "no_cache");
headers.append(
"Cache-Control",
"no-cache, no-store, max-age=0, must-revalidate",
);
}

headers.set("Content-Length", String(file.size));
if (req.method === "HEAD") {
file.close();
return new Response(null, { status: 200, headers });
}

return new Response(file.readable, { headers });
return new Response(file.readable, { headers });
} finally {
span.end();
}
};
}
5 changes: 3 additions & 2 deletions src/plugins/fs_routes/render_middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,9 @@ export function renderMiddleware<State>(
return async (ctx) => {
let result: PageResponse<unknown> | undefined;
if (handler !== undefined) {
const res = await tracer.startActiveSpan("handler", async (span) => {
span.setAttribute("fresh.span_type", "fs_routes/handler");
const res = await tracer.startActiveSpan("handler", {
attributes: { "fresh.span_type": "fs_routes/handler" },
}, async (span) => {
try {
const res = await handler(ctx);
span.setAttribute(
Expand Down

0 comments on commit 28c45de

Please sign in to comment.