Open History to see the last commit
1import { AuthSettingsWriteScope } from "@t3tools/contracts";
2import { readEnvironmentScope } from "../../state/session";
3import { useRef, useState } from "react";
4import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
5import type { SshDeviceHostConfig } from "@t3tools/contracts";
6import { deviceEnvironment } from "../../state/device";
7import { useAtomCommand } from "../../state/use-atom-command";
8import {
9 checkDeviceHostConnections,
10 deviceHostConnectionKey,
11 type DeviceHostCheck,
12 type DeviceHostCheckTarget,
13} from "./deviceHostConnectionChecks";
14import { msg } from "gt-react";
15import { m } from "../../i18n/messages";
16
17export function useHostConnectionChecks(targets: ReadonlyArray<DeviceHostCheckTarget>) {
18 const test = useAtomCommand(deviceEnvironment.testHost, { reportFailure: false });
19 const [checks, setChecks] = useState<Record<string, Record<string, DeviceHostCheck>>>({});
20 const running = useRef(new Set<string>());
21 const testConnection = (host: SshDeviceHostConfig) => {
22 const key = deviceHostConnectionKey(host);
23 if (running.current.has(key)) return;
24 running.current.add(key);
25 setChecks((current) => ({ ...current, [key]: {} }));
26 const results: Record<string, DeviceHostCheck> = {};
27 return checkDeviceHostConnections(
28 targets,
29 host,
30 async (environmentId, input) => {
31 if (!readEnvironmentScope(environmentId, AuthSettingsWriteScope)) {
32 throw new Error(m(msg("This connection cannot test device hosts.")));
33 }
34 const result = await test({ environmentId, input });
35 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
36 return result.value;
37 },
38 (environmentId, result) => {
39 results[environmentId] = result;
40 setChecks((current) => ({
41 ...current,
42 [key]: { ...current[key], [environmentId]: result },
43 }));
44 },
45 )
46 .then(() => results)
47 .finally(() => running.current.delete(key));
48 };
49 return { checks, testConnection };
50}