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

SimlockDeviceHostEditor.tsx

303 lines11.0 KB

1import { useAtomValue } from "@effect/atom-react";
2import { useId, useState, type ReactNode } from "react";
3import type { EnvironmentId, SimlockDeviceHostConfig } from "@t3tools/contracts";
4import * as Cause from "effect/Cause";
5import * as Option from "effect/Option";
6import { AsyncResult, Atom } from "effect/reactivity";
7import { XIcon } from "lucide-react";
8​
9import { deviceSimlockIdentityCheck } from "../../state/device";
10import { environmentAtomList, environmentIdsKey } from "../../state/environmentAtomList";
11​
12import { Button } from "../ui/button";
13import {
14 Dialog,
15 DialogDescription,
16 DialogFooter,
17 DialogHeader,
18 DialogPanel,
19 DialogPopup,
20 DialogTitle,
21} from "../ui/dialog";
22import { Input } from "../ui/input";
23import { Spinner } from "../ui/spinner";
24import { SecretInput } from "./SecretInput";
25import {
26 planSimlockDeviceHostSave,
27 simlockDeviceHostProblem,
28 type SimlockHostEnvironment,
29 type SimlockTokenEntry,
30} from "./simlockDeviceHostsSettings.logic";
31​
32const failureMessage = (cause: Cause.Cause<unknown>) => {
33 const error = Cause.squash(cause);
34 return error instanceof Error ? error.message : String(error);
35};
36​
37/** The gateway each environment's own agent-device points at, if any. */
38const machineGatewaysAtom = environmentAtomList("web-simlock-machine-gateways", (environmentId) =>
39 deviceSimlockIdentityCheck({ environmentId, input: {} }),
40);
41​
42const NO_CHECK = Atom.make(AsyncResult.initial()).pipe(Atom.withLabel("simlock-identity:none"));
43​
44/** Shared fields once, then one agent token per environment: Simlock counts leases per token. */
45export function SimlockDeviceHostEditor(props: {
46 host: SimlockDeviceHostConfig;
47 isNew: boolean;
48 environments: ReadonlyArray<SimlockHostEnvironment>;
49 busy: boolean;
50 onSave: (
51 host: SimlockDeviceHostConfig,
52 tokens: ReadonlyMap<EnvironmentId, SimlockTokenEntry>,
53 ) => void;
54 onClose: () => void;
55}) {
56 const [draft, setDraft] = useState(props.host);
57 const [urlEdited, setUrlEdited] = useState(false);
58 const machineGateways = useAtomValue(
59 machineGatewaysAtom(
60 environmentIdsKey(
61 props.isNew ? props.environments.map((environment) => environment.environmentId) : [],
62 ),
63 ),
64 );
65 // A new host starts at the gateway an environment's agent-device already uses.
66 const detectedUrl = machineGateways
67 .map((result) => Option.getOrUndefined(AsyncResult.value(result))?.gatewayUrl)
68 .find(Boolean);
69 const gatewayUrl = urlEdited || draft.gatewayUrl ? draft.gatewayUrl : (detectedUrl ?? "");
70 const savedToken = (environment: SimlockHostEnvironment) =>
71 environment.hosts.some((host) => host.id === props.host.id && host.agentToken !== "");
72 const [tokens, setTokens] = useState<ReadonlyMap<EnvironmentId, SimlockTokenEntry>>(
73 () =>
74 new Map(
75 props.environments.map((environment) => [
76 environment.environmentId,
77 savedToken(environment) ? { kind: "saved" } : { kind: "cleared" },
78 ]),
79 ),
80 );
81 const next: SimlockDeviceHostConfig = {
82 ...draft,
83 label: draft.label.trim(),
84 gatewayUrl: gatewayUrl.trim(),
85 };
86 const checkUrl = simlockDeviceHostProblem(next) === null ? next.gatewayUrl : null;
87 const plan = planSimlockDeviceHostSave(props.environments, next, tokens);
88 const problem = "problem" in plan ? plan.problem : null;
89 const several = props.environments.length > 1;
90​
91 const limit = (
92 field: "maxLeases" | "maxLeaseMinutes",
93 label: string,
94 min: number,
95 max: number,
96 ) => (
97 <label className="block space-y-1.5">
98 <span>{label}</span>
99 <Input
100 type="number"
101 min={min}
102 max={max}
103 value={draft[field]}
104 disabled={props.busy}
105 onChange={(event) => {
106 const value = Number(event.target.value);
107 setDraft((current) => ({ ...current, [field]: value }));
108 }}
109 />
110 </label>
111 );
112​
113 return (
114 <Dialog
115 open
116 onOpenChange={(open) => {
117 if (!open && !props.busy) props.onClose();
118 }}
119 >
120 <DialogPopup showCloseButton={!props.busy}>
121 <form
122 className="flex min-h-0 flex-col"
123 onSubmit={(event) => {
124 event.preventDefault();
125 if (problem === null && !props.busy) props.onSave(next, tokens);
126 }}
127 >
128 <DialogHeader>
129 <DialogTitle>{props.isNew ? "Add Simlock host" : "Edit Simlock host"}</DialogTitle>
130 <DialogDescription>
131 {several
132 ? "Each selected environment's server leases devices from your Simlock gateway with its own agent token, and releases them when they close."
133 : "The environment's server leases devices from your Simlock gateway and releases them when they close."}
134 </DialogDescription>
135 </DialogHeader>
136 <DialogPanel>
137 <label className="block space-y-1.5 text-sm">
138 <span>Name</span>
139 <Input
140 autoFocus
141 required
142 value={draft.label}
143 disabled={props.busy}
144 onChange={(event) => {
145 const label = event.target.value;
146 setDraft((current) => ({ ...current, label }));
147 }}
148 />
149 </label>
150 <label className="block space-y-1.5 text-sm">
151 <span>Gateway URL</span>
152 <Input
153 required
154 type="url"
155 placeholder="https://gateway.example.ts.net:4700"
156 value={gatewayUrl}
157 disabled={props.busy}
158 onChange={(event) => {
159 const gatewayUrl = event.target.value;
160 setUrlEdited(true);
161 setDraft((current) => ({ ...current, gatewayUrl }));
162 }}
163 />
164 </label>
165 <div className="space-y-3">
166 {props.environments.map((environment) => (
167 <SimlockTokenField
168 key={environment.environmentId}
169 environmentId={environment.environmentId}
170 hostId={props.isNew ? null : props.host.id}
171 gatewayUrl={checkUrl}
172 label={several ? `Agent token · ${environment.label}` : "Agent token"}
173 token={tokens.get(environment.environmentId) ?? { kind: "cleared" }}
174 hasSaved={savedToken(environment)}
175 busy={props.busy}
176 onChange={(token) =>
177 setTokens((current) => new Map(current).set(environment.environmentId, token))
178 }
179 />
180 ))}
181 <p className="text-xs text-muted-foreground">
182 Leases, drives, and streams devices. Create one{several ? " per environment" : ""}{" "}
183 with <code>simlock --gateway token create --role agent</code>, or leave it blank to
184 add it later. A blank token uses the machine's{" "}
185 <code>AGENT_DEVICE_DAEMON_AUTH_TOKEN</code> when its{" "}
186 <code>AGENT_DEVICE_DAEMON_BASE_URL</code> is this gateway.
187 </p>
188 </div>
189 <div className="grid grid-cols-2 gap-3 text-sm">
190 {limit("maxLeases", "Devices at once", 1, 20)}
191 {limit("maxLeaseMinutes", "Lease minutes", 5, 240)}
192 </div>
193 <p className="text-xs text-muted-foreground">
194 A lease ends after the lease minutes even while in use.
195 {props.isNew ? null : " Saving restarts this host, which releases its devices."}
196 </p>
197 {problem === null || !gatewayUrl ? null : (
198 <p className="text-xs text-destructive" role="alert">
199 {problem}
200 </p>
201 )}
202 </DialogPanel>
203 <DialogFooter>
204 <Button type="button" variant="ghost" disabled={props.busy} onClick={props.onClose}>
205 Cancel
206 </Button>
207 <Button type="submit" disabled={props.busy || problem !== null}>
208 {props.busy ? <Spinner size="xs" /> : null} Save host
209 </Button>
210 </DialogFooter>
211 </form>
212 </DialogPopup>
213 </Dialog>
214 );
216​
217function SimlockTokenField(props: {
218 environmentId: EnvironmentId;
219 hostId: string | null;
220 gatewayUrl: string | null;
221 label: ReactNode;
222 token: SimlockTokenEntry;
223 hasSaved: boolean;
224 busy: boolean;
225 onChange: (token: SimlockTokenEntry) => void;
226}) {
227 const id = useId();
228 const entered = props.token.kind === "new" ? props.token.value.trim() : "";
229 // A cleared field asks about the machine's own token, which a blank one falls back to.
230 const check = useAtomValue(
231 props.gatewayUrl === null
232 ? NO_CHECK
233 : deviceSimlockIdentityCheck({
234 environmentId: props.environmentId,
235 input: {
236 gatewayUrl: props.gatewayUrl,
237 ...(entered
238 ? { agentToken: entered }
239 : props.token.kind === "saved" && props.hostId !== null
240 ? { hostId: props.hostId }
241 : {}),
242 },
243 }),
244 );
245 const identity = AsyncResult.isSuccess(check) ? check.value : null;
246 const status =
247 props.gatewayUrl === null ? null : check._tag === "Initial" || check.waiting ? (
248 <span className="text-muted-foreground">Checking…</span>
249 ) : identity ? (
250 <span className="text-muted-foreground">
251 {identity.tokenSource === "env"
252 ? `Using this machine's agent-device token (${identity.signedInAs}).`
253 : `Accepted as ${identity.signedInAs}.`}
254 </span>
255 ) : AsyncResult.isFailure(check) ? (
256 <span
257 className={props.token.kind === "cleared" ? "text-muted-foreground" : "text-destructive"}
258 >
259 {failureMessage(check.cause)}
260 </span>
261 ) : null;
262 return (
263 <div className="space-y-1.5 text-sm">
264 <label htmlFor={id} className="block">
265 {props.label}
266 </label>
267 <div className="flex items-center gap-2">
268 <SecretInput
269 id={id}
270 className="min-w-0 flex-1"
271 configured={props.token.kind === "saved"}
272 value={props.token.kind === "new" ? props.token.value : ""}
273 disabled={props.busy}
274 onChange={(event) => {
275 const value = event.target.value;
276 // Emptying the field is not clearing the saved token; the Clear
277 // button is, so a saved token comes back here.
278 props.onChange(
279 value
280 ? { kind: "new", value }
281 : props.hasSaved
282 ? { kind: "saved" }
283 : { kind: "cleared" },
284 );
285 }}
286 />
287 {props.token.kind !== "cleared" ? (
288 <Button
289 type="button"
290 size="icon-sm"
291 variant="ghost-destructive"
292 aria-label="Clear agent token"
293 disabled={props.busy}
294 onClick={() => props.onChange({ kind: "cleared" })}
295 >
296 <XIcon className="size-3.5" />
297 </Button>
298 ) : null}
299 </div>
300 {status ? <p className="text-xs">{status}</p> : null}
301 </div>
302 );