Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions apps/cloud/src/observability/telemetry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ import { trace } from "@opentelemetry/api";
// which workerd does support.
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http/build/esm/platform/browser/index.js";
import { resourceFromAttributes } from "@opentelemetry/resources";
import { SimpleSpanProcessor } from "@opentelemetry/sdk-trace-base";
import { BatchSpanProcessor } from "@opentelemetry/sdk-trace-base";
import { WebTracerProvider } from "@opentelemetry/sdk-trace-web";
import { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION } from "@opentelemetry/semantic-conventions";
import { env } from "cloudflare:workers";
Expand All @@ -61,14 +61,21 @@ const ensureGlobalTracerProvider = (): boolean => {
[ATTR_SERVICE_VERSION]: SERVICE_VERSION,
}),
spanProcessors: [
new SimpleSpanProcessor(
// Batch, not Simple: SimpleSpanProcessor issues one synchronous fetch
// per span END — a busy MCP request emits dozens of spans, and the
// serialized export fetches add seconds of latency inside the request
// (enough to flip pause/resume timing in e2e). Batch buffers and
// ships on a timer; `ctx.waitUntil(flushTracerProvider())` at the end
// of each request still drains the buffer before the isolate exits.
new BatchSpanProcessor(
new OTLPTraceExporter({
url: env.AXIOM_TRACES_URL ?? "https://api.axiom.co/v1/traces",
headers: {
Authorization: `Bearer ${env.AXIOM_TOKEN}`,
"X-Axiom-Dataset": env.AXIOM_DATASET ?? "executor-cloud",
},
}),
{ scheduledDelayMillis: 1_000, maxExportBatchSize: 512 },
),
],
});
Expand Down
70 changes: 45 additions & 25 deletions apps/cloud/src/server.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { SpanStatusCode, trace } from "@opentelemetry/api";
import { SpanKind, SpanStatusCode, context, trace } from "@opentelemetry/api";
import {
ATTR_HTTP_REQUEST_METHOD,
ATTR_HTTP_RESPONSE_STATUS_CODE,
Expand Down Expand Up @@ -72,32 +72,52 @@ const cloudflareHandler: ExportedHandler<Env> = {
return fetchHandler(request, env, ctx);
}
const url = new URL(request.url);
return tracer.startActiveSpan(`http.server ${request.method}`, async (span) => {
span.setAttribute(ATTR_HTTP_REQUEST_METHOD, request.method);
span.setAttribute(ATTR_URL_FULL, request.url);
span.setAttribute(ATTR_URL_PATH, url.pathname);
span.setAttribute(ATTR_URL_SCHEME, url.protocol.replace(/:$/, ""));
// Adapter boundary: Cloudflare's fetch handler is a Promise-based
// callback and the OTel span lifecycle needs to observe both the
// resolved response and any thrown error before `span.end()`. Sentry's
// outer wrapper still captures the exception; we only mark span status.
// oxlint-disable-next-line executor/no-try-catch-or-throw -- adapter boundary
try {
const response = await fetchHandler(request, env, ctx);
span.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE, response.status);
if (response.status >= 500) {
// Join the caller's W3C trace when the request carries one — the web UI
// sends traceparent on every API fetch, so the browser's spans and this
// request share one trace id end to end. Same parsing the DO path does
// in session-durable-object.ts.
const traceparentMatch = /^[0-9a-f]{2}-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/.exec(
request.headers.get("traceparent") ?? "",
);
const parentContext = traceparentMatch
? trace.setSpanContext(context.active(), {
traceId: traceparentMatch[1]!,
spanId: traceparentMatch[2]!,
traceFlags: parseInt(traceparentMatch[3]!, 16),
isRemote: true,
})
: context.active();
return tracer.startActiveSpan(
`http.server ${request.method}`,
{ kind: SpanKind.SERVER },
parentContext,
async (span) => {
span.setAttribute(ATTR_HTTP_REQUEST_METHOD, request.method);
span.setAttribute(ATTR_URL_FULL, request.url);
span.setAttribute(ATTR_URL_PATH, url.pathname);
span.setAttribute(ATTR_URL_SCHEME, url.protocol.replace(/:$/, ""));
// Adapter boundary: Cloudflare's fetch handler is a Promise-based
// callback and the OTel span lifecycle needs to observe both the
// resolved response and any thrown error before `span.end()`. Sentry's
// outer wrapper still captures the exception; we only mark span status.
// oxlint-disable-next-line executor/no-try-catch-or-throw -- adapter boundary
try {
const response = await fetchHandler(request, env, ctx);
span.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE, response.status);
if (response.status >= 500) {
span.setStatus({ code: SpanStatusCode.ERROR });
}
return response;
} catch (err) {
span.setStatus({ code: SpanStatusCode.ERROR });
// oxlint-disable-next-line executor/no-try-catch-or-throw -- adapter boundary; preserve original error to Cloudflare runtime
throw err;
} finally {
span.end();
ctx.waitUntil(flushTracerProvider());
}
return response;
} catch (err) {
span.setStatus({ code: SpanStatusCode.ERROR });
// oxlint-disable-next-line executor/no-try-catch-or-throw -- adapter boundary; preserve original error to Cloudflare runtime
throw err;
} finally {
span.end();
ctx.waitUntil(flushTracerProvider());
}
});
},
);
},
};

Expand Down
9 changes: 9 additions & 0 deletions apps/cloud/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,15 @@ export default defineConfig(({ mode }) => {
.filter(([key]) => key.startsWith("VITE_PUBLIC_"))
.map(([key, value]) => [`import.meta.env.${key}`, JSON.stringify(value)]),
),
// Browser OTLP spans (VITE_PUBLIC_OTLP_TRACES_URL=/v1/traces, set by the
// e2e global setup) go same-origin and proxy to the local motel server —
// motel serves no CORS headers, so a direct cross-origin post would die
// in preflight. Dev-only; unrouted when nothing listens.
server: {
proxy: {
"/v1/traces": process.env.MOTEL_URL ?? "http://127.0.0.1:27686",
},
},
resolve: { tsconfigPaths: true },
plugins: [
devCrashGuard(),
Expand Down
Loading
Loading