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 { mobileApplicationActiveWakeup } from "./app-state-wakeups";
31import { connectionStorageLayer } 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 connectivityLayer = 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
85const wakeupsLayer = Wakeups.layer({
86 changes: Stream.merge(
87 Stream.callback<"application-active-probe" | "application-active-reconnect">((queue) =>
88 Effect.acquireRelease(
89 Effect.sync(() => {
90 let backgroundedAtMs = AppState.currentState === "background" ? Date.now() : null;
91 return AppState.addEventListener("change", (state) => {
92 if (state === "background") {
93 backgroundedAtMs = Date.now();
94 return;
95 }
96 if (state === "active") {
97 Queue.offerUnsafe(queue, mobileApplicationActiveWakeup(backgroundedAtMs, Date.now()));
98 backgroundedAtMs = null;
99 }
100 });
101 }),
102 (subscription) => Effect.sync(() => subscription.remove()),
103 ).pipe(Effect.asVoid),
104 ),
105 managedRelayAccountChanges(appAtomRegistry).pipe(
106 Stream.map(() => "credentials-changed" as const),
107 ),
108 ),
109});
110
111const capabilitiesLayer = Layer.effectContext(
112 Effect.gen(function* () {
113 const storage = yield* MobileStorage.MobileStorage;
114 return Context.make(
115 ClientCapabilities.CloudSession,
116 ClientCapabilities.CloudSession.of({
117 identity: Effect.sync(() =>
118 Option.fromNullishOr(appAtomRegistry.get(managedRelaySessionAtom)),
119 ),
120 clerkToken: Effect.gen(function* () {
121 const session = appAtomRegistry.get(managedRelaySessionAtom);
122 if (session === null) {
123 return yield* new ConnectionBlockedError({
124 reason: "authentication",
125 detail: "Sign in to T3 Connect to connect this environment.",
126 });
127 }
128 const token = yield* session.readClerkToken().pipe(
129 Effect.mapError(
130 (error) =>
131 new ConnectionTransientError({
132 reason: "network",
133 detail: error.message,
134 }),
135 ),
136 );
137 if (token === null) {
138 return yield* new ConnectionBlockedError({
139 reason: "authentication",
140 detail: "The T3 Connect session is unavailable.",
141 });
142 }
143 return token;
144 }),
145 }),
146 ).pipe(
147 Context.add(
148 ClientCapabilities.PrimaryEnvironmentAuth,
149 ClientCapabilities.PrimaryEnvironmentAuth.of({
150 bearerToken: Effect.succeed(Option.none()),
151 }),
152 ),
153 Context.add(
154 ClientCapabilities.RelayDeviceIdentity,
155 ClientCapabilities.RelayDeviceIdentity.of({
156 deviceId: storage.loadOrCreateAgentAwarenessDeviceId.pipe(
157 Effect.mapError(
158 (cause) =>
159 new ConnectionTransientError({
160 reason: "remote-unavailable",
161 detail: `Could not load the mobile device identity: ${String(cause)}`,
162 }),
163 ),
164 Effect.map(Option.some),
165 ),
166 }),
167 ),
168 Context.add(
169 ClientCapabilities.ClientPresentation,
170 ClientCapabilities.ClientPresentation.of({
171 metadata: authClientMetadata(Constants.expoConfig?.version),
172 scopes: AuthStandardClientScopes,
173 }),
174 ),
175 Context.add(
176 ClientCapabilities.SshEnvironmentGateway,
177 ClientCapabilities.SshEnvironmentGateway.of({
178 provision: () =>
179 Effect.fail(
180 new ConnectionBlockedError({
181 reason: "unsupported",
182 detail: "SSH environments are only available in the desktop app.",
183 }),
184 ),
185 prepare: () =>
186 Effect.fail(
187 new ConnectionBlockedError({
188 reason: "unsupported",
189 detail: "SSH environments are only available in the desktop app.",
190 }),
191 ),
192 disconnect: () => Effect.void,
193 }),
194 ),
195 );
196 }),
197);
198
199const platformConnectionSourceLayer = Layer.succeed(
200 PlatformConnectionSource.PlatformConnectionSource,
201 PlatformConnectionSource.PlatformConnectionSource.of({
202 registrations: Stream.empty,
203 }),
204);
205
206const providedConnectionStorageLayer = connectionStorageLayer.pipe(
207 Layer.provide(Runtime.runtimeContextLayer),
208);
209const providedCapabilitiesLayer = capabilitiesLayer.pipe(
210 Layer.provide(Runtime.runtimeContextLayer),
211);
212
213const environmentOwnedDataCleanupLayer = Layer.succeed(
214 Persistence.EnvironmentOwnedDataCleanup,
215 Persistence.EnvironmentOwnedDataCleanup.of({
216 clear: (environmentId) =>
217 Effect.all(
218 [
219 Effect.promise(() => clearThreadOutboxEnvironment(environmentId)),
220 Effect.promise(() => clearComposerDraftsEnvironment(environmentId)),
221 ],
222 { concurrency: "unbounded", discard: true },
223 ).pipe(
224 Effect.catch((cause) =>
225 Effect.logWarning("Could not clear mobile environment-owned data.", {
226 environmentId,
227 cause,
228 }),
229 ),
230 ),
231 }),
232);
233
234type ConnectionPlatformLayerSource =
235 | typeof providedConnectionStorageLayer
236 | typeof Runtime.runtimeContextLayer
237 | typeof connectivityLayer
238 | typeof wakeupsLayer
239 | typeof providedCapabilitiesLayer
240 | typeof platformConnectionSourceLayer
241 | typeof environmentOwnedDataCleanupLayer;
242
243export const connectionPlatformLayer: Layer.Layer<
244 Layer.Success<ConnectionPlatformLayerSource>,
245 Layer.Error<ConnectionPlatformLayerSource>,
246 Layer.Services<ConnectionPlatformLayerSource>
247> = Layer.mergeAll(
248 providedConnectionStorageLayer,
249 Runtime.runtimeContextLayer,
250 connectivityLayer,
251 wakeupsLayer,
252 providedCapabilitiesLayer,
253 platformConnectionSourceLayer,
254 environmentOwnedDataCleanupLayer,
255);