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