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);