Open History to see the last commit
1import { ClientCapabilities, PlatformConnectionSource } from "@t3tools/client-runtime/platform";
2import {
3 ConnectionBlockedError,
4 ConnectionTransientError,
5 Connectivity,
6 Wakeups,
7} from "@t3tools/client-runtime/connection";
8import { managedRelayAccountChanges, managedRelaySessionAtom } from "@t3tools/client-runtime/relay";
9import * as Clock from "effect/Clock";
10import * as Context from "effect/Context";
11import * as Effect from "effect/Effect";
12import * as Layer from "effect/Layer";
13import * as Option from "effect/Option";
14import * as Queue from "effect/Queue";
15import * as Stream from "effect/Stream";
16import Constants from "expo-constants";
17import * as Network from "expo-network";
18import { AppState } from "react-native";
19
20import { authClientMetadata } from "../lib/authClientMetadata";
21import * as Runtime from "../lib/runtime";
22import * as MobileStorage from "../persistence/mobile-storage";
23import { appAtomRegistry } from "../state/atom-registry";
24import { mobileApplicationActiveWakeup } from "./app-state-wakeups";
25import * as EnvironmentOwnedDataCleanup from "./environment-owned-data-cleanup";
26import * as ConnectionStorage from "./storage";
27
28function networkStatus(state: Network.NetworkState): "unknown" | "offline" | "online" {
29 if (state.isConnected === false) {
30 return "offline";
31 }
32 if (state.isConnected === true) {
33 return "online";
34 }
35 return "unknown";
36}
37
38const layerConnectivity = Connectivity.layer({
39 status: Effect.tryPromise({
40 try: () => Network.getNetworkStateAsync(),
41 catch: () => undefined,
42 }).pipe(
43 Effect.match({
44 onFailure: () => "unknown" as const,
45 onSuccess: networkStatus,
46 }),
47 ),
48 changes: Stream.callback((queue) =>
49 Effect.acquireRelease(
50 Effect.sync(() => {
51 let active = true;
52 const networkSubscription = Network.addNetworkStateListener((state) => {
53 Queue.offerUnsafe(queue, networkStatus(state));
54 });
55 const appStateSubscription = AppState.addEventListener("change", (state) => {
56 if (state !== "active") {
57 return;
58 }
59 void Network.getNetworkStateAsync()
60 .then((current) => {
61 if (active) {
62 Queue.offerUnsafe(queue, networkStatus(current));
63 }
64 })
65 .catch(() => undefined);
66 });
67 return {
68 close: () => {
69 active = false;
70 networkSubscription.remove();
71 appStateSubscription.remove();
72 },
73 };
74 }),
75 ({ close }) => Effect.sync(close),
76 ).pipe(Effect.asVoid),
77 ),
78});
79
80/** Wake connections on network path changes; online/offline misses Wi-Fi-to-cellular moves. */
81const networkPathChanges = Stream.callback<"network-changed">((queue) =>
82 Effect.acquireRelease(
83 Effect.sync(() => {
84 let active = true;
85 let previous: Network.NetworkStateType | undefined;
86 const record = (state: Network.NetworkState) => {
87 const type = state.isConnected === true ? state.type : undefined;
88 if (previous !== undefined && type !== undefined && type !== previous) {
89 Queue.offerUnsafe(queue, "network-changed");
90 }
91 previous = type ?? previous;
92 };
93 // Seed the current type: the listener reports only changes and would miss the first move.
94 void Network.getNetworkStateAsync()
95 .then((state) => {
96 if (active && previous === undefined && state.isConnected === true) {
97 previous = state.type;
98 }
99 })
100 .catch(() => undefined);
101 const subscription = Network.addNetworkStateListener(record);
102 return {
103 remove: () => {
104 active = false;
105 subscription.remove();
106 },
107 };
108 }),
109 (subscription) => Effect.sync(() => subscription.remove()),
110 ).pipe(Effect.asVoid),
111);
112
113const layerWakeups = Wakeups.layer({
114 changes: Stream.mergeAll(
115 [
116 Stream.callback<"application-active-probe" | "application-active-long">((queue) =>
117 Effect.acquireRelease(
118 Effect.gen(function* () {
119 const nowMs = yield* Clock.currentTimeMillis;
120 let backgroundedAtMs = AppState.currentState === "background" ? nowMs : null;
121 return AppState.addEventListener("change", (state) => {
122 if (state === "background") {
123 backgroundedAtMs = Date.now();
124 return;
125 }
126 if (state === "active") {
127 Queue.offerUnsafe(
128 queue,
129 mobileApplicationActiveWakeup(backgroundedAtMs, Date.now()),
130 );
131 backgroundedAtMs = null;
132 }
133 });
134 }),
135 (subscription) => Effect.sync(() => subscription.remove()),
136 ).pipe(Effect.asVoid),
137 ),
138 managedRelayAccountChanges(appAtomRegistry).pipe(
139 Stream.map(() => "credentials-changed" as const),
140 ),
141 networkPathChanges,
142 ],
143 { concurrency: "unbounded" },
144 ),
145});
146
147const layerCapabilities = Layer.effectContext(
148 Effect.gen(function* () {
149 const storage = yield* MobileStorage.MobileStorage;
150 return Context.make(
151 ClientCapabilities.CloudSession,
152 ClientCapabilities.CloudSession.of({
153 identity: Effect.sync(() =>
154 Option.fromNullishOr(appAtomRegistry.get(managedRelaySessionAtom)),
155 ),
156 clerkToken: Effect.gen(function* () {
157 const session = appAtomRegistry.get(managedRelaySessionAtom);
158 if (session === null) {
159 return yield* new ConnectionBlockedError({
160 reason: "authentication",
161 detail: "Sign in to T3 Connect to connect this environment.",
162 });
163 }
164 const token = yield* session.readClerkToken().pipe(
165 Effect.mapError(
166 (error) =>
167 new ConnectionTransientError({
168 reason: "network",
169 detail: error.message,
170 }),
171 ),
172 );
173 if (token === null) {
174 return yield* new ConnectionBlockedError({
175 reason: "authentication",
176 detail: "The T3 Connect session is unavailable.",
177 });
178 }
179 return token;
180 }),
181 }),
182 ).pipe(
183 Context.add(
184 ClientCapabilities.PrimaryEnvironmentAuth,
185 ClientCapabilities.PrimaryEnvironmentAuth.of({
186 bearerToken: Effect.succeedNone,
187 }),
188 ),
189 // The relay device id already persists in secure storage; analytics only sends its hash.
190 Context.add(ClientCapabilities.AnalyticsDevice, {
191 id: storage.loadOrCreateAgentAwarenessDeviceId.pipe(Effect.option),
192 }),
193 Context.add(
194 ClientCapabilities.RelayDeviceIdentity,
195 ClientCapabilities.RelayDeviceIdentity.of({
196 deviceId: storage.loadOrCreateAgentAwarenessDeviceId.pipe(
197 Effect.mapError(
198 (cause) =>
199 new ConnectionTransientError({
200 reason: "remote-unavailable",
201 detail: `Could not load the mobile device identity: ${String(cause)}`,
202 }),
203 ),
204 Effect.asSome,
205 ),
206 }),
207 ),
208 Context.add(
209 ClientCapabilities.ClientPresentation,
210 ClientCapabilities.ClientPresentation.of({
211 metadata: authClientMetadata(Constants.expoConfig?.version),
212 }),
213 ),
214 Context.add(
215 ClientCapabilities.SshEnvironmentGateway,
216 ClientCapabilities.SshEnvironmentGateway.of({
217 provision: Effect.fn("ClientCapabilities.SshEnvironmentGateway.provision")(() =>
218 Effect.fail(
219 new ConnectionBlockedError({
220 reason: "unsupported",
221 detail: "SSH environments are only available in the desktop app.",
222 }),
223 ),
224 ),
225 prepare: Effect.fn("ClientCapabilities.SshEnvironmentGateway.prepare")(() =>
226 Effect.fail(
227 new ConnectionBlockedError({
228 reason: "unsupported",
229 detail: "SSH environments are only available in the desktop app.",
230 }),
231 ),
232 ),
233 disconnect: Effect.fn("ClientCapabilities.SshEnvironmentGateway.disconnect")(
234 () => Effect.void,
235 ),
236 }),
237 ),
238 );
239 }),
240);
241
242const layerPlatformConnectionSource = Layer.succeed(
243 PlatformConnectionSource.PlatformConnectionSource,
244 PlatformConnectionSource.PlatformConnectionSource.of({
245 registrations: Stream.empty,
246 }),
247);
248
249const layerProvidedConnectionStorage = ConnectionStorage.layer.pipe(Layer.provide(Runtime.layer));
250const layerProvidedCapabilities = layerCapabilities.pipe(Layer.provide(Runtime.layer));
251
252type ConnectionPlatformLayerSource =
253 | typeof layerProvidedConnectionStorage
254 | typeof Runtime.layer
255 | typeof layerConnectivity
256 | typeof layerWakeups
257 | typeof layerProvidedCapabilities
258 | typeof layerPlatformConnectionSource
259 | typeof EnvironmentOwnedDataCleanup.layer;
260
261export const layer: Layer.Layer<
262 Layer.Success<ConnectionPlatformLayerSource>,
263 Layer.Error<ConnectionPlatformLayerSource>,
264 Layer.Services<ConnectionPlatformLayerSource>
265> = Layer.mergeAll(
266 layerProvidedConnectionStorage,
267 Runtime.layer,
268 layerConnectivity,
269 layerWakeups,
270 layerProvidedCapabilities,
271 layerPlatformConnectionSource,
272 EnvironmentOwnedDataCleanup.layer,
273);