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