Skip to content
TypeScript

feat(web): configure OpenTelemetry exports in diagnostics (#12538)

Matthew Feroze7db61f6799f
diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts
index 60589ac9106..bb5ce86e60d 100644
--- a/apps/server/src/environment/ServerEnvironment.ts
+++ b/apps/server/src/environment/ServerEnvironment.ts
@@ -229,6 +229,7 @@ export const make = Effect.gen(function* () {
threadAutoSettlement: true,
storageCleanup: true,
storageCleanupRun: true,
+ otlpEndpointCheck: true,
projectWorktreeCleanup: true,
worktreesDirectory: true,
threadRestartContinuation: true,
diff --git a/apps/server/src/observability/OtlpEndpointCheck.test.ts b/apps/server/src/observability/OtlpEndpointCheck.test.ts
new file mode 100644
index 00000000000..e7551d722ad
--- /dev/null
+++ b/apps/server/src/observability/OtlpEndpointCheck.test.ts
@@ -0,0 +1,249 @@
+import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
+import * as NodeServices from "@effect/platform-node/NodeServices";
+import { assert, it } from "@effect/vitest";
+import { DEFAULT_SIGNAL_EXPORT } from "@t3tools/shared/observability";
+import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as Tracer from "effect/Tracer";
+import * as NetAddress from "effect/net/NetAddress";
+import {
+ FetchHttpClient,
+ HttpClient,
+ HttpClientError,
+ HttpClientResponse,
+ HttpServer,
+ HttpServerRequest,
+ HttpServerResponse,
+} from "effect/http";
+import { describe } from "vite-plus/test";
+
+import * as ServerConfig from "../config.ts";
+import * as OtlpEndpointCheck from "./OtlpEndpointCheck.ts";
+
+interface PostedRequest {
+ readonly url: string;
+ readonly headers: Readonly<Record<string, string>>;
+ readonly body: string;
+ readonly signal: AbortSignal;
+}
+
+/** Answers every post with `status`, or fails like a refused connection when it is null. */
+const checkWith = (
+ status: number | null,
+ overrides: Partial<ServerConfig.ServerConfig["Service"]> = {},
+ httpClientLayer?: Layer.Layer<HttpClient.HttpClient>,
+) => {
+ const requests: Array<PostedRequest> = [];
+ const httpClient = HttpClient.make((request, _url, signal) => {
+ requests.push({
+ url: request.url,
+ headers: request.headers,
+ body: request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "",
+ signal,
+ });
+ return status === null
+ ? Effect.fail(
+ new HttpClientError.HttpClientError({
+ reason: new HttpClientError.TransportError({ request }),
+ }),
+ )
+ : Effect.succeed(HttpClientResponse.fromWeb(request, new Response(null, { status })));
+ });
+ const configLayer = Layer.effect(
+ ServerConfig.ServerConfig,
+ Effect.gen(function* () {
+ const config = yield* ServerConfig.ServerConfig;
+ return ServerConfig.make({ ...config, ...overrides });
+ }),
+ ).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-otlp-check-" })));
+ const layer = OtlpEndpointCheck.layer.pipe(
+ Layer.provide(httpClientLayer ?? Layer.succeed(HttpClient.HttpClient, httpClient)),
+ Layer.provide(configLayer),
+ Layer.provide(NodeServices.layer),
+ );
+ return { requests, layer };
+};
+
+const check = (input: Parameters<OtlpEndpointCheck.OtlpEndpointCheck["Service"]["check"]>[0]) =>
+ Effect.gen(function* () {
+ const service = yield* OtlpEndpointCheck.OtlpEndpointCheck;
+ return yield* service.check(input);
+ });
+
+describe("OtlpEndpointCheck", () => {
+ it.effect("posts an empty export for the signal with the T3 headers", () => {
+ const { requests, layer } = checkWith(200, {
+ otlpMetricsUrl: "http://collector:4318/v1/metrics",
+ otlpMetricsExport: { ...DEFAULT_SIGNAL_EXPORT, headers: { authorization: "Bearer t3" } },
+ });
+ return Effect.gen(function* () {
+ const result = yield* check({ signal: "metrics", url: "http://collector:4318/v1/metrics" });
+
+ assert.strictEqual(result._tag, "Accepted");
+ assert.lengthOf(requests, 1);
+ assert.strictEqual(requests[0]?.url, "http://collector:4318/v1/metrics");
+ assert.strictEqual(requests[0]?.headers.authorization, "Bearer t3");
+ assert.strictEqual(requests[0]?.body, `{"resourceMetrics":[]}`);
+ }).pipe(Effect.provide(layer));
+ });
+
+ it.effect("keeps T3 credentials paired with each running signal endpoint", () => {
+ const signalExport = { ...DEFAULT_SIGNAL_EXPORT, headers: { "x-api-key": "secret" } };
+ const { requests, layer } = checkWith(200, {
+ otlpTracesUrl: "https://collector.example.com/v1/traces",
+ otlpMetricsUrl: "https://collector.example.com/v1/metrics",
+ otlpLogsUrl: "https://collector.example.com/v1/logs",
+ otlpTracesExport: signalExport,
+ otlpMetricsExport: signalExport,
+ otlpLogsExport: signalExport,
+ otelEnvironment: OtelEnvironment.none,
+ });
+ return Effect.gen(function* () {
+ for (const signal of ["traces", "metrics", "logs"] as const) {
+ const runningUrl = `https://collector.example.com/v1/${signal}`;
+ yield* check({ signal, url: runningUrl });
+ yield* check({ signal, url: "https://elsewhere.example.com/collect" });
+ yield* check({ signal, url: `${runningUrl}/other` });
+ yield* check({ signal, url: `${runningUrl}?tenant=other` });
+ }
+
+ assert.lengthOf(requests, 12);
+ requests.forEach((request, index) => {
+ if (index % 4 === 0) assert.strictEqual(request.headers["x-api-key"], "secret");
+ else assert.isUndefined(request.headers["x-api-key"]);
+ });
+ }).pipe(Effect.provide(layer));
+ });
+
+ it.effect("does not send export credentials when the signal has no running endpoint", () => {
+ const { requests, layer } = checkWith(200, {
+ otlpLogsUrl: undefined,
+ otlpLogsExport: { ...DEFAULT_SIGNAL_EXPORT, headers: { authorization: "Bearer t3" } },
+ otelEnvironment: OtelEnvironment.none,
+ });
+ return Effect.gen(function* () {
+ const result = yield* check({ signal: "logs", url: "https://new.example.com/v1/logs" });
+
+ assert.strictEqual(result._tag, "Accepted");
+ assert.lengthOf(requests, 1);
+ assert.isUndefined(requests[0]?.headers.authorization);
+ }).pipe(Effect.provide(layer));
+ });
+
+ it.effect("releases the request once the status is known", () => {
+ const { requests, layer } = checkWith(200);
+ return Effect.gen(function* () {
+ yield* check({ signal: "traces", url: "http://collector:4318/v1/traces" });
+
+ assert.isTrue(requests[0]?.signal.aborted);
+ }).pipe(Effect.provide(layer));
+ });
+
+ it.effect("keeps endpoint URLs and credentials out of traces", () => {
+ const url = "https://collector.example.com/v1/logs?api_key=query-secret";
+ const { requests, layer } = checkWith(200, {
+ otlpLogsUrl: url,
+ otlpLogsExport: {
+ ...DEFAULT_SIGNAL_EXPORT,
+ headers: { "x-honeycomb-team": "header-secret" },
+ },
+ otelEnvironment: OtelEnvironment.none,
+ });
+ const recorded: Array<unknown> = [];
+ const tracer = Tracer.make({
+ span: (options) => {
+ const span = new Tracer.NativeSpan(options);
+ const end = span.end.bind(span);
+ span.end = (endTime, exit) => {
+ end(endTime, exit);
+ recorded.push({ name: span.name, attributes: Object.fromEntries(span.attributes) });
+ };
+ return span;
+ },
+ });
+ return Effect.gen(function* () {
+ yield* check({ signal: "logs", url }).pipe(Effect.withTracer(tracer));
+
+ assert.strictEqual(requests[0]?.headers["x-honeycomb-team"], "header-secret");
+ assert.notInclude(JSON.stringify(recorded), "secret");
+ }).pipe(Effect.provide(layer));
+ });
+
+ it.effect("does not forward credentials through a receiver redirect", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const requests: Array<{ url: string; apiKey: string | undefined }> = [];
+ const server = yield* HttpServer.HttpServer;
+ yield* server.serve(
+ Effect.gen(function* () {
+ const request = yield* HttpServerRequest.HttpServerRequest;
+ yield* request.text;
+ requests.push({ url: request.url, apiKey: request.headers["x-api-key"] });
+ return request.url === "/v1/traces"
+ ? HttpServerResponse.redirect("/other", { status: 307 })
+ : HttpServerResponse.empty({ status: 200 });
+ }),
+ );
+ if (!NetAddress.isInetAddress(server.address)) {
+ return yield* Effect.die(new Error("Expected a TCP address"));
+ }
+ const url = `http://127.0.0.1:${server.address.port}/v1/traces`;
+ const { layer } = checkWith(
+ 200,
+ {
+ otlpTracesUrl: url,
+ otlpTracesExport: { ...DEFAULT_SIGNAL_EXPORT, headers: { "x-api-key": "secret" } },
+ },
+ FetchHttpClient.layer,
+ );
+ const result = yield* check({ signal: "traces", url }).pipe(Effect.provide(layer));
+
+ assert.deepStrictEqual(result, { _tag: "Rejected", status: 307 });
+ assert.deepStrictEqual(requests, [{ url: "/v1/traces", apiKey: "secret" }]);
+ }),
+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),
+ );
+
+ it.effect("reports the status a receiver rejects the export with", () => {
+ const { layer } = checkWith(401);
+ return Effect.gen(function* () {
+ const result = yield* check({ signal: "traces", url: "http://collector:4318/v1/traces" });
+
+ assert.deepStrictEqual(result, { _tag: "Rejected", status: 401 });
+ }).pipe(Effect.provide(layer));
+ });
+
+ it.effect("reports an endpoint that cannot be reached", () => {
+ const { layer } = checkWith(null);
+ return Effect.gen(function* () {
+ const result = yield* check({ signal: "logs", url: "http://localhost:1/v1/logs" });
+
+ assert.deepStrictEqual(result, { _tag: "Unreachable", timedOut: false });
+ }).pipe(Effect.provide(layer));
+ });
+
+ it.effect("keeps OTEL endpoint credentials off other endpoints", () => {
+ const otelUrl = "https://otel.example.com/v1/traces";
+ const otelExport = { ...DEFAULT_SIGNAL_EXPORT, headers: { "x-api-key": "secret" } };
+ const { requests, layer } = checkWith(200, {
+ otlpTracesUrl: otelUrl,
+ otlpTracesExport: otelExport,
+ otelEnvironment: {
+ ...OtelEnvironment.none,
+ traces: OtelEnvironment.OtelSignal.Export({
+ url: otelUrl,
+ protocol: otelExport.protocol,
+ headers: otelExport.headers,
+ }),
+ },
+ });
+ return Effect.gen(function* () {
+ yield* check({ signal: "traces", url: otelUrl });
+ yield* check({ signal: "traces", url: "https://elsewhere.example.com/v1/traces" });
+
+ assert.strictEqual(requests[0]?.headers["x-api-key"], "secret");
+ assert.isUndefined(requests[1]?.headers["x-api-key"]);
+ }).pipe(Effect.provide(layer));
+ });
+});
diff --git a/apps/server/src/observability/OtlpEndpointCheck.ts b/apps/server/src/observability/OtlpEndpointCheck.ts
new file mode 100644
index 00000000000..919f83ec2e5
--- /dev/null
+++ b/apps/server/src/observability/OtlpEndpointCheck.ts
@@ -0,0 +1,98 @@
+import type {
+ OtlpEndpointCheckInput,
+ OtlpEndpointCheckResult,
+ OtlpSignal,
+} from "@t3tools/contracts";
+import { layerOtlpSerialization } from "@t3tools/shared/observability";
+import * as Clock from "effect/Clock";
+import * as Context from "effect/Context";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
+import { FetchHttpClient, HttpClient } from "effect/http";
+import { OtlpSerialization } from "effect/observability";
+
+import * as ServerConfig from "../config.ts";
+
+const CHECK_TIMEOUT = "5 seconds";
+
+export class OtlpEndpointCheck extends Context.Service<
+ OtlpEndpointCheck,
+ {
+ /**
+ * Posts an empty export for the signal to `url` from this server, with the
+ * running signal's protocol. Credentials are used only for its exact
+ * running endpoint, and redirects are not followed. Receivers accept an
+ * empty export without storing anything.
+ */
+ readonly check: (input: OtlpEndpointCheckInput) => Effect.Effect<OtlpEndpointCheckResult>;
+ }
+>()("t3/observability/OtlpEndpointCheck") {}
+
+const emptyExport = (
+ serialization: OtlpSerialization.OtlpSerialization["Service"],
+ signal: OtlpSignal,
+) => {
+ switch (signal) {
+ case "traces":
+ return serialization.traces({ resourceSpans: [] });
+ case "metrics":
+ return serialization.metrics({ resourceMetrics: [] });
+ case "logs":
+ return serialization.logs({ resourceLogs: [] });
+ }
+};
+
+const make = Effect.gen(function* () {
+ const config = yield* ServerConfig.ServerConfig;
+ const httpClient = yield* HttpClient.HttpClient;
+
+ const running = {
+ traces: { url: config.otlpTracesUrl, export: config.otlpTracesExport },
+ metrics: { url: config.otlpMetricsUrl, export: config.otlpMetricsExport },
+ logs: { url: config.otlpLogsUrl, export: config.otlpLogsExport },
+ } satisfies Record<OtlpSignal, unknown>;
+
+ const check = Effect.fn("OtlpEndpointCheck.check")(function* ({
+ signal,
+ url,
+ }: OtlpEndpointCheckInput) {
+ const { url: runningUrl, export: signalExport } = running[signal];
+ // Keep credentials paired with the running endpoint, regardless of source.
+ const headers = url === runningUrl ? signalExport.headers : undefined;
+ const body = yield* Effect.gen(function* () {
+ const serialization = yield* OtlpSerialization.OtlpSerialization;
+ return emptyExport(serialization, signal);
+ }).pipe(Effect.provide(layerOtlpSerialization(signalExport.protocol)));
+ const startedAt = yield* Clock.currentTimeMillis;
+ // Only the status matters. The scope aborts the request once it is read, so a receiver
+ // that keeps its body open cannot hold the connection. Tracing stays off, as it does for
+ // real exports, because request spans record the URL and custom credential headers.
+ const response = yield* HttpClient.withScope(httpClient)
+ .post(url, { body, headers })
+ .pipe(
+ Effect.map(({ status }) => ({ status })),
+ Effect.scoped,
+ Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }),
+ Effect.withTracerEnabled(false),
+ Effect.timeoutOption(CHECK_TIMEOUT),
+ Effect.option,
+ );
+ if (Option.isNone(response)) {
+ return { _tag: "Unreachable", timedOut: false } as const;
+ }
+ if (Option.isNone(response.value)) {
+ return { _tag: "Unreachable", timedOut: true } as const;
+ }
+ const { status } = response.value.value;
+ if (status < 200 || status >= 300) {
+ return { _tag: "Rejected", status } as const;
+ }
+ const latencyMs = (yield* Clock.currentTimeMillis) - startedAt;
+ return { _tag: "Accepted", latencyMs } as const;
+ });
+
+ return OtlpEndpointCheck.of({ check });
+});
+
+export const layer = Layer.effect(OtlpEndpointCheck, make);
diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts
index 4fe5ffa6a56..db52eb31acf 100644
--- a/apps/server/src/observability/RpcInstrumentation.ts
+++ b/apps/server/src/observability/RpcInstrumentation.ts
@@ -76,6 +76,7 @@ const RPC_AGGREGATES = {
[WS_METHODS.serverGetProcessResourceHistory]: "server",
[WS_METHODS.serverGetResourceTelemetryHistory]: "server",
[WS_METHODS.serverRetryResourceTelemetry]: "server",
+ [WS_METHODS.serverCheckOtlpEndpoint]: "server",
[WS_METHODS.serverGetUsageSummary]: "server",
[WS_METHODS.serverRefreshUsageRates]: "server",
[WS_METHODS.serverSignalProcess]: "server",
diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts
index 6deb654772f..f3606bdb83c 100644
--- a/apps/server/src/ws.ts
+++ b/apps/server/src/ws.ts
@@ -229,6 +229,7 @@ import { pullRequestSyncKey } from "./pullRequest/pullRequestSyncKey.ts";
import * as SqlClient from "effect/sql/SqlClient";
import * as PullRequestSyncReactor from "./orchestration-v2/PullRequestSyncReactor.ts";
import * as SourceControlDiscovery from "./sourceControl/SourceControlDiscovery.ts";
+import * as OtlpEndpointCheck from "./observability/OtlpEndpointCheck.ts";
import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";
import * as SourceControlBuiltInDrivers from "./sourceControl/builtInDrivers.ts";
import * as SourceControlProviderRegistry from "./sourceControl/SourceControlProviderRegistry.ts";
@@ -1303,6 +1304,7 @@ const layerWsRpc = (
);
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
const sourceControlDiscovery = yield* SourceControlDiscovery.SourceControlDiscovery;
+ const otlpEndpointCheck = yield* OtlpEndpointCheck.OtlpEndpointCheck;
const automaticGitFetchInterval = serverSettings.getSettings.pipe(
Effect.map(
(settings) => resolveServerBackgroundActivitySettings(settings).automaticGitFetchInterval,
@@ -2416,6 +2418,7 @@ const layerWsRpc = (
[WS_METHODS.serverGetUsageSummary]: (input) => usage.readSummary(input),
[WS_METHODS.serverRefreshUsageRates]: (_input) => usage.refreshRates,
[WS_METHODS.serverRetryResourceTelemetry]: (_input) => resourceTelemetry.retry,
+ [WS_METHODS.serverCheckOtlpEndpoint]: (input) => otlpEndpointCheck.check(input),
[WS_METHODS.serverSignalProcess]: (input) => processDiagnostics.signal(input),
[WS_METHODS.serverReportClientActivity]: (input, metadata) =>
Ref.update(rpcClientIds, (clientIds) => {
@@ -3200,6 +3203,7 @@ export const layer = Layer.unwrap(
// One server-lifetime service means clients share the same PR caches, and a WS
// mutation invalidates the HTTP diff cache that every client reads from.
Layer.provide(Layer.succeed(PullRequestService.PullRequestService, pullRequests)),
+ Layer.provide(OtlpEndpointCheck.layer),
Layer.provide(
SourceControlDiscovery.layer.pipe(
Layer.provide(
diff --git a/apps/web/src/components/settings/DiagnosticsSettings.tsx b/apps/web/src/components/settings/DiagnosticsSettings.tsx
index 466deaa13ab..645c043dee7 100644
--- a/apps/web/src/components/settings/DiagnosticsSettings.tsx
+++ b/apps/web/src/components/settings/DiagnosticsSettings.tsx
@@ -38,6 +38,7 @@ import { ResourceTelemetryDiagnostics } from "./ResourceTelemetryDiagnostics";
import { SettingsPageContainer, SettingsSection, useRelativeTimeTick } from "./settingsLayout";
import { useAtomCommand } from "../../state/use-atom-command";
import { useSettingsScope } from "./SettingsScopeContext";
+import { TelemetryExportSettings } from "./TelemetryExportSettings";
const NUMBER_FORMAT = new Intl.NumberFormat();
@@ -811,6 +812,20 @@ export function DiagnosticsSettingsPanel() {
const isInitialLoading = isPending && data === null;
const isProcessInitialLoading = isProcessPending && processData === null;
+ const isResourceInitialLoading = isResourcePending && resourceData === null;
+ // The export form waits for each environment's first tables so a search target below them
+ // stays in view. Later loads, such as a new resource window, must not remount it and drop drafts.
+ const [exportFormEnvironmentId, setExportFormEnvironmentId] =
+ useState<typeof environmentId>(null);
+ if (
+ exportFormEnvironmentId !== environmentId &&
+ canReadDiagnostics &&
+ !isInitialLoading &&
+ !isProcessInitialLoading &&
+ !isResourceInitialLoading
+ ) {
+ setExportFormEnvironmentId(environmentId);
+ }
const signalProcess = useCallback(
async (pid: number, signal: ServerProcessSignal) => {
const targetEnvironmentId = environmentIdRef.current;
@@ -1054,7 +1069,7 @@ export function DiagnosticsSettingsPanel() {
<ProcessResourceHistoryTable
processes={resourceData?.topProcesses ?? []}
emptyLabel={
- isResourcePending && resourceData === null
+ isResourceInitialLoading
? "Collecting process resource samples..."
: "No process resource samples found for this window."
}
@@ -1330,6 +1345,7 @@ export function DiagnosticsSettingsPanel() {
<EmptyRows label={isInitialLoading ? "Loading span names..." : "No spans found."} />
)}
</SettingsSection>
+ {exportFormEnvironmentId === environmentId && <TelemetryExportSettings />}
</SettingsPageContainer>
);
}
diff --git a/apps/web/src/components/settings/SettingsSidebarNav.tsx b/apps/web/src/components/settings/SettingsSidebarNav.tsx
index 048e19b7a6b..d10abed376b 100644
--- a/apps/web/src/components/settings/SettingsSidebarNav.tsx
+++ b/apps/web/src/components/settings/SettingsSidebarNav.tsx
@@ -78,6 +78,7 @@ const SETTINGS_SECTION_ICONS: Readonly<
Record<SettingsPath, ComponentType<{ className?: string }>>
> = {
"/settings/general": Settings2Icon,
+ "/settings/diagnostics": Settings2Icon,
"/settings/appearance": PaletteIcon,
"/settings/projects": PanelsTopLeftIcon,
"/settings/keybindings": KeyboardIcon,
@@ -95,11 +96,13 @@ const SETTINGS_NAV_ITEMS: ReadonlyArray<{
label: string;
to: SettingsPath;
icon: ComponentType<{ className?: string }>;
-}> = (Object.keys(SETTINGS_SECTION_LABELS) as SettingsPath[]).map((to) => ({
- to,
- label: SETTINGS_SECTION_LABELS[to],
- icon: SETTINGS_SECTION_ICONS[to],
-}));
+}> = (Object.keys(SETTINGS_SECTION_LABELS) as SettingsPath[])
+ .filter((to) => to !== "/settings/diagnostics")
+ .map((to) => ({
+ to,
+ label: SETTINGS_SECTION_LABELS[to],
+ icon: SETTINGS_SECTION_ICONS[to],
+ }));
function SettingsSectionIcon({ to }: { to: SettingsPath }) {
const Icon = SETTINGS_SECTION_ICONS[to];
diff --git a/apps/web/src/components/settings/TelemetryExportSettings.test.tsx b/apps/web/src/components/settings/TelemetryExportSettings.test.tsx
new file mode 100644
index 00000000000..9e89ac811bc
--- /dev/null
+++ b/apps/web/src/components/settings/TelemetryExportSettings.test.tsx
@@ -0,0 +1,73 @@
+import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts";
+import { act, type ReactNode } from "react";
+import { create, type ReactTestRenderer } from "react-test-renderer";
+import { afterEach, describe, expect, it, vi } from "vite-plus/test";
+
+const { state, updateSettings } = vi.hoisted(() => ({
+ state: { observability: {} as typeof DEFAULT_SERVER_SETTINGS.observability },
+ updateSettings: vi.fn(async () => ({ _tag: "Success" as const, value: undefined })),
+}));
+
+vi.mock("@effect/atom-react", () => ({ useAtomValue: () => true }));
+vi.mock("../../state/server", () => ({
+ serverEnvironment: {
+ updateSettings: "updateSettings",
+ checkOtlpEndpoint: { permissionAtom: () => null },
+ },
+}));
+vi.mock("../../state/use-atom-command", () => ({
+ useAtomCommand: (command: unknown) => (command === "updateSettings" ? updateSettings : vi.fn()),
+}));
+vi.mock("./SettingsScopeContext", () => ({
+ useSettingsScope: () => ({
+ scope: { kind: "environment" },
+ environment: {
+ environmentId: "env",
+ label: "MAC1",
+ serverConfig: { environment: { capabilities: {} } },
+ },
+ }),
+}));
+vi.mock("./useScopedSettings", () => ({
+ useScopedSettings: (select: (settings: typeof state) => unknown) => select(state),
+}));
+vi.mock("./settingsLayout", () => ({
+ SettingsSection: ({ children }: { children: ReactNode }) => <section>{children}</section>,
+}));
+
+import { TelemetryExportSettings } from "./TelemetryExportSettings";
+
+let renderer: ReactTestRenderer | null = null;
+afterEach(async () => {
+ await act(() => renderer?.unmount());
+ renderer = null;
+ updateSettings.mockClear();
+});
+
+const type = (id: string, value: string) =>
+ act(() => renderer!.root.findByProps({ id }).props.onChange({ target: { value } }));
+
+describe("TelemetryExportSettings", () => {
+ it("does not resend a field the user restored after another client changed it", async () => {
+ state.observability = {
+ ...DEFAULT_SERVER_SETTINGS.observability,
+ otlpTracesUrl: "http://old/v1/traces",
+ };
+ await act(() => {
+ renderer = create(<TelemetryExportSettings />);
+ });
+
+ await type("otlpTracesUrl", "http://draft/v1/traces");
+ await type("otlpTracesUrl", "http://old/v1/traces");
+ // Another client saves a new traces endpoint.
+ state.observability = { ...state.observability, otlpTracesUrl: "http://other/v1/traces" };
+ await act(() => renderer!.update(<TelemetryExportSettings />));
+ await type("otlpMetricsUrl", "http://new/v1/metrics");
+ await act(() => renderer!.root.findByType("form").props.onSubmit({ preventDefault() {} }));
+
+ expect(updateSettings).toHaveBeenCalledWith({
+ environmentId: "env",
+ input: { patch: { observability: { otlpMetricsUrl: "http://new/v1/metrics" } } },
+ });
+ });
+});
diff --git a/apps/web/src/components/settings/TelemetryExportSettings.tsx b/apps/web/src/components/settings/TelemetryExportSettings.tsx
new file mode 100644
index 00000000000..a3124ff43b0
--- /dev/null
+++ b/apps/web/src/components/settings/TelemetryExportSettings.tsx
@@ -0,0 +1,243 @@
+import { useAtomValue } from "@effect/atom-react";
+import type { OtlpEndpointCheckResult, OtlpSignal } from "@t3tools/contracts";
+import { useEffect, useEffectEvent, useState } from "react";
+
+import { serverEnvironment } from "../../state/server";
+import { useAtomCommand } from "../../state/use-atom-command";
+import { Button } from "../ui/button";
+import { Input } from "../ui/input";
+import { Label } from "../ui/label";
+import { ConnectionStatusDot } from "../ConnectionStatusDot";
+import { useSettingsScope } from "./SettingsScopeContext";
+import { useScopedSettings } from "./useScopedSettings";
+import { SettingsSection } from "./settingsLayout";
+import { SettingsScopeNotice } from "./SettingsScopeNotice";
+
+const SIGNALS = [
+ { key: "otlpTracesUrl", label: "Traces", signal: "traces" },
+ { key: "otlpMetricsUrl", label: "Metrics", signal: "metrics" },
+ { key: "otlpLogsUrl", label: "Logs", signal: "logs" },
+] as const;
+
+type SignalKey = (typeof SIGNALS)[number]["key"];
+
+/** The latest check for a signal; it describes the field only while `url` is still its value. */
+type EndpointCheck = { readonly url: string; readonly result: OtlpEndpointCheckResult | null };
+
+const isHttpUrl = (url: string) => /^https?:\/\/./i.test(url);
+
+function endpointStatus(url: string, check: EndpointCheck | undefined) {
+ if (url === "") return { label: "Off", dot: "bg-muted-foreground/40" };
+ if (check?.url !== url) return { label: "Not checked", dot: "bg-muted-foreground/40" };
+ const { result } = check;
+ if (result === null) return { label: "Checking…", dot: "bg-warning" };
+ switch (result._tag) {
+ case "Accepted":
+ return { label: `Connected · ${Math.round(result.latencyMs)} ms`, dot: "bg-success" };
+ case "Rejected":
+ return { label: `Rejected · HTTP ${result.status}`, dot: "bg-destructive" };
+ case "Unreachable":
+ return { label: result.timedOut ? "Timed out" : "Unreachable", dot: "bg-destructive" };
+ }
+}
+
+export function TelemetryExportSettings() {
+ const { environment, scope } = useSettingsScope();
+ if (scope.kind !== "environment" || !environment) {
+ return (
+ <SettingsSection title="OpenTelemetry export" id="telemetry-export">
+ <SettingsScopeNotice target="environment">
+ Choose one environment to configure its telemetry exports.
+ </SettingsScopeNotice>
+ </SettingsSection>
+ );
+ }
+ // Mounts per environment so its saved endpoints are the ones checked on open.
+ return <TelemetryExportForm key={environment.environmentId} />;
+}
+
+function TelemetryExportForm() {
+ const { environment } = useSettingsScope();
+ const saved = useScopedSettings((settings) => settings.observability);
+ const [draft, setDraft] = useState<Partial<typeof saved>>({});
+ const [saving, setSaving] = useState(false);
+ const [message, setMessage] = useState<string | null>(null);
+ const environmentId = environment?.environmentId;
+ // Checks need the same grant as saving, so one permission covers the whole form.
+ const canEdit = useAtomValue(
+ serverEnvironment.checkOtlpEndpoint.permissionAtom(environmentId ?? null),
+ );
+ // Servers from before endpoint checks keep the editor without Test.
+ const canCheck =
+ canEdit && environment?.serverConfig?.environment.capabilities.otlpEndpointCheck === true;
+ // Saved endpoints open as pending; the effect below sends their checks.
+ const [checks, setChecks] = useState<Partial<Record<SignalKey, EndpointCheck>>>(() =>
+ Object.fromEntries(
+ SIGNALS.filter(({ key }) => isHttpUrl(saved[key])).map(({ key }) => [
+ key,
+ { url: saved[key], result: null },
+ ]),
+ ),
+ );
+ const updateSettings = useAtomCommand(serverEnvironment.updateSettings, { reportFailure: true });
+ const checkOtlpEndpoint = useAtomCommand(serverEnvironment.checkOtlpEndpoint);
+ const values = { ...saved, ...draft };
+ const changedSignals = SIGNALS.filter(({ key }) => values[key].trim() !== saved[key]);
+ const changed = changedSignals.length > 0;
+ const running = environment?.serverConfig?.observability;
+
+ const sendCheck = async (key: SignalKey, signal: OtlpSignal, url: string) => {
+ if (!environmentId) return;
+ const response = await checkOtlpEndpoint({ environmentId, input: { signal, url } });
+ // A newer check for the same field replaces this one.
+ setChecks((previous) => {
+ if (previous[key]?.url !== url || previous[key].result !== null) return previous;
+ const next = { ...previous };
+ if (response._tag === "Success") next[key] = { url, result: response.value };
+ else delete next[key];
+ return next;
+ });
+ };
+
+ const checkEndpoint = (key: SignalKey, signal: OtlpSignal, url: string) => {
+ if (!isHttpUrl(url)) return;
+ setChecks((previous) => ({ ...previous, [key]: { url, result: null } }));
+ void sendCheck(key, signal, url);
+ };
+
+ // Sends checks still pending, such as the saved endpoints' when the form opens.
+ const sendPendingChecks = useEffectEvent(() => {
+ for (const { key, signal } of SIGNALS) {
+ const check = checks[key];
+ if (check?.result === null) void sendCheck(key, signal, check.url);
+ }
+ });
+ useEffect(() => {
+ // oxlint-disable-next-line react/set-state-in-effect -- State changes only after the response arrives.
+ if (canCheck) sendPendingChecks();
+ }, [canCheck]);
+
+ return (
+ <SettingsSection title="OpenTelemetry export" id="telemetry-export">
+ <form
+ className="grid gap-4 px-4 py-4 sm:px-5"
+ onSubmit={async (event) => {
+ event.preventDefault();
+ if (!environment || saving) return;
+ setSaving(true);
+ setMessage(null);
+ try {
+ const result = await updateSettings({
+ environmentId: environment.environmentId,
+ input: {
+ patch: {
+ observability: Object.fromEntries(
+ changedSignals.map(({ key }) => [key, values[key]]),
+ ),
+ },
+ },
+ });
+ if (result._tag === "Success") {
+ setDraft({});
+ setMessage("Saved. Restart the server to apply.");
+ }
+ } finally {
+ setSaving(false);
+ }
+ }}
+ >
+ <p className="text-xs text-muted-foreground">
+ Send traces, metrics, and logs to an OTLP HTTP receiver. Restart the server to apply.
+ Environment variables override these settings.
+ </p>
+ {!canEdit && (
+ <p className="text-xs text-muted-foreground">
+ This connection lacks permission to change settings on{" "}
+ {environment?.label ?? "the selected environment"}.
+ </p>
+ )}
+ {SIGNALS.map(({ key, label, signal }) => {
+ const url = values[key].trim();
+ const status = canCheck ? endpointStatus(url, checks[key]) : null;
+ return (
+ <div key={key} className="grid gap-1.5">
+ <div className="flex items-center justify-between gap-3">
+ <div className="flex items-center gap-1.5">
+ {status && <ConnectionStatusDot dotClassName={status.dot} />}
+ <Label htmlFor={key}>{label} endpoint</Label>
+ </div>
+ {status && <span className="text-xs text-muted-foreground">{status.label}</span>}
+ </div>
+ <div className="flex gap-2">
+ <Input
+ id={key}
+ size="sm"
+ type="url"
+ pattern="[Hh][Tt][Tt][Pp][Ss]?://.*"
+ title="Enter an HTTP or HTTPS endpoint, or leave empty to disable export."
+ placeholder={`http://localhost:4318/v1/${signal}`}
+ value={values[key]}
+ disabled={saving || !canEdit}
+ onChange={(event) => {
+ const value = event.target.value;
+ // Restoring the saved value drops the draft, so a later save can't resend it
+ // over another client's change.
+ setDraft((previous) => {
+ const next = { ...previous, [key]: value };
+ if (value.trim() === saved[key]) delete next[key];
+ return next;
+ });
+ setMessage(null);
+ }}
+ />
+ {canCheck && (
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ disabled={!isHttpUrl(url) || checks[key]?.result === null}
+ onClick={() => void checkEndpoint(key, signal, url)}
+ >
+ Test
+ </Button>
+ )}
+ </div>
+ {saved[key] !== (running?.[key] ?? "") && (
+ <p className="break-all text-xs text-muted-foreground">
+ Running: {running?.[key] || "Disabled"}
+ </p>
+ )}
+ </div>
+ );
+ })}
+ <div className="flex items-center justify-between gap-3">
+ <p role="status" className="text-xs text-muted-foreground">
+ {message}
+ </p>
+ <div className="flex shrink-0 gap-2">
+ <Button
+ type="button"
+ size="xs"
+ variant="outline"
+ disabled={!changed || saving || !canEdit}
+ onClick={() => {
+ setDraft({});
+ setMessage(null);
+ // A tested draft replaced the saved endpoint's status; check the saved one again.
+ if (!canCheck) return;
+ for (const { key, signal } of SIGNALS) {
+ if (checks[key]?.url !== saved[key]) checkEndpoint(key, signal, saved[key]);
+ }
+ }}
+ >
+ Discard
+ </Button>
+ <Button type="submit" size="xs" disabled={!changed || saving || !canEdit}>
+ {saving ? "Saving…" : "Save"}
+ </Button>
+ </div>
+ </div>
+ </form>
+ </SettingsSection>
+ );
+}
diff --git a/apps/web/src/components/settings/settingsSearch.test.ts b/apps/web/src/components/settings/settingsSearch.test.ts
index 2fd5707164b..54045342ebc 100644
--- a/apps/web/src/components/settings/settingsSearch.test.ts
+++ b/apps/web/src/components/settings/settingsSearch.test.ts
@@ -45,6 +45,19 @@ const ITEMS: ReadonlyArray<SettingsSearchItem> = [
];
describe("searchSettings", () => {
+ it.each(["OTel", "OTLP", "telemetry export", "Grafana"])(
+ "finds environment telemetry settings for %s",
+ (query) => {
+ expect(searchSettings(query)).toContainEqual(
+ expect.objectContaining({
+ id: "telemetry-export",
+ to: "/settings/diagnostics",
+ targetId: "telemetry-export",
+ scope: "environment",
+ }),
+ );
+ },
+ );
it.each(["send shortcut", "multiline", "new line"])("finds Send shortcut for %s", (query) => {
expect(searchSettings(query).map((item) => item.id)).toContain("send-shortcut");
});
@@ -397,6 +410,15 @@ describe("searchSettings", () => {
});
describe("settings search targets", () => {
+ it("requires an environment for the resolved telemetry export destination", () => {
+ const result = searchSettings("OpenTelemetry export").find(
+ (item) => item.id === "telemetry-export",
+ )!;
+ const target = getSettingsSearchTargetScope(result.targetId ?? result.id)!;
+ expect(isSettingsSearchScopeAvailable(target.scope, "all")).toBe(false);
+ expect(isSettingsSearchScopeAvailable(target.scope, "project")).toBe(false);
+ expect(isSettingsSearchScopeAvailable(target.scope, "environment")).toBe(true);
+ });
it.each([
"auto-settle-inactive-threads",
"auto-settle-merged-threads",
diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts
index ccb2d2a24a2..798aabeb8ba 100644
--- a/apps/web/src/components/settings/settingsSearch.ts
+++ b/apps/web/src/components/settings/settingsSearch.ts
@@ -16,6 +16,7 @@ import {
export type SettingsPath =
| "/settings/projects"
| "/settings/general"
+ | "/settings/diagnostics"
| "/settings/appearance"
| "/settings/keybindings"
| "/settings/snap-shot"
@@ -92,6 +93,7 @@ export interface SettingsSearchAvailability {
* subtitles both render from this record, so each label exists once.
*/
export const SETTINGS_SECTION_LABELS: Readonly<Record<SettingsPath, string>> = {
+ "/settings/diagnostics": "Diagnostics",
"/settings/projects": "Project",
"/settings/general": "General",
"/settings/appearance": "Appearance",
@@ -574,6 +576,14 @@ export const SETTINGS_SEARCH_ITEMS = [
to: "/settings/general",
searchTerms: ["telemetry analytics usage data tracking legal opt out"],
},
+ {
+ id: "telemetry-export",
+ title: "OpenTelemetry export",
+ to: "/settings/diagnostics",
+ targetId: "telemetry-export",
+ scope: "environment",
+ searchTerms: ["OTel OTLP telemetry export endpoints logs traces metrics Grafana"],
+ },
{
id: "diagnostics",
title: "Diagnostics",
@@ -979,6 +989,7 @@ export type SettingsSearchItemId = (typeof SETTINGS_SEARCH_ITEMS)[number]["id"];
const SEARCH_ITEMS_BY_ID = new Map(SETTINGS_SEARCH_ITEMS.map((item) => [item.id, item] as const));
const SETTINGS_CATEGORY_SCOPES: Readonly<Record<SettingsPath, SettingsSearchScope | null>> = {
+ "/settings/diagnostics": "environment",
"/settings/projects": "project",
"/settings/general": null,
"/settings/appearance": null,
diff --git a/docs/operations/observability.md b/docs/operations/observability.md
index c199f6aba73..632bbd34e9f 100644
--- a/docs/operations/observability.md
+++ b/docs/operations/observability.md
@@ -172,6 +172,10 @@ Default Grafana login:
#### 2. Export OTLP env vars
+For endpoint settings and startup precedence, see the
+[user telemetry guide](../user/telemetry.md#export-diagnostics-to-your-own-receiver).
+In a worktree, use `vp run dev` instead of `npx t3` to keep state isolated.
+
```bash
export T3CODE_OTLP_TRACES_URL=http://localhost:4318/v1/traces
export T3CODE_OTLP_METRICS_URL=http://localhost:4318/v1/metrics
diff --git a/docs/user/telemetry.md b/docs/user/telemetry.md
index 2f7e44825dc..61925062d3e 100644
--- a/docs/user/telemetry.md
+++ b/docs/user/telemetry.md
@@ -12,3 +12,20 @@ starting it. This stops product events from being recorded or sent.
The desktop app reads the variable from your shell profile (for example `~/.zshrc`) on macOS and
Linux, so export it there and restart the app. On Windows, set it as a user environment variable.
+
+## Export diagnostics to your own receiver
+
+To send traces, metrics, or logs to an OpenTelemetry receiver, open
+**Settings > General > Diagnostics**, select an environment, and enter each signal's OTLP HTTP
+endpoint under **OpenTelemetry export** (for example `http://localhost:4318/v1/traces`). Save, then
+restart that environment's server. The receiver must be reachable from the server's machine.
+**Test** sends an empty export from the server to check an endpoint before or after you save it;
+saved endpoints are checked when the section opens. Checks send authentication headers only to
+the signal's currently running endpoint and do not follow redirects. To check a new endpoint
+that requires authentication, save it and restart the server first.
+
+`T3CODE_OTLP_*_URL` and standard `OTEL_EXPORTER_OTLP_*` environment variables override the saved
+settings. For endpoints saved here or set with `T3CODE_OTLP_*_URL`, set `T3CODE_OTLP_HEADERS` for
+receivers that need authentication and `T3CODE_OTLP_PROTOCOL=http/protobuf` for receivers that do
+not accept JSON. An endpoint set with `OTEL_EXPORTER_OTLP_*` takes its headers and protocol from
+`OTEL_EXPORTER_OTLP_HEADERS` and `OTEL_EXPORTER_OTLP_PROTOCOL` instead.
diff --git a/packages/client-runtime/src/state/commandPermissions.test.ts b/packages/client-runtime/src/state/commandPermissions.test.ts
index b2c6933fabb..58a77730a40 100644
--- a/packages/client-runtime/src/state/commandPermissions.test.ts
+++ b/packages/client-runtime/src/state/commandPermissions.test.ts
@@ -85,6 +85,27 @@ describe("command permissions", () => {
),
);
+ it.effect("requires the destination settings grant to check OTLP endpoints", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const registry = yield* setup;
+ const check = createCommandPermissions(runtime, WS_METHODS.serverCheckOtlpEndpoint);
+ registry.set(sessions(env), AsyncResult.success(grant(true)));
+ expect(registry.get(check.permissionAtom(env))).toBe(false);
+ registry.set(
+ sessions(env),
+ AsyncResult.success({
+ ...grant(false),
+ scopes: [AuthSettingsWriteScope],
+ permissions: [AuthSettingsWriteScope],
+ }),
+ );
+ expect(registry.get(check.permissionAtom(env))).toBe(true);
+ yield* check.authorize(registry, env);
+ }),
+ ),
+ );
+
it.effect("uses the target grant for both availability and execution", () =>
Effect.scoped(
Effect.gen(function* () {
diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.ts
index 1d49fd71f70..31aadd0025b 100644
--- a/packages/client-runtime/src/state/server.ts
+++ b/packages/client-runtime/src/state/server.ts
@@ -1350,6 +1350,10 @@ export function createServerEnvironmentAtoms<R, E>(
key: ({ environmentId }) => environmentId,
},
}),
+ checkOtlpEndpoint: createEnvironmentRpcCommand(runtime, {
+ label: "environment-data:server:check-otlp-endpoint",
+ tag: WS_METHODS.serverCheckOtlpEndpoint,
+ }),
retryResourceTelemetry: createEnvironmentRpcCommand(runtime, {
label: "environment-data:server:retry-resource-telemetry",
tag: WS_METHODS.serverRetryResourceTelemetry,
diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.ts
index c84169e6e33..533f7b75e88 100644
--- a/packages/contracts/src/clientRpcPermissions.ts
+++ b/packages/contracts/src/clientRpcPermissions.ts
@@ -11,6 +11,8 @@ import { WS_METHODS } from "./rpc.ts";
/** Incremental client enforcement; the server still authorizes every request. */
export const CLIENT_GUARDED_RPC_SCOPES = {
[WS_METHODS.serverRunStorageCleanup]: AuthSettingsWriteScope,
+ // Endpoint checks exist to configure exports, so they need the same grant as saving them.
+ [WS_METHODS.serverCheckOtlpEndpoint]: AuthSettingsWriteScope,
[WS_METHODS.pullRequestsRunAction]: AuthSourceControlWriteScope,
[WS_METHODS.pullRequestsUpdate]: AuthSourceControlWriteScope,
[WS_METHODS.pullRequestsComment]: AuthSourceControlWriteScope,
diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts
index 2a61480a907..08bfb3225a6 100644
--- a/packages/contracts/src/environment.ts
+++ b/packages/contracts/src/environment.ts
@@ -126,6 +126,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
threadAutoSettlement: Schema.optionalKey(Schema.Boolean),
storageCleanup: Schema.optionalKey(Schema.Boolean),
storageCleanupRun: Schema.optionalKey(Schema.Boolean),
+ /** Server checks OTLP endpoints for the telemetry export settings. */
+ otlpEndpointCheck: Schema.optionalKey(Schema.Boolean),
projectWorktreeCleanup: Schema.optionalKey(Schema.Boolean),
/** Server honors the `worktreesDirectory` setting. */
worktreesDirectory: Schema.optionalKey(Schema.Boolean),
diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts
index 05c124a51d5..420930a6237 100644
--- a/packages/contracts/src/rpc.ts
+++ b/packages/contracts/src/rpc.ts
@@ -287,6 +287,8 @@ import {} from "./previewAutomation.ts";
import {
ServerConfigStreamEvent,
DesktopUpdateCommitInput,
+ OtlpEndpointCheckInput,
+ OtlpEndpointCheckResult,
ServerConfig,
ServerProviderUpdateError,
ServerProviderUpdateInput,
@@ -499,6 +501,7 @@ export const WS_METHODS = {
serverGetProcessResourceHistory: "server.getProcessResourceHistory",
serverGetResourceTelemetryHistory: "server.getResourceTelemetryHistory",
serverRetryResourceTelemetry: "server.retryResourceTelemetry",
+ serverCheckOtlpEndpoint: "server.checkOtlpEndpoint",
serverSignalProcess: "server.signalProcess",
serverReportClientActivity: "server.reportClientActivity",
serverReportHostPowerState: "server.reportHostPowerState",
@@ -886,6 +889,12 @@ const WsServerRetryResourceTelemetryRpc = Rpc.make(WS_METHODS.serverRetryResourc
error: EnvironmentAuthorizationError,
});
+const WsServerCheckOtlpEndpointRpc = Rpc.make(WS_METHODS.serverCheckOtlpEndpoint, {
+ payload: OtlpEndpointCheckInput,
+ success: OtlpEndpointCheckResult,
+ error: EnvironmentAuthorizationError,
+});
+
const WsServerGetUsageSummaryRpc = Rpc.make(WS_METHODS.serverGetUsageSummary, {
payload: UsageSummaryInput,
success: UsageSummary,
@@ -1891,6 +1900,7 @@ export const WsRpcGroup = RpcGroup.make(
WsServerGetProcessResourceHistoryRpc,
WsServerGetResourceTelemetryHistoryRpc,
WsServerRetryResourceTelemetryRpc,
+ WsServerCheckOtlpEndpointRpc,
WsServerGetUsageSummaryRpc,
WsServerRefreshUsageRatesRpc,
WsServerSignalProcessRpc,
diff --git a/packages/contracts/src/server.test.ts b/packages/contracts/src/server.test.ts
index fdb6b82b3db..091c41cfc4d 100644
--- a/packages/contracts/src/server.test.ts
+++ b/packages/contracts/src/server.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, it } from "vite-plus/test";
import { ExecutionEnvironmentDescriptor } from "./environment.ts";
import {
+ OtlpEndpointCheckInput,
resolveEnvironmentMachineKind,
ServerConfig,
ServerObservability,
@@ -266,3 +267,16 @@ describe("resolveEnvironmentMachineKind", () => {
).toBe("server");
});
});
+
+describe("OtlpEndpointCheckInput", () => {
+ const decode = Schema.decodeUnknownSync(OtlpEndpointCheckInput);
+
+ it("accepts HTTP receivers only", () => {
+ expect(decode({ signal: "traces", url: "https://collector.example.com/v1/traces" }).url).toBe(
+ "https://collector.example.com/v1/traces",
+ );
+ for (const url of ["data:text/plain,ok", "file:///etc/hosts", "collector:4318/v1/traces"]) {
+ expect(() => decode({ signal: "traces", url })).toThrow();
+ }
+ });
+});
diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.ts
index a726f05a311..985e6bbc126 100644
--- a/packages/contracts/src/server.ts
+++ b/packages/contracts/src/server.ts
@@ -357,6 +357,27 @@ export const ServerObservability = Schema.Struct({
});
export type ServerObservability = typeof ServerObservability.Type;
+export const OtlpSignal = Schema.Literals(["traces", "metrics", "logs"]);
+export type OtlpSignal = typeof OtlpSignal.Type;
+
+export const OtlpEndpointCheckInput = Schema.Struct({
+ signal: OtlpSignal,
+ // Receivers are HTTP only; other schemes, such as data:, answer without contacting one.
+ url: TrimmedNonEmptyString.check(Schema.isPattern(/^https?:\/\/./i)),
+});
+export type OtlpEndpointCheckInput = typeof OtlpEndpointCheckInput.Type;
+
+/**
+ * What the server saw when it sent an empty export to an endpoint: accepted,
+ * answered with an error status, or never answered.
+ */
+export const OtlpEndpointCheckResult = Schema.Union([
+ Schema.TaggedStruct("Accepted", { latencyMs: Schema.Number }),
+ Schema.TaggedStruct("Rejected", { status: Schema.Number }),
+ Schema.TaggedStruct("Unreachable", { timedOut: Schema.Boolean }),
+]);
+export type OtlpEndpointCheckResult = typeof OtlpEndpointCheckResult.Type;
+
export const ServerTraceDiagnosticsErrorKind = Schema.Literals([
"trace-file-not-found",
"trace-file-read-failed",