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

useHostConnectionChecks.ts

46 lines1.7 KB

1import { useRef, useState } from "react";
2import * as Cause from "effect/Cause";
3import type { SshDeviceHostConfig } from "@t3tools/contracts";
4import { deviceEnvironment } from "../../state/device";
5import { useAtomCommand } from "../../state/use-atom-command";
6import {
7 checkDeviceHostConnections,
8 deviceHostConnectionKey,
9 type DeviceHostCheck,
10 type DeviceHostCheckTarget,
11} from "./deviceHostConnectionChecks";
12​
13export function useHostConnectionChecks(targets: ReadonlyArray<DeviceHostCheckTarget>) {
14 const test = useAtomCommand(deviceEnvironment.testHost, { reportFailure: false });
15 const [checks, setChecks] = useState<Record<string, Record<string, DeviceHostCheck>>>({});
16 const running = useRef(new Set<string>());
17 const testConnection = async (host: SshDeviceHostConfig) => {
18 const key = deviceHostConnectionKey(host);
19 if (running.current.has(key)) return;
20 running.current.add(key);
21 setChecks((current) => ({ ...current, [key]: {} }));
22 const results: Record<string, DeviceHostCheck> = {};
23 try {
24 await checkDeviceHostConnections(
25 targets,
26 host,
27 async (environmentId, input) => {
28 const result = await test({ environmentId, input });
29 if (result._tag === "Failure") throw new Error(Cause.pretty(result.cause));
30 return result.value;
31 },
32 (environmentId, result) => {
33 results[environmentId] = result;
34 setChecks((current) => ({
35 ...current,
36 [key]: { ...current[key], [environmentId]: result },
37 }));
38 },
39 );
40 return results;
41 } finally {
42 running.current.delete(key);
43 }
44 };
45 return { checks, testConnection };