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 const wakeup = mobileApplicationActiveWakeup(backgroundedAtMs, Date.now());
130 if (wakeup !== null) Queue.offerUnsafe(queue, wakeup);
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: m(
162 msg("Sign in to {product} to connect this environment.", { product: "T3 Connect" }),
163 ),
164 });
165 }
166 const token = yield* session.readClerkToken().pipe(
167 Effect.mapError(
168 (error) =>
169 new ConnectionTransientError({
170 reason: "network",
171 detail: error.message,
172 }),
173 ),
174 );
175 if (token === null) {
176 return yield* new ConnectionBlockedError({
177 reason: "authentication",
178 detail: m(msg("The {product} session is unavailable.", { product: "T3 Connect" })),
179 });
180 }
181 return token;
182 }),
183 }),
184 ).pipe(
185 Context.add(
186 ClientCapabilities.PrimaryEnvironmentAuth,
187 ClientCapabilities.PrimaryEnvironmentAuth.of({
188 bearerToken: Effect.succeedNone,
189 }),
190 ),
191 Context.add(ClientCapabilities.AnalyticsDevice, {
192 id: storage.loadOrCreateAnalyticsDeviceId.pipe(Effect.option),
193 }),
194 Context.add(
195 ClientCapabilities.RelayDeviceIdentity,
196 ClientCapabilities.RelayDeviceIdentity.of({
197 deviceId: storage.loadOrCreateAgentAwarenessDeviceId.pipe(
198 Effect.mapError(
199 (cause) =>
200 new ConnectionTransientError({
201 reason: "remote-unavailable",
202 detail: m(
203 msg("Could not load the mobile device identity: {cause}", {
204 cause: String(cause),
205 }),
206 ),
207 }),
208 ),
209 Effect.asSome,
210 ),
211 }),
212 ),
213 Context.add(
214 ClientCapabilities.ClientPresentation,
215 ClientCapabilities.ClientPresentation.of({
216 metadata: authClientMetadata(Constants.expoConfig?.version),
217 }),
218 ),
219 Context.add(
220 ClientCapabilities.SshEnvironmentGateway,
221 ClientCapabilities.SshEnvironmentGateway.of({
222 provision: Effect.fn("ClientCapabilities.SshEnvironmentGateway.provision")(() =>
223 Effect.fail(
224 new ConnectionBlockedError({
225 reason: "unsupported",
226 detail: m(
227 msg("{feature} environments are only available in the desktop app.", {
228 feature: "SSH",
229 }),
230 ),
231 }),
232 ),
233 ),
234 prepare: Effect.fn("ClientCapabilities.SshEnvironmentGateway.prepare")(() =>
235 Effect.fail(
236 new ConnectionBlockedError({
237 reason: "unsupported",
238 detail: m(
239 msg("{feature} environments are only available in the desktop app.", {
240 feature: "SSH",
241 }),
242 ),
243 }),
244 ),
245 ),
246 disconnect: Effect.fn("ClientCapabilities.SshEnvironmentGateway.disconnect")(
247 () => Effect.void,
248 ),
249 }),
250 ),
251 );
252 }),
253);
254
255const layerPlatformConnectionSource = Layer.succeed(
256 PlatformConnectionSource.PlatformConnectionSource,
257 PlatformConnectionSource.PlatformConnectionSource.of({
258 registrations: Stream.empty,
259 }),
260);
261
262const layerProvidedConnectionStorage = ConnectionStorage.layer.pipe(Layer.provide(Runtime.layer));
263const layerProvidedCapabilities = layerCapabilities.pipe(Layer.provide(Runtime.layer));
264
265type ConnectionPlatformLayerSource =
266 | typeof layerProvidedConnectionStorage
267 | typeof Runtime.layer
268 | typeof layerConnectivity
269 | typeof layerWakeups
270 | typeof layerProvidedCapabilities
271 | typeof layerPlatformConnectionSource
272 | typeof EnvironmentOwnedDataCleanup.layer;
273
274export const layer: Layer.Layer<
275 Layer.Success<ConnectionPlatformLayerSource>,
276 Layer.Error<ConnectionPlatformLayerSource>,
277 Layer.Services<ConnectionPlatformLayerSource>
278> = Layer.mergeAll(
279 layerProvidedConnectionStorage,
280 Runtime.layer,
281 layerConnectivity,
282 layerWakeups,
283 layerProvidedCapabilities,
284 layerPlatformConnectionSource,
285 EnvironmentOwnedDataCleanup.layer,
286);