feat: add open telemetry instrumentation (#2786)

This commit adds some useful automatic instrumentation for when users
are using `--unstable-otel`:

- Fresh renames the span for incoming HTTP requests to `$METHOD $ROUTE`
and the `http.route` attribute is added.
- Fresh creates a span around FS route handlers, showing whether they
returned a response or data.
- Fresh creates a span around async components, showing how long they
took to execute.
- Fresh adds a span around preact rendering, showing how long rendering
takes.
- Fresh adds a span around static file serving, showing how long it took
and whether there were requests without a cache bust key.

We can improve this in the future with more telemetry, such as metrics.
This commit is contained in:
Luca Casonato
2024-12-10 15:03:50 +01:00
committed by GitHub
parent 4a25ac385f
commit 65d61bd1d5
22 changed files with 1380 additions and 203 deletions
+14 -6
View File
@@ -1,3 +1,8 @@
import * as path from "@std/path";
import { type ComponentType, h } from "preact";
import { renderToString } from "preact-render-to-string";
import { trace } from "@opentelemetry/api";
import { DENO_DEPLOYMENT_ID } from "./runtime/build_id.ts";
import * as colors from "@std/fmt/colors";
import { type MiddlewareFn, runMiddlewares } from "./middlewares/mod.ts";
@@ -14,10 +19,7 @@ import {
type ResolvedFreshConfig,
} from "./config.ts";
import { type BuildCache, ProdBuildCache } from "./build_cache.ts";
import * as path from "@std/path";
import { type ComponentType, h } from "preact";
import type { ServerIslandRegistry } from "./context.ts";
import { renderToString } from "preact-render-to-string";
import { FinishSetup, ForgotBuild } from "./finish_setup.tsx";
import { HttpError } from "./error.ts";
@@ -140,8 +142,8 @@ export class App<State> {
// Special case when user calls one of these:
// - `app.mountApp("/", otherApp)`
// - `app.mountApp("*", otherApp)`
const isSelf = path === "*" || path === "/";
// - `app.mountApp("/*", otherApp)`
const isSelf = path === "/*" || path === "/";
if (isSelf && middlewares.length > 0) {
this.#router._middlewares.push(...middlewares);
}
@@ -205,7 +207,7 @@ export class App<State> {
? DEFAULT_NOT_ALLOWED_METHOD
: DEFAULT_NOT_FOUND;
const { params, handlers } = matched;
const { params, handlers, pattern } = matched;
const ctx = new FreshReqContext<State>(
req,
url,
@@ -217,6 +219,12 @@ export class App<State> {
this.#buildCache!,
);
const span = trace.getActiveSpan();
if (span && pattern) {
span.updateName(`${method} ${pattern}`);
span.setAttribute("http.route", pattern);
}
try {
if (handlers.length === 1 && handlers[0].length === 1) {
return handlers[0][0](ctx);
+27 -8
View File
@@ -6,6 +6,7 @@ import {
type VNode,
} from "preact";
import { renderToString } from "preact-render-to-string";
import { SpanStatusCode } from "@opentelemetry/api";
import type { ResolvedFreshConfig } from "./config.ts";
import type { BuildCache } from "./build_cache.ts";
import {
@@ -15,6 +16,7 @@ import {
} from "./runtime/server/preact_hooks.tsx";
import { DEV_ERROR_OVERLAY_URL } from "./constants.ts";
import { BUILD_ID } from "./runtime/build_id.ts";
import { tracer } from "./otel.ts";
export interface Island {
file: string | URL;
@@ -184,14 +186,31 @@ export class FreshReqContext<State>
headers.set("X-Fresh-Id", partialId);
}
const html = preactRender(
vnode,
this,
this.#islandRegistry,
this.#buildCache,
partialId,
headers,
);
const html = tracer.startActiveSpan("render", (span) => {
span.setAttribute("fresh.span_type", "render");
try {
return preactRender(
vnode,
this,
this.#islandRegistry,
this.#buildCache,
partialId,
headers,
);
} catch (err) {
if (err instanceof Error) {
span.recordException(err);
} else {
span.setStatus({
code: SpanStatusCode.ERROR,
message: String(err),
});
}
throw err;
} finally {
span.end();
}
});
return new Response(html, responseInit);
}
}
+1 -1
View File
@@ -68,7 +68,7 @@ export class Builder implements FreshBuilder {
const devApp = new App<T>(app.config)
.use(liveReload())
.use(devErrorOverlay())
.mountApp("*", app);
.mountApp("/*", app);
devApp.config.mode = "development";
+3 -4
View File
@@ -1,6 +1,7 @@
import * as semver from "@std/semver";
import * as colors from "@std/fmt/colors";
import * as path from "@std/path";
import { CURRENT_FRESH_VERSION } from "../otel.ts";
export interface CheckFile {
last_checked: string;
@@ -48,10 +49,8 @@ async function fetchLatestVersion() {
throw new Error(`Could not fetch latest version.`);
}
async function readCurrentVersion() {
return (await import("../../deno.json", {
with: { type: "json" },
})).default.version;
function readCurrentVersion() {
return CURRENT_FRESH_VERSION;
}
export async function updateCheck(
+66 -50
View File
@@ -4,6 +4,7 @@ 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";
/**
* Fresh middleware to enable file-system based routing.
@@ -25,6 +26,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
@@ -39,60 +41,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 ext = path.extname(pathname);
const etag = file.hash;
const contentType = getContentType(ext);
const headers = new Headers({
"Content-Type": contentType ?? "text/plain",
vary: "If-None-Match",
const span = tracer.startSpan("static file", {
attributes: { "fresh.span_type": "static_file" },
startTime,
});
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}"`);
}
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,
},
});
}
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 ext = path.extname(pathname);
const etag = file.hash;
headers.set("Content-Length", String(file.size));
if (req.method === "HEAD") {
file.close();
return new Response(null, { status: 200, headers });
}
const contentType = getContentType(ext);
const headers = new Headers({
"Content-Type": contentType ?? "text/plain",
vary: "If-None-Match",
});
return new Response(file.readable, { headers });
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}"`);
}
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 });
} finally {
span.end();
}
};
}
+6
View File
@@ -0,0 +1,6 @@
import { trace } from "@opentelemetry/api";
import denoJson from "../deno.json" with { type: "json" };
export const CURRENT_FRESH_VERSION = denoJson.version;
export const tracer = trace.getTracer("fresh", CURRENT_FRESH_VERSION);
+1 -1
View File
@@ -251,7 +251,7 @@ export async function fsRoutes<State>(
errorComponents.push(mod.component);
}
let parent = mod.path.slice(0, -"_error".length);
parent = parent === "/" ? "*" : parent + "*";
parent = parent + "*";
// Add error route as its own route
if (!specialPaths.has(mod.path)) {
+52 -2
View File
@@ -3,6 +3,8 @@ import type { MiddlewareFn } from "../../middlewares/mod.ts";
import type { HandlerFn, PageResponse } from "../../handlers.ts";
import type { FreshReqContext, PageProps } from "../../context.ts";
import { HttpError } from "../../error.ts";
import { tracer } from "../../otel.ts";
import { SpanStatusCode } from "@opentelemetry/api";
export type AsyncAnyComponent<P> = {
(
@@ -31,7 +33,30 @@ export function renderMiddleware<State>(
return async (ctx) => {
let result: PageResponse<unknown> | undefined;
if (handler !== undefined) {
const res = await handler(ctx);
const res = await tracer.startActiveSpan("handler", {
attributes: { "fresh.span_type": "fs_routes/handler" },
}, async (span) => {
try {
const res = await handler(ctx);
span.setAttribute(
"fresh.handler_response",
res instanceof Response ? "http" : "data",
);
return res;
} catch (err) {
if (err instanceof Error) {
span.recordException(err);
} else {
span.setStatus({
code: SpanStatusCode.ERROR,
message: String(err),
});
}
throw err;
} finally {
span.end();
}
});
if (res instanceof Response) {
return res;
@@ -56,7 +81,32 @@ export function renderMiddleware<State>(
const fn = components[i];
if (isAsyncAnyComponent(fn)) {
const result = (await fn(props)) as VNode | Response;
const result = await tracer.startActiveSpan(
"invoke async component",
async (span) => {
span.setAttribute("fresh.span_type", "fs_routes/async_component");
try {
const result = (await fn(props)) as VNode | Response;
span.setAttribute(
"fresh.component_response",
result instanceof Response ? "http" : "jsx",
);
return result;
} catch (err) {
if (err instanceof Error) {
span.recordException(err);
} else {
span.setStatus({
code: SpanStatusCode.ERROR,
message: String(err),
});
}
throw err;
} finally {
span.end();
}
},
);
if (result instanceof Response) {
return result;
}
+10 -10
View File
@@ -11,6 +11,7 @@ export interface RouteResult<T> {
handlers: T[][];
methodMatch: boolean;
patternMatch: boolean;
pattern: string | null;
}
export interface Router<T> {
@@ -28,7 +29,7 @@ export interface Router<T> {
export const IS_PATTERN = /[*:{}+?()]/;
export function mergePaths(a: string, b: string) {
if (a === "" || a === "/" || a === "*") return b;
if (a === "" || a === "/" || a === "/*") return b;
if (b === "/") return a;
if (a.endsWith("/")) {
return a.slice(0, -1) + b;
@@ -48,7 +49,7 @@ export class UrlPatternRouter<T> implements Router<T> {
add(method: Method | "ALL", pathname: string | URLPattern, handlers: T[]) {
if (
typeof pathname === "string" && pathname !== "*" &&
typeof pathname === "string" && pathname !== "/*" &&
IS_PATTERN.test(pathname)
) {
this._routes.push({
@@ -71,6 +72,7 @@ export class UrlPatternRouter<T> implements Router<T> {
handlers: [],
methodMatch: false,
patternMatch: false,
pattern: null,
};
if (this._middlewares.length > 0) {
@@ -84,16 +86,15 @@ export class UrlPatternRouter<T> implements Router<T> {
// to be either wildcard `*` match or an exact pathname match.
if (
typeof route.path === "string" &&
(route.path === "*" || route.path === url.pathname)
(route.path === "/*" || route.path === url.pathname)
) {
if (route.method !== "ALL") {
result.patternMatch = true;
}
if (route.method !== "ALL") result.patternMatch = true;
result.pattern = route.path;
if (route.method === "ALL" || route.method === method) {
result.handlers.push(route.handlers);
if (route.path === "*" && route.method === "ALL") {
if (route.path === "/*" && route.method === "ALL") {
continue;
}
@@ -104,9 +105,8 @@ export class UrlPatternRouter<T> implements Router<T> {
} else if (route.path instanceof URLPattern) {
const match = route.path.exec(url);
if (match !== null) {
if (route.method !== "ALL") {
result.patternMatch = true;
}
if (route.method !== "ALL") result.patternMatch = true;
result.pattern = route.path.pathname;
if (route.method === "ALL" || route.method === method) {
result.handlers.push(route.handlers);
+10 -3
View File
@@ -30,6 +30,7 @@ Deno.test("UrlPatternRouter - GET get first match", () => {
params: {},
handlers: [[A]],
methodMatch: true,
pattern: "/",
patternMatch: true,
});
});
@@ -39,8 +40,8 @@ Deno.test("UrlPatternRouter - GET get matches with middlewares", () => {
const A = () => {};
const B = () => {};
const C = () => {};
router.add("ALL", "*", [A]);
router.add("ALL", "*", [B]);
router.add("ALL", "/*", [A]);
router.add("ALL", "/*", [B]);
router.add("GET", "/", [C]);
const res = router.match("GET", new URL("/", "http://localhost"));
@@ -48,6 +49,7 @@ Deno.test("UrlPatternRouter - GET get matches with middlewares", () => {
params: {},
handlers: [[A], [B], [C]],
methodMatch: true,
pattern: "/",
patternMatch: true,
});
});
@@ -62,6 +64,7 @@ Deno.test("UrlPatternRouter - GET extract params", () => {
params: { foo: "a", bar: "b" },
handlers: [[A]],
methodMatch: true,
pattern: "/:foo/:bar/c",
patternMatch: true,
});
@@ -71,6 +74,7 @@ Deno.test("UrlPatternRouter - GET extract params", () => {
params: { foo: "a a", bar: "b" },
handlers: [[A]],
methodMatch: true,
pattern: "/:foo/:bar/c",
patternMatch: true,
});
});
@@ -85,6 +89,7 @@ Deno.test("UrlPatternRouter - Wrong method match", () => {
params: {},
handlers: [],
methodMatch: false,
pattern: "/foo",
patternMatch: true,
});
});
@@ -101,6 +106,7 @@ Deno.test("UrlPatternRouter - wrong + correct method", () => {
params: {},
handlers: [[B]],
methodMatch: true,
pattern: "/foo",
patternMatch: true,
});
});
@@ -117,6 +123,7 @@ Deno.test("UrlPatternRouter - convert patterns automatically", () => {
},
handlers: [[A]],
methodMatch: true,
pattern: "/books/:id",
patternMatch: true,
});
});
@@ -173,7 +180,7 @@ Deno.test("pathToPattern", async (t) => {
Deno.test("mergePaths", () => {
expect(mergePaths("", "")).toEqual("");
expect(mergePaths("/", "/foo")).toEqual("/foo");
expect(mergePaths("*", "/foo")).toEqual("/foo");
expect(mergePaths("/*", "/foo")).toEqual("/foo");
expect(mergePaths("/foo/bar", "/baz")).toEqual("/foo/bar/baz");
expect(mergePaths("/foo/bar/", "/baz")).toEqual("/foo/bar/baz");
expect(mergePaths("/foo/bar", "baz")).toEqual("/foo/bar/baz");