Open History to see the last commit
1import * as Config from "effect/Config";
2import * as ConfigProvider from "effect/ConfigProvider";
3import * as Data from "effect/Data";
4import * as Effect from "effect/Effect";
5import * as Option from "effect/Option";
6import * as Schema from "effect/Schema";
7import * as SchemaTransformation from "effect/SchemaTransformation";
8
9import type { OtlpEndpointSource } from "@t3tools/contracts";
10
11import { OtlpHeadersFromString, OtlpProtocol, type SignalExport } from "./observability.ts";
12
13type OtlpSignalName = "TRACES" | "METRICS" | "LOGS";
14
15export type OtelSignal = Data.TaggedEnum<{
16 Unset: {};
17 Off: {};
18 Export: {
19 readonly url: string;
20 readonly variable: string;
21 readonly protocol: OtlpProtocol;
22 readonly headers: Readonly<Record<string, string>> | undefined;
23 };
24}>;
25export const OtelSignal = Data.taggedEnum<OtelSignal>();
26
27export interface OtelEnvironment {
28 readonly disabled: boolean;
29 readonly warnings: ReadonlyArray<string>;
30 readonly resourceAttributes: Readonly<Record<string, string>>;
31 readonly traces: OtelSignal;
32 readonly metrics: OtelSignal;
33 readonly logs: OtelSignal;
34}
35
36const blankAsUnset = (value: string | undefined): string | undefined => {
37 const trimmed = value?.trim();
38 return trimmed === undefined || trimmed === "" ? undefined : trimmed;
39};
40
41interface Flag {
42 readonly value: boolean | undefined;
43 readonly warning?: string;
44}
45
46const TrimmedLowercase = Schema.String.pipe(
47 Schema.decodeTo(
48 Schema.String,
49 SchemaTransformation.trim().pipe(
50 SchemaTransformation.composeTransformation(SchemaTransformation.toLowerCase()),
51 ),
52 ),
53);
54
55const flag = (
56 name: string,
57 truthy: ReadonlyArray<string>,
58 falsy: ReadonlyArray<string>,
59 invalid: (value: string) => string,
60) =>
61 Config.schema(
62 TrimmedLowercase.pipe(Schema.decodeTo(Schema.Literals([...truthy, ...falsy]))),
63 name,
64 ).pipe(
65 Config.map((value): Flag => ({ value: truthy.includes(value) })),
66 Config.orElse(() =>
67 Config.String(name).pipe(
68 Config.map((raw): Flag => {
69 const value = raw.trim();
70 return value === ""
71 ? { value: undefined }
72 : { value: undefined, warning: invalid(value) };
73 }),
74 ),
75 ),
76 Config.withDefault<Flag>({ value: undefined }),
77 );
78
79// `Config.Boolean`'s literals, which effect does not export on their own.
80const T3CODE_TRUE = ["true", "yes", "on", "1", "y"];
81const T3CODE_FALSE = ["false", "no", "off", "0", "n"];
82
83const RESOURCE_ATTRIBUTES = "OTEL_RESOURCE_ATTRIBUTES";
84
85interface ResourceAttributes {
86 readonly value: Readonly<Record<string, string>>;
87 readonly warning?: string;
88}
89
90const resourceAttributes = Config.Record(
91 Schema.StringFromUriComponent,
92 Schema.StringFromUriComponent,
93 RESOURCE_ATTRIBUTES,
94).pipe(
95 Config.map((value): ResourceAttributes => ({ value })),
96 Config.orElse(() =>
97 Config.String(RESOURCE_ATTRIBUTES).pipe(
98 // The value is left out because attributes can carry credentials.
99 Config.map((): ResourceAttributes => ({
100 value: {},
101 warning: `${RESOURCE_ATTRIBUTES} is not a list of percent-encoded key=value pairs and was ignored`,
102 })),
103 ),
104 ),
105 Config.withDefault<ResourceAttributes>({ value: {} }),
106);
107
108interface Setting<A> {
109 readonly value: A | undefined;
110 readonly warning?: string;
111}
112
113const readOrWarn = <A>(
114 name: string,
115 parse: (raw: string) => Option.Option<A>,
116 warning: string,
117): Config.Config<Setting<A>> =>
118 Config.String(name).pipe(
119 Config.option,
120 Config.map((option): Setting<A> => {
121 const raw = blankAsUnset(Option.getOrUndefined(option));
122 if (raw === undefined) {
123 return { value: undefined };
124 }
125 return Option.match(parse(raw), {
126 onNone: () => ({ value: undefined, warning }),
127 onSome: (value) => ({ value }),
128 });
129 }),
130 );
131
132const parseHttpUrl = (raw: string) =>
133 Option.liftThrowable((value: string) => new URL(value))(raw).pipe(
134 Option.filter((url) => url.protocol === "http:" || url.protocol === "https:"),
135 );
136
137const NOT_EXPORTED = "so the signals it configures are not exported";
138
139const endpoint = (name: string) =>
140 readOrWarn(name, parseHttpUrl, `${name} is not an http or https URL, ${NOT_EXPORTED}`);
141
142// The specification reads enum values case-insensitively.
143const protocol = (name: string) =>
144 readOrWarn(
145 name,
146 (raw) => Schema.decodeUnknownOption(OtlpProtocol)(raw.toLowerCase()),
147 `${name} is not http/protobuf or http/json, ${NOT_EXPORTED}`,
148 );
149
150const headers = (name: string) =>
151 readOrWarn(
152 name,
153 Schema.decodeUnknownOption(OtlpHeadersFromString),
154 `${name} is not a list of key=value pairs with percent-encoded values, ${NOT_EXPORTED}`,
155 );
156
157type Exporter = "otlp" | "none";
158
159const EXPORTERS: ReadonlySet<string> = new Set<Exporter>(["otlp", "none"]);
160
161const isExporter = (entry: string): entry is Exporter => EXPORTERS.has(entry);
162
163const exporter = (name: string): Config.Config<Setting<Exporter>> =>
164 Config.String(name).pipe(
165 Config.option,
166 Config.map((option): Setting<Exporter> => {
167 const entries = (Option.getOrUndefined(option) ?? "")
168 .split(",")
169 .map((entry) => entry.trim().toLowerCase())
170 .filter((entry) => entry !== "");
171 const ignored = [...new Set(entries.filter((entry) => !isExporter(entry)))];
172 const known = new Set(entries.filter(isExporter));
173 const value = known.has("otlp") ? "otlp" : known.has("none") ? "none" : undefined;
174 return ignored.length === 0
175 ? { value }
176 : {
177 value,
178 warning: `${name} names ${ignored.join(", ")}, which T3 Code does not export to, so ${ignored.length === 1 ? "it was" : "they were"} ignored`,
179 };
180 }),
181 );
182
183interface Settings {
184 readonly endpoint: Setting<URL>;
185 readonly protocol: Setting<OtlpProtocol>;
186 readonly headers: Setting<Readonly<Record<string, string>>>;
187}
188
189const settings = (prefix: string): Config.Config<Settings> =>
190 Config.all({
191 endpoint: endpoint(`${prefix}ENDPOINT`),
192 protocol: protocol(`${prefix}PROTOCOL`),
193 headers: headers(`${prefix}HEADERS`),
194 });
195
196/** The signal's own variable claims the signal once set, valid or not. */
197const isClaimed = (setting: Setting<unknown>) =>
198 setting.value !== undefined || setting.warning !== undefined;
199
200const claimed = <A>(own: Setting<A>, generic: Setting<A>) => (isClaimed(own) ? own : generic);
201
202/** Appends the signal's path, keeping the query an intake may take its API key in. */
203const withSignalPath = (signal: OtlpSignalName, base: URL) => {
204 const url = new URL(base);
205 const slash = url.pathname.endsWith("/") ? "" : "/";
206 url.pathname += `${slash}v1/${signal.toLowerCase()}`;
207 return url;
208};
209
210interface ResolvedSignal {
211 readonly signal: OtelSignal;
212 readonly used: ReadonlyArray<Setting<unknown>>;
213}
214
215const signal = (
216 name: OtlpSignalName,
217 exporter: Setting<Exporter>,
218 own: Settings,
219 generic: Settings,
220): ResolvedSignal => {
221 if (exporter.value === "none") {
222 return { signal: OtelSignal.Off(), used: [exporter] };
223 }
224 const resolved = endpointSignal(name, own, generic);
225 return { signal: resolved.signal, used: [exporter, ...resolved.used] };
226};
227
228const endpointSignal = (name: OtlpSignalName, own: Settings, generic: Settings): ResolvedSignal => {
229 const ownEndpoint = isClaimed(own.endpoint);
230 const endpoint = ownEndpoint ? own.endpoint : generic.endpoint;
231 if (endpoint.value === undefined) {
232 const signal = endpoint.warning === undefined ? OtelSignal.Unset() : OtelSignal.Off();
233 return { signal, used: [endpoint] };
234 }
235 const protocol = claimed(own.protocol, generic.protocol);
236 const headers = claimed(own.headers, generic.headers);
237 const used = [endpoint, protocol, headers];
238 if (protocol.warning !== undefined || headers.warning !== undefined) {
239 return { signal: OtelSignal.Off(), used };
240 }
241 const url = ownEndpoint ? endpoint.value : withSignalPath(name, endpoint.value);
242 return {
243 signal: OtelSignal.Export({
244 url: url.toString(),
245 variable: ownEndpoint ? `OTEL_EXPORTER_OTLP_${name}_ENDPOINT` : "OTEL_EXPORTER_OTLP_ENDPOINT",
246 protocol: protocol.value ?? "http/protobuf",
247 headers: headers.value,
248 }),
249 used,
250 };
251};
252
253const sdkFlags = {
254 t3: flag(
255 "T3CODE_OTEL_SDK_DISABLED",
256 T3CODE_TRUE,
257 T3CODE_FALSE,
258 (value) => `T3CODE_OTEL_SDK_DISABLED=${value} is not a yes or a no and was ignored`,
259 ),
260 // OTEL booleans are true only for case-insensitive true; warn on unrecognized values.
261 spec: flag(
262 "OTEL_SDK_DISABLED",
263 ["true"],
264 ["false"],
265 (value) =>
266 `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`,
267 ),
268};
269
270export const load: Effect.Effect<OtelEnvironment> = Config.all({
271 ...sdkFlags,
272 resource: resourceAttributes,
273 generic: settings("OTEL_EXPORTER_OTLP_"),
274 traces: settings("OTEL_EXPORTER_OTLP_TRACES_"),
275 metrics: settings("OTEL_EXPORTER_OTLP_METRICS_"),
276 logs: settings("OTEL_EXPORTER_OTLP_LOGS_"),
277 exporters: Config.all({
278 traces: exporter("OTEL_TRACES_EXPORTER"),
279 metrics: exporter("OTEL_METRICS_EXPORTER"),
280 logs: exporter("OTEL_LOGS_EXPORTER"),
281 }),
282}).pipe(
283 Effect.map(({ t3, spec, resource, generic, exporters, ...own }) => {
284 const disabled = t3.value ?? spec.value ?? false;
285 const signals = disabled
286 ? undefined
287 : {
288 traces: signal("TRACES", exporters.traces, own.traces, generic),
289 metrics: signal("METRICS", exporters.metrics, own.metrics, generic),
290 logs: signal("LOGS", exporters.logs, own.logs, generic),
291 };
292 const used = new Set(
293 signals === undefined ? [] : Object.values(signals).flatMap((resolved) => resolved.used),
294 );
295 const warnings = [
296 t3.warning,
297 spec.warning,
298 resource.warning,
299 ...Array.from(used, (setting) => setting.warning),
300 ].filter((warning) => warning !== undefined);
301 if (disabled) {
302 warnings.push(
303 t3.value
304 ? "T3CODE_OTEL_SDK_DISABLED is set, so no telemetry is exported, whatever configured it"
305 : "OTEL_SDK_DISABLED is set, so no telemetry is exported, whatever configured it; set T3CODE_OTEL_SDK_DISABLED=false to export anyway",
306 );
307 }
308 return {
309 disabled,
310 warnings,
311 resourceAttributes: resource.value,
312 traces: signals?.traces.signal ?? OtelSignal.Unset(),
313 metrics: signals?.metrics.signal ?? OtelSignal.Unset(),
314 logs: signals?.logs.signal ?? OtelSignal.Unset(),
315 };
316 }),
317 Effect.orDie,
318);
319
320export const isRelayTracingEnabled = (env: Readonly<Record<string, string | undefined>>) =>
321 Config.all({
322 ...sdkFlags,
323 telemetry: flag("T3CODE_TELEMETRY_ENABLED", T3CODE_TRUE, T3CODE_FALSE, String),
324 }).pipe(
325 Effect.map(
326 ({ telemetry, t3, spec }) => telemetry.value !== false && !(t3.value ?? spec.value ?? false),
327 ),
328 Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnvRecord(env))),
329 Effect.orDie,
330 Effect.runSync,
331 );
332
333export type SignalName = "traces" | "metrics" | "logs";
334
335export interface SignalEndpoint {
336 readonly url: string;
337 readonly export: SignalExport;
338 readonly source: OtlpEndpointSource;
339 /** The environment variable that set the endpoint, when `source` is `environment`. */
340 readonly variable?: string;
341}
342
343export const resolveSignalEndpoint = (
344 otel: OtelEnvironment,
345 signal: SignalName,
346 t3: { readonly url: string | undefined; readonly export: SignalExport },
347 fallback: { readonly bootstrapUrl: string | undefined; readonly settingsUrl: string | undefined },
348): SignalEndpoint | undefined => {
349 if (otel.disabled) {
350 return undefined;
351 }
352 const t3Url = blankAsUnset(t3.url);
353 if (t3Url !== undefined) {
354 return {
355 url: t3Url,
356 export: t3.export,
357 source: "environment",
358 variable: `T3CODE_OTLP_${signal.toUpperCase()}_URL`,
359 };
360 }
361 return OtelSignal.$match(otel[signal], {
362 Export: ({ url, variable, protocol, headers }): SignalEndpoint => ({
363 url,
364 export: { protocol, headers, exportIntervalMs: t3.export.exportIntervalMs },
365 source: "environment",
366 variable,
367 }),
368 Off: () => undefined,
369 Unset: (): SignalEndpoint | undefined => {
370 const settingsUrl = blankAsUnset(fallback.settingsUrl);
371 // The desktop forwards the saved setting as its bootstrap URL, so only a differing one is
372 // the desktop's own.
373 const url = blankAsUnset(fallback.bootstrapUrl) ?? settingsUrl;
374 if (url === undefined) return undefined;
375 return { url, export: t3.export, source: url === settingsUrl ? "settings" : "bootstrap" };
376 },
377 });
378};
379
380/** Give OTLP exporters the accepted resource attributes so their own decoding cannot fail. */
381export const layerResourceAttributes = (attributes: Readonly<Record<string, string>>) =>
382 ConfigProvider.layerAdd(
383 ConfigProvider.fromEnv({
384 env: {
385 [RESOURCE_ATTRIBUTES]: Object.entries(attributes)
386 .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
387 .join(","),
388 },
389 preserveEmptyStrings: true,
390 }),
391 { asPrimary: true },
392 );
393
394export const none: OtelEnvironment = {
395 disabled: false,
396 warnings: [],
397 resourceAttributes: {},
398 traces: OtelSignal.Unset(),
399 metrics: OtelSignal.Unset(),
400 logs: OtelSignal.Unset(),
401};