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";
14
15export function useHostConnectionChecks(targets: ReadonlyArray<DeviceHostCheckTarget>) {
16 const test = useAtomCommand(deviceEnvironment.testHost, { reportFailure: false });
17 const [checks, setChecks] = useState<Record<string, Record<string, DeviceHostCheck>>>({});
18 const running = useRef(new Set<string>());
19 const testConnection = async (host: SshDeviceHostConfig) => {
20 const key = deviceHostConnectionKey(host);
21 if (running.current.has(key)) return;
22 running.current.add(key);
23 setChecks((current) => ({ ...current, [key]: {} }));
24 const results: Record<string, DeviceHostCheck> = {};
25 await checkDeviceHostConnections(
26 targets,
27 host,
28 async (environmentId, input) => {
29 if (!readEnvironmentScope(environmentId, AuthSettingsWriteScope)) {
30 throw new Error("This connection cannot test device hosts.");
31 }
32 const result = await test({ environmentId, input });
33 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
34 return result.value;
35 },
36 (environmentId, result) => {
37 results[environmentId] = result;
38 setChecks((current) => ({
39 ...current,
40 [key]: { ...current[key], [environmentId]: result },
41 }));
42 },
43 ).finally(() => running.current.delete(key));
44 return results;
45 };
46 return { checks, testConnection };
47}