TypeScript
fix(observability): every app reports its own environment and release channel (#24340)
Yordis Prietoa960f5602fb5
diff --git a/.github/workflows/web-preview.yml b/.github/workflows/web-preview.ymlindex 3def8478bbd..4b3f8952d50 100644--- a/.github/workflows/web-preview.yml+++ b/.github/workflows/web-preview.yml@@ -82,7 +82,8 @@ jobs:--archive=tgz \--yes \--token "$VERCEL_TOKEN" \- --scope "$vercel_scope"+ --scope "$vercel_scope" \+ --build-env "VITE_RELEASE_CHANNEL=preview")"printf '%s\n' "$deployment_output"# Vercel can print lockfile warnings to stdout before the deployment URL.diff --git a/apps/desktop/src/app/DesktopObservability.ts b/apps/desktop/src/app/DesktopObservability.tsindex 6baf2c4117f..836d1230796 100644--- a/apps/desktop/src/app/DesktopObservability.ts+++ b/apps/desktop/src/app/DesktopObservability.ts@@ -7,6 +7,7 @@ import {import * as HostProcess from "@t3tools/shared/HostProcess";import * as SharedObservability from "@t3tools/shared/observability";import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";+import { releaseChannelOf, releaseResourceAttributes } from "@t3tools/shared/releaseResource";import {parsePersistedServerObservabilitySettings,type PersistedServerObservabilitySettings,@@ -595,14 +596,21 @@ const layerTelemetry = Layer.unwrap(Effect.gen(function* () {const environment = yield* DesktopEnvironment.DesktopEnvironment;const endpoints = yield* resolveOtlpEndpoints;+ // Unpackaged runs launch a script, so Electron reports its own version.+ const serviceVersion = environment.isPackaged+ ? environment.appVersion+ : desktopPackageJson.version;const resource = {serviceName: "t3code-desktop",- // Unpackaged runs launch a script, so Electron reports its own version.- serviceVersion: environment.isPackaged ? environment.appVersion : desktopPackageJson.version,+ serviceVersion,attributes: {"service.namespace": "t3code","service.runtime": "desktop","service.mode": environment.isDevelopment ? "development" : "packaged",+ ...releaseResourceAttributes(+ environment.isDevelopment ? "dev" : releaseChannelOf(serviceVersion),+ endpoints.resourceAttributes,+ ),"host.name": endpoints.resourceAttributes["host.name"] || (yield* HostProcess.Hostname),},};diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.test.tsindex 8d70ab4c479..7464d8fbe9e 100644--- a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts+++ b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts@@ -678,7 +678,7 @@ describe("DesktopBackendConfiguration", () => {),);- it.effect("resolveWsl carries the kill switch into the distro", () =>+ it.effect("resolveWsl carries the kill switch and resource attributes into the distro", () =>Effect.gen(function* () {const fileSystem = yield* FileSystem.FileSystem;const baseDir = yield* fileSystem.makeTempDirectoryScoped({@@ -688,10 +688,12 @@ describe("DesktopBackendConfiguration", () => {const previousWslEnv = process.env.WSLENV;const previousDisabled = process.env.OTEL_SDK_DISABLED;const previousTelemetry = process.env.T3CODE_TELEMETRY_ENABLED;+ const previousResourceAttributes = process.env.OTEL_RESOURCE_ATTRIBUTES;try {delete process.env.WSLENV;process.env.OTEL_SDK_DISABLED = "true";process.env.T3CODE_TELEMETRY_ENABLED = "false";+ process.env.OTEL_RESOURCE_ATTRIBUTES = "deployment.environment.name=staging";yield* Effect.gen(function* () {const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;@@ -701,6 +703,8 @@ describe("DesktopBackendConfiguration", () => {assert.include((config.env.WSLENV ?? "").split(":"), "OTEL_SDK_DISABLED");assert.equal(config.env.T3CODE_TELEMETRY_ENABLED, "false");assert.include((config.env.WSLENV ?? "").split(":"), "T3CODE_TELEMETRY_ENABLED");+ assert.equal(config.env.OTEL_RESOURCE_ATTRIBUTES, "deployment.environment.name=staging");+ assert.include((config.env.WSLENV ?? "").split(":"), "OTEL_RESOURCE_ATTRIBUTES");}).pipe(Effect.provide(layerBackendConfiguration().pipe(@@ -722,6 +726,7 @@ describe("DesktopBackendConfiguration", () => {restoreEnv("WSLENV", previousWslEnv);restoreEnv("OTEL_SDK_DISABLED", previousDisabled);restoreEnv("T3CODE_TELEMETRY_ENABLED", previousTelemetry);+ restoreEnv("OTEL_RESOURCE_ATTRIBUTES", previousResourceAttributes);}}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),);diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.tsindex 06b4c6b5981..ca69f5d0258 100644--- a/apps/desktop/src/backend/DesktopBackendConfiguration.ts+++ b/apps/desktop/src/backend/DesktopBackendConfiguration.ts@@ -110,6 +110,7 @@ const WSL_FORWARDED_ENV_NAMES = ["OTEL_TRACES_EXPORTER","OTEL_METRICS_EXPORTER","OTEL_LOGS_EXPORTER",+ "OTEL_RESOURCE_ATTRIBUTES",] as const;const WSL_SERVER_SYSTEM_PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";diff --git a/apps/mobile/src/features/observability/tracing.ts b/apps/mobile/src/features/observability/tracing.tsindex e2b8ee0f168..9a5e7254df2 100644--- a/apps/mobile/src/features/observability/tracing.ts+++ b/apps/mobile/src/features/observability/tracing.ts@@ -1,4 +1,5 @@import Constants from "expo-constants";+import { type ReleaseChannel, releaseResourceAttributes } from "@t3tools/shared/releaseResource";import * as RelayTracing from "@t3tools/shared/relayTracing";import { hasTracingPublicConfig, resolveCloudPublicConfig } from "../cloud/publicConfig";@@ -14,6 +15,12 @@ export interface TracingResource {readonly appVariant: string;}+const RELEASE_CHANNEL_BY_VARIANT: Readonly<Record<string, ReleaseChannel | undefined>> = {+ development: "dev",+ preview: "preview",+ production: "stable",+};+export function resolveTracingConfig(): TracingConfig | null {const config = resolveCloudPublicConfig();if (!hasTracingPublicConfig(config)) {@@ -24,11 +31,16 @@ export function resolveTracingConfig(): TracingConfig | null {}export function layerFromConfig(config: TracingConfig | null, resource: TracingResource) {+ const channel =+ typeof __DEV__ !== "undefined" && __DEV__+ ? "dev"+ : RELEASE_CHANNEL_BY_VARIANT[resource.appVariant];return RelayTracing.layer(config, {serviceName: "t3code-mobile",serviceVersion: resource.serviceVersion,runtime: "react-native",client: `mobile-${resource.appVariant}`,+ attributes: channel && releaseResourceAttributes(channel),});}diff --git a/apps/server/src/config.ts b/apps/server/src/config.tsindex 11628ae95c3..8f58185ad99 100644--- a/apps/server/src/config.ts+++ b/apps/server/src/config.ts@@ -12,8 +12,15 @@ import type { OtlpEndpointSource } from "@t3tools/contracts";import { sweepStalePendingAttachments } from "./attachmentStore.ts";import { DEFAULT_SIGNAL_EXPORT, type SignalExport } from "@t3tools/shared/observability";import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";+import { type ReleaseChannel, releaseResourceAttributes } from "@t3tools/shared/releaseResource";import packageJson from "../package.json" with { type: "json" };+// Official release workflows set this telemetry channel; other builds report dev.+// Unlike __T3CODE_BUILD_CHANNEL__, this is not the sign-in page's latest/nightly channel.+declare const __T3CODE_TELEMETRY_CHANNEL__: ReleaseChannel | undefined;+export const telemetryChannel: ReleaseChannel =+ typeof __T3CODE_TELEMETRY_CHANNEL__ === "undefined" ? "dev" : __T3CODE_TELEMETRY_CHANNEL__;+export const DEFAULT_PORT = 3773;export const RuntimeMode = Schema.Literals(["web", "desktop"]);@@ -114,6 +121,7 @@ export const otlpResource = ("service.namespace": "t3code","service.runtime": "t3-server","t3code.server.managed_by": config.mode === "desktop" ? "desktop" : "standalone",+ ...releaseResourceAttributes(telemetryChannel, config.otelEnvironment.resourceAttributes),"host.name": config.otelEnvironment.resourceAttributes["host.name"] || hostName,},});diff --git a/apps/server/src/telemetry/AnalyticsService.ts b/apps/server/src/telemetry/AnalyticsService.tsindex bc0a0ad562a..54e3a3e6105 100644--- a/apps/server/src/telemetry/AnalyticsService.ts+++ b/apps/server/src/telemetry/AnalyticsService.ts@@ -50,10 +50,6 @@ const RETRY_MAX_DELAY_MS = 300_000;// These statuses reject the batch itself; unlike 408/429, retrying cannot help.const REJECTED_BATCH_STATUSES = new Set([400, 401, 413]);-// Official release workflows set this telemetry channel; other builds report dev.-// Unlike __T3CODE_BUILD_CHANNEL__, this is not the sign-in page's latest/nightly channel.-declare const __T3CODE_TELEMETRY_CHANNEL__: "stable" | "nightly" | "preview" | "dev" | undefined;-/** `random` is in [0, 1). */function retryDelayMs(failures: number, random: number): number {const ceiling = Math.min(RETRY_MAX_DELAY_MS, RETRY_BASE_DELAY_MS * 2 ** (failures - 1));@@ -142,8 +138,6 @@ export const make = Effect.gen(function* () {// The background flush and the shutdown flush must not send the same batch at once.const flushLock = yield* Semaphore.make(1);const clientType = serverConfig.mode === "desktop" ? "desktop-app" : "cli-web-client";- const telemetryChannel =- typeof __T3CODE_TELEMETRY_CHANNEL__ === "undefined" ? "dev" : __T3CODE_TELEMETRY_CHANNEL__;const hostPlatform = yield* HostProcess.Platform;const hostArchitecture = yield* HostProcess.Architecture;@@ -198,7 +192,7 @@ export const make = Effect.gen(function* () {wsl: Option.getOrUndefined(telemetryConfig.wslDistroName),arch: hostArchitecture,t3CodeVersion: packageJson.version,- telemetryChannel,+ telemetryChannel: ServerConfig.telemetryChannel,clientType,serverOs: serverOsFromNodePlatform(hostPlatform),serverArch: hostArchitecture,diff --git a/apps/web/src/observability/clientTracing.ts b/apps/web/src/observability/clientTracing.tsindex 73a2611c7d4..561b9c692bd 100644--- a/apps/web/src/observability/clientTracing.ts+++ b/apps/web/src/observability/clientTracing.ts@@ -8,17 +8,25 @@ import { OtlpExporter, OtlpSerialization, OtlpTracer } from "effect/observabilitimport { settleAsyncResult, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";import { resolvePrimaryEnvironmentHttpUrl } from "../environments/primary";+import { releaseChannelOf, releaseResourceAttributes } from "@t3tools/shared/releaseResource";import * as ClientTracer from "./clientTracer";import * as PrimaryEnvironmentHttpLayer from "../environments/primary/httpLayer";import { isElectron } from "../env";import { APP_VERSION } from "~/branding";const DEFAULT_EXPORT_INTERVAL_MS = 1_000;+// PR previews can't mark themselves in APP_VERSION without breaking the version-skew check against the server.+const RELEASE_CHANNEL =+ import.meta.env.DEV || import.meta.env.VITE_RELEASE_CHANNEL === "dev"+ ? "dev"+ : import.meta.env.VITE_RELEASE_CHANNEL === "preview"+ ? "preview"+ : releaseChannelOf(APP_VERSION);const CLIENT_TRACING_RESOURCE = {serviceName: "t3code-web",attributes: {"service.namespace": "t3code",- "deployment.environment.name": import.meta.env.DEV ? "development" : "production",+ ...releaseResourceAttributes(RELEASE_CHANNEL),"service.runtime": "t3-web","t3code.client.surface": isElectron ? "desktop" : "web","service.version": APP_VERSION,diff --git a/apps/web/src/vite-env.d.ts b/apps/web/src/vite-env.d.tsindex acc73a399a3..37a133afafe 100644--- a/apps/web/src/vite-env.d.ts+++ b/apps/web/src/vite-env.d.ts@@ -7,6 +7,7 @@ interface ImportMetaEnv {readonly VITE_WS_URL: string;readonly VITE_HOSTED_APP_URL: string;readonly VITE_HOSTED_APP_CHANNEL: string;+ readonly VITE_RELEASE_CHANNEL: string;readonly VITE_CLERK_PUBLISHABLE_KEY: string;readonly VITE_CLERK_JWT_TEMPLATE: string;readonly VITE_CLERK_CLI_OAUTH_CLIENT_ID: string;diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.tsindex ede07403975..577dda09c9b 100644--- a/apps/web/vite.config.ts+++ b/apps/web/vite.config.ts@@ -39,6 +39,8 @@ 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 configuredReleaseChannel =+ process.env.T3CODE_BUILT_DEV === "1" ? "dev" : process.env.VITE_RELEASE_CHANNEL?.trim() || "";const configuredAppVersion = process.env.APP_VERSION?.trim() || pkg.version;const configuredDesktopUpdateRepository =process.env.T3CODE_DESKTOP_UPDATE_REPOSITORY?.trim() ||@@ -237,6 +239,7 @@ export default defineConfig(() => {"import.meta.env.T3CODE_DESKTOP_UPDATE_REPOSITORY": JSON.stringify(configuredDesktopUpdateRepository,),+ "import.meta.env.VITE_RELEASE_CHANNEL": JSON.stringify(configuredReleaseChannel),"import.meta.env.APP_VERSION": JSON.stringify(configuredAppVersion),},resolve: {diff --git a/docs/operations/observability.md b/docs/operations/observability.mdindex 7ed00910e3a..dc6767128b3 100644--- a/docs/operations/observability.md+++ b/docs/operations/observability.md@@ -627,9 +627,17 @@ with a startup warning, rather than sending it to the Settings endpoint.Service names are fixed: `t3code-server` for the backend and `t3code-desktop` for the desktop mainprocess, both in `service.namespace` `t3code`. `OTEL_SERVICE_NAME` and a `service.name` or`service.namespace` in `OTEL_RESOURCE_ATTRIBUTES` are ignored. Tell installations apart with other-resource attributes, such as `OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=development`.-The UI reports `deployment.environment.name` from its build: `development` under the Vite dev server-and `production` otherwise.+resource attributes, such as `OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=staging`.++Each process reports its own build, not the one it talks to: the server, the desktop main process,+the UI, and the mobile app each carry `t3code.release.channel` (`dev`, `stable`, `nightly`, or+`preview`, from their own version; desktop PR builds count as `preview`, and a server not built by a+release workflow reports `dev`) and `deployment.environment.name` (`development`, `production`, or+`staging` for `preview`). On the server and the desktop main process either key in+`OTEL_RESOURCE_ATTRIBUTES` wins. The UI and mobile app never read that variable: Vercel PR previews+set `VITE_RELEASE_CHANNEL=preview` because their `APP_VERSION` must stay comparable with the+server's, and the mobile app maps its build variant (`development`, `preview`, `production`), or+reports `dev` from a development bundle.Attributes specific to T3 Code use the `t3code.` prefix. The UI runs as `t3code-web` in both abrowser and the desktop window, since it is the same code, and `t3code.client.surface` is `desktop`diff --git a/packages/shared/package.json b/packages/shared/package.jsonindex 5d0c5b76d35..baa12fd43c5 100644--- a/packages/shared/package.json+++ b/packages/shared/package.json@@ -59,6 +59,10 @@"types": "./src/logging.ts","import": "./src/logging.ts"},+ "./releaseResource": {+ "types": "./src/releaseResource.ts",+ "import": "./src/releaseResource.ts"+ },"./observability": {"types": "./src/observability.ts","import": "./src/observability.ts"diff --git a/packages/shared/src/relayTracing.ts b/packages/shared/src/relayTracing.tsindex 3988e6a71ab..360d7b203a1 100644--- a/packages/shared/src/relayTracing.ts+++ b/packages/shared/src/relayTracing.ts@@ -20,6 +20,7 @@ export interface RelayClientTracingResource {readonly runtime: string;readonly client: string;readonly component?: string;+ readonly attributes?: Readonly<Record<string, string>> | undefined;}export class RelayClientTracer extends Context.Reference(@@ -168,6 +169,7 @@ export function layer("service.runtime": resource.runtime,"t3code.component": resource.component ?? "relay-client","t3code.client.surface": resource.client,+ ...resource.attributes,},},}).pipe(Layer.provide(OtlpSerialization.layerJson));diff --git a/packages/shared/src/releaseResource.test.ts b/packages/shared/src/releaseResource.test.tsnew file mode 100644index 00000000000..c5243a47daa--- /dev/null+++ b/packages/shared/src/releaseResource.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from "@effect/vitest";++import { releaseChannelOf, releaseResourceAttributes } from "./releaseResource.ts";++describe("releaseResourceAttributes", () => {+ it.each([+ ["dev", {}, "dev", "development"],+ ["stable", {}, "stable", "production"],+ ["nightly", {}, "nightly", "production"],+ ["preview", {}, "preview", "staging"],+ [+ "stable",+ { "deployment.environment.name": "staging", "t3code.release.channel": "" },+ "stable",+ "staging",+ ],+ ] as const)(+ "%s (operator: %o) reports %s in %s",+ (channel, operatorAttributes, expectedChannel, environment) => {+ expect(releaseResourceAttributes(channel, operatorAttributes)).toEqual({+ "t3code.release.channel": expectedChannel,+ "deployment.environment.name": environment,+ });+ },+ );++ it.each([+ ["0.1.2", "stable"],+ ["0.1.2-nightly.20261025.1", "nightly"],+ ["0.1.2-preview.20261025.1", "preview"],+ ["0.1.2-pr.24340.123", "preview"],+ ] as const)("classifies %s as %s", (version, channel) => {+ expect(releaseChannelOf(version)).toBe(channel);+ });+});diff --git a/packages/shared/src/releaseResource.ts b/packages/shared/src/releaseResource.tsnew file mode 100644index 00000000000..492a6e05536--- /dev/null+++ b/packages/shared/src/releaseResource.ts@@ -0,0 +1,24 @@+import { type CliReleaseChannel, cliReleaseChannelOf } from "./cliRelease.ts";++export type ReleaseChannel = "dev" | CliReleaseChannel;++// Desktop PR preview builds are stamped `X.Y.Z-pr.<number>.<run>`; the CLI updater must not see them as preview.+export const releaseChannelOf = (version: string): ReleaseChannel =>+ /-pr\.\d+\.\d+$/.test(version) ? "preview" : cliReleaseChannelOf(version);++// Effect lets code attributes beat OTEL_RESOURCE_ATTRIBUTES, so the operator value is applied here.+export const releaseResourceAttributes = (+ channel: ReleaseChannel,+ operatorAttributes: Readonly<Record<string, unknown>> = {},+) => {+ const operatorValue = (key: string) => {+ const value = operatorAttributes[key];+ return typeof value === "string" && value !== "" ? value : undefined;+ };+ return {+ "t3code.release.channel": operatorValue("t3code.release.channel") ?? channel,+ "deployment.environment.name":+ operatorValue("deployment.environment.name") ??+ (channel === "dev" ? "development" : channel === "preview" ? "staging" : "production"),+ };+};