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(msg`Sign in to ${{ product: "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: m(msg`The ${{ product: "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 Context.add(ClientCapabilities.AnalyticsDevice, {
190 id: storage.loadOrCreateAnalyticsDeviceId.pipe(Effect.option),
191 }),
192 Context.add(
193 ClientCapabilities.RelayDeviceIdentity,
194 ClientCapabilities.RelayDeviceIdentity.of({
195 deviceId: storage.loadOrCreateAgentAwarenessDeviceId.pipe(
196 Effect.mapError(
197 (cause) =>
198 new ConnectionTransientError({
199 reason: "remote-unavailable",
200 detail: m(
201 msg`Could not load the mobile device identity: ${{ cause: String(cause) }}`,
202 ),
203 }),
204 ),
205 Effect.asSome,
206 ),
207 }),
208 ),
209 Context.add(
210 ClientCapabilities.ClientPresentation,
211 ClientCapabilities.ClientPresentation.of({
212 metadata: authClientMetadata(Constants.expoConfig?.version),
213 }),
214 ),
215 Context.add(
216 ClientCapabilities.SshEnvironmentGateway,
217 ClientCapabilities.SshEnvironmentGateway.of({
218 provision: Effect.fn("ClientCapabilities.SshEnvironmentGateway.provision")(() =>
219 Effect.fail(
220 new ConnectionBlockedError({
221 reason: "unsupported",
222 detail: m(
223 msg`${{ feature: "SSH" }} environments are only available in the desktop app.`,
224 ),
225 }),
226 ),
227 ),
228 prepare: Effect.fn("ClientCapabilities.SshEnvironmentGateway.prepare")(() =>
229 Effect.fail(
230 new ConnectionBlockedError({
231 reason: "unsupported",
232 detail: m(
233 msg`${{ feature: "SSH" }} environments are only available in the desktop app.`,
234 ),
235 }),
236 ),
237 ),
238 disconnect: Effect.fn("ClientCapabilities.SshEnvironmentGateway.disconnect")(
239 () => Effect.void,
240 ),
241 }),
242 ),
243 );
244 }),
245);
246
247const layerPlatformConnectionSource = Layer.succeed(
248 PlatformConnectionSource.PlatformConnectionSource,
249 PlatformConnectionSource.PlatformConnectionSource.of({
250 registrations: Stream.empty,
251 }),
252);
253
254const layerProvidedConnectionStorage = ConnectionStorage.layer.pipe(Layer.provide(Runtime.layer));
255const layerProvidedCapabilities = layerCapabilities.pipe(Layer.provide(Runtime.layer));
256
257type ConnectionPlatformLayerSource =
258 | typeof layerProvidedConnectionStorage
259 | typeof Runtime.layer
260 | typeof layerConnectivity
261 | typeof layerWakeups
262 | typeof layerProvidedCapabilities
263 | typeof layerPlatformConnectionSource
264 | typeof EnvironmentOwnedDataCleanup.layer;
265
266export const layer: Layer.Layer<
267 Layer.Success<ConnectionPlatformLayerSource>,
268 Layer.Error<ConnectionPlatformLayerSource>,
269 Layer.Services<ConnectionPlatformLayerSource>
270> = Layer.mergeAll(
271 layerProvidedConnectionStorage,
272 Runtime.layer,
273 layerConnectivity,
274 layerWakeups,
275 layerProvidedCapabilities,
276 layerPlatformConnectionSource,
277 EnvironmentOwnedDataCleanup.layer,
278);