feat(observability): honor the standard OTEL_* environment variables #12621
Closedyordis(GitHub profile, opens in a new tab)wants to merge 5 commits into
main fromrefs/pull/12621/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- docs/operations/observability.md lines 211 to 212OutdatedResolvedby yordis(GitHub profile, opens in a new tab)@@ -191,0 +192,21 @@192+### Option 3: The Standard `OTEL_*` Variables193+194+If your machine already exports the OpenTelemetry environment variables for everything else running on195+it, the server joins in without being told twice. Nothing above is required:196+197+```bash198+export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318199+export OTEL_RESOURCE_ATTRIBUTES=deployment.environment=lab200+```201+202+The base endpoint is a base, not a full URL: traces go to `<endpoint>/v1/traces`, metrics to203+`<endpoint>/v1/metrics`, and log records to `<endpoint>/v1/logs`, exactly as the specification says.204+Set `OTEL_EXPORTER_OTLP_{TRACES,METRICS,LOGS}_ENDPOINT` when a signal needs a full URL of its own.205+206+Ambient `OTEL_*` variables turn export on by themselves. A work collector in your shell profile means207+T3 Code exports to it, so use `OTEL_SDK_DISABLED=true` if that is not what you want. If the reverse is208+your problem, a profile that disables every other SDK on the machine, `T3CODE_OTEL_SDK_DISABLED=false`209+keeps T3 Code exporting.210+211+The server is what reads these. The desktop app passes its own environment to the backend it spawns,212+so a variable exported before launching the desktop app reaches the server; the Electron main processpackages/shared/src/otelEnvironment.ts line 178OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +158,21 @@158+ value: undefined,159+ warnings: [`${name}=${raw} is not a yes or a no and was ignored`],160+ };161+ },162+ ),163+ );164+165+/**166+ * A number that is not a number is warned about and dropped, which is what the167+ * specification asks for anywhere a value is unrecognized. Letting the read168+ * fail instead would take every other variable down with it and turn one typo169+ * into no telemetry at all.170+ */171+const readInt = (name: string, warnings: Array<string>) =>172+ optionalString(name).pipe(173+ Effect.map((raw) => {174+ if (raw === undefined) {175+ return undefined;176+ }177+ const value = Number(raw);178+ if (!Number.isSafeInteger(value) || value < 0) {packages/shared/src/otelEnvironment.ts line 259OutdatedResolvedby yordis(GitHub profile, opens in a new tab)@@ -0,0 +239,21 @@239+ return parsed === undefined240+ ? {241+ value: undefined,242+ warnings: [`${name} is not a valid list of key=value pairs and was ignored`],243+ }244+ : { value: parsed, warnings: [] };245+ }),246+ );247+248+/**249+ * `OTEL_EXPORTER_OTLP_<SIGNAL>_ENDPOINT` is a full URL and is used as given.250+ * The generic `OTEL_EXPORTER_OTLP_ENDPOINT` is a base, and the spec has each251+ * signal append its own path to it.252+ */253+const signalEndpoint = (signal: OtlpSignalName) =>254+ Effect.gen(function* () {255+ const specific = yield* optionalString(`OTEL_EXPORTER_OTLP_${signal}_ENDPOINT`);256+ if (specific !== undefined) {257+ return specific;258+ }259+ const base = yield* optionalString("OTEL_EXPORTER_OTLP_ENDPOINT");@@ -382,3 +399,10 @@382399 );383400 const logLevel = Option.getOrElse(cliLogLevel, () => env.logLevel);384401402+ // A signal whose endpoint came from somewhere else is not this route's to403+ // configure. Dropping the whole signal, rather than the endpoint alone,404+ // is what stops an ambient OTEL_EXPORTER_OTLP_ENDPOINT from changing the405+ // wire format, headers, batching, or aggregation of an export that a406+ // T3CODE_OTLP_* name or Settings already answered, and stops startup from407+ // reporting that signal as declined while it is exporting.408+ const namedTracesUrl = named(
- apps/server/src/cli/config.ts lines 447 to 452OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -403 +433,20 @@403- otlpServiceName: env.otlpServiceName,433+ otlpTracesUrl: otelEnvironment.disabled434+ ? undefined435+ : (namedTracesUrl ?? otelEnvironment.traces.settings?.url),436+ otlpMetricsUrl: otelEnvironment.disabled437+ ? undefined438+ : (namedMetricsUrl ?? otelEnvironment.metrics.settings?.url),439+ otlpLogsUrl: otelEnvironment.disabled440+ ? undefined441+ : (namedLogsUrl ?? otelEnvironment.logs.settings?.url),442+ // T3 Code has one interval variable and it deliberately covers every443+ // signal. The per-signal part is the fallback under it: the environment444+ // names a span delay, a metric interval, and a log record delay445+ // separately, so a signal that took its endpoint elsewhere must not446+ // inherit another one's.447+ otlpExportIntervalMs:448+ env.otlpExportIntervalMs ?? otelEnvironment.traces.settings?.exportIntervalMs ?? 10_000,449+ otlpMetricsExportIntervalMs:450+ env.otlpExportIntervalMs ?? otelEnvironment.metrics.settings?.exportIntervalMs ?? 10_000,451+ otlpLogsExportIntervalMs:452+ env.otlpExportIntervalMs ?? otelEnvironment.logs.settings?.exportIntervalMs ?? 10_000,apps/server/src/observability/Layers/Observability.ts lines 46 to 47OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -25,0 +27,21 @@27+ yield* Effect.logWarning(warning);28+ }29+30+ // One variable can decline every signal, and saying so three times reads31+ // like three separate problems.32+ const declined = new Set(33+ [otel.traces.declined, otel.metrics.declined, otel.logs.declined].filter(34+ (reason) => reason !== undefined,35+ ),36+ );37+ for (const reason of declined) {38+ yield* Effect.logWarning(reason);39+ }40+41+ // Each signal builds its own serializer, so the wire format travels with42+ // the settings of the endpoint that asked for it. A signal these variables43+ // did not supply keeps what T3CODE_OTLP_PROTOCOL asked for.44+ const serializationFor = (settings: typeof otel.traces.settings) =>45+ otlpSerializationLayer(settings?.protocol ?? config.otlpProtocol);46+ const headersFor = (settings: typeof otel.traces.settings) =>47+ settings?.headers ?? config.otlpHeaders;docs/operations/observability.md lines 713 to 715OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -551,3 +710,6 @@551710 `T3CODE_OTLP_HEADERS`: extra headers for all three exporters, same format as552711 `OTEL_EXPORTER_OTLP_HEADERS`: comma-separated `key=value` pairs with percent-encoded values.553712 `T3CODE_OTLP_PROTOCOL`: `http/json` (default) or `http/protobuf`713+`T3CODE_OTEL_SDK_DISABLED`: stops every export, whatever configured it, including Settings. Read714+ before `OTEL_SDK_DISABLED`, so `false` here keeps T3 Code exporting on a machine that sets the715+ standard name.packages/shared/src/otelEnvironment.ts lines 231 to 234Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +182,21 @@182+ return value;183+ }),184+ );185+186+/**187+ * Headers and resource attributes are a W3C Baggage string: comma separated188+ * pairs, optional whitespace around each one, and percent encoded values.189+ *190+ * Splitting on every `=` rather than the first one truncates exactly the191+ * credentials people put here, since base64 basic auth ends in `=` padding,192+ * and leaving the encoding in place sends a literal `%20` as part of a bearer193+ * token. Both fail as an authentication error against the collector, which194+ * reads like a bad token rather than a parsing bug.195+ */196+const parseBaggage = (raw: string): Readonly<Record<string, string>> | undefined => {197+ const entries: Record<string, string> = {};198+ for (const member of raw.split(",")) {199+ const separator = member.indexOf("=");200+ if (separator === -1) {201+ continue;202+ }packages/shared/src/otelEnvironment.ts lines 271 to 280OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +260,21 @@260+ if (base === undefined) {261+ return undefined;262+ }263+ const trimmed = base.endsWith("/") ? base.slice(0, -1) : base;264+ return `${trimmed}/v1/${signal.toLowerCase()}`;265+ });266+267+/**268+ * `OTEL_<SIGNAL>_EXPORTER` is a list, and `otlp` is its default. A value that269+ * names other exporters and not `otlp` is a deliberate "not this one".270+ */271+const signalWantsOtlp = (signal: OtlpSignalName) =>272+ optionalString(`OTEL_${signal}_EXPORTER`).pipe(273+ Effect.map((value) => {274+ if (value === undefined) {275+ return true;276+ }277+ return value278+ .split(",")279+ .map((entry) => entry.trim().toLowerCase())280+ .includes("otlp");packages/shared/src/otelEnvironment.ts lines 341 to 345OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +325,21 @@325+ signal: OtlpSignalName,326+ protocol: OtlpProtocol,327+ temporality: MetricsTemporality | undefined,328+) =>329+ Effect.gen(function* () {330+ const url = yield* signalEndpoint(signal);331+ if (url === undefined || !(yield* signalWantsOtlp(signal))) {332+ return { value: undefined, warnings: [] };333+ }334+ const numbers: Array<string> = [];335+ const specific = yield* optionalRecord(`OTEL_EXPORTER_OTLP_${signal}_HEADERS`);336+ const generic = yield* optionalRecord("OTEL_EXPORTER_OTLP_HEADERS");337+ const headers = specific.value ?? generic.value;338+ const batching = SIGNAL_BATCHING[signal];339+ const exportIntervalMs =340+ (yield* readInt(batching.scheduleDelay, numbers)) ?? batching.defaultScheduleDelayMs;341+ const maxBatchSize =342+ batching.maxExportBatchSize === undefined343+ ? undefined344+ : ((yield* readInt(batching.maxExportBatchSize, numbers)) ??345+ SPEC_DEFAULT_MAX_EXPORT_BATCH_SIZE);
- docs/operations/observability.md line 323OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -191,0 +303,21 @@303+ `OTEL_EXPORTER_OTLP_CERTIFICATE`, `OTEL_EXPORTER_OTLP_CLIENT_KEY`, and304+ `OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE` are ignored. A collector that requires mutual TLS needs a305+ proxy in front of it.306+**No export timeouts.** `OTEL_EXPORTER_OTLP_TIMEOUT`,307+ `OTEL_EXPORTER_OTLP_{TRACES,METRICS,LOGS}_TIMEOUT`, and `OTEL_METRIC_EXPORT_TIMEOUT` are308+ per-request deadlines, and this exporter has no per-request knob, so they are ignored. Spending309+ them on the shutdown flush instead would be the wrong meaning and would let a generous collector310+ timeout hold the server open on every restart.311+**`lowmemory` temporality is not available.** `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE`312+ accepts `cumulative` and `delta`. `lowmemory` logs a warning and falls back to `cumulative`.313+**`OTEL_SERVICE_VERSION` is not a specification variable.** It is read as a convenience because314+ the exporter library reads it too. `OTEL_RESOURCE_ATTRIBUTES=service.version=...` is the portable315+ spelling.316+317+Everything else not listed above is ignored, including `OTEL_BSP_MAX_QUEUE_SIZE`,318+`OTEL_BLRP_MAX_QUEUE_SIZE`, `OTEL_BSP_EXPORT_TIMEOUT`, `OTEL_BLRP_EXPORT_TIMEOUT`, sampler319+variables, propagator variables, and the attribute and span limit variables.320+321+#### When A Value Cannot Be Used322+323+A variable T3 Code cannot act on never stops it from starting. Two things can happen instead, and
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- docs/operations/observability.md lines 338 to 339OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -191,0 +319,21 @@319+ backend at `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT` and set the preference to `delta`.320+**`lowmemory` temporality cannot be expressed per instrument kind.** It asks for delta on321+ synchronous counters and histograms and cumulative on the rest, and one temporality is applied to322+ every instrument here. It resolves to `delta` with a warning, which is what it asks for on the323+ counters and timers T3 Code actually records.324+**`OTEL_SERVICE_VERSION` is not a specification variable.** It is read as a convenience because325+ the exporter library reads it too. `OTEL_RESOURCE_ATTRIBUTES=service.version=...` is the portable326+ spelling.327+328+Everything else not listed above is ignored, including `OTEL_BSP_MAX_QUEUE_SIZE`,329+`OTEL_BLRP_MAX_QUEUE_SIZE`, `OTEL_BSP_EXPORT_TIMEOUT`, `OTEL_BLRP_EXPORT_TIMEOUT`, sampler330+variables, propagator variables, and the attribute and span limit variables.331+332+#### When A Value Cannot Be Used333+334+A variable T3 Code cannot act on never stops it from starting. Two things can happen instead, and335+both are logged once at startup:336+337+**A warning, then the default.** A misspelled protocol, a temporality that is not a preference, a338+ timeout or batch size that is not a whole number, or a pair list that is not valid percent339+ encoding is reported and ignored, and everything else keeps exporting. One bad value never costspackages/shared/src/otelEnvironment.ts lines 154 to 155OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +135,21 @@135+ * have been used instead.136+ */137+const blankAsUnset = (value: string | undefined) => {138+ const trimmed = value?.trim();139+ return trimmed === undefined || trimmed === "" ? undefined : trimmed;140+};141+142+const optionalString = (name: string) =>143+ Config.String(name).pipe(144+ Config.option,145+ Config.map((value) => blankAsUnset(Option.getOrUndefined(value))),146+ );147+148+/**149+ * The specification defines exactly one true value: the case-insensitive150+ * string `true`. Everything else is false, including values that read as151+ * affirmative elsewhere, because implementations are told not to extend the152+ * list.153+ */154+const specBoolean = (name: string) =>155+ optionalString(name).pipe(Effect.map((raw) => raw?.toLowerCase() === "true"));packages/shared/src/otelEnvironment.ts line 235Resolvedby yordis(GitHub profile, opens in a new tab)@@ -0,0 +204,21 @@204+ }),205+ );206+207+/**208+ * Headers and resource attributes are a W3C Baggage string: comma separated209+ * pairs, optional whitespace around each one, and percent encoded values.210+ *211+ * Splitting on every `=` rather than the first one truncates exactly the212+ * credentials people put here, since base64 basic auth ends in `=` padding,213+ * and leaving the encoding in place sends a literal `%20` as part of a bearer214+ * token. Both fail as an authentication error against the collector, which215+ * reads like a bad token rather than a parsing bug.216+ */217+const parseBaggage = (raw: string): Readonly<Record<string, string>> | undefined => {218+ const entries: Record<string, string> = {};219+ for (const member of raw.split(",")) {220+ const separator = member.indexOf("=");221+ if (separator === -1) {222+ continue;223+ }224+ const key = member.slice(0, separator).trim();
github-actions[bot](GitHub profile, opens in a new tab) removed labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
- docs/operations/observability.md lines 335 to 336OutdatedResolvedby yordis(GitHub profile, opens in a new tab)@@ -191,0 +316,21 @@316+ deliberate "not this one", so that signal is not exported and the name that did it is logged. A317+ list that names nothing recognizable is treated as the typo it probably is: it is reported and318+ ignored, and the signal keeps exporting, because reading `otlpp` as "not OTLP" would turn one319+ transposed letter into a signal that stops with nothing in the log to connect the two.320+**No compression and no client TLS.** `OTEL_EXPORTER_OTLP_COMPRESSION`,321+ `OTEL_EXPORTER_OTLP_CERTIFICATE`, `OTEL_EXPORTER_OTLP_CLIENT_KEY`, and322+ `OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE` are ignored. A collector that requires mutual TLS needs a323+ proxy in front of it.324+**No export timeouts.** `OTEL_EXPORTER_OTLP_TIMEOUT`,325+ `OTEL_EXPORTER_OTLP_{TRACES,METRICS,LOGS}_TIMEOUT`, and `OTEL_METRIC_EXPORT_TIMEOUT` are326+ per-request deadlines, and this exporter has no per-request knob, so they are ignored. Spending327+ them on the shutdown flush instead would be the wrong meaning and would let a generous collector328+ timeout hold the server open on every restart.329+**Only an `OTEL_*` metrics endpoint can choose its aggregation.**330+ `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE` configures the metrics signal, and by the rule331+ in Precedence above a signal is configured by whichever source named its endpoint. A metrics332+ endpoint that came from `T3CODE_OTLP_METRICS_URL`, the desktop bootstrap envelope, or Settings333+ therefore exports `cumulative`, and there is no `T3CODE_*` spelling of this preference to change334+ that. This matters for one class of backend: a receiver that accepts delta histograms only, which335+ is how Datadog's OTLP intake behaves, drops cumulative histograms without reporting an error, so336+ every `_duration` timer would go missing while the `_total` counters kept arriving. Point such a
- packages/shared/src/otelEnvironment.ts lines 326 to 363OutdatedResolvedby yordis(GitHub profile, opens in a new tab)@@ -0,0 +343,21 @@343+ }344+ const name = `OTEL_${signal}_EXPORTER`;345+ const entries = raw346+ .split(",")347+ .map((entry) => entry.trim().toLowerCase())348+ .filter((entry) => entry !== "");349+ if (entries.includes("otlp")) {350+ // A list is an ordered preference and OTLP is the only entry honored351+ // here, so anything standing beside it did nothing. Saying so is what352+ // keeps the transposed letter in `otlp,otlpp` from reading like a353+ // second exporter that took.354+ if (entries.some((entry) => entry !== "otlp")) {355+ warnings.push(356+ `${name}=${raw} names otlp, so this signal is exported over OTLP and nothing else in that list is honored`,357+ );358+ }359+ return true;360+ }361+ const recognized = entries.filter(362+ (entry) => entry === "none" || FOREIGN_EXPORTERS.has(entry),363+ );packages/shared/src/otelEnvironment.ts lines 317 to 318OutdatedResolvedby yordis(GitHub profile, opens in a new tab)@@ -0,0 +298,21 @@298+ : { value: parsed, warnings: [] };299+ }),300+ );301+302+/**303+ * `OTEL_EXPORTER_OTLP_<SIGNAL>_ENDPOINT` is a full URL and is used as given.304+ * The generic `OTEL_EXPORTER_OTLP_ENDPOINT` is a base, and the spec has each305+ * signal append its own path to it.306+ */307+const signalEndpoint = (signal: OtlpSignalName) =>308+ Effect.gen(function* () {309+ const specific = yield* optionalString(`OTEL_EXPORTER_OTLP_${signal}_ENDPOINT`);310+ if (specific !== undefined) {311+ return specific;312+ }313+ const base = yield* optionalString("OTEL_EXPORTER_OTLP_ENDPOINT");314+ if (base === undefined) {315+ return undefined;316+ }317+ const trimmed = base.endsWith("/") ? base.slice(0, -1) : base;318+ return `${trimmed}/v1/${signal.toLowerCase()}`;
- docs/operations/observability.md lines 213 to 216OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -191,0 +196,21 @@196+197+```bash198+export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318199+export OTEL_RESOURCE_ATTRIBUTES=deployment.environment=lab200+```201+202+The base endpoint is a base, not a full URL: traces go to `<endpoint>/v1/traces`, metrics to203+`<endpoint>/v1/metrics`, and log records to `<endpoint>/v1/logs`, exactly as the specification says.204+Set `OTEL_EXPORTER_OTLP_{TRACES,METRICS,LOGS}_ENDPOINT` when a signal needs a full URL of its own.205+206+Ambient `OTEL_*` variables turn export on by themselves. A work collector in your shell profile means207+T3 Code exports to it, so use `OTEL_SDK_DISABLED=true` if that is not what you want. If the reverse is208+your problem, a profile that disables every other SDK on the machine, `T3CODE_OTEL_SDK_DISABLED=false`209+keeps T3 Code exporting.210+211+The server is what reads these, and only the server. The desktop app passes its own environment to212+the backend it spawns, so a variable exported before launching the desktop app reaches the server.213+The Electron main process is a second producer and still configures itself from `T3CODE_OTLP_*`, the214+bootstrap envelope, and Settings as it already did, so neither an ambient endpoint nor215+`OTEL_SDK_DISABLED` nor `T3CODE_OTEL_SDK_DISABLED` changes what it exports. Wiring the main process216+to the same reader is follow-up work.@@ -393,13 +460,8 @@393- env.otlpTracesUrl ??394- bootstrap?.otlpTracesUrl ??395- persistedObservabilitySettings.otlpTracesUrl,396- otlpMetricsUrl:397- env.otlpMetricsUrl ??398- bootstrap?.otlpMetricsUrl ??399- persistedObservabilitySettings.otlpMetricsUrl,400- otlpLogsUrl:401- env.otlpLogsUrl ?? bootstrap?.otlpLogsUrl ?? persistedObservabilitySettings.otlpLogsUrl,402- otlpExportIntervalMs: env.otlpExportIntervalMs,403- otlpServiceName: env.otlpServiceName,404- otlpHeaders: env.otlpHeaders,405- otlpProtocol: env.otlpProtocol,460+ otlpTracesUrl: otelEnvironment.disabled ? undefined : traces.url,461+ otlpMetricsUrl: otelEnvironment.disabled ? undefined : metrics.url,462+ otlpLogsUrl: otelEnvironment.disabled ? undefined : logs.url,463+ otlpTracesExport: signalExport(otelEnvironment.traces.settings),464+ otlpMetricsExport: signalExport(otelEnvironment.metrics.settings),465+ otlpLogsExport: signalExport(otelEnvironment.logs.settings),466+ otlpServiceName: named(env.otlpServiceName) ?? "t3-server",467+ otelEnvironment,
- docs/operations/observability.md lines 221 to 221OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -191,0 +201,21 @@201+202+The base endpoint is a base, not a full URL: traces go to `<endpoint>/v1/traces`, metrics to203+`<endpoint>/v1/metrics`, and log records to `<endpoint>/v1/logs`, exactly as the specification says.204+Set `OTEL_EXPORTER_OTLP_{TRACES,METRICS,LOGS}_ENDPOINT` when a signal needs a full URL of its own.205+206+Ambient `OTEL_*` variables turn export on by themselves. A work collector in your shell profile means207+T3 Code exports to it, so use `OTEL_SDK_DISABLED=true` if that is not what you want. If the reverse is208+your problem, a profile that disables every other SDK on the machine, `T3CODE_OTEL_SDK_DISABLED=false`209+keeps T3 Code exporting.210+211+The server is what reads these, and only the server. The desktop app passes its own environment to212+the backend it spawns, so a variable exported before launching the desktop app reaches the server.213+The Electron main process is a second producer and still configures itself from `T3CODE_OTLP_*`, the214+bootstrap envelope, and Settings as it already did, so neither an ambient endpoint nor215+`OTEL_SDK_DISABLED` nor `T3CODE_OTEL_SDK_DISABLED` changes what it exports. Wiring the main process216+to the same reader is follow-up work.217+218+On macOS, ambient variables reach the desktop app only when it is launched from a shell. Opening it219+from the Dock, Finder, or Spotlight inherits `launchd`'s environment instead, which is why the220+instrumented walkthrough above launches from the same shell that exported the variables. Settings and221+`T3CODE_OTLP_*` are not affected.packages/shared/src/otelEnvironment.ts line 507OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +487,21 @@487+ * own way.488+ */489+ temporality: Parsed<MetricsTemporality> | undefined,490+) =>491+ Effect.gen(function* () {492+ const url = yield* signalEndpoint(signal);493+ // An exporter list is moot without an endpoint, so it is neither read nor494+ // reported until one signal has somewhere to go.495+ if (url === undefined) {496+ return { value: undefined, warnings: [], off: false } satisfies ReadSignal;497+ }498+ const numbers: Array<string> = [];499+ if (!(yield* signalWantsOtlp(signal, numbers))) {500+ return { value: undefined, warnings: numbers, off: true } satisfies ReadSignal;501+ }502+ const specific = yield* optionalRecord(`OTEL_EXPORTER_OTLP_${signal}_HEADERS`);503+ const generic = yield* optionalRecord("OTEL_EXPORTER_OTLP_HEADERS");504+ const headers = specific.value ?? generic.value;505+ const batching = SIGNAL_BATCHING[signal];506+ const exportIntervalMs =507+ (yield* readInt(batching.scheduleDelay, numbers)) ?? batching.defaultScheduleDelayMs;
- packages/shared/src/otelEnvironment.ts lines 235 to 243Resolvedby yordis(GitHub profile, opens in a new tab)@@ -0,0 +276,21 @@276+const parseBaggage = (raw: string): Readonly<Record<string, string>> | undefined => {277+ const entries: Record<string, string> = {};278+ for (const member of raw.split(",")) {279+ // Trailing and doubled commas are whitespace, not a member.280+ if (member.trim() === "") {281+ continue;282+ }283+ const separator = member.indexOf("=");284+ if (separator === -1) {285+ return undefined;286+ }287+ const key = member.slice(0, separator).trim();288+ if (key === "") {289+ return undefined;290+ }291+ const value = member.slice(separator + 1).trim();292+ try {293+ entries[key] = decodeURIComponent(value);294+ } catch {295+ return undefined;296+ }
juliusmarminge reviewed
packages/shared/src/otelEnvironment.ts line 177OutdatedResolvedby yordis(GitHub profile, opens in a new tab)@@ -0,0 +157,21 @@157+158+const optionalString = (name: string) =>159+ Config.String(name).pipe(160+ Config.option,161+ Config.map((value) => blankAsUnset(Option.getOrUndefined(value))),162+ );163+164+/**165+ * The specification defines exactly one true value: the case-insensitive166+ * string `true`. Everything else is false, including values that read as167+ * affirmative elsewhere, because implementations are told not to extend the168+ * list.169+ *170+ * `yes` is therefore not a request this reader can act on, and it is reported171+ * rather than quietly answered. Resolving it to false is what the172+ * specification asks for, so an operator who meant to switch export off is173+ * told it is still on instead of finding out from the collector.174+ */175+const specBoolean = (name: string) =>176+ optionalString(name).pipe(177+ Effect.map((raw): Parsed<boolean> => {packages/shared/src/otelEnvironment.ts line 230OutdatedResolvedby yordis(GitHub profile, opens in a new tab)@@ -0,0 +210,21 @@210+ if (["false", "0", "no", "off"].includes(value)) {211+ return { value: false, warnings: [] };212+ }213+ return {214+ value: undefined,215+ warnings: [`${name}=${raw} is not a yes or a no and was ignored`],216+ };217+ },218+ ),219+ );220+221+/**222+ * A number that is not a number is warned about and dropped, which is what the223+ * specification asks for anywhere a value is unrecognized. Letting the read224+ * fail instead would take every other variable down with it and turn one typo225+ * into no telemetry at all.226+ */227+const readInt = (name: string, warnings: Array<string>) =>228+ optionalString(name).pipe(229+ Effect.map((raw) => {230+ if (raw === undefined) {packages/shared/src/otelEnvironment.ts line 257OutdatedResolvedby yordis(GitHub profile, opens in a new tab)@@ -0,0 +237,21 @@237+ }238+ return value;239+ }),240+ );241+242+/**243+ * Zero is not a smaller number here, it is a loop with nothing holding it244+ * back, so it is refused wherever the exporter would act on it every time245+ * around.246+ *247+ * A batch size of zero is met by every record, so the exporter stops batching248+ * and posts one HTTP request per span or log record. An interval of zero is249+ * worse: the export loop sleeps the interval and then exports forever, so250+ * metrics post continuously because a collection cycle exports whether251+ * anything was recorded or not, and traces and logs spin a fiber on an empty252+ * buffer. Neither is a value a collector or a CPU survives, which is why both253+ * read as a mistake rather than as a request.254+ */255+const readPositiveInt = (name: string, warnings: Array<string>, subject: string) =>256+ readInt(name, warnings).pipe(257+ Effect.map((value) => {packages/shared/src/otelEnvironment.ts line 327OutdatedResolvedby yordis(GitHub profile, opens in a new tab)@@ -0,0 +307,21 @@307+ // collector problem. A list that produced no pair at all is malformed for308+ // the same reason, not a request for no headers, and returning `{}` would309+ // count as a supplied value and shadow the generic variable this signal310+ // should have fallen back to.311+ return Object.keys(entries).length === 0 ? undefined : entries;312+};313+314+interface Parsed<A> {315+ readonly value: A | undefined;316+ readonly warnings: ReadonlyArray<string>;317+}318+319+/**320+ * A pair list that fails to decode discards the whole variable, which is what321+ * the resource specification asks for and the safer answer for headers too: a322+ * half-parsed credential reaches the collector as an authentication error,323+ * while nothing plus a warning says where to look.324+ */325+const optionalRecord = (name: string) =>326+ optionalString(name).pipe(327+ Effect.map((raw) => {packages/shared/src/otelEnvironment.ts line 421OutdatedResolvedby yordis(GitHub profile, opens in a new tab)@@ -0,0 +401,21 @@401+ * from swallowing "this is not a name for this signal".402+ */403+const FOREIGN_EXPORTERS: Readonly<Record<OtlpSignalName, ReadonlySet<string>>> = {404+ TRACES: new Set(["console", "logging", "zipkin", "jaeger"]),405+ METRICS: new Set(["console", "logging", "prometheus"]),406+ LOGS: new Set(["console", "logging"]),407+};408+409+/**410+ * `OTEL_<SIGNAL>_EXPORTER` is a list, and `otlp` is its default. A value that411+ * names other exporters and not `otlp` is a deliberate "not this one".412+ *413+ * A value that names nothing recognizable is a typo, and a typo is ignored414+ * here the way every other unreadable value is, which leaves the default in415+ * place. Reading `otlpp` as "not OTLP" would turn one transposed letter into a416+ * signal that stops exporting with nothing in the log to connect the two,417+ * which is the failure this whole reader exists to avoid.418+ */419+const signalWantsOtlp = (signal: OtlpSignalName, warnings: Array<string>) =>420+ optionalString(`OTEL_${signal}_EXPORTER`).pipe(421+ Effect.map((raw) => {packages/shared/src/otelEnvironment.ts line 650OutdatedResolvedby yordis(GitHub profile, opens in a new tab)@@ -0,0 +630,21 @@630+ * cannot express, because one temporality is applied to every instrument here631+ * rather than chosen per instrument kind. It resolves to `delta` instead of the632+ * default, and says so.633+ *634+ * `delta` is the honest answer rather than a near-enough one. `lowmemory` asks635+ * for delta on synchronous counters and histograms and cumulative on the rest,636+ * and every metric T3 Code records is a monotonic counter or a timer, so the637+ * kinds the two preferences disagree about are kinds nothing here produces.638+ * Falling back to the default would have inverted the only part of the request639+ * that is about the data, and inverted it toward the value that loses it: a640+ * receiver that accepts delta histograms only does not record the cumulative641+ * ones it is sent, so every duration metric would disappear while the counters642+ * kept arriving.643+ *644+ * A value that is not a preference at all is a different case and stays645+ * ignored. It carries no intent to honor.646+ */647+const resolveMetricsTemporality = optionalString(648+ "OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE",649+).pipe(650+ Effect.map((raw): Parsed<MetricsTemporality> => {juliusmarminge requested changes
- packages/shared/src/otelEnvironment.ts lines 117 to 117OutdatedResolvedby yordis(GitHub profile, opens in a new tab)@@ -0,0 +97,21 @@97+}98+99+const usable = <A>(value: A | undefined): Parsed<A> => ({ value, warnings: [] });100+101+/**102+ * Turns a read that would fail into the default plus a warning naming the value103+ * that caused it. Wrap every leaf read below in this.104+ */105+const ignoring = <A>(106+ name: string,107+ expected: string,108+ config: Config.Config<A>,109+): Config.Config<Parsed<A>> =>110+ config.pipe(111+ Config.option,112+ Config.map((value) => usable(Option.getOrUndefined(value))),113+ Config.orElse(() =>114+ Config.String(name).pipe(115+ Config.map((raw): Parsed<A> => ({116+ value: undefined,117+ warnings: [`${name}=${raw} is not ${expected} and was ignored`],
- @@ -0,0 +473,21 @@473+474+const wireProtocol = (name: string) =>475+ ignoring(476+ name,477+ "a known OTLP protocol",478+ Config.schema(folded(Schema.Literals(["http/json", "http/protobuf", "grpc"])), name),479+ ).pipe(Config.map((parsed) => ({ ...parsed, name })));480+481+/**482+ * Each signal builds its own serializer, so all three are answered separately483+ * and are free to disagree, and `grpc` declines only the signal that named it.484+ */485+const resolveProtocol = Effect.gen(function* () {486+ const generic = yield* wireProtocol("OTEL_EXPORTER_OTLP_PROTOCOL");487+ const named = {488+ traces: yield* wireProtocol("OTEL_EXPORTER_OTLP_TRACES_PROTOCOL"),489+ metrics: yield* wireProtocol("OTEL_EXPORTER_OTLP_METRICS_PROTOCOL"),490+ logs: yield* wireProtocol("OTEL_EXPORTER_OTLP_LOGS_PROTOCOL"),491+ };492+ const decide = (own: typeof generic): SignalProtocol => {493+ const asked = own.value === undefined ? generic : own;
Sign in to join this conversation.
macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed