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