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

TelemetryExportSettings.tsx

329 lines12.3 KB

1import { useAtomValue } from "@effect/atom-react";
2import type { OtlpEndpointCheckResult, OtlpSignal, ServerObservability } from "@t3tools/contracts";
3import { useEffect, useEffectEvent, useState } from "react";
4import { msg, T, useGT, useMessages, Var } from "gt-react";
5import { m, type MessageResolver } from "../../i18n/messages";
6​
7import { serverEnvironment } from "../../state/server";
8import { useAtomCommand } from "../../state/use-atom-command";
9import { Button } from "../ui/button";
10import { Input } from "../ui/input";
11import { Label } from "../ui/label";
12import { ConnectionStatusDot } from "../ConnectionStatusDot";
13import { useSettingsScope } from "./SettingsScopeContext";
14import { useScopedSettings } from "./useScopedSettings";
15import { SettingsSection } from "./settingsLayout";
16import { SettingsScopeNotice } from "./SettingsScopeNotice";
17​
18const SIGNALS = [
19 {
20 key: "otlpTracesUrl",
21 sourceKey: "otlpTracesSource",
22 variableKey: "otlpTracesVariable",
23 label: msg("Traces endpoint"),
24 signal: "traces",
25 },
26 {
27 key: "otlpMetricsUrl",
28 sourceKey: "otlpMetricsSource",
29 variableKey: "otlpMetricsVariable",
30 label: msg("Metrics endpoint"),
31 signal: "metrics",
32 },
33 {
34 key: "otlpLogsUrl",
35 sourceKey: "otlpLogsSource",
36 variableKey: "otlpLogsVariable",
37 label: msg("Logs endpoint"),
38 signal: "logs",
39 },
40] as const;
41​
42type SignalDescriptor = (typeof SIGNALS)[number];
43type SignalKey = SignalDescriptor["key"];
44​
45const OVERRIDE_LABELS = {
46 environment: msg("Set by environment"),
47 bootstrap: msg("Set by desktop"),
48} as const;
49​
50function runningOverride(
51 running: ServerObservability | undefined,
52 { key, sourceKey, variableKey }: SignalDescriptor,
53 resolve: MessageResolver = m,
54) {
55 const url = running?.[key];
56 const source = running?.[sourceKey];
57 if (url === undefined || (source !== "environment" && source !== "bootstrap")) return undefined;
58 return { url, label: resolve(OVERRIDE_LABELS[source]), variable: running?.[variableKey] };
60​
61type EndpointCheck = { readonly url: string; readonly result: OtlpEndpointCheckResult | null };
62​
63const isHttpUrl = (url: string) => /^https?:\/\/./i.test(url);
64​
65function endpointStatus(
66 url: string,
67 check: EndpointCheck | undefined,
68 resolve: MessageResolver = m,
69) {
70 if (url === "") {
71 return {
72 label: resolve(msg({ context: "export disabled" })`Off`),
73 dot: "bg-muted-foreground/40",
74 };
75 }
76 if (check?.url !== url) {
77 return { label: resolve(msg("Not checked")), dot: "bg-muted-foreground/40" };
78 }
79 const { result } = check;
80 if (result === null) return { label: resolve(msg("Checking…")), dot: "bg-warning" };
81 switch (result._tag) {
82 case "Accepted":
83 return {
84 label: resolve(msg`Connected · ${{ ms: Math.round(result.latencyMs) }} ms`),
85 dot: "bg-success",
86 };
87 case "Rejected":
88 return {
89 label: resolve(msg`Rejected · HTTP ${{ status: result.status }}`),
90 dot: "bg-destructive",
91 };
92 case "Unreachable":
93 return {
94 label: result.timedOut ? resolve(msg("Timed out")) : resolve(msg("Unreachable")),
95 dot: "bg-destructive",
96 };
97 }
99​
100export function TelemetryExportSettings() {
101 const gt = useGT();
102 const { environment, scope } = useSettingsScope();
103 if (scope.kind !== "environment" || !environment) {
104 return (
105 <SettingsSection title={gt`OpenTelemetry export`} id="telemetry-export">
106 <SettingsScopeNotice target="environment">
107 {gt`Choose one environment to configure its telemetry exports.`}
108 </SettingsScopeNotice>
109 </SettingsSection>
110 );
111 }
112 return <TelemetryExportForm key={environment.environmentId} />;
114​
115function TelemetryExportForm() {
116 const messages = useMessages();
117 const gt = useGT();
118 const { environment } = useSettingsScope();
119 const saved = useScopedSettings((settings) => settings.observability);
120 const [draft, setDraft] = useState<Partial<typeof saved>>({});
121 const [saving, setSaving] = useState(false);
122 const [message, setMessage] = useState<string | null>(null);
123 const environmentId = environment?.environmentId;
124 const canEdit = useAtomValue(
125 serverEnvironment.checkOtlpEndpoint.permissionAtom(environmentId ?? null),
126 );
127 const canCheck =
128 canEdit && environment?.serverConfig?.environment.capabilities.otlpEndpointCheck === true;
129 const running = environment?.serverConfig?.observability;
130 const [checks, setChecks] = useState<Partial<Record<SignalKey, EndpointCheck>>>(() =>
131 Object.fromEntries(
132 SIGNALS.flatMap((descriptor) => {
133 const url = runningOverride(running, descriptor)?.url ?? saved[descriptor.key];
134 return isHttpUrl(url) ? [[descriptor.key, { url, result: null }]] : [];
135 }),
136 ),
137 );
138 const updateSettings = useAtomCommand(serverEnvironment.updateSettings, { reportFailure: true });
139 const checkOtlpEndpoint = useAtomCommand(serverEnvironment.checkOtlpEndpoint);
140 const values = { ...saved, ...draft };
141 const changedSignals = SIGNALS.filter(({ key }) => values[key].trim() !== saved[key]);
142 const changed = changedSignals.length > 0;
143​
144 const sendCheck = async (key: SignalKey, signal: OtlpSignal, attempt: EndpointCheck) => {
145 if (!environmentId) return;
146 const { url } = attempt;
147 const response = await checkOtlpEndpoint({ environmentId, input: { signal, url } });
148 setChecks((previous) => {
149 if (previous[key] !== attempt) return previous;
150 const next = { ...previous };
151 if (response._tag === "Success") next[key] = { url, result: response.value };
152 else delete next[key];
153 return next;
154 });
155 };
156​
157 const checkEndpoint = (key: SignalKey, signal: OtlpSignal, url: string) => {
158 if (!isHttpUrl(url)) return;
159 const attempt = { url, result: null };
160 setChecks((previous) => ({ ...previous, [key]: attempt }));
161 void sendCheck(key, signal, attempt);
162 };
163​
164 const sendPendingChecks = useEffectEvent(() => {
165 for (const { key, signal } of SIGNALS) {
166 const check = checks[key];
167 if (check?.result === null) void sendCheck(key, signal, check);
168 }
169 });
170 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- sends pending endpoint check requests once the environment can run them
171 useEffect(() => {
172 // oxlint-disable-next-line react/set-state-in-effect -- State changes only after the response arrives.
173 if (canCheck) sendPendingChecks();
174 }, [canCheck]);
175​
176 return (
177 <SettingsSection title={gt`OpenTelemetry export`} id="telemetry-export">
178 <form
179 className="grid gap-4 px-4 py-4 sm:px-5"
180 onSubmit={async (event) => {
181 event.preventDefault();
182 if (!environment || saving) return;
183 setSaving(true);
184 setMessage(null);
185 const result = await updateSettings({
186 environmentId: environment.environmentId,
187 input: {
188 patch: {
189 observability: Object.fromEntries(
190 changedSignals.map(({ key }) => [key, values[key]]),
191 ),
192 },
193 },
194 });
195 setSaving(false);
196 if (result._tag === "Success") {
197 setDraft({});
198 setMessage(gt`Saved. Restart the server to apply.`);
199 }
200 }}
201 >
202 <p className="text-xs text-muted-foreground">
203 <T>
204 Send traces, metrics, and logs to an OTLP HTTP receiver. Restart the server to apply.
205 Environment variables override these settings.
206 </T>
207 </p>
208 {!canEdit && (
209 <p className="text-xs text-muted-foreground">
210 {environment
211 ? gt`This connection lacks permission to change settings on ${{ environment: environment.label }}.`
212 : gt`This connection lacks permission to change settings on the selected environment.`}
213 </p>
214 )}
215 {SIGNALS.map((descriptor) => {
216 const { key, label, signal } = descriptor;
217 const override = runningOverride(running, descriptor, messages);
218 const url = override?.url ?? values[key].trim();
219 const check = canCheck ? endpointStatus(url, checks[key], messages) : null;
220 const status = override
221 ? {
222 label: check ? `${override.label} · ${check.label}` : override.label,
223 dot: check?.dot ?? "bg-muted-foreground/40",
224 }
225 : check;
226 return (
227 <div key={key} className="grid gap-1.5">
228 <div className="flex items-center justify-between gap-3">
229 <div className="flex items-center gap-1.5">
230 {status && <ConnectionStatusDot dotClassName={status.dot} />}
231 <Label htmlFor={key}>{messages(label)}</Label>
232 </div>
233 {status && <span className="text-xs text-muted-foreground">{status.label}</span>}
234 </div>
235 <div className="flex gap-2">
236 <Input
237 id={key}
238 size="sm"
239 type="url"
240 pattern="[Hh][Tt][Tt][Pp][Ss]?://.*"
241 title={gt`Enter an HTTP or HTTPS endpoint, or leave empty to disable export.`}
242 placeholder={`http://localhost:4318/v1/${signal}`}
243 value={values[key]}
244 disabled={saving || !canEdit}
245 onChange={(event) => {
246 const value = event.target.value;
247 // Clear restored drafts so later saves cannot overwrite another client's changes.
248 setDraft((previous) => {
249 const next = { ...previous, [key]: value };
250 if (value.trim() === saved[key]) delete next[key];
251 return next;
252 });
253 setMessage(null);
254 }}
255 />
256 {canCheck && (
257 <Button
258 type="button"
259 size="sm"
260 variant="outline"
261 disabled={
262 !isHttpUrl(url) || (checks[key]?.url === url && checks[key].result === null)
263 }
264 onClick={() => void checkEndpoint(key, signal, url)}
265 >
266 <T>Test</T>
267 </Button>
268 )}
269 </div>
270 {(saved[key] !== (running?.[key] ?? "") || override?.variable) && (
271 <p className="break-all text-xs text-muted-foreground">
272 {override?.variable ? (
273 running?.[key] ? (
274 <T>
275 Running: <Var>{running[key]}</Var> from{" "}
276 <code className="font-mono">
277 <Var>{override.variable}</Var>
278 </code>
279 </T>
280 ) : (
281 <T>
282 Running: Disabled from{" "}
283 <code className="font-mono">
284 <Var>{override.variable}</Var>
285 </code>
286 </T>
287 )
288 ) : running?.[key] ? (
289 gt`Running: ${{ url: running[key] }}`
290 ) : (
291 gt`Running: Disabled`
292 )}
293 </p>
294 )}
295 </div>
296 );
297 })}
298 <div className="flex items-center justify-between gap-3">
299 <p role="status" className="text-xs text-muted-foreground">
300 {message}
301 </p>
302 <div className="flex shrink-0 gap-2">
303 <Button
304 type="button"
305 size="xs"
306 variant="outline"
307 disabled={!changed || saving || !canEdit}
308 onClick={() => {
309 setDraft({});
310 setMessage(null);
311 if (!canCheck) return;
312 for (const descriptor of SIGNALS) {
313 const { key, signal } = descriptor;
314 if (runningOverride(running, descriptor)) continue;
315 if (checks[key]?.url !== saved[key]) checkEndpoint(key, signal, saved[key]);
316 }
317 }}
318 >
319 <T>Discard</T>
320 </Button>
321 <Button type="submit" size="xs" disabled={!changed || saving || !canEdit}>
322 {saving ? gt`Saving…` : gt`Save`}
323 </Button>
324 </div>
325 </div>
326 </form>
327 </SettingsSection>
328 );