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

device.ts

194 lines6.3 KB

1import { useAtomValue } from "@effect/atom-react";
2import { createDeviceEnvironmentAtoms } from "@t3tools/client-runtime/state/device";
3import {
4 type DeviceHubAccess,
5 resolveDeviceHubAccess,
6} from "@t3tools/client-runtime/state/deviceHubAccess";
7import {
8 createEnvironmentRpcQueryAtomFamily,
9 runAtomCommand,
10} from "@t3tools/client-runtime/state/runtime";
11import {
12 type DeviceDetail,
13 type DeviceServiceState,
14 type EnvironmentId,
15 WS_METHODS,
16} from "@t3tools/contracts";
17import * as Effect from "effect/Effect";
18import { useMessages } from "gt-react";
19import * as Option from "effect/Option";
20import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
21​
22import { connectionAtomRuntime } from "../connection/runtime";
23import { appAtomRegistry } from "../rpc/atomRegistry";
24import { environmentSession } from "./session";
25import { formatEnvironmentQueryError, useEnvironmentQuery } from "./query";
26​
27export const deviceEnvironment = createDeviceEnvironmentAtoms(connectionAtomRuntime);
28​
29const EMPTY_DEVICE_STATE: DeviceServiceState = {
30 hosts: [],
31 hostStatus: "disabled",
32 hostStatuses: {},
33 devices: [],
34 sessions: [],
35 onboardingCompleted: false,
36 agentAccessEnabled: false,
37 hubBasePath: "/api/device-hub",
38 revision: 0,
39};
40​
41export function useDeviceState(environmentId: EnvironmentId | null): {
42 readonly state: DeviceServiceState;
43 readonly loaded: boolean;
44 readonly error: string | null;
45 readonly refresh: () => void;
46} {
47 const resolve = useMessages();
48 const query = useEnvironmentQuery(
49 environmentId === null ? null : deviceEnvironment.state({ environmentId, input: {} }),
50 resolve,
51 );
52 return {
53 state: query.data ?? EMPTY_DEVICE_STATE,
54 loaded: query.data !== null,
55 error: query.error,
56 refresh: query.refresh,
57 };
59​
60const deviceHubAccessAtom = Atom.family((environmentId: EnvironmentId) =>
61 connectionAtomRuntime
62 .atom((get) => {
63 const prepared = Option.getOrNull(
64 get(environmentSession.preparedConnectionValueAtom(environmentId)),
65 );
66 if (prepared === null) return Effect.never;
67 return resolveDeviceHubAccess({ prepared, hubBasePath: EMPTY_DEVICE_STATE.hubBasePath });
68 })
69 .pipe(Atom.setIdleTTL(60_000), Atom.withLabel(`device-hub-access:${environmentId}`)),
70);
71​
72export function useDeviceHubAccess(
73 environmentId: EnvironmentId | null,
74 hostId = "local",
75): DeviceHubAccess | null {
76 const result = useAtomValue(
77 environmentId === null ? EMPTY_ACCESS_ATOM : deviceHubAccessAtom(environmentId),
78 );
79 return AsyncResult.isSuccess(result)
80 ? { ...result.value, query: { ...result.value.query, hostId } }
81 : null;
83​
84const EMPTY_ACCESS_ATOM = Atom.make(AsyncResult.initial<DeviceHubAccess, never>()).pipe(
85 Atom.withLabel("device-hub-access:empty"),
86);
87​
88export function refreshDeviceHubAccess(environmentId: EnvironmentId): void {
89 appAtomRegistry.refresh(deviceHubAccessAtom(environmentId));
91​
92/** Mints a fresh hub ticket for a one-off request that failed with 401. Resolves null on failure. */
93export function renewDeviceHubAccess(
94 environmentId: EnvironmentId,
95 hostId = "local",
96): Promise<DeviceHubAccess | null> {
97 const atom = deviceHubAccessAtom(environmentId);
98 appAtomRegistry.refresh(atom);
99 return Effect.runPromise(
100 AtomRegistry.getResult(appAtomRegistry, atom, { suspendOnWaiting: true }).pipe(
101 Effect.map((access) => ({ ...access, query: { ...access.query, hostId } })),
102 Effect.timeout("10 seconds"),
103 Effect.orElseSucceed(() => null),
104 ),
105 );
107​
108export interface DeviceDetailKey {
109 readonly environmentId: EnvironmentId;
110 readonly hostId: string;
111 readonly deviceId: string;
113​
114export interface DeviceDetailView {
115 /** Settings the host last confirmed, by a read or by an action's answer. */
116 readonly detail: DeviceDetail | null;
117 readonly error: string | null;
119​
120export const deviceDetailAtom = Atom.family((key: DeviceDetailKey) =>
121 Atom.make<DeviceDetailView>({ detail: null, error: null }).pipe(
122 Atom.withLabel(`device-detail:${key.hostId}:${key.deviceId}`),
123 ),
124);
125​
126/**
127 * Reads a device's settings into its detail view while mounted. Reads and
128 * actions share one serial lane per environment, so a read never answers
129 * before an action that was sent ahead of it.
130 */
131export const deviceDetailReadAtom = Atom.family((key: DeviceDetailKey) =>
132 Atom.make((get) =>
133 Effect.promise(() =>
134 runAtomCommand(
135 get.registry,
136 deviceEnvironment.detail,
137 { environmentId: key.environmentId, input: { hostId: key.hostId, deviceId: key.deviceId } },
138 { reportFailure: false },
139 ),
140 ).pipe(
141 Effect.map((result) =>
142 get.set(
143 deviceDetailAtom(key),
144 result._tag === "Success"
145 ? { detail: result.value, error: null }
146 : { detail: null, error: formatEnvironmentQueryError(result.cause) },
147 ),
148 ),
149 ),
150 ).pipe(Atom.withLabel(`device-detail-read:${key.hostId}:${key.deviceId}`)),
151);
152​
153/**
154 * Probes the environment's device hosts while mounted. Remote hosts report
155 * their platforms only after a probe. Probing never installs or starts helpers.
156 */
157export const deviceHostProbeAtom = Atom.family((environmentId: EnvironmentId) =>
158 Atom.make((get) =>
159 Effect.promise(() =>
160 runAtomCommand(
161 get.registry,
162 deviceEnvironment.list,
163 { environmentId, input: {} },
164 { reportFailure: false },
165 ),
166 ).pipe(Effect.asVoid),
167 ).pipe(Atom.withLabel(`device-host-probe:${environmentId}`)),
168);
169​
170export const NO_DEVICE_PROBE_ATOM = Atom.make(AsyncResult.initial<void, never>()).pipe(
171 Atom.withLabel("device-host-probe:none"),
172);
173​
174/**
175 * The Expo account an Expo host editor shows as it opens, for the saved
176 * credential. Each open checks again; edits and manual checks use the command.
177 */
178export const deviceEasAccountCheck = createEnvironmentRpcQueryAtomFamily(connectionAtomRuntime, {
179 label: "environment-data:device:eas-account-check",
180 tag: WS_METHODS.deviceEasAccount,
181 staleTimeMs: 0,
182 idleTtlMs: 0,
183});
184​
185/** Who a Simlock token is, checked as the host editor's URL and token fields change. */
186export const deviceSimlockIdentityCheck = createEnvironmentRpcQueryAtomFamily(
187 connectionAtomRuntime,
188 {
189 label: "environment-data:device:simlock-identity-check",
190 tag: WS_METHODS.deviceSimlockIdentity,
191 staleTimeMs: 0,
192 idleTtlMs: 0,
193 },
194);