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

otelEnvironment.ts

373 lines12.7 KB

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