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