Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

[codex] Trace first-party relay clients (#2995)

Julius Marminge708d5383a9c7
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index e1fb92163..2348417ab 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -180,12 +180,46 @@ jobs:
clerk_cli_oauth_client_id: ${{ steps.public_config.outputs.clerk_cli_oauth_client_id }}
relay_url: ${{ steps.public_config.outputs.relay_url }}
env:
+ CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }}
+ CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
RELAY_DOMAIN: ${{ vars.RELAY_DOMAIN }}
RELAY_API_ZONE_NAME: ${{ vars.RELAY_API_ZONE_NAME }}
CLERK_PUBLISHABLE_KEY: ${{ vars.CLERK_PUBLISHABLE_KEY }}
CLERK_JWT_TEMPLATE: ${{ vars.CLERK_JWT_TEMPLATE }}
CLERK_CLI_OAUTH_CLIENT_ID: ${{ vars.CLERK_CLI_OAUTH_CLIENT_ID }}
steps:
+ - name: Checkout
+ uses: actions/checkout@v6
+ with:
+ ref: ${{ needs.preflight.outputs.ref }}
+
+ - name: Setup Vite+
+ uses: voidzero-dev/setup-vp@v1
+ with:
+ node-version-file: package.json
+ cache: true
+ run-install: |
+ args:
+ - --filter=t3code-relay...
+
+ - id: relay_state
+ name: Read production relay tracing config
+ shell: bash
+ run: |
+ vp run --filter t3code-relay deploy \
+ --stage prod \
+ --read-state \
+ --github-output \
+ --github-env-file "$RUNNER_TEMP/relay-client-tracing.env"
+
+ - name: Upload relay client tracing config
+ uses: actions/upload-artifact@v7
+ with:
+ name: relay-client-tracing-config
+ path: ${{ runner.temp }}/relay-client-tracing.env
+ if-no-files-found: error
+ retention-days: 1
+
- id: public_config
name: Resolve production relay public config
shell: bash
@@ -272,6 +306,20 @@ jobs:
cache: true
run-install: true
+ - name: Download relay client tracing config
+ uses: actions/download-artifact@v8
+ with:
+ name: relay-client-tracing-config
+ path: ${{ runner.temp }}/relay-client-tracing
+
+ - name: Load relay client tracing config
+ shell: bash
+ run: |
+ config_path="$RUNNER_TEMP/relay-client-tracing/relay-client-tracing.env"
+ tracing_token="$(sed -n 's/^T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=//p' "$config_path")"
+ echo "::add-mask::$tracing_token"
+ cat "$config_path" >> "$GITHUB_ENV"
+
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
@@ -508,6 +556,20 @@ jobs:
- --filter=@t3tools/web...
- --filter=@t3tools/scripts...
+ - name: Download relay client tracing config
+ uses: actions/download-artifact@v8
+ with:
+ name: relay-client-tracing-config
+ path: ${{ runner.temp }}/relay-client-tracing
+
+ - name: Load relay client tracing config
+ shell: bash
+ run: |
+ config_path="$RUNNER_TEMP/relay-client-tracing/relay-client-tracing.env"
+ tracing_token="$(sed -n 's/^T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=//p' "$config_path")"
+ echo "::add-mask::$tracing_token"
+ cat "$config_path" >> "$GITHUB_ENV"
+
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
@@ -670,6 +732,20 @@ jobs:
- --filter=@t3tools/scripts...
- --filter=@t3tools/web...
+ - name: Download relay client tracing config
+ uses: actions/download-artifact@v8
+ with:
+ name: relay-client-tracing-config
+ path: ${{ runner.temp }}/relay-client-tracing
+
+ - name: Load relay client tracing config
+ shell: bash
+ run: |
+ config_path="$RUNNER_TEMP/relay-client-tracing/relay-client-tracing.env"
+ tracing_token="$(sed -n 's/^T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=//p' "$config_path")"
+ echo "::add-mask::$tracing_token"
+ cat "$config_path" >> "$GITHUB_ENV"
+
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
@@ -716,6 +792,9 @@ jobs:
--build-env "T3CODE_CLERK_PUBLISHABLE_KEY=${T3CODE_CLERK_PUBLISHABLE_KEY:-}" \
--build-env "T3CODE_CLERK_JWT_TEMPLATE=${T3CODE_CLERK_JWT_TEMPLATE:-}" \
--build-env "T3CODE_RELAY_URL=${T3CODE_RELAY_URL:-}" \
+ --build-env "T3CODE_RELAY_CLIENT_OTLP_TRACES_URL=${T3CODE_RELAY_CLIENT_OTLP_TRACES_URL:-}" \
+ --build-env "T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET=${T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET:-}" \
+ --build-env "T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=${T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN:-}" \
--build-env "VITE_HOSTED_APP_URL=$router_url" \
--build-env "VITE_HOSTED_APP_CHANNEL=$channel_name"
)"
diff --git a/apps/mobile/src/features/observability/mobileTracing.test.ts b/apps/mobile/src/features/observability/mobileTracing.test.ts
index 53bf41604..0b0f83c69 100644
--- a/apps/mobile/src/features/observability/mobileTracing.test.ts
+++ b/apps/mobile/src/features/observability/mobileTracing.test.ts
@@ -4,6 +4,7 @@ import * as Layer from "effect/Layer";
import { vi } from "vite-plus/test";
import { remoteHttpClientLayer } from "@t3tools/client-runtime";
+import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
import { makeMobileTracingLayer } from "./mobileTracing";
@@ -29,7 +30,7 @@ it.effect("exports spans through the scoped mobile OTLP layer", () => {
},
).pipe(Layer.provide(remoteHttpClientLayer(fetchFn)));
const tracedApplication = Layer.effectDiscard(
- Effect.void.pipe(Effect.withSpan("mobile.test.span")),
+ Effect.void.pipe(Effect.withSpan("mobile.test.span"), withRelayClientTracing),
).pipe(Layer.provide(tracingLayer));
return Effect.gen(function* () {
diff --git a/apps/mobile/src/features/observability/mobileTracing.ts b/apps/mobile/src/features/observability/mobileTracing.ts
index 32f3d9f94..dfc6f875c 100644
--- a/apps/mobile/src/features/observability/mobileTracing.ts
+++ b/apps/mobile/src/features/observability/mobileTracing.ts
@@ -1,7 +1,5 @@
import Constants from "expo-constants";
-import * as Layer from "effect/Layer";
-import type { HttpClient } from "effect/unstable/http";
-import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
+import { makeRelayClientTracingLayer } from "@t3tools/shared/relayTracing";
import { hasMobileTracingPublicConfig, resolveCloudPublicConfig } from "../cloud/publicConfig";
@@ -28,27 +26,13 @@ export function resolveMobileTracingConfig(): MobileTracingConfig | null {
export function makeMobileTracingLayer(
config: MobileTracingConfig | null,
resource: MobileTracingResource,
-): Layer.Layer<never, never, HttpClient.HttpClient> {
- if (config === null) {
- return Layer.empty;
- }
-
- return OtlpTracer.layer({
- url: config.tracesUrl,
- headers: {
- Authorization: `Bearer ${config.tracesToken}`,
- "X-Axiom-Dataset": config.tracesDataset,
- },
- resource: {
- serviceName: "t3-mobile",
- serviceVersion: resource.serviceVersion,
- attributes: {
- "service.runtime": "react-native",
- "service.component": "mobile",
- "deployment.environment.name": resource.appVariant,
- },
- },
- }).pipe(Layer.provide(OtlpSerialization.layerJson));
+) {
+ return makeRelayClientTracingLayer(config, {
+ serviceName: "t3-mobile-relay-client",
+ serviceVersion: resource.serviceVersion,
+ runtime: "react-native",
+ client: `mobile-${resource.appVariant}`,
+ });
}
export const mobileTracingLayer = makeMobileTracingLayer(resolveMobileTracingConfig(), {
diff --git a/apps/server/src/cli/connect.ts b/apps/server/src/cli/connect.ts
index 167fb75a3..54f9fd40d 100644
--- a/apps/server/src/cli/connect.ts
+++ b/apps/server/src/cli/connect.ts
@@ -6,6 +6,7 @@ import {
} from "@t3tools/contracts";
import { RelayOkResponse } from "@t3tools/contracts/relay";
import * as RelayClient from "@t3tools/shared/relayClient";
+import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
import * as Console from "effect/Console";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
@@ -29,6 +30,7 @@ import * as CliState from "../cloud/CliState.ts";
import * as CliTokenManager from "../cloud/CliTokenManager.ts";
import { CLOUD_LINKED_USER_ID, RELAY_URL_SECRET } from "../cloud/config.ts";
import { relayUrlConfig } from "../cloud/publicConfig.ts";
+import { headlessRelayClientTracingLayer } from "../cloud/relayTracing.ts";
import { ServerConfig } from "../config.ts";
import { ServerEnvironmentLive } from "../environment/Layers/ServerEnvironment.ts";
import { ServerEnvironment } from "../environment/Services/ServerEnvironment.ts";
@@ -228,6 +230,7 @@ const unlinkRelayEnvironment = Effect.fn("cloud.cli.unlink_relay_environment")(f
httpClient.execute,
Effect.flatMap(HttpClientResponse.filterStatusOk),
Effect.flatMap(HttpClientResponse.schemaBodyJson(RelayOkResponse)),
+ withRelayClientTracing,
);
return response.ok
? ({ status: "revoked" } satisfies RelayUnlinkResult)
@@ -299,6 +302,7 @@ const runCloudCommand = <A, E>(
RelayClient.layerCloudflared({ baseDir: config.baseDir }),
EnvironmentAuth.runtimeLayer,
ServerEnvironmentLive,
+ headlessRelayClientTracingLayer,
).pipe(
Layer.provideMerge(FetchHttpClient.layer),
Layer.provideMerge(Layer.succeed(ServerConfig, config)),
diff --git a/apps/server/src/cloud/http.test.ts b/apps/server/src/cloud/http.test.ts
index 799ab609f..8ea7ca06f 100644
--- a/apps/server/src/cloud/http.test.ts
+++ b/apps/server/src/cloud/http.test.ts
@@ -3,13 +3,19 @@ import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
-import { HttpClient } from "effect/unstable/http";
+import * as Tracer from "effect/Tracer";
+import { HttpClient, HttpServerRequest } from "effect/unstable/http";
+import { RelayClientTracer } from "@t3tools/shared/relayTracing";
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import { ServerEnvironment } from "../environment/Services/ServerEnvironment.ts";
import * as CliTokenManager from "./CliTokenManager.ts";
-import { consumeCloudReplayGuards, reconcileDesiredCloudLink } from "./http.ts";
+import {
+ consumeCloudReplayGuards,
+ reconcileDesiredCloudLink,
+ traceRelayBrokerHandler,
+} from "./http.ts";
import {
CloudManagedEndpointRuntime,
type CloudManagedEndpointRuntimeShape,
@@ -69,6 +75,38 @@ describe("consumeCloudReplayGuards", () => {
);
});
+describe("traceRelayBrokerHandler", () => {
+ it.effect("continues the incoming relay trace with the product tracer", () =>
+ Effect.gen(function* () {
+ const spans: Array<Tracer.Span> = [];
+ const productTracer = Tracer.make({
+ span: (options) => {
+ const span = new Tracer.NativeSpan(options);
+ spans.push(span);
+ return span;
+ },
+ });
+ const request = HttpServerRequest.fromWeb(
+ new Request("https://environment.example.test/api/t3-cloud/mint-credential", {
+ headers: {
+ traceparent: "00-0123456789abcdef0123456789abcdef-0123456789abcdef-01",
+ },
+ }),
+ );
+
+ yield* traceRelayBrokerHandler(Effect.void.pipe(Effect.withSpan("relay.mint.handler"))).pipe(
+ Effect.provideService(HttpServerRequest.HttpServerRequest, request),
+ Effect.provideService(RelayClientTracer, Option.some(productTracer)),
+ );
+
+ expect(spans).toHaveLength(1);
+ const span = spans[0]!;
+ expect(span.traceId).toBe("0123456789abcdef0123456789abcdef");
+ expect(Option.getOrUndefined(span.parent)?.spanId).toBe("0123456789abcdef");
+ }),
+ );
+});
+
describe("reconcileDesiredCloudLink", () => {
it.effect("requires stored CLI authorization without exposing an HTTP endpoint", () =>
Effect.gen(function* () {
diff --git a/apps/server/src/cloud/http.ts b/apps/server/src/cloud/http.ts
index 896990849..b78d47a20 100644
--- a/apps/server/src/cloud/http.ts
+++ b/apps/server/src/cloud/http.ts
@@ -29,6 +29,7 @@ import {
RelayLinkProofRequest,
RelayManagedEndpointOrigin,
} from "@t3tools/contracts/relay";
+import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
import {
normalizeRelayIssuer,
RELAY_HEALTH_REQUEST_TYP,
@@ -47,7 +48,7 @@ import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as HttpEffect from "effect/unstable/http/HttpEffect";
-import { HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
+import { HttpServerRequest, HttpServerResponse, HttpTraceContext } from "effect/unstable/http";
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
@@ -110,6 +111,19 @@ const requireRelayUrl = relayUrlConfig.pipe(
),
);
+export const traceRelayBrokerHandler = <A, E, R>(
+ effect: Effect.Effect<A, E, R>,
+): Effect.Effect<A, E, R | HttpServerRequest.HttpServerRequest> =>
+ HttpServerRequest.HttpServerRequest.pipe(
+ Effect.flatMap((request) =>
+ Option.match(HttpTraceContext.fromHeaders(request.headers), {
+ onNone: () => effect,
+ onSome: (parent) => effect.pipe(Effect.withParentSpan(parent)),
+ }),
+ ),
+ withRelayClientTracing,
+ );
+
function bytesToString(bytes: Uint8Array): string {
return new TextDecoder().decode(bytes);
}
@@ -512,6 +526,7 @@ const relayClientRequest = <A>(
message: `T3 Connect relay request failed: ${String(cause)}`,
}),
),
+ withRelayClientTracing,
);
const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesiredLinkWith")(
@@ -938,7 +953,7 @@ export const connectHttpApiLayer = HttpApiBuilder.group(
.handle("health", ({ payload }) => cloudEnvironmentHealthHandler(dependencies, payload))
.handle("mintCredential", ({ payload }) => cloudMintCredentialHandler(dependencies, payload))
.handle("t3MintCredential", ({ payload }) =>
- cloudMintCredentialHandler(dependencies, payload),
+ traceRelayBrokerHandler(cloudMintCredentialHandler(dependencies, payload)),
);
}),
);
diff --git a/apps/server/src/cloud/publicConfig.test.ts b/apps/server/src/cloud/publicConfig.test.ts
index 558560bff..4cce901fa 100644
--- a/apps/server/src/cloud/publicConfig.test.ts
+++ b/apps/server/src/cloud/publicConfig.test.ts
@@ -2,7 +2,11 @@ import { assert, it } from "@effect/vitest";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Effect from "effect/Effect";
-import { makeCloudCliOAuthConfig, makeRelayUrlConfig } from "./publicConfig.ts";
+import {
+ makeCloudCliOAuthConfig,
+ makeRelayUrlConfig,
+ resolveRelayClientTracingConfig,
+} from "./publicConfig.ts";
const provideEnv = (env: Readonly<Record<string, string>>) =>
Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env })));
@@ -83,3 +87,39 @@ it.effect("requires Clerk OAuth config when the server bundle has no injected va
clerkCliOAuthClientIdFallback: "",
}).pipe(provideEnv({}), Effect.flip),
);
+
+it("resolves relay client tracing from runtime config with build-time fallback", () => {
+ const fallback = {
+ tracesUrl: "https://embedded.example.test/v1/traces",
+ tracesDataset: "embedded-dataset",
+ tracesToken: "embedded-token",
+ };
+
+ assert.deepEqual(resolveRelayClientTracingConfig({}, fallback), fallback);
+ assert.deepEqual(
+ resolveRelayClientTracingConfig(
+ {
+ T3CODE_RELAY_CLIENT_OTLP_TRACES_URL: "https://runtime.example.test/v1/traces",
+ T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET: "runtime-dataset",
+ T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN: "runtime-token",
+ },
+ fallback,
+ ),
+ {
+ tracesUrl: "https://runtime.example.test/v1/traces",
+ tracesDataset: "runtime-dataset",
+ tracesToken: "runtime-token",
+ },
+ );
+ assert.equal(
+ resolveRelayClientTracingConfig(
+ {
+ T3CODE_RELAY_CLIENT_OTLP_TRACES_URL: "http://insecure.example.test/v1/traces",
+ T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET: "runtime-dataset",
+ T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN: "runtime-token",
+ },
+ fallback,
+ ),
+ null,
+ );
+});
diff --git a/apps/server/src/cloud/publicConfig.ts b/apps/server/src/cloud/publicConfig.ts
index 5c64a2423..b344107d7 100644
--- a/apps/server/src/cloud/publicConfig.ts
+++ b/apps/server/src/cloud/publicConfig.ts
@@ -9,6 +9,9 @@ import * as SchemaIssue from "effect/SchemaIssue";
declare const __T3CODE_BUILD_RELAY_URL__: string | undefined;
declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
declare const __T3CODE_BUILD_CLERK_CLI_OAUTH_CLIENT_ID__: string | undefined;
+declare const __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_URL__: string | undefined;
+declare const __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_DATASET__: string | undefined;
+declare const __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_TOKEN__: string | undefined;
const CLOUD_CLI_OAUTH_REDIRECT_URI = "http://127.0.0.1:34338/callback";
const CLOUD_CLI_OAUTH_SCOPES = ["openid", "profile", "email"] as const;
@@ -32,6 +35,15 @@ function readBuildTimeValue(value: string | undefined): string {
return typeof value === "undefined" ? "" : value.trim();
}
+function normalizeSecureUrl(value: string): string | null {
+ try {
+ const url = new URL(value);
+ return url.protocol === "https:" ? url.toString() : null;
+ } catch {
+ return null;
+ }
+}
+
export const buildTimeRelayUrl =
typeof __T3CODE_BUILD_RELAY_URL__ === "undefined"
? ""
@@ -46,6 +58,37 @@ export const buildTimeClerkCliOAuthClientId = readBuildTimeValue(
? undefined
: __T3CODE_BUILD_CLERK_CLI_OAUTH_CLIENT_ID__,
);
+export const buildTimeRelayClientTracing = {
+ tracesUrl: readBuildTimeValue(
+ typeof __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_URL__ === "undefined"
+ ? undefined
+ : __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_URL__,
+ ),
+ tracesDataset: readBuildTimeValue(
+ typeof __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_DATASET__ === "undefined"
+ ? undefined
+ : __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_DATASET__,
+ ),
+ tracesToken: readBuildTimeValue(
+ typeof __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_TOKEN__ === "undefined"
+ ? undefined
+ : __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_TOKEN__,
+ ),
+} as const;
+
+export function resolveRelayClientTracingConfig(
+ env: Readonly<Record<string, string | undefined>> = process.env,
+ fallback = buildTimeRelayClientTracing,
+) {
+ const tracesUrl = env.T3CODE_RELAY_CLIENT_OTLP_TRACES_URL?.trim() || fallback.tracesUrl;
+ const tracesDataset =
+ env.T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET?.trim() || fallback.tracesDataset;
+ const tracesToken = env.T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN?.trim() || fallback.tracesToken;
+ const normalizedTracesUrl = normalizeSecureUrl(tracesUrl);
+ return normalizedTracesUrl && tracesDataset && tracesToken
+ ? { tracesUrl: normalizedTracesUrl, tracesDataset, tracesToken }
+ : null;
+}
export function makeRelayUrlConfig(fallback = buildTimeRelayUrl) {
const runtimeConfig = Config.nonEmptyString("T3CODE_RELAY_URL");
diff --git a/apps/server/src/cloud/relayTracing.ts b/apps/server/src/cloud/relayTracing.ts
new file mode 100644
index 000000000..e35c94545
--- /dev/null
+++ b/apps/server/src/cloud/relayTracing.ts
@@ -0,0 +1,21 @@
+import { makeRelayClientTracingLayer } from "@t3tools/shared/relayTracing";
+
+import { resolveRelayClientTracingConfig } from "./publicConfig.ts";
+
+const relayClientTracingConfig = resolveRelayClientTracingConfig();
+
+export const headlessRelayClientTracingLayer = makeRelayClientTracingLayer(
+ relayClientTracingConfig,
+ {
+ serviceName: "t3-headless-relay-client",
+ runtime: "node",
+ client: "headless-cli",
+ },
+);
+
+export const serverRelayBrokerTracingLayer = makeRelayClientTracingLayer(relayClientTracingConfig, {
+ serviceName: "t3-server",
+ runtime: "node",
+ client: "environment-server",
+ component: "relay-broker",
+});
diff --git a/apps/server/src/relay/AgentAwarenessRelay.test.ts b/apps/server/src/relay/AgentAwarenessRelay.test.ts
index bbfbd236a..9e0ad364d 100644
--- a/apps/server/src/relay/AgentAwarenessRelay.test.ts
+++ b/apps/server/src/relay/AgentAwarenessRelay.test.ts
@@ -17,6 +17,7 @@ import type {
RelayAgentActivityState,
} from "@t3tools/contracts/relay";
import { CommandId, ProviderInstanceId } from "@t3tools/contracts";
+import { RelayClientTracer } from "@t3tools/shared/relayTracing";
import { RELAY_ACTIVITY_PUBLISH_TYP, verifyRelayJwt } from "@t3tools/shared/relayJwt";
import { describe, expect, it } from "@effect/vitest";
import * as Deferred from "effect/Deferred";
@@ -25,6 +26,7 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
import * as Stream from "effect/Stream";
+import * as Tracer from "effect/Tracer";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import { ServerEnvironment } from "../environment/Services/ServerEnvironment.ts";
@@ -522,6 +524,20 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
const runFork = Effect.runForkWith(context);
const events = yield* Queue.unbounded<OrchestrationEvent>();
const fetchSeen = yield* Deferred.make<URL>();
+ const userSpans: Array<string> = [];
+ const productSpans: Array<string> = [];
+ const collectingTracer = (spans: Array<string>) =>
+ Tracer.make({
+ span: (options) => {
+ const span = new Tracer.NativeSpan(options);
+ const end = span.end.bind(span);
+ span.end = (endTime, exit) => {
+ end(endTime, exit);
+ spans.push(span.name);
+ };
+ return span;
+ },
+ });
const secrets = makeMemorySecretStore();
const now = "2026-05-25T00:00:00.000Z";
const projectId = "project-1" as ProjectId;
@@ -648,6 +664,8 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
const url = yield* Deferred.await(fetchSeen).pipe(Effect.timeout("2 seconds"));
expect(url.origin).toBe("https://transport.example.test");
+ expect(productSpans).toContain("makePublishProof");
+ expect(userSpans).not.toContain("makePublishProof");
}).pipe(
Effect.provide(
AgentAwarenessRelay.layer.pipe(
@@ -655,6 +673,8 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
Layer.provideMerge(NodeServices.layer),
),
),
+ Effect.provideService(RelayClientTracer, Option.some(collectingTracer(productSpans))),
+ Effect.withTracer(collectingTracer(userSpans)),
);
}),
),
diff --git a/apps/server/src/relay/AgentAwarenessRelay.ts b/apps/server/src/relay/AgentAwarenessRelay.ts
index 960f27e75..d02c83d56 100644
--- a/apps/server/src/relay/AgentAwarenessRelay.ts
+++ b/apps/server/src/relay/AgentAwarenessRelay.ts
@@ -12,6 +12,7 @@ import type {
} from "@t3tools/contracts";
import { projectThreadAwareness } from "@t3tools/shared/agentAwareness";
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
+import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
import {
RELAY_ACTIVITY_PUBLISH_TYP,
signRelayJwt,
@@ -409,6 +410,7 @@ const make = Effect.gen(function* () {
});
}),
Effect.withSpan("AgentAwarenessRelay.publishThread"),
+ withRelayClientTracing,
);
const publishActiveThreadsUnsafe = Effect.gen(function* () {
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index f5f51efc9..42a692c53 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -74,6 +74,7 @@ import { authHttpApiLayer, environmentAuthenticatedAuthLayer } from "./auth/http
import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import { connectHttpApiLayer, reconcileDesiredCloudLink } from "./cloud/http.ts";
+import { serverRelayBrokerTracingLayer } from "./cloud/relayTracing.ts";
import * as CloudManagedEndpointRuntime from "./cloud/ManagedEndpointRuntime.ts";
import * as CloudCliTokenManager from "./cloud/CliTokenManager.ts";
import * as CloudCliState from "./cloud/CliState.ts";
@@ -477,6 +478,7 @@ export const makeServerLayer = Layer.unwrap(
return serverApplicationLayer.pipe(
Layer.provideMerge(RuntimeServicesLive),
+ Layer.provideMerge(serverRelayBrokerTracingLayer),
Layer.provideMerge(HttpServerLive),
Layer.provide(ObservabilityLive),
Layer.provideMerge(FetchHttpClient.layer),
diff --git a/apps/server/vite.config.ts b/apps/server/vite.config.ts
index 7e88ac775..473df069e 100644
--- a/apps/server/vite.config.ts
+++ b/apps/server/vite.config.ts
@@ -49,6 +49,15 @@ export default mergeConfig(
__T3CODE_BUILD_CLERK_CLI_OAUTH_CLIENT_ID__: JSON.stringify(
repoEnv.T3CODE_CLERK_CLI_OAUTH_CLIENT_ID?.trim() ?? "",
),
+ __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_URL__: JSON.stringify(
+ repoEnv.T3CODE_RELAY_CLIENT_OTLP_TRACES_URL?.trim() ?? "",
+ ),
+ __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_DATASET__: JSON.stringify(
+ repoEnv.T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET?.trim() ?? "",
+ ),
+ __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_TOKEN__: JSON.stringify(
+ repoEnv.T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN?.trim() ?? "",
+ ),
},
},
test: {
diff --git a/apps/web/src/cloud/linkEnvironment.test.ts b/apps/web/src/cloud/linkEnvironment.test.ts
index dc09a7fa0..30cb59678 100644
--- a/apps/web/src/cloud/linkEnvironment.test.ts
+++ b/apps/web/src/cloud/linkEnvironment.test.ts
@@ -318,6 +318,14 @@ describe("web cloud link environment client", () => {
method: "POST",
url: "https://managed.example.test/oauth/token",
});
+ const traceparents = fetchMock.mock.calls.map(
+ (call) => call[1]?.headers.traceparent as string | undefined,
+ );
+ expect(traceparents.every((traceparent) => typeof traceparent === "string")).toBe(true);
+ expect(new Set(traceparents.map((traceparent) => traceparent?.split("-")[1])).size).toBe(1);
+ expect(connection.relayTraceHeaders.traceparent?.split("-")[1]).toBe(
+ traceparents[0]?.split("-")[1],
+ );
}),
);
diff --git a/apps/web/src/cloud/linkEnvironment.ts b/apps/web/src/cloud/linkEnvironment.ts
index b13b324a4..4c94ab416 100644
--- a/apps/web/src/cloud/linkEnvironment.ts
+++ b/apps/web/src/cloud/linkEnvironment.ts
@@ -1,7 +1,7 @@
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
-import { HttpClient } from "effect/unstable/http";
+import { HttpClient, HttpTraceContext, type Headers } from "effect/unstable/http";
import {
EnvironmentCloudEndpointUnavailableError,
type EnvironmentCloudLinkStateResult,
@@ -29,6 +29,7 @@ import {
ManagedRelayDpopSigner,
type WsRpcClient,
} from "@t3tools/client-runtime";
+import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
import { ensureLocalApi } from "../localApi";
import {
@@ -245,6 +246,7 @@ export interface CloudManagedConnection {
readonly wsBaseUrl: string;
readonly relayUrl: string;
readonly accessToken: string;
+ readonly relayTraceHeaders: Headers.Headers;
}
export function collectCloudLinkTargets(input: {
@@ -437,8 +439,15 @@ export function connectManagedCloudEnvironment(input: {
wsBaseUrl: connected.endpoint.wsBaseUrl,
relayUrl: configuredRelayUrl,
accessToken: session.access_token,
+ relayTraceHeaders: HttpTraceContext.toHeaders(yield* Effect.currentSpan.pipe(Effect.orDie)),
};
- });
+ }).pipe(
+ Effect.withSpan("relay.environment.connect", {
+ root: true,
+ attributes: { "relay.environment_id": input.environment.environmentId },
+ }),
+ withRelayClientTracing,
+ );
}
export function readPrimaryCloudLinkState(): Effect.Effect<
diff --git a/apps/web/src/cloud/publicConfig.ts b/apps/web/src/cloud/publicConfig.ts
index 291f1830c..f7b3ca6bc 100644
--- a/apps/web/src/cloud/publicConfig.ts
+++ b/apps/web/src/cloud/publicConfig.ts
@@ -5,12 +5,26 @@ export interface CloudPublicConfig {
readonly clerkPublishableKey: string | null;
readonly clerkJwtTemplate: string | null;
readonly relayUrl: string | null;
+ readonly relayTracing: {
+ readonly tracesUrl: string | null;
+ readonly tracesDataset: string | null;
+ readonly tracesToken: string | null;
+ };
}
function trimNonEmpty(value: string | undefined): string | null {
return value?.trim() || null;
}
+function normalizeSecureUrl(value: string): string | null {
+ try {
+ const url = new URL(value);
+ return url.protocol === "https:" ? url.toString() : null;
+ } catch {
+ return null;
+ }
+}
+
export function resolveCloudPublicConfig(): CloudPublicConfig {
return {
clerkPublishableKey: trimNonEmpty(
@@ -20,9 +34,29 @@ export function resolveCloudPublicConfig(): CloudPublicConfig {
relayUrl: normalizeSecureRelayUrl(
(import.meta.env.VITE_T3CODE_RELAY_URL as string | undefined) ?? "",
),
+ relayTracing: {
+ tracesUrl: normalizeSecureUrl(
+ (import.meta.env.VITE_RELAY_OTLP_TRACES_URL as string | undefined) ?? "",
+ ),
+ tracesDataset: trimNonEmpty(
+ import.meta.env.VITE_RELAY_OTLP_TRACES_DATASET as string | undefined,
+ ),
+ tracesToken: trimNonEmpty(import.meta.env.VITE_RELAY_OTLP_TRACES_TOKEN as string | undefined),
+ },
};
}
+export function resolveRelayTracingConfig() {
+ const { relayTracing } = resolveCloudPublicConfig();
+ return relayTracing.tracesUrl && relayTracing.tracesDataset && relayTracing.tracesToken
+ ? {
+ tracesUrl: relayTracing.tracesUrl,
+ tracesDataset: relayTracing.tracesDataset,
+ tracesToken: relayTracing.tracesToken,
+ }
+ : null;
+}
+
export function hasCloudPublicConfig(): boolean {
const config = resolveCloudPublicConfig();
return Boolean(config.clerkPublishableKey && config.clerkJwtTemplate && config.relayUrl);
diff --git a/apps/web/src/environments/runtime/service.addSavedEnvironment.test.ts b/apps/web/src/environments/runtime/service.addSavedEnvironment.test.ts
index f099338ab..a9da256f8 100644
--- a/apps/web/src/environments/runtime/service.addSavedEnvironment.test.ts
+++ b/apps/web/src/environments/runtime/service.addSavedEnvironment.test.ts
@@ -1,8 +1,13 @@
import { EnvironmentAuthInvalidError, EnvironmentId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
+import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
+import * as Tracer from "effect/Tracer";
+import { Headers } from "effect/unstable/http";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
+import { RelayClientTracer } from "@t3tools/shared/relayTracing";
+
const decodeEnvironmentAuthInvalidError = Schema.decodeUnknownSync(EnvironmentAuthInvalidError);
let mockSavedRecords: Array<Record<string, unknown>> = [];
@@ -12,8 +17,11 @@ const mockFetchRemoteEnvironmentDescriptor = vi.fn();
const mockBootstrapRemoteBearerSession = vi.fn();
const mockFetchRemoteSessionState = vi.fn();
const mockFetchRemoteDpopSessionState = vi.fn();
+const mockResolveRemoteDpopWebSocketConnectionUrl = vi.fn();
const mockResolveRemoteWebSocketConnectionUrl = vi.fn();
+const mockWsTransportConnectors: Array<() => Promise<string>> = [];
let managedRelayDpopSigner: typeof import("@t3tools/client-runtime").ManagedRelayDpopSigner;
+let mockRelayClientTracer = Option.none<Tracer.Tracer>();
const mockRemoteHttpRunPromise = vi.fn(<A, E>(effect: Effect.Effect<A, E>) =>
Effect.runPromise(
effect.pipe(
@@ -24,6 +32,7 @@ const mockRemoteHttpRunPromise = vi.fn(<A, E>(effect: Effect.Effect<A, E>) =>
createProof: () => Effect.succeed("dpop-proof"),
}),
),
+ Effect.provideService(RelayClientTracer, mockRelayClientTracer),
),
),
);
@@ -164,12 +173,16 @@ vi.mock("@t3tools/client-runtime", async (importOriginal) => {
fetchRemoteEnvironmentDescriptor: mockFetchRemoteEnvironmentDescriptor,
fetchRemoteSessionState: mockFetchRemoteSessionState,
fetchRemoteDpopSessionState: mockFetchRemoteDpopSessionState,
+ resolveRemoteDpopWebSocketConnectionUrl: mockResolveRemoteDpopWebSocketConnectionUrl,
resolveRemoteWebSocketConnectionUrl: mockResolveRemoteWebSocketConnectionUrl,
};
});
vi.mock("../../rpc/wsTransport", () => ({
- WsTransport: vi.fn(),
+ WsTransport: vi.fn(function WsTransport(connect: () => Promise<string>) {
+ mockWsTransportConnectors.push(connect);
+ return {};
+ }),
}));
describe("addSavedEnvironment", () => {
@@ -181,6 +194,8 @@ describe("addSavedEnvironment", () => {
vi.resetModules();
vi.clearAllMocks();
mockSavedRecords = [];
+ mockRelayClientTracer = Option.none();
+ mockWsTransportConnectors.length = 0;
vi.stubGlobal("window", {
desktopBridge: {
ensureSshEnvironment: mockEnsureSshEnvironment,
@@ -237,6 +252,9 @@ describe("addSavedEnvironment", () => {
mockResolveRemoteWebSocketConnectionUrl.mockReturnValue(
Effect.succeed("wss://remote.example.com/?wsTicket=remote-token"),
);
+ mockResolveRemoteDpopWebSocketConnectionUrl.mockReturnValue(
+ Effect.succeed("wss://remote.example.com/?wsTicket=remote-dpop-token"),
+ );
mockFetchSshEnvironmentDescriptor.mockResolvedValue({
environmentId: EnvironmentId.make("environment-1"),
label: "Remote environment",
@@ -386,6 +404,7 @@ describe("addSavedEnvironment", () => {
wsBaseUrl: "wss://managed.example.com/",
relayUrl: "https://relay.example.com",
accessToken: "managed-access-token",
+ relayTraceHeaders: Headers.empty,
});
expect(mockWriteSavedEnvironmentCredential).toHaveBeenCalledWith(
@@ -406,6 +425,19 @@ describe("addSavedEnvironment", () => {
it("renews expired managed DPoP credentials through the relay", async () => {
const environmentId = EnvironmentId.make("environment-1");
+ const productSpans: Array<Tracer.Span> = [];
+ mockRelayClientTracer = Option.some(
+ Tracer.make({
+ span: (options) => {
+ const span = new Tracer.NativeSpan(options);
+ productSpans.push(span);
+ return span;
+ },
+ }),
+ );
+ const relayTraceHeaders = Headers.fromInput({
+ traceparent: "00-0123456789abcdef0123456789abcdef-0123456789abcdef-01",
+ });
mockSavedRecords = [
{
environmentId,
@@ -443,6 +475,7 @@ describe("addSavedEnvironment", () => {
wsBaseUrl: "wss://managed.example.com/",
relayUrl: "https://relay.example.com",
accessToken: "renewed-access-token",
+ relayTraceHeaders,
}),
);
@@ -460,6 +493,16 @@ describe("addSavedEnvironment", () => {
method: "dpop",
accessToken: "renewed-access-token",
});
+ const renewedTransportConnector = mockWsTransportConnectors.at(-1);
+ expect(renewedTransportConnector).toBeDefined();
+ await renewedTransportConnector!();
+ expect(mockResolveRemoteDpopWebSocketConnectionUrl).toHaveBeenCalledWith({
+ wsBaseUrl: "wss://managed.example.com/",
+ httpBaseUrl: "https://managed.example.com/",
+ accessToken: "renewed-access-token",
+ dpopProof: "dpop-proof",
+ });
+ expect(productSpans.some((span) => span.name === "relay.environment.reconnect")).toBe(false);
await resetEnvironmentServiceForTests();
});
diff --git a/apps/web/src/environments/runtime/service.ts b/apps/web/src/environments/runtime/service.ts
index e9a438976..cbd0c9961 100644
--- a/apps/web/src/environments/runtime/service.ts
+++ b/apps/web/src/environments/runtime/service.ts
@@ -26,7 +26,10 @@ import {
import { type QueryClient } from "@tanstack/react-query";
import { Throttler } from "@tanstack/react-pacer";
import * as Effect from "effect/Effect";
+import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
+import { Headers, HttpTraceContext } from "effect/unstable/http";
+import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
import {
createKnownEnvironment,
getKnownEnvironmentWsBaseUrl,
@@ -1173,6 +1176,7 @@ function createPrimaryEnvironmentClient(
function createSavedEnvironmentClient(
environmentId: EnvironmentId,
credentialRef: { current: SavedEnvironmentCredential },
+ relayTraceHeadersRef: { current: Headers.Headers | null },
): WsRpcClient {
useSavedEnvironmentRuntimeStore.getState().ensure(environmentId);
@@ -1196,21 +1200,10 @@ function createSavedEnvironmentClient(
}
if (credential.method === "dpop") {
try {
+ const relayTraceHeaders = relayTraceHeadersRef.current;
+ relayTraceHeadersRef.current = null;
return await webRuntime.runPromise(
- createManagedRelayDpopProof({
- method: "POST",
- url: new URL("/api/auth/websocket-ticket", record.httpBaseUrl).toString(),
- accessToken: credential.accessToken,
- }).pipe(
- Effect.flatMap((proof) =>
- resolveRemoteDpopWebSocketConnectionUrl({
- wsBaseUrl: record.wsBaseUrl,
- httpBaseUrl: record.httpBaseUrl,
- accessToken: credential.accessToken,
- dpopProof: proof,
- }),
- ),
- ),
+ resolveManagedRelayWebSocketUrl(record, credential, relayTraceHeaders),
);
} catch (error) {
if (!isEnvironmentAuthInvalidError(error)) {
@@ -1223,19 +1216,10 @@ function createSavedEnvironmentClient(
const renewedCredential = renewed.credential;
credentialRef.current = renewedCredential;
return await webRuntime.runPromise(
- createManagedRelayDpopProof({
- method: "POST",
- url: new URL("/api/auth/websocket-ticket", renewed.record.httpBaseUrl).toString(),
- accessToken: renewedCredential.accessToken,
- }).pipe(
- Effect.flatMap((proof) =>
- resolveRemoteDpopWebSocketConnectionUrl({
- wsBaseUrl: renewed.record.wsBaseUrl,
- httpBaseUrl: renewed.record.httpBaseUrl,
- accessToken: renewedCredential.accessToken,
- dpopProof: proof,
- }),
- ),
+ resolveManagedRelayWebSocketUrl(
+ renewed.record,
+ renewedCredential,
+ renewed.relayTraceHeaders,
),
);
}
@@ -1339,9 +1323,44 @@ async function refreshSavedEnvironmentMetadata(
.rename(record.environmentId, serverConfig.environment.label);
}
+const resolveManagedRelayWebSocketUrl = Effect.fn(
+ "web.environment.resolveManagedRelayWebSocketUrl",
+)(function* (
+ record: SavedEnvironmentRecord,
+ credential: Extract<SavedEnvironmentCredential, { readonly method: "dpop" }>,
+ traceHeaders: Headers.Headers | null,
+) {
+ const request = createManagedRelayDpopProof({
+ method: "POST",
+ url: new URL("/api/auth/websocket-ticket", record.httpBaseUrl).toString(),
+ accessToken: credential.accessToken,
+ }).pipe(
+ Effect.flatMap((proof) =>
+ resolveRemoteDpopWebSocketConnectionUrl({
+ wsBaseUrl: record.wsBaseUrl,
+ httpBaseUrl: record.httpBaseUrl,
+ accessToken: credential.accessToken,
+ dpopProof: proof,
+ }),
+ ),
+ );
+ const parent = traceHeaders ? HttpTraceContext.fromHeaders(traceHeaders) : Option.none();
+ return yield* (
+ Option.isSome(parent)
+ ? request.pipe(Effect.withParentSpan(parent.value))
+ : request.pipe(
+ Effect.withSpan("relay.environment.reconnect", {
+ root: true,
+ attributes: { "relay.environment_id": record.environmentId },
+ }),
+ )
+ ).pipe(withRelayClientTracing);
+});
+
async function renewManagedRelayCredential(record: SavedEnvironmentRecord): Promise<{
readonly record: SavedEnvironmentRecord;
readonly credential: SavedEnvironmentCredential;
+ readonly relayTraceHeaders: Headers.Headers;
} | null> {
if (!record.relayManaged) {
return null;
@@ -1382,7 +1401,7 @@ async function renewManagedRelayCredential(record: SavedEnvironmentRecord): Prom
throw new Error("Unable to persist refreshed managed environment credentials.");
}
useSavedEnvironmentRegistryStore.getState().upsert(nextRecord);
- return { record: nextRecord, credential };
+ return { record: nextRecord, credential, relayTraceHeaders: connected.relayTraceHeaders };
}
function registerConnection(connection: EnvironmentConnection): EnvironmentConnection {
@@ -1466,6 +1485,7 @@ async function ensureSavedEnvironmentConnection(
readonly scopes?: ReadonlyArray<AuthEnvironmentScope> | null;
readonly serverConfig?: ServerConfig | null;
readonly allowManagedRenewal?: boolean;
+ readonly relayTraceHeaders?: Headers.Headers;
},
): Promise<EnvironmentConnection> {
const existing = environmentConnections.get(record.environmentId);
@@ -1511,9 +1531,14 @@ async function ensureSavedEnvironmentConnection(
}
const activeCredential = { current: credential };
+ const relayTraceHeaders = { current: options?.relayTraceHeaders ?? null };
const client =
options?.client ??
- createSavedEnvironmentClient(activeRecord.environmentId, activeCredential);
+ createSavedEnvironmentClient(
+ activeRecord.environmentId,
+ activeCredential,
+ relayTraceHeaders,
+ );
const initialConfigSnapshot = createDeferredPromise<ServerConfig>();
const knownEnvironment = createKnownEnvironment({
id: activeRecord.environmentId,
@@ -1589,6 +1614,7 @@ async function ensureSavedEnvironmentConnection(
scopes: scopeHint,
serverConfig: options?.serverConfig ?? null,
allowManagedRenewal: false,
+ relayTraceHeaders: renewed.relayTraceHeaders,
});
}
}
@@ -1916,6 +1942,7 @@ export async function addManagedRelayEnvironment(input: {
readonly wsBaseUrl: string;
readonly relayUrl: string;
readonly accessToken: string;
+ readonly relayTraceHeaders: Headers.Headers;
}): Promise<SavedEnvironmentRecord> {
const existingRecord = getSavedEnvironmentRecord(input.environmentId);
const record: SavedEnvironmentRecord = {
@@ -1939,7 +1966,10 @@ export async function addManagedRelayEnvironment(input: {
}
useSavedEnvironmentRegistryStore.getState().upsert(record);
await removeConnection(record.environmentId).catch(() => false);
- await ensureSavedEnvironmentConnection(record, { credential });
+ await ensureSavedEnvironmentConnection(record, {
+ credential,
+ relayTraceHeaders: input.relayTraceHeaders,
+ });
return record;
}
diff --git a/apps/web/src/lib/runtime.ts b/apps/web/src/lib/runtime.ts
index 6c17a2f0b..1d7903ced 100644
--- a/apps/web/src/lib/runtime.ts
+++ b/apps/web/src/lib/runtime.ts
@@ -5,6 +5,7 @@ import { FetchHttpClient } from "effect/unstable/http";
import { remoteHttpClientLayer } from "@t3tools/client-runtime";
import { httpHeaderRedactionLayer } from "@t3tools/shared/httpObservability";
+import { makeRelayClientTracingLayer } from "@t3tools/shared/relayTracing";
import {
PrimaryEnvironmentHttpClient,
primaryEnvironmentHttpClientLive,
@@ -13,13 +14,19 @@ import { primaryEnvironmentRequestInit } from "../environments/primary/requestIn
import { browserCryptoLayer } from "../cloud/dpop";
import { webManagedRelayClientLayer } from "../cloud/managedRelayLayer";
-import { resolveCloudPublicConfig } from "../cloud/publicConfig";
+import { resolveCloudPublicConfig, resolveRelayTracingConfig } from "../cloud/publicConfig";
function configuredRelayUrl(): string {
return resolveCloudPublicConfig().relayUrl ?? "http://relay.invalid";
}
const webHttpClientLayer = remoteHttpClientLayer(globalThis.fetch);
+const webRelayTracingLayer = makeRelayClientTracingLayer(resolveRelayTracingConfig(), {
+ serviceName: "t3-web-relay-client",
+ serviceVersion: import.meta.env.APP_VERSION,
+ runtime: "browser",
+ client: typeof window !== "undefined" && window.desktopBridge ? "desktop" : "web",
+}).pipe(Layer.provide(webHttpClientLayer));
export const remoteHttpRuntime = ManagedRuntime.make(webHttpClientLayer);
@@ -57,6 +64,7 @@ export const webRuntime = ManagedRuntime.make(
browserCryptoLayer,
webManagedRelayClientLayer(configuredRelayUrl()).pipe(
Layer.provide(Layer.mergeAll(webHttpClientLayer, browserCryptoLayer)),
+ Layer.provideMerge(webRelayTracingLayer),
),
),
);
diff --git a/apps/web/src/vite-env.d.ts b/apps/web/src/vite-env.d.ts
index 0c06dbb9d..d8a6d71b4 100644
--- a/apps/web/src/vite-env.d.ts
+++ b/apps/web/src/vite-env.d.ts
@@ -9,6 +9,9 @@ interface ImportMetaEnv {
readonly VITE_HOSTED_APP_CHANNEL: string;
readonly VITE_CLERK_PUBLISHABLE_KEY: string;
readonly VITE_CLERK_JWT_TEMPLATE: string;
+ readonly VITE_RELAY_OTLP_TRACES_URL: string;
+ readonly VITE_RELAY_OTLP_TRACES_DATASET: string;
+ readonly VITE_RELAY_OTLP_TRACES_TOKEN: string;
readonly APP_VERSION: string;
}
diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts
index 6dcb24e19..bfa0f8e46 100644
--- a/apps/web/vite.config.ts
+++ b/apps/web/vite.config.ts
@@ -19,6 +19,9 @@ const configuredWsUrl = process.env.VITE_WS_URL?.trim();
const configuredRelayUrl = repoEnv.VITE_T3CODE_RELAY_URL?.trim() || "";
const configuredClerkPublishableKey = repoEnv.VITE_CLERK_PUBLISHABLE_KEY?.trim() || "";
const configuredClerkJwtTemplate = repoEnv.VITE_CLERK_JWT_TEMPLATE?.trim() || "";
+const configuredRelayTracingUrl = repoEnv.VITE_RELAY_OTLP_TRACES_URL?.trim() || "";
+const configuredRelayTracingDataset = repoEnv.VITE_RELAY_OTLP_TRACES_DATASET?.trim() || "";
+const configuredRelayTracingToken = repoEnv.VITE_RELAY_OTLP_TRACES_TOKEN?.trim() || "";
const configuredHostedAppChannel = process.env.VITE_HOSTED_APP_CHANNEL?.trim() || "";
const configuredAppVersion = process.env.APP_VERSION?.trim() || pkg.version;
const configuredHostedAppUrl = (() => {
@@ -135,6 +138,11 @@ export default defineConfig(() => {
"import.meta.env.VITE_T3CODE_RELAY_URL": JSON.stringify(configuredRelayUrl),
"import.meta.env.VITE_CLERK_PUBLISHABLE_KEY": JSON.stringify(configuredClerkPublishableKey),
"import.meta.env.VITE_CLERK_JWT_TEMPLATE": JSON.stringify(configuredClerkJwtTemplate),
+ "import.meta.env.VITE_RELAY_OTLP_TRACES_URL": JSON.stringify(configuredRelayTracingUrl),
+ "import.meta.env.VITE_RELAY_OTLP_TRACES_DATASET": JSON.stringify(
+ configuredRelayTracingDataset,
+ ),
+ "import.meta.env.VITE_RELAY_OTLP_TRACES_TOKEN": JSON.stringify(configuredRelayTracingToken),
"import.meta.env.VITE_HOSTED_APP_URL": JSON.stringify(configuredHostedAppUrl ?? ""),
"import.meta.env.VITE_HOSTED_APP_CHANNEL": JSON.stringify(configuredHostedAppChannel),
"import.meta.env.APP_VERSION": JSON.stringify(configuredAppVersion),
diff --git a/infra/relay/alchemy.run.ts b/infra/relay/alchemy.run.ts
index 5dbdea8df..b9e35fd13 100644
--- a/infra/relay/alchemy.run.ts
+++ b/infra/relay/alchemy.run.ts
@@ -42,6 +42,9 @@ export default Alchemy.Stack(
mobileTracingUrl: observability.traces.otelTracesEndpoint,
mobileTracingDataset: observability.traces.name,
mobileTracingToken: observability.mobileIngestToken.token,
+ clientTracingUrl: observability.traces.otelTracesEndpoint,
+ clientTracingDataset: observability.traces.name,
+ clientTracingToken: observability.clientIngestToken.token,
};
}),
);
diff --git a/infra/relay/scripts/deploy.test.ts b/infra/relay/scripts/deploy.test.ts
index 08f6bb55c..992cb2d88 100644
--- a/infra/relay/scripts/deploy.test.ts
+++ b/infra/relay/scripts/deploy.test.ts
@@ -1,10 +1,16 @@
-import { describe, expect, it } from "vite-plus/test";
+import * as NodeServices from "@effect/platform-node/NodeServices";
+import { describe, expect, it } from "@effect/vitest";
+import * as Effect from "effect/Effect";
+import * as FileSystem from "effect/FileSystem";
+import * as Path from "effect/Path";
import {
hasDeployChanges,
+ publicConfigFromOutput,
reconcileRootEnvPublicConfig,
reconcileRootEnvRelayUrl,
serializeGithubOutput,
+ serializeRelayClientTracingEnvironment,
} from "./deploy.ts";
describe("hasDeployChanges", () => {
@@ -62,6 +68,9 @@ describe("reconcileRootEnvPublicConfig", () => {
mobileTracingUrl: "https://api.axiom.co/v1/traces",
mobileTracingDataset: "t3-code-mobile-traces-dev",
mobileTracingToken: "xaat-public-ingest",
+ clientTracingUrl: "https://api.axiom.co/v1/traces",
+ clientTracingDataset: "t3-code-relay-client-traces-dev",
+ clientTracingToken: "xaat-relay-client-ingest",
} as const;
it("adds the complete local client config", () => {
@@ -71,6 +80,9 @@ describe("reconcileRootEnvPublicConfig", () => {
"T3CODE_MOBILE_OTLP_TRACES_URL=https://api.axiom.co/v1/traces",
"T3CODE_MOBILE_OTLP_TRACES_DATASET=t3-code-mobile-traces-dev",
"T3CODE_MOBILE_OTLP_TRACES_TOKEN=xaat-public-ingest",
+ "T3CODE_RELAY_CLIENT_OTLP_TRACES_URL=https://api.axiom.co/v1/traces",
+ "T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET=t3-code-relay-client-traces-dev",
+ "T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=xaat-relay-client-ingest",
"",
].join("\n"),
);
@@ -85,6 +97,9 @@ describe("reconcileRootEnvPublicConfig", () => {
"T3CODE_MOBILE_OTLP_TRACES_URL=https://old.example.test/v1/traces",
"T3CODE_MOBILE_OTLP_TRACES_DATASET=old-dataset",
"T3CODE_MOBILE_OTLP_TRACES_TOKEN=old-token",
+ "T3CODE_RELAY_CLIENT_OTLP_TRACES_URL=https://old.example.test/v1/traces",
+ "T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET=old-client-dataset",
+ "T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=old-client-token",
"",
].join("\n"),
config,
@@ -96,6 +111,9 @@ describe("reconcileRootEnvPublicConfig", () => {
"T3CODE_MOBILE_OTLP_TRACES_URL=https://api.axiom.co/v1/traces",
"T3CODE_MOBILE_OTLP_TRACES_DATASET=t3-code-mobile-traces-dev",
"T3CODE_MOBILE_OTLP_TRACES_TOKEN=xaat-public-ingest",
+ "T3CODE_RELAY_CLIENT_OTLP_TRACES_URL=https://api.axiom.co/v1/traces",
+ "T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET=t3-code-relay-client-traces-dev",
+ "T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=xaat-relay-client-ingest",
"",
].join("\n"),
);
@@ -113,3 +131,73 @@ describe("serializeGithubOutput", () => {
).toBe("changed=false\nresult=noop\nrelay_url=https://relay.example.test\n");
});
});
+
+describe("serializeRelayClientTracingEnvironment", () => {
+ it("serializes tracing config for downstream GITHUB_ENV loading", () => {
+ expect(
+ serializeRelayClientTracingEnvironment({
+ relayUrl: "https://relay.example.test",
+ mobileTracingUrl: "https://api.axiom.co/v1/traces",
+ mobileTracingDataset: "mobile",
+ mobileTracingToken: "mobile-token",
+ clientTracingUrl: "https://api.axiom.co/v1/traces",
+ clientTracingDataset: "relay",
+ clientTracingToken: "client-token",
+ }),
+ ).toBe(
+ [
+ "T3CODE_RELAY_CLIENT_OTLP_TRACES_URL=https://api.axiom.co/v1/traces",
+ "T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET=relay",
+ "T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=client-token",
+ "",
+ ].join("\n"),
+ );
+ });
+});
+
+describe("release workflow tracing config propagation", () => {
+ it.effect("uses an artifact instead of a masked cross-job token output", () =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const workflowPath = yield* path.fromFileUrl(
+ new URL("../../../.github/workflows/release.yml", import.meta.url),
+ );
+ const workflow = yield* fileSystem.readFileString(workflowPath);
+
+ expect(workflow).not.toContain("client_tracing_token:");
+ expect(workflow).not.toContain("needs.relay_public_config.outputs.client_tracing_token");
+ expect(workflow).toContain('--github-env-file "$RUNNER_TEMP/relay-client-tracing.env"');
+ expect(workflow).toContain("name: relay-client-tracing-config");
+ expect(workflow).toContain('cat "$config_path" >> "$GITHUB_ENV"');
+ }).pipe(Effect.provide(NodeServices.layer)),
+ );
+});
+
+describe("publicConfigFromOutput", () => {
+ it("reads the complete public tracing config from persisted Alchemy output", () => {
+ expect(
+ publicConfigFromOutput({
+ url: "https://relay.example.test",
+ mobileTracingUrl: "https://api.axiom.co/v1/traces",
+ mobileTracingDataset: "mobile",
+ mobileTracingToken: "mobile-token",
+ clientTracingUrl: "https://api.axiom.co/v1/traces",
+ clientTracingDataset: "relay",
+ clientTracingToken: "client-token",
+ }),
+ ).toEqual({
+ relayUrl: "https://relay.example.test",
+ mobileTracingUrl: "https://api.axiom.co/v1/traces",
+ mobileTracingDataset: "mobile",
+ mobileTracingToken: "mobile-token",
+ clientTracingUrl: "https://api.axiom.co/v1/traces",
+ clientTracingDataset: "relay",
+ clientTracingToken: "client-token",
+ });
+ });
+
+ it("rejects incomplete stack output", () => {
+ expect(publicConfigFromOutput({ url: "https://relay.example.test" })).toBeNull();
+ });
+});
diff --git a/infra/relay/scripts/deploy.ts b/infra/relay/scripts/deploy.ts
index e4ed492db..2ef82ec4f 100644
--- a/infra/relay/scripts/deploy.ts
+++ b/infra/relay/scripts/deploy.ts
@@ -8,10 +8,12 @@ import { provideFreshArtifactStore } from "alchemy/Artifacts";
import { AuthProviders } from "alchemy/Auth/AuthProvider";
import { CredentialsStoreLive } from "alchemy/Auth/Credentials";
import { ProfileLive } from "alchemy/Auth/Profile";
+import * as Cloudflare from "alchemy/Cloudflare";
import { Cli } from "alchemy/Cli/Cli";
import { LoggingCli } from "alchemy/Cli/LoggingCli";
import * as Plan from "alchemy/Plan";
import * as Stage from "alchemy/Stage";
+import * as State from "alchemy/State/State";
import { TelemetryLive } from "alchemy/Telemetry/Layer";
import { PlatformServices } from "alchemy/Util/PlatformServices";
import * as Config from "effect/Config";
@@ -41,6 +43,8 @@ export interface RelayDeployOptions {
readonly yes: boolean;
readonly adopt: boolean;
readonly githubOutput: boolean;
+ readonly githubEnvFile: Option.Option<string>;
+ readonly readState: boolean;
}
export interface RelayPublicConfig {
@@ -48,6 +52,9 @@ export interface RelayPublicConfig {
readonly mobileTracingUrl: string;
readonly mobileTracingDataset: string;
readonly mobileTracingToken: string;
+ readonly clientTracingUrl: string;
+ readonly clientTracingDataset: string;
+ readonly clientTracingToken: string;
}
const publicConfigEnvEntries = (config: RelayPublicConfig) =>
@@ -56,6 +63,9 @@ const publicConfigEnvEntries = (config: RelayPublicConfig) =>
T3CODE_MOBILE_OTLP_TRACES_URL: config.mobileTracingUrl,
T3CODE_MOBILE_OTLP_TRACES_DATASET: config.mobileTracingDataset,
T3CODE_MOBILE_OTLP_TRACES_TOKEN: config.mobileTracingToken,
+ T3CODE_RELAY_CLIENT_OTLP_TRACES_URL: config.clientTracingUrl,
+ T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET: config.clientTracingDataset,
+ T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN: config.clientTracingToken,
}) as const;
export function reconcileRootEnvPublicConfig(contents: string, config: RelayPublicConfig): string {
@@ -82,9 +92,13 @@ export function reconcileRootEnvRelayUrl(contents: string, relayUrl: string): st
mobileTracingUrl: "",
mobileTracingDataset: "",
mobileTracingToken: "",
+ clientTracingUrl: "",
+ clientTracingDataset: "",
+ clientTracingToken: "",
})
.split("\n")
.filter((line) => !line.startsWith("T3CODE_MOBILE_OTLP_TRACES_"))
+ .filter((line) => !line.startsWith("T3CODE_RELAY_CLIENT_OTLP_TRACES_"))
.join("\n");
}
@@ -98,7 +112,7 @@ export function hasDeployChanges(plan: Plan.Plan): boolean {
);
}
-export type RelayDeployResult = "applied" | "noop" | "dry-run" | "cancelled";
+export type RelayDeployResult = "applied" | "noop" | "dry-run" | "cancelled" | "state";
export interface RelayDeployOutcome {
readonly result: RelayDeployResult;
@@ -112,6 +126,14 @@ export function serializeGithubOutput(entries: Readonly<Record<string, string |
.join("");
}
+export function serializeRelayClientTracingEnvironment(config: RelayPublicConfig): string {
+ return serializeGithubOutput({
+ T3CODE_RELAY_CLIENT_OTLP_TRACES_URL: config.clientTracingUrl,
+ T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET: config.clientTracingDataset,
+ T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN: config.clientTracingToken,
+ });
+}
+
const relayRoot = Effect.service(Path.Path).pipe(
Effect.flatMap((path) => path.fromFileUrl(new URL("..", import.meta.url))),
);
@@ -151,7 +173,7 @@ const reconcileRootEnv = Effect.fn("relay.deploy.reconcileRootEnv")(function* (
const contents = (yield* fs.exists(rootEnvPath)) ? yield* fs.readFileString(rootEnvPath) : "";
yield* fs.writeFileString(rootEnvPath, reconcileRootEnvPublicConfig(contents, config));
- yield* Console.log(`Updated ${rootEnvPath} with relay URL and mobile tracing configuration`);
+ yield* Console.log(`Updated ${rootEnvPath} with relay public client configuration`);
});
const writeGithubOutput = Effect.fn("relay.deploy.writeGithubOutput")(function* (
@@ -165,14 +187,34 @@ const writeGithubOutput = Effect.fn("relay.deploy.writeGithubOutput")(function*
changed: outcome.changed,
result: outcome.result,
...(Option.isSome(outcome.publicConfig)
- ? { relay_url: outcome.publicConfig.value.relayUrl }
+ ? {
+ relay_url: outcome.publicConfig.value.relayUrl,
+ }
: {}),
}),
{ flag: "a" },
);
});
-const deployServices = Layer.mergeAll(
+const writeGithubEnvFile = Effect.fn("relay.deploy.writeGithubEnvFile")(function* (
+ outcome: RelayDeployOutcome,
+ outputPath: string,
+) {
+ if (Option.isNone(outcome.publicConfig)) {
+ return yield* new RelayDeployError({
+ message: "Relay public client config is unavailable for the GitHub environment file",
+ });
+ }
+ const fs = yield* FileSystem.FileSystem;
+ yield* Console.log(`::add-mask::${outcome.publicConfig.value.clientTracingToken}`);
+ yield* fs.writeFileString(
+ outputPath,
+ serializeRelayClientTracingEnvironment(outcome.publicConfig.value),
+ );
+});
+
+const deployBaseServices = Layer.mergeAll(
+ Layer.succeed(AuthProviders, {}),
Layer.provideMerge(AlchemyContextLive, PlatformServices),
Layer.provide(ProfileLive, PlatformServices),
Layer.provide(CredentialsStoreLive, PlatformServices),
@@ -180,6 +222,64 @@ const deployServices = Layer.mergeAll(
TelemetryLive,
LoggingCli,
);
+const deployServices = deployBaseServices;
+
+export function publicConfigFromOutput(output: unknown): RelayPublicConfig | null {
+ if (typeof output !== "object" || output === null) {
+ return null;
+ }
+ const value = output as Record<string, unknown>;
+ const text = (name: string) => (typeof value[name] === "string" ? value[name] : undefined);
+ const secret = (name: string): string | undefined => {
+ const candidate = value[name];
+ if (!Redacted.isRedacted(candidate)) {
+ return text(name);
+ }
+ const redacted = Redacted.value(candidate);
+ return typeof redacted === "string" ? redacted : undefined;
+ };
+ const relayUrl = text("url");
+ const mobileTracingUrl = text("mobileTracingUrl");
+ const mobileTracingDataset = text("mobileTracingDataset");
+ const mobileTracingToken = secret("mobileTracingToken");
+ const clientTracingUrl = text("clientTracingUrl");
+ const clientTracingDataset = text("clientTracingDataset");
+ const clientTracingToken = secret("clientTracingToken");
+ return relayUrl &&
+ mobileTracingUrl &&
+ mobileTracingDataset &&
+ mobileTracingToken &&
+ clientTracingUrl &&
+ clientTracingDataset &&
+ clientTracingToken
+ ? {
+ relayUrl,
+ mobileTracingUrl,
+ mobileTracingDataset,
+ mobileTracingToken,
+ clientTracingUrl,
+ clientTracingDataset,
+ clientTracingToken,
+ }
+ : null;
+}
+
+const readRelayPublicConfig = Effect.fn("relay.deploy.readState")(function* (stage: string) {
+ const state = yield* State.State;
+ const service = yield* state;
+ const output = yield* service.getOutput({ stack: "T3CodeRelay", stage });
+ const publicConfig = publicConfigFromOutput(output);
+ if (publicConfig === null) {
+ return yield* new RelayDeployError({
+ message: `Alchemy relay state for stage ${stage} did not include complete public client config`,
+ });
+ }
+ return {
+ result: "state",
+ changed: false,
+ publicConfig: Option.some(publicConfig),
+ } satisfies RelayDeployOutcome;
+});
const runRelayDeploy = Effect.fn("relay.deploy.run")(
function* (
@@ -188,7 +288,6 @@ const runRelayDeploy = Effect.fn("relay.deploy.run")(
_stage: string,
) {
const stack = yield* RelayStack;
-
const cli = yield* Cli;
const plan = yield* Plan.make(stack, { force: options.force }).pipe(
Effect.provide(stack.services),
@@ -223,7 +322,10 @@ const runRelayDeploy = Effect.fn("relay.deploy.run")(
output.url === undefined ||
output.mobileTracingUrl === undefined ||
output.mobileTracingDataset === undefined ||
- output.mobileTracingToken === undefined
+ output.mobileTracingToken === undefined ||
+ output.clientTracingUrl === undefined ||
+ output.clientTracingDataset === undefined ||
+ output.clientTracingToken === undefined
) {
return yield* new RelayDeployError({
message: "Alchemy relay deploy output did not include complete public client config",
@@ -237,6 +339,9 @@ const runRelayDeploy = Effect.fn("relay.deploy.run")(
mobileTracingUrl: output.mobileTracingUrl,
mobileTracingDataset: output.mobileTracingDataset,
mobileTracingToken: Redacted.value(output.mobileTracingToken),
+ clientTracingUrl: output.clientTracingUrl,
+ clientTracingDataset: output.clientTracingDataset,
+ clientTracingToken: Redacted.value(output.clientTracingToken),
}),
} satisfies RelayDeployOutcome;
},
@@ -264,13 +369,18 @@ export const deploy = Effect.fn("relay.deploy")(function* (options: RelayDeployO
Effect.provide(ConfigProvider.layer(configProvider)),
);
const stage = Option.getOrElse(options.stage, () => configuredStage);
- const outcome = yield* runRelayDeploy(options, configProvider, stage);
+ const outcome = options.readState
+ ? yield* readRelayPublicConfig(stage).pipe(Effect.provide(Cloudflare.state()))
+ : yield* runRelayDeploy(options, configProvider, stage);
if (Option.isSome(outcome.publicConfig)) {
yield* reconcileRootEnv(outcome.publicConfig.value);
}
if (options.githubOutput) {
yield* writeGithubOutput(outcome);
}
+ if (Option.isSome(options.githubEnvFile)) {
+ yield* writeGithubEnvFile(outcome, options.githubEnvFile.value);
+ }
});
export const relayDeployCommand = Command.make(
@@ -306,6 +416,16 @@ export const relayDeployCommand = Command.make(
Flag.withDescription("Append relay deployment metadata to GITHUB_OUTPUT."),
Flag.withDefault(false),
),
+ githubEnvFile: Flag.string("github-env-file").pipe(
+ Flag.withDescription(
+ "Write relay client tracing variables to a file suitable for GITHUB_ENV.",
+ ),
+ Flag.optional,
+ ),
+ readState: Flag.boolean("read-state").pipe(
+ Flag.withDescription("Read the deployed stack output without planning or applying changes."),
+ Flag.withDefault(false),
+ ),
},
deploy,
).pipe(Command.withDescription("Deploy the T3 Code relay through Alchemy."));
diff --git a/infra/relay/src/observability.ts b/infra/relay/src/observability.ts
index 0f831586e..e0a79599c 100644
--- a/infra/relay/src/observability.ts
+++ b/infra/relay/src/observability.ts
@@ -50,6 +50,14 @@ export const RelayObservability = Effect.gen(function* () {
})),
});
+ const clientIngestToken = yield* Axiom.ApiToken("RelayClientAxiomIngestToken", {
+ name: relayResourceNameForStage("t3-code-relay-client-otel-ingest", stage),
+ description: "Owned by Alchemy. Scoped OTLP ingest token for first-party relay client spans.",
+ datasetCapabilities: Output.map(traces.name, (dataset) => ({
+ [dataset]: { ingest: ["create" as const] },
+ })),
+ });
+
yield* Axiom.View("RelayRecentSpansView", {
name: relayResourceNameForStage("t3-code-relay-recent-spans", stage),
description: "Recent relay HTTP request spans.",
@@ -57,7 +65,7 @@ export const RelayObservability = Effect.gen(function* () {
aplQuery: Output.map(traces.name, relayRecentSpansQuery),
});
- return { traces, workerIngestToken, mobileIngestToken } as const;
+ return { traces, workerIngestToken, mobileIngestToken, clientIngestToken } as const;
});
export const withSpanAttributes =
diff --git a/packages/client-runtime/src/managedRelay.ts b/packages/client-runtime/src/managedRelay.ts
index a3bc973c6..f4b9b1f93 100644
--- a/packages/client-runtime/src/managedRelay.ts
+++ b/packages/client-runtime/src/managedRelay.ts
@@ -26,6 +26,7 @@ import {
RelayUnregisterDeviceEndpoint,
} from "@t3tools/contracts/relay";
import { encodeOAuthScope, oauthScopeSetEquals } from "@t3tools/shared/oauthScope";
+import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
import { normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
@@ -357,6 +358,7 @@ export function managedRelayClientLayer(options: ManagedRelayClientLayerOptions)
relayClientError("Could not list relay-managed environments.", cause),
),
timeoutRelayRequest("Relay environment listing timed out."),
+ withRelayClientTracing,
),
listDevices: (input) =>
client.client
@@ -369,6 +371,7 @@ export function managedRelayClientLayer(options: ManagedRelayClientLayerOptions)
relayClientError("Could not list relay client devices.", cause),
),
timeoutRelayRequest("Relay client device listing timed out."),
+ withRelayClientTracing,
),
createEnvironmentLinkChallenge: (input) =>
client.client
@@ -381,6 +384,7 @@ export function managedRelayClientLayer(options: ManagedRelayClientLayerOptions)
relayClientError("Could not create relay environment link challenge.", cause),
),
timeoutRelayRequest("Relay environment link challenge timed out."),
+ withRelayClientTracing,
),
linkEnvironment: (input) =>
client.client
@@ -393,6 +397,7 @@ export function managedRelayClientLayer(options: ManagedRelayClientLayerOptions)
relayClientError("Could not link relay environment.", cause),
),
timeoutRelayRequest("Relay environment linking timed out."),
+ withRelayClientTracing,
),
unlinkEnvironment: (input) =>
client.client
@@ -405,6 +410,7 @@ export function managedRelayClientLayer(options: ManagedRelayClientLayerOptions)
relayClientError("Could not unlink relay environment.", cause),
),
timeoutRelayRequest("Relay environment unlinking timed out."),
+ withRelayClientTracing,
),
getEnvironmentStatus: (input) =>
Effect.gen(function* () {
@@ -424,7 +430,7 @@ export function managedRelayClientLayer(options: ManagedRelayClientLayerOptions)
),
timeoutRelayRequest("Relay environment status request timed out."),
);
- }),
+ }).pipe(withRelayClientTracing),
connectEnvironment: (input) =>
Effect.gen(function* () {
const authorization = yield* authorize({
@@ -448,7 +454,7 @@ export function managedRelayClientLayer(options: ManagedRelayClientLayerOptions)
),
timeoutRelayRequest("Relay environment connection timed out."),
);
- }),
+ }).pipe(withRelayClientTracing),
registerDevice: (input) =>
Effect.gen(function* () {
const authorization = yield* authorizeMobileRegistration({
@@ -466,7 +472,7 @@ export function managedRelayClientLayer(options: ManagedRelayClientLayerOptions)
),
timeoutRelayRequest("Relay mobile device registration timed out."),
);
- }),
+ }).pipe(withRelayClientTracing),
unregisterDevice: (input) =>
Effect.gen(function* () {
const authorization = yield* authorizeMobileRegistration({
@@ -484,7 +490,7 @@ export function managedRelayClientLayer(options: ManagedRelayClientLayerOptions)
),
timeoutRelayRequest("Relay mobile device unregistration timed out."),
);
- }),
+ }).pipe(withRelayClientTracing),
registerLiveActivity: (input) =>
Effect.gen(function* () {
const authorization = yield* authorizeMobileRegistration({
@@ -502,7 +508,7 @@ export function managedRelayClientLayer(options: ManagedRelayClientLayerOptions)
),
timeoutRelayRequest("Relay Live Activity registration timed out."),
);
- }),
+ }).pipe(withRelayClientTracing),
resetTokenCache: SynchronizedRef.set(cachedTokens, []),
});
}),
diff --git a/packages/shared/package.json b/packages/shared/package.json
index ad3db08eb..97d51c897 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -158,6 +158,10 @@
"./hostProcess": {
"types": "./src/hostProcess.ts",
"import": "./src/hostProcess.ts"
+ },
+ "./relayTracing": {
+ "types": "./src/relayTracing.ts",
+ "import": "./src/relayTracing.ts"
}
},
"scripts": {
diff --git a/packages/shared/src/relayTracing.test.ts b/packages/shared/src/relayTracing.test.ts
new file mode 100644
index 000000000..10f4e1087
--- /dev/null
+++ b/packages/shared/src/relayTracing.test.ts
@@ -0,0 +1,57 @@
+import { describe, expect, it } from "@effect/vitest";
+import * as Effect from "effect/Effect";
+import * as Option from "effect/Option";
+import * as Tracer from "effect/Tracer";
+
+import { RelayClientTracer, withRelayClientTracing } from "./relayTracing.ts";
+
+function collectingTracer(spans: Array<string>): Tracer.Tracer {
+ return Tracer.make({
+ span: (options) => {
+ const span = new Tracer.NativeSpan(options);
+ const end = span.end.bind(span);
+ span.end = (endTime, exit) => {
+ end(endTime, exit);
+ spans.push(span.name);
+ };
+ return span;
+ },
+ });
+}
+
+describe("withRelayClientTracing", () => {
+ it.effect("uses the product tracer only for relay operations", () =>
+ Effect.gen(function* () {
+ const userSpans: Array<string> = [];
+ const productSpans: Array<string> = [];
+ const userTracer = collectingTracer(userSpans);
+ const productTracer = collectingTracer(productSpans);
+
+ yield* Effect.void.pipe(Effect.withSpan("user.operation"), Effect.withTracer(userTracer));
+ yield* Effect.void.pipe(
+ Effect.withSpan("relay.operation"),
+ withRelayClientTracing,
+ Effect.provideService(RelayClientTracer, Option.some(productTracer)),
+ Effect.withTracer(userTracer),
+ );
+
+ expect(userSpans).toEqual(["user.operation"]);
+ expect(productSpans).toEqual(["relay.operation"]);
+ }),
+ );
+
+ it.effect("preserves the active tracer when product tracing is disabled", () =>
+ Effect.gen(function* () {
+ const userSpans: Array<string> = [];
+ const userTracer = collectingTracer(userSpans);
+
+ yield* Effect.void.pipe(
+ Effect.withSpan("relay.operation"),
+ withRelayClientTracing,
+ Effect.withTracer(userTracer),
+ );
+
+ expect(userSpans).toEqual(["relay.operation"]);
+ }),
+ );
+});
diff --git a/packages/shared/src/relayTracing.ts b/packages/shared/src/relayTracing.ts
new file mode 100644
index 000000000..6005856d9
--- /dev/null
+++ b/packages/shared/src/relayTracing.ts
@@ -0,0 +1,70 @@
+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 * as Tracer from "effect/Tracer";
+import type { HttpClient } from "effect/unstable/http";
+import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
+
+export interface RelayClientTracingConfig {
+ readonly tracesUrl: string;
+ readonly tracesDataset: string;
+ readonly tracesToken: string;
+}
+
+export interface RelayClientTracingResource {
+ readonly serviceName: string;
+ readonly serviceVersion?: string;
+ readonly runtime: string;
+ readonly client: string;
+ readonly component?: string;
+}
+
+export class RelayClientTracer extends Context.Reference(
+ "@t3tools/shared/relayTracing/RelayClientTracer",
+ {
+ defaultValue: () => Option.none<Tracer.Tracer>(),
+ },
+) {}
+
+export const withRelayClientTracing = <A, E, R>(
+ effect: Effect.Effect<A, E, R>,
+): Effect.Effect<A, E, R> =>
+ RelayClientTracer.pipe(
+ Effect.flatMap(
+ Option.match({
+ onNone: () => effect,
+ onSome: (tracer) => effect.pipe(Effect.provideService(Tracer.Tracer, tracer)),
+ }),
+ ),
+ );
+
+export function makeRelayClientTracingLayer(
+ config: RelayClientTracingConfig | null,
+ resource: RelayClientTracingResource,
+): Layer.Layer<never, never, HttpClient.HttpClient> {
+ if (config === null) {
+ return Layer.succeed(RelayClientTracer, Option.none());
+ }
+
+ const tracerLayer = OtlpTracer.layer({
+ url: config.tracesUrl,
+ headers: {
+ Authorization: `Bearer ${config.tracesToken}`,
+ "X-Axiom-Dataset": config.tracesDataset,
+ },
+ resource: {
+ serviceName: resource.serviceName,
+ serviceVersion: resource.serviceVersion,
+ attributes: {
+ "service.runtime": resource.runtime,
+ "service.component": resource.component ?? "relay-client",
+ "t3.client.surface": resource.client,
+ },
+ },
+ }).pipe(Layer.provide(OtlpSerialization.layerJson));
+
+ return Layer.effect(RelayClientTracer, Tracer.Tracer.pipe(Effect.map(Option.some))).pipe(
+ Layer.provide(tracerLayer),
+ );
+}
diff --git a/scripts/lib/public-config.test.ts b/scripts/lib/public-config.test.ts
index 3d4a8f6de..6f6e83156 100644
--- a/scripts/lib/public-config.test.ts
+++ b/scripts/lib/public-config.test.ts
@@ -33,6 +33,12 @@ describe("loadRepoEnv", () => {
expect(env.EXPO_PUBLIC_OTLP_TRACES_URL).toBeUndefined();
expect(env.EXPO_PUBLIC_OTLP_TRACES_DATASET).toBeUndefined();
expect(env.EXPO_PUBLIC_OTLP_TRACES_TOKEN).toBeUndefined();
+ expect(env.T3CODE_RELAY_CLIENT_OTLP_TRACES_URL).toBeUndefined();
+ expect(env.T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET).toBeUndefined();
+ expect(env.T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN).toBeUndefined();
+ expect(env.VITE_RELAY_OTLP_TRACES_URL).toBeUndefined();
+ expect(env.VITE_RELAY_OTLP_TRACES_DATASET).toBeUndefined();
+ expect(env.VITE_RELAY_OTLP_TRACES_TOKEN).toBeUndefined();
});
it("applies process, root local, and root precedence in that order", () => {
@@ -91,6 +97,29 @@ describe("loadRepoEnv", () => {
mobileOtlpTracesUrl: "https://api.axiom.co/v1/traces",
mobileOtlpTracesDataset: "mobile-traces",
mobileOtlpTracesToken: "mobile-token",
+ relayClientOtlpTracesUrl: undefined,
+ relayClientOtlpTracesDataset: undefined,
+ relayClientOtlpTracesToken: undefined,
+ });
+ });
+
+ it("projects canonical relay client tracing values to web build aliases", () => {
+ expect(
+ loadRepoEnv({
+ baseEnv: {
+ T3CODE_RELAY_CLIENT_OTLP_TRACES_URL: "https://api.axiom.co/v1/traces",
+ T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET: "relay-client-traces",
+ T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN: "relay-client-token",
+ },
+ repoRoot: makeTemporaryDirectory(),
+ }),
+ ).toEqual({
+ T3CODE_RELAY_CLIENT_OTLP_TRACES_URL: "https://api.axiom.co/v1/traces",
+ T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET: "relay-client-traces",
+ T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN: "relay-client-token",
+ VITE_RELAY_OTLP_TRACES_URL: "https://api.axiom.co/v1/traces",
+ VITE_RELAY_OTLP_TRACES_DATASET: "relay-client-traces",
+ VITE_RELAY_OTLP_TRACES_TOKEN: "relay-client-token",
});
});
diff --git a/scripts/lib/public-config.ts b/scripts/lib/public-config.ts
index fcae15312..9b988df9c 100644
--- a/scripts/lib/public-config.ts
+++ b/scripts/lib/public-config.ts
@@ -12,6 +12,9 @@ export interface T3CodePublicConfig {
readonly mobileOtlpTracesUrl: string | undefined;
readonly mobileOtlpTracesDataset: string | undefined;
readonly mobileOtlpTracesToken: string | undefined;
+ readonly relayClientOtlpTracesUrl: string | undefined;
+ readonly relayClientOtlpTracesDataset: string | undefined;
+ readonly relayClientOtlpTracesToken: string | undefined;
}
type Environment = Readonly<Record<string, string | undefined>>;
@@ -78,6 +81,24 @@ export function loadRepoEnv({
EXPO_PUBLIC_OTLP_TRACES_TOKEN: config.mobileOtlpTracesToken,
}
: {}),
+ ...(config.relayClientOtlpTracesUrl
+ ? {
+ T3CODE_RELAY_CLIENT_OTLP_TRACES_URL: config.relayClientOtlpTracesUrl,
+ VITE_RELAY_OTLP_TRACES_URL: config.relayClientOtlpTracesUrl,
+ }
+ : {}),
+ ...(config.relayClientOtlpTracesDataset
+ ? {
+ T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET: config.relayClientOtlpTracesDataset,
+ VITE_RELAY_OTLP_TRACES_DATASET: config.relayClientOtlpTracesDataset,
+ }
+ : {}),
+ ...(config.relayClientOtlpTracesToken
+ ? {
+ T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN: config.relayClientOtlpTracesToken,
+ VITE_RELAY_OTLP_TRACES_TOKEN: config.relayClientOtlpTracesToken,
+ }
+ : {}),
};
}
@@ -112,6 +133,21 @@ export function resolvePublicConfig(...sources: readonly Environment[]): T3CodeP
"T3CODE_MOBILE_OTLP_TRACES_TOKEN",
"EXPO_PUBLIC_OTLP_TRACES_TOKEN",
),
+ relayClientOtlpTracesUrl: firstNonEmpty(
+ sources,
+ "T3CODE_RELAY_CLIENT_OTLP_TRACES_URL",
+ "VITE_RELAY_OTLP_TRACES_URL",
+ ),
+ relayClientOtlpTracesDataset: firstNonEmpty(
+ sources,
+ "T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET",
+ "VITE_RELAY_OTLP_TRACES_DATASET",
+ ),
+ relayClientOtlpTracesToken: firstNonEmpty(
+ sources,
+ "T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN",
+ "VITE_RELAY_OTLP_TRACES_TOKEN",
+ ),
};
}