Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

otelEnvironment.ts

425 lines14.7 KB

1/**
2 * otelEnvironment: the OpenTelemetry kill switch, exporter, and endpoint variables,
3 * shared by the server and the desktop main process so both agree on what
4 * turns export off and where it goes.
5 *
6 * `T3CODE_OTEL_SDK_DISABLED` is read first, so a machine that sets
7 * `OTEL_SDK_DISABLED` for everything else can still opt T3 Code back in.
8 *
9 * @module otelEnvironment
10 */
11import * as Config from "effect/Config";
12import * as ConfigProvider from "effect/ConfigProvider";
13import * as Data from "effect/Data";
14import * as Effect from "effect/Effect";
15import * as Option from "effect/Option";
16import * as Schema from "effect/Schema";
17import * as SchemaTransformation from "effect/SchemaTransformation";
18​
19import { OtlpHeadersFromString, OtlpProtocol, type SignalExport } from "./observability.ts";
20​
21/** The signals T3 Code exports, spelled as the variable names spell them. */
22type OtlpSignalName = "TRACES" | "METRICS" | "LOGS";
23​
24/**
25 * What the OTEL variables say about one signal. `Off` is a signal they
26 * claimed with an endpoint, protocol, or headers that do not read, or turned
27 * off with `OTEL_<SIGNAL>_EXPORTER=none`, so it is exported nowhere rather
28 * than to the bootstrap or Settings collector.
29 */
30export type OtelSignal = Data.TaggedEnum<{
31 Unset: {};
32 Off: {};
33 Export: {
34 readonly url: string;
35 readonly protocol: OtlpProtocol;
36 readonly headers: Readonly<Record<string, string>> | undefined;
37 };
38}>;
39export const OtelSignal = Data.taggedEnum<OtelSignal>();
40​
41export interface OtelEnvironment {
42 /** Whether OTLP export is off, whatever endpoint is configured. */
43 readonly disabled: boolean;
44 /** Messages for the caller to log once at startup. */
45 readonly warnings: ReadonlyArray<string>;
46 /** `OTEL_RESOURCE_ATTRIBUTES`, or nothing when it could not be read. */
47 readonly resourceAttributes: Readonly<Record<string, string>>;
48 readonly traces: OtelSignal;
49 readonly metrics: OtelSignal;
50 readonly logs: OtelSignal;
52​
53/** A set but blank value reads as unset, so the source under it can answer. */
54const blankAsUnset = (value: string | undefined): string | undefined => {
55 const trimmed = value?.trim();
56 return trimmed === undefined || trimmed === "" ? undefined : trimmed;
57};
58​
59interface Flag {
60 /** `undefined` when the variable is unset, blank, or unreadable. */
61 readonly value: boolean | undefined;
62 readonly warning?: string;
64​
65const TrimmedLowercase = Schema.String.pipe(
66 Schema.decodeTo(
67 Schema.String,
68 SchemaTransformation.trim().compose(SchemaTransformation.toLowerCase()),
69 ),
70);
71​
72/**
73 * Reads a boolean that accepts `truthy` and `falsy`, ignoring case and padding.
74 * Any other value is ignored with a warning rather than failing startup.
75 */
76const flag = (
77 name: string,
78 truthy: ReadonlyArray<string>,
79 falsy: ReadonlyArray<string>,
80 invalid: (value: string) => string,
81) =>
82 Config.schema(
83 TrimmedLowercase.pipe(Schema.decodeTo(Schema.Literals([...truthy, ...falsy]))),
84 name,
85 ).pipe(
86 Config.map((value): Flag => ({ value: truthy.includes(value) })),
87 Config.orElse(() =>
88 Config.String(name).pipe(
89 Config.map((raw): Flag => {
90 const value = raw.trim();
91 return value === ""
92 ? { value: undefined }
93 : { value: undefined, warning: invalid(value) };
94 }),
95 ),
96 ),
97 Config.withDefault<Flag>({ value: undefined }),
98 );
99​
100// `Config.Boolean`'s literals, which effect does not export on their own.
101const T3CODE_TRUE = ["true", "yes", "on", "1", "y"];
102const T3CODE_FALSE = ["false", "no", "off", "0", "n"];
103​
104const RESOURCE_ATTRIBUTES = "OTEL_RESOURCE_ATTRIBUTES";
105​
106interface ResourceAttributes {
107 readonly value: Readonly<Record<string, string>>;
108 readonly warning?: string;
110​
111// The schema Effect's OTLP exporters read this variable with.
112const resourceAttributes = Config.Record(
113 Schema.StringFromUriComponent,
114 Schema.StringFromUriComponent,
115 RESOURCE_ATTRIBUTES,
116).pipe(
117 Config.map((value): ResourceAttributes => ({ value })),
118 Config.orElse(() =>
119 Config.String(RESOURCE_ATTRIBUTES).pipe(
120 // The value is left out because attributes can carry credentials.
121 Config.map((): ResourceAttributes => ({
122 value: {},
123 warning: `${RESOURCE_ATTRIBUTES} is not a list of percent-encoded key=value pairs and was ignored`,
124 })),
125 ),
126 ),
127 Config.withDefault<ResourceAttributes>({ value: {} }),
128);
129​
130interface Setting<A> {
131 readonly value: A | undefined;
132 readonly warning?: string;
134​
135/**
136 * Reads one variable. Blank reads as unset, and a value `parse` rejects warns
137 * without echoing it, since these variables carry credentials.
138 */
139const readOrWarn = <A>(
140 name: string,
141 parse: (raw: string) => Option.Option<A>,
142 warning: string,
143): Config.Config<Setting<A>> =>
144 Config.String(name).pipe(
145 Config.option,
146 Config.map((option): Setting<A> => {
147 const raw = blankAsUnset(Option.getOrUndefined(option));
148 if (raw === undefined) {
149 return { value: undefined };
150 }
151 return Option.match(parse(raw), {
152 onNone: () => ({ value: undefined, warning }),
153 onSome: (value) => ({ value }),
154 });
155 }),
156 );
157​
158const parseHttpUrl = (raw: string) =>
159 Option.liftThrowable((value: string) => new URL(value))(raw).pipe(
160 Option.filter((url) => url.protocol === "http:" || url.protocol === "https:"),
161 );
162​
163const NOT_EXPORTED = "so the signals it configures are not exported";
164​
165const endpoint = (name: string) =>
166 readOrWarn(name, parseHttpUrl, `${name} is not an http or https URL, ${NOT_EXPORTED}`);
167​
168// The specification reads enum values case-insensitively.
169const protocol = (name: string) =>
170 readOrWarn(
171 name,
172 (raw) => Schema.decodeUnknownOption(OtlpProtocol)(raw.toLowerCase()),
173 `${name} is not http/protobuf or http/json, ${NOT_EXPORTED}`,
174 );
175​
176const headers = (name: string) =>
177 readOrWarn(
178 name,
179 Schema.decodeUnknownOption(OtlpHeadersFromString),
180 `${name} is not a list of key=value pairs with percent-encoded values, ${NOT_EXPORTED}`,
181 );
182​
183type Exporter = "otlp" | "none";
184​
185const EXPORTERS: ReadonlySet<string> = new Set<Exporter>(["otlp", "none"]);
186​
187const isExporter = (entry: string): entry is Exporter => EXPORTERS.has(entry);
188​
189/**
190 * `OTEL_<SIGNAL>_EXPORTER`, a case-insensitive list whose default is `otlp`.
191 * Entries T3 Code has no exporter for are named in a warning and dropped, and
192 * a list left with nothing to honor reads as unset, as the specification asks
193 * of any enum value an implementation does not recognize.
194 */
195const exporter = (name: string): Config.Config<Setting<Exporter>> =>
196 Config.String(name).pipe(
197 Config.option,
198 Config.map((option): Setting<Exporter> => {
199 const entries = (Option.getOrUndefined(option) ?? "")
200 .split(",")
201 .map((entry) => entry.trim().toLowerCase())
202 .filter((entry) => entry !== "");
203 const ignored = [...new Set(entries.filter((entry) => !isExporter(entry)))];
204 const known = new Set(entries.filter(isExporter));
205 const value = known.has("otlp") ? "otlp" : known.has("none") ? "none" : undefined;
206 return ignored.length === 0
207 ? { value }
208 : {
209 value,
210 warning: `${name} names ${ignored.join(", ")}, which T3 Code does not export to, so ${ignored.length === 1 ? "it was" : "they were"} ignored`,
211 };
212 }),
213 );
214​
215interface Settings {
216 readonly endpoint: Setting<URL>;
217 readonly protocol: Setting<OtlpProtocol>;
218 readonly headers: Setting<Readonly<Record<string, string>>>;
220​
221const settings = (prefix: string): Config.Config<Settings> =>
222 Config.all({
223 endpoint: endpoint(`${prefix}ENDPOINT`),
224 protocol: protocol(`${prefix}PROTOCOL`),
225 headers: headers(`${prefix}HEADERS`),
226 });
227​
228/** The signal's own variable claims the signal once set, valid or not. */
229const isClaimed = (setting: Setting<unknown>) =>
230 setting.value !== undefined || setting.warning !== undefined;
231​
232const claimed = <A>(own: Setting<A>, generic: Setting<A>) => (isClaimed(own) ? own : generic);
233​
234/** Appends the signal's path, keeping the query an intake may take its API key in. */
235const withSignalPath = (signal: OtlpSignalName, base: URL) => {
236 const url = new URL(base);
237 const slash = url.pathname.endsWith("/") ? "" : "/";
238 url.pathname += `${slash}v1/${signal.toLowerCase()}`;
239 return url;
240};
241​
242interface ResolvedSignal {
243 readonly signal: OtelSignal;
244 /** The settings this signal read, whose warnings are the signal's to report. */
245 readonly used: ReadonlyArray<Setting<unknown>>;
247​
248/**
249 * A signal whose endpoint, protocol, or headers do not read is not exported
250 * rather than sent somewhere, in a format, or without the credentials its
251 * collector expects. `none` turns the signal off before any of those are read,
252 * whether or not an endpoint was named.
253 */
254const signal = (
255 name: OtlpSignalName,
256 exporter: Setting<Exporter>,
257 own: Settings,
258 generic: Settings,
259): ResolvedSignal => {
260 if (exporter.value === "none") {
261 return { signal: OtelSignal.Off(), used: [exporter] };
262 }
263 const resolved = endpointSignal(name, own, generic);
264 return { signal: resolved.signal, used: [exporter, ...resolved.used] };
265};
266​
267const endpointSignal = (name: OtlpSignalName, own: Settings, generic: Settings): ResolvedSignal => {
268 const ownEndpoint = isClaimed(own.endpoint);
269 const endpoint = ownEndpoint ? own.endpoint : generic.endpoint;
270 if (endpoint.value === undefined) {
271 const signal = endpoint.warning === undefined ? OtelSignal.Unset() : OtelSignal.Off();
272 return { signal, used: [endpoint] };
273 }
274 const protocol = claimed(own.protocol, generic.protocol);
275 const headers = claimed(own.headers, generic.headers);
276 const used = [endpoint, protocol, headers];
277 if (protocol.warning !== undefined || headers.warning !== undefined) {
278 return { signal: OtelSignal.Off(), used };
279 }
280 const url = ownEndpoint ? endpoint.value : withSignalPath(name, endpoint.value);
281 return {
282 signal: OtelSignal.Export({
283 url: url.toString(),
284 protocol: protocol.value ?? "http/protobuf",
285 headers: headers.value,
286 }),
287 used,
288 };
289};
290​
291export const load: Effect.Effect<OtelEnvironment> = Config.all({
292 t3: flag(
293 "T3CODE_OTEL_SDK_DISABLED",
294 T3CODE_TRUE,
295 T3CODE_FALSE,
296 (value) => `T3CODE_OTEL_SDK_DISABLED=${value} is not a yes or a no and was ignored`,
297 ),
298 // The specification: a boolean it defines is true "only by the
299 // case-insensitive string `true`", implementations "MUST NOT" accept other
300 // values as true, and should warn about unrecognized ones.
301 spec: flag(
302 "OTEL_SDK_DISABLED",
303 ["true"],
304 ["false"],
305 (value) =>
306 `OTEL_SDK_DISABLED=${value} was read as false; the OpenTelemetry specification recognizes only the string true, so use OTEL_SDK_DISABLED=true or T3CODE_OTEL_SDK_DISABLED to say it any other way`,
307 ),
308 resource: resourceAttributes,
309 generic: settings("OTEL_EXPORTER_OTLP_"),
310 traces: settings("OTEL_EXPORTER_OTLP_TRACES_"),
311 metrics: settings("OTEL_EXPORTER_OTLP_METRICS_"),
312 logs: settings("OTEL_EXPORTER_OTLP_LOGS_"),
313 exporters: Config.all({
314 traces: exporter("OTEL_TRACES_EXPORTER"),
315 metrics: exporter("OTEL_METRICS_EXPORTER"),
316 logs: exporter("OTEL_LOGS_EXPORTER"),
317 }),
318}).pipe(
319 Effect.map(({ t3, spec, resource, generic, exporters, ...own }) => {
320 const disabled = t3.value ?? spec.value ?? false;
321 // The kill switch wins outright, so the signals say nothing once it is set.
322 const signals = disabled
323 ? undefined
324 : {
325 traces: signal("TRACES", exporters.traces, own.traces, generic),
326 metrics: signal("METRICS", exporters.metrics, own.metrics, generic),
327 logs: signal("LOGS", exporters.logs, own.logs, generic),
328 };
329 // A generic variable read by several signals warns once.
330 const used = new Set(
331 signals === undefined ? [] : Object.values(signals).flatMap((resolved) => resolved.used),
332 );
333 const warnings = [
334 t3.warning,
335 spec.warning,
336 resource.warning,
337 ...Array.from(used, (setting) => setting.warning),
338 ].filter((warning) => warning !== undefined);
339 if (disabled) {
340 warnings.push(
341 t3.value
342 ? "T3CODE_OTEL_SDK_DISABLED is set, so no telemetry is exported, whatever configured it"
343 : "OTEL_SDK_DISABLED is set, so no telemetry is exported, whatever configured it; set T3CODE_OTEL_SDK_DISABLED=false to export anyway",
344 );
345 }
346 return {
347 disabled,
348 warnings,
349 resourceAttributes: resource.value,
350 traces: signals?.traces.signal ?? OtelSignal.Unset(),
351 metrics: signals?.metrics.signal ?? OtelSignal.Unset(),
352 logs: signals?.logs.signal ?? OtelSignal.Unset(),
353 };
354 }),
355 // Every read above falls back instead of failing, so this cannot happen.
356 Effect.orDie,
357);
358​
359export type SignalName = "traces" | "metrics" | "logs";
360​
361export interface SignalEndpoint {
362 readonly url: string;
363 readonly export: SignalExport;
365​
366/**
367 * Where one signal exports and how. `T3CODE_OTLP_*_URL` wins outright with
368 * T3 Code's own export, then an OTEL endpoint with its own headers and
369 * protocol, since `T3CODE_OTLP_HEADERS` was written for a different
370 * collector, then the first of `fallbackUrls` with T3 Code's own export.
371 */
372export const resolveSignalEndpoint = (
373 otel: OtelEnvironment,
374 signal: SignalName,
375 t3: { readonly url: string | undefined; readonly export: SignalExport },
376 ...fallbackUrls: ReadonlyArray<string | undefined>
377): SignalEndpoint | undefined => {
378 if (otel.disabled) {
379 return undefined;
380 }
381 const t3Url = blankAsUnset(t3.url);
382 if (t3Url !== undefined) {
383 return { url: t3Url, export: t3.export };
384 }
385 return OtelSignal.$match(otel[signal], {
386 Export: ({ url, protocol, headers }): SignalEndpoint => ({
387 url,
388 export: { protocol, headers, exportIntervalMs: t3.export.exportIntervalMs },
389 }),
390 Off: () => undefined,
391 Unset: () => {
392 const url = fallbackUrls.map(blankAsUnset).find((candidate) => candidate !== undefined);
393 return url === undefined ? undefined : { url, export: t3.export };
394 },
395 });
396};
397​
398/**
399 * Provide this around Effect's OTLP exporters, which read
400 * `OTEL_RESOURCE_ATTRIBUTES` for themselves and die when it does not decode,
401 * so they see what `load` accepted instead.
402 */
403export const layerResourceAttributes = (attributes: Readonly<Record<string, string>>) =>
404 ConfigProvider.layerAdd(
405 ConfigProvider.fromEnv({
406 env: {
407 [RESOURCE_ATTRIBUTES]: Object.entries(attributes)
408 .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
409 .join(","),
410 },
411 // Keeps an emptied list from falling through to the raw value.
412 preserveEmptyStrings: true,
413 }),
414 { asPrimary: true },
415 );
416​
417/** An environment that asked for nothing, for tests and for the pairing CLI. */
418export const none: OtelEnvironment = {
419 disabled: false,
420 warnings: [],
421 resourceAttributes: {},
422 traces: OtelSignal.Unset(),
423 metrics: OtelSignal.Unset(),
424 logs: OtelSignal.Unset(),
425};