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

use-remote-environment-registry.ts

233 lines8.2 KB

1import { useAtomValue } from "@effect/atom-react";
2import type { PreparedConnection } from "@t3tools/client-runtime/connection";
3import type { EnvironmentId } from "@t3tools/contracts";
4import type { ServerConfig } from "@t3tools/contracts";
5import * as Cause from "effect/Cause";
6import * as Option from "effect/Option";
7import { AsyncResult, Atom } from "effect/unstable/reactivity";
8import { useCallback, useMemo } from "react";
9import { Alert } from "react-native";
10​
11import { useEnvironmentServerConfig } from "../state/entities";
12import { useConnectionController } from "../features/connection/useConnectionController";
13import { environmentPresentations, useEnvironmentPresentation } from "./presentation";
14import {
15 projectEnvironmentPresentation,
16 type EnvironmentPresentation,
17} from "../state/environments";
18import { useWorkspaceState } from "../state/workspace";
19import type { SavedRemoteConnection } from "../lib/connection";
20import { appAtomRegistry } from "./atom-registry";
21import type { ConnectedEnvironmentSummary, EnvironmentRuntimeState } from "./remote-runtime-types";
22import { environmentSession, usePreparedConnection } from "./session";
23import { environmentCatalog } from "../connection/catalog";
24​
25const connectionPairingUrlAtom = Atom.make("").pipe(
26 Atom.keepAlive,
27 Atom.withLabel("mobile:connection-pairing-url"),
28);
29​
30const pendingConnectionErrorAtom = Atom.make<string | null>(null).pipe(
31 Atom.keepAlive,
32 Atom.withLabel("mobile:pending-connection-error"),
33);
34​
35export function setPendingConnectionError(message: string | null): void {
36 appAtomRegistry.set(pendingConnectionErrorAtom, message);
38​
39function toSavedConnection(
40 environment: EnvironmentPresentation,
41 prepared: Option.Option<PreparedConnection>,
42): SavedRemoteConnection {
43 const displayUrl = environment.displayUrl ?? "";
44 const active = Option.getOrNull(prepared);
45 const httpBaseUrl = active?.httpBaseUrl ?? displayUrl;
46 const socketUrl = active?.socketUrl ?? "";
47 const wsBaseUrl =
48 socketUrl === ""
49 ? displayUrl.startsWith("https://")
50 ? displayUrl.replace(/^https:/, "wss:")
51 : displayUrl.replace(/^http:/, "ws:")
52 : new URL(socketUrl).origin;
53 const authorization = active?.httpAuthorization ?? null;
54​
55 return {
56 environmentId: environment.environmentId,
57 environmentLabel: environment.label,
58 pairingUrl: displayUrl,
59 displayUrl,
60 httpBaseUrl,
61 wsBaseUrl,
62 bearerToken: authorization?._tag === "Bearer" ? authorization.token : null,
63 ...(environment.relayManaged
64 ? {
65 authenticationMethod: "dpop" as const,
66 relayManaged: true as const,
67 ...(authorization?._tag === "Dpop" ? { dpopAccessToken: authorization.accessToken } : {}),
68 }
69 : { authenticationMethod: "bearer" as const }),
70 };
72​
73const savedConnectionsByIdAtom = Atom.make((get) => {
74 const presentationById = get(environmentPresentations.presentationsAtom);
75 return Object.fromEntries(
76 [...presentationById.entries()].map(([environmentId, presentation]) => [
77 environmentId,
78 toSavedConnection(
79 projectEnvironmentPresentation(environmentId, presentation),
80 get(environmentSession.preparedConnectionValueAtom(environmentId)),
81 ),
82 ]),
83 ) as Record<EnvironmentId, SavedRemoteConnection>;
84}).pipe(Atom.withLabel("mobile:saved-connections-by-id"));
85​
86function toRuntimeState(
87 environment: EnvironmentPresentation,
88 serverConfig: ServerConfig | null,
89): EnvironmentRuntimeState {
90 return {
91 connectionState: environment.connection.phase,
92 connectionError: environment.connection.error,
93 connectionErrorTraceId: environment.connection.traceId,
94 serverConfig,
95 };
97​
98export function useSavedRemoteConnections() {
99 const catalog = useAtomValue(environmentCatalog.catalogValueAtom);
100 const savedConnectionsById = useAtomValue(savedConnectionsByIdAtom);
101​
102 return {
103 isLoadingSavedConnection: !catalog.isReady,
104 savedConnectionsById,
105 };
107​
108export function useSavedRemoteConnection(
109 environmentId: EnvironmentId | null,
110): SavedRemoteConnection | null {
111 const { presentation } = useEnvironmentPresentation(environmentId);
112 const prepared = usePreparedConnection(environmentId);
113 if (environmentId === null || presentation === null) {
114 return null;
115 }
116 return toSavedConnection(projectEnvironmentPresentation(environmentId, presentation), prepared);
118​
119export function useRemoteEnvironmentRuntime(
120 environmentId: EnvironmentId | null,
121): EnvironmentRuntimeState | null {
122 const { presentation } = useEnvironmentPresentation(environmentId);
123 const serverConfig = useEnvironmentServerConfig(environmentId);
124 if (environmentId === null || presentation === null) {
125 return null;
126 }
127 return toRuntimeState(projectEnvironmentPresentation(environmentId, presentation), serverConfig);
129​
130export function useRemoteConnectionStatus() {
131 const workspace = useWorkspaceState();
132 const pendingConnectionError = useAtomValue(pendingConnectionErrorAtom);
133 const connectedEnvironments = useMemo<ReadonlyArray<ConnectedEnvironmentSummary>>(
134 () =>
135 workspace.environments.map((environment) => ({
136 environmentId: environment.environmentId,
137 environmentLabel: environment.environmentLabel,
138 displayUrl: environment.displayUrl,
139 isRelayManaged: environment.isRelayManaged,
140 connectionState: environment.connectionState,
141 connectionError: environment.connectionError,
142 connectionErrorTraceId: environment.connectionErrorTraceId,
143 })),
144 [workspace.environments],
145 );
146​
147 return {
148 connectedEnvironments,
149 connectionState: workspace.state.connectionState,
150 connectionError: pendingConnectionError ?? workspace.state.connectionError,
151 };
153​
154export function useRemoteConnections() {
155 const controller = useConnectionController();
156 const connectionPairingUrl = useAtomValue(connectionPairingUrlAtom);
157 const pendingConnectionError = useAtomValue(pendingConnectionErrorAtom);
158 const { connectedEnvironments, connectionError, connectionState } = useRemoteConnectionStatus();
159​
160 const onChangeConnectionPairingUrl = useCallback((pairingUrl: string) => {
161 appAtomRegistry.set(connectionPairingUrlAtom, pairingUrl);
162 }, []);
163​
164 const onConnectPress = useCallback(
165 async (pairingUrl?: string) => {
166 const nextPairingUrl = pairingUrl ?? connectionPairingUrl;
167 setPendingConnectionError(null);
168 const result = await controller.connectPairingUrl(nextPairingUrl);
169 if (AsyncResult.isFailure(result)) {
170 const error = Cause.squash(result.cause);
171 const message =
172 error instanceof Error ? error.message : "Failed to pair with the environment.";
173 setPendingConnectionError(message);
174 } else {
175 appAtomRegistry.set(connectionPairingUrlAtom, "");
176 }
177 return result;
178 },
179 [connectionPairingUrl, controller],
180 );
181​
182 const onReconnectEnvironment = useCallback(
183 (environmentId: EnvironmentId) => controller.retryEnvironment(environmentId),
184 [controller],
185 );
186 const onUpdateEnvironment = useCallback(
187 (
188 environmentId: EnvironmentId,
189 updates: { readonly label: string; readonly displayUrl: string },
190 ) => controller.updateEnvironment(environmentId, updates),
191 [controller],
192 );
193​
194 const onRemoveEnvironmentPress = useCallback(
195 (environmentId: EnvironmentId) => {
196 const environment = connectedEnvironments.find(
197 (candidate) => candidate.environmentId === environmentId,
198 );
199 if (!environment) {
200 return;
201 }
202 Alert.alert(
203 "Remove environment?",
204 `Disconnect and forget ${environment.environmentLabel} on this device.`,
205 [
206 { text: "Cancel", style: "cancel" },
207 {
208 text: "Remove",
209 style: "destructive",
210 onPress: () => {
211 void controller.removeEnvironment(environmentId);
212 },
213 },
214 ],
215 );
216 },
217 [connectedEnvironments, controller],
218 );
219​
220 return {
221 connectionPairingUrl,
222 connectionState,
223 connectionError,
224 pairingConnectionError: pendingConnectionError,
225 connectedEnvironments,
226 connectedEnvironmentCount: connectedEnvironments.length,
227 onChangeConnectionPairingUrl,
228 onConnectPress,
229 onReconnectEnvironment,
230 onUpdateEnvironment,
231 onRemoveEnvironmentPress,
232 };