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

otelEnvironment.ts

157 lines5.3 KB

1/**
2 * otelEnvironment: the OpenTelemetry kill switch, shared by the server and the
3 * desktop main process so both agree on what turns export off.
4 *
5 * `T3CODE_OTEL_SDK_DISABLED` is read first, so a machine that sets
6 * `OTEL_SDK_DISABLED` for everything else can still opt T3 Code back in.
7 *
8 * @module otelEnvironment
9 */
10import * as Config from "effect/Config";
11import * as ConfigProvider from "effect/ConfigProvider";
12import * as Effect from "effect/Effect";
13import * as Schema from "effect/Schema";
14import * as SchemaTransformation from "effect/SchemaTransformation";
15​
16export interface OtelEnvironment {
17 /** Whether OTLP export is off, whatever endpoint is configured. */
18 readonly disabled: boolean;
19 /** Messages for the caller to log once at startup. */
20 readonly warnings: ReadonlyArray<string>;
21 /** `OTEL_RESOURCE_ATTRIBUTES`, or nothing when it could not be read. */
22 readonly resourceAttributes: Readonly<Record<string, string>>;
24​
25interface Flag {
26 /** `undefined` when the variable is unset, blank, or unreadable. */
27 readonly value: boolean | undefined;
28 readonly warning?: string;
30​
31const TrimmedLowercase = Schema.String.pipe(
32 Schema.decodeTo(
33 Schema.String,
34 SchemaTransformation.trim().compose(SchemaTransformation.toLowerCase()),
35 ),
36);
37​
38/**
39 * Reads a boolean that accepts `truthy` and `falsy`, ignoring case and padding.
40 * Any other value is ignored with a warning rather than failing startup.
41 */
42const flag = (
43 name: string,
44 truthy: ReadonlyArray<string>,
45 falsy: ReadonlyArray<string>,
46 invalid: (value: string) => string,
47) =>
48 Config.schema(
49 TrimmedLowercase.pipe(Schema.decodeTo(Schema.Literals([...truthy, ...falsy]))),
50 name,
51 ).pipe(
52 Config.map((value): Flag => ({ value: truthy.includes(value) })),
53 Config.orElse(() =>
54 Config.String(name).pipe(
55 Config.map((raw): Flag => {
56 const value = raw.trim();
57 return value === ""
58 ? { value: undefined }
59 : { value: undefined, warning: invalid(value) };
60 }),
61 ),
62 ),
63 Config.withDefault<Flag>({ value: undefined }),
64 );
65​
66// `Config.Boolean`'s literals, which effect does not export on their own.
67const T3CODE_TRUE = ["true", "yes", "on", "1", "y"];
68const T3CODE_FALSE = ["false", "no", "off", "0", "n"];
69​
70const RESOURCE_ATTRIBUTES = "OTEL_RESOURCE_ATTRIBUTES";
71​
72interface ResourceAttributes {
73 readonly value: Readonly<Record<string, string>>;
74 readonly warning?: string;
76​
77// The schema Effect's OTLP exporters read this variable with.
78const resourceAttributes = Config.Record(
79 Schema.StringFromUriComponent,
80 Schema.StringFromUriComponent,
81 RESOURCE_ATTRIBUTES,
82).pipe(
83 Config.map((value): ResourceAttributes => ({ value })),
84 Config.orElse(() =>
85 Config.String(RESOURCE_ATTRIBUTES).pipe(
86 // The value is left out because attributes can carry credentials.
87 Config.map((): ResourceAttributes => ({
88 value: {},
89 warning: `${RESOURCE_ATTRIBUTES} is not a list of percent-encoded key=value pairs and was ignored`,
90 })),
91 ),
92 ),
93 Config.withDefault<ResourceAttributes>({ value: {} }),
94);
95​
96export const load: Effect.Effect<OtelEnvironment> = Config.all({
97 t3: flag(
98 "T3CODE_OTEL_SDK_DISABLED",
99 T3CODE_TRUE,
100 T3CODE_FALSE,
101 (value) => `T3CODE_OTEL_SDK_DISABLED=${value} is not a yes or a no and was ignored`,
102 ),
103 // The specification: a boolean it defines is true "only by the
104 // case-insensitive string `true`", implementations "MUST NOT" accept other
105 // values as true, and should warn about unrecognized ones.
106 spec: flag(
107 "OTEL_SDK_DISABLED",
108 ["true"],
109 ["false"],
110 (value) =>
111 `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`,
112 ),
113 resource: resourceAttributes,
114}).pipe(
115 Effect.map(({ t3, spec, resource }) => {
116 const disabled = t3.value ?? spec.value ?? false;
117 const warnings = [t3.warning, spec.warning, resource.warning].filter(
118 (warning) => warning !== undefined,
119 );
120 if (disabled) {
121 warnings.push(
122 t3.value
123 ? "T3CODE_OTEL_SDK_DISABLED is set, so no telemetry is exported, whatever configured it"
124 : "OTEL_SDK_DISABLED is set, so no telemetry is exported, whatever configured it; set T3CODE_OTEL_SDK_DISABLED=false to export anyway",
125 );
126 }
127 return { disabled, warnings, resourceAttributes: resource.value };
128 }),
129 // Every read above falls back instead of failing, so this cannot happen.
130 Effect.orDie,
131);
132​
133/**
134 * Provide this around Effect's OTLP exporters, which read
135 * `OTEL_RESOURCE_ATTRIBUTES` for themselves and die when it does not decode,
136 * so they see what `load` accepted instead.
137 */
138export const layerResourceAttributes = (attributes: Readonly<Record<string, string>>) =>
139 ConfigProvider.layerAdd(
140 ConfigProvider.fromEnv({
141 env: {
142 [RESOURCE_ATTRIBUTES]: Object.entries(attributes)
143 .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
144 .join(","),
145 },
146 // Keeps an emptied list from falling through to the raw value.
147 preserveEmptyStrings: true,
148 }),
149 { asPrimary: true },
150 );
151​
152/** An environment that asked for nothing, for tests and for the pairing CLI. */
153export const none: OtelEnvironment = {
154 disabled: false,
155 warnings: [],
156 resourceAttributes: {},
157};