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

TelemetryExportSettings.tsx

278 lines10.7 KB

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