Open History to see the last commit
1import {
2 ClientPresentation,
3 CloudSession,
4 EnvironmentOwnedDataCleanup,
5 PlatformConnectionSource,
6 PrimaryEnvironmentAuth,
7 RelayDeviceIdentity,
8 SshEnvironmentGateway,
9} from "@t3tools/client-runtime/platform";
10import {
11 ConnectionBlockedError,
12 ConnectionTransientError,
13 Connectivity,
14 Wakeups,
15} from "@t3tools/client-runtime/connection";
16import { managedRelayAccountChanges, managedRelaySessionAtom } from "@t3tools/client-runtime/relay";
17import { AuthStandardClientScopes } from "@t3tools/contracts";
18import * as Context from "effect/Context";
19import * as Effect from "effect/Effect";
20import * as Layer from "effect/Layer";
21import * as Option from "effect/Option";
22import * as Queue from "effect/Queue";
23import * as Stream from "effect/Stream";
24import * as Network from "expo-network";
25import { AppState } from "react-native";
26
27import { authClientMetadata } from "../lib/authClientMetadata";
28import * as Runtime from "../lib/runtime";
29import * as MobileStorage from "../persistence/mobile-storage";
30import { appAtomRegistry } from "../state/atom-registry";
31import { clearThreadOutboxEnvironment } from "../state/thread-outbox";
32import { clearComposerDraftsEnvironment } from "../state/use-composer-drafts";
33import { connectionStorageLayer } from "./storage";
34
35function networkStatus(state: Network.NetworkState): "unknown" | "offline" | "online" {
36 if (state.isConnected === false || state.isInternetReachable === false) {
37 return "offline";
38 }
39 if (state.isConnected === true) {
40 return "online";
41 }
42 return "unknown";
43}
44
45const connectivityLayer = Connectivity.layer({
46 status: Effect.tryPromise({
47 try: () => Network.getNetworkStateAsync(),
48 catch: () => undefined,
49 }).pipe(
50 Effect.match({
51 onFailure: () => "unknown" as const,
52 onSuccess: networkStatus,
53 }),
54 ),
55 changes: Stream.callback((queue) =>
56 Effect.acquireRelease(
57 Effect.sync(() =>
58 Network.addNetworkStateListener((state) => {
59 Queue.offerUnsafe(queue, networkStatus(state));
60 }),
61 ),
62 (subscription) => Effect.sync(() => subscription.remove()),
63 ).pipe(Effect.asVoid),
64 ),
65});
66
67const wakeupsLayer = Wakeups.layer({
68 changes: Stream.merge(
69 Stream.callback<"application-active">((queue) =>
70 Effect.acquireRelease(
71 Effect.sync(() =>
72 AppState.addEventListener("change", (state) => {
73 if (state === "active") {
74 Queue.offerUnsafe(queue, "application-active");
75 }
76 }),
77 ),
78 (subscription) => Effect.sync(() => subscription.remove()),
79 ).pipe(Effect.asVoid),
80 ),
81 managedRelayAccountChanges(appAtomRegistry).pipe(
82 Stream.map(() => "credentials-changed" as const),
83 ),
84 ),
85});
86
87const capabilitiesLayer = Layer.effectContext(
88 Effect.gen(function* () {
89 const storage = yield* MobileStorage.MobileStorage;
90 return Context.make(
91 CloudSession,
92 CloudSession.of({
93 clerkToken: Effect.gen(function* () {
94 const session = appAtomRegistry.get(managedRelaySessionAtom);
95 if (session === null) {
96 return yield* new ConnectionBlockedError({
97 reason: "authentication",
98 detail: "Sign in to T3 Connect to connect this environment.",
99 });
100 }
101 const token = yield* session.readClerkToken().pipe(
102 Effect.mapError(
103 (error) =>
104 new ConnectionTransientError({
105 reason: "network",
106 detail: error.message,
107 }),
108 ),
109 );
110 if (token === null) {
111 return yield* new ConnectionBlockedError({
112 reason: "authentication",
113 detail: "The T3 Connect session is unavailable.",
114 });
115 }
116 return token;
117 }),
118 }),
119 ).pipe(
120 Context.add(
121 PrimaryEnvironmentAuth,
122 PrimaryEnvironmentAuth.of({ bearerToken: Effect.succeed(Option.none()) }),
123 ),
124 Context.add(
125 RelayDeviceIdentity,
126 RelayDeviceIdentity.of({
127 deviceId: storage.loadOrCreateAgentAwarenessDeviceId.pipe(
128 Effect.mapError(
129 (cause) =>
130 new ConnectionTransientError({
131 reason: "remote-unavailable",
132 detail: `Could not load the mobile device identity: ${String(cause)}`,
133 }),
134 ),
135 Effect.map(Option.some),
136 ),
137 }),
138 ),
139 Context.add(
140 ClientPresentation,
141 ClientPresentation.of({
142 metadata: authClientMetadata(),
143 scopes: AuthStandardClientScopes,
144 }),
145 ),
146 Context.add(
147 SshEnvironmentGateway,
148 SshEnvironmentGateway.of({
149 provision: () =>
150 Effect.fail(
151 new ConnectionBlockedError({
152 reason: "unsupported",
153 detail: "SSH environments are only available in the desktop app.",
154 }),
155 ),
156 prepare: () =>
157 Effect.fail(
158 new ConnectionBlockedError({
159 reason: "unsupported",
160 detail: "SSH environments are only available in the desktop app.",
161 }),
162 ),
163 disconnect: () => Effect.void,
164 }),
165 ),
166 );
167 }),
168);
169
170const platformConnectionSourceLayer = Layer.succeed(
171 PlatformConnectionSource,
172 PlatformConnectionSource.of({
173 registrations: Stream.empty,
174 }),
175);
176
177const providedConnectionStorageLayer = connectionStorageLayer.pipe(
178 Layer.provide(Runtime.runtimeContextLayer),
179);
180const providedCapabilitiesLayer = capabilitiesLayer.pipe(
181 Layer.provide(Runtime.runtimeContextLayer),
182);
183
184const environmentOwnedDataCleanupLayer = Layer.succeed(
185 EnvironmentOwnedDataCleanup,
186 EnvironmentOwnedDataCleanup.of({
187 clear: (environmentId) =>
188 Effect.all(
189 [
190 Effect.promise(() => clearThreadOutboxEnvironment(environmentId)),
191 Effect.promise(() => clearComposerDraftsEnvironment(environmentId)),
192 ],
193 { concurrency: "unbounded", discard: true },
194 ).pipe(
195 Effect.catch((cause) =>
196 Effect.logWarning("Could not clear mobile environment-owned data.", {
197 environmentId,
198 cause,
199 }),
200 ),
201 ),
202 }),
203);
204
205type ConnectionPlatformLayerSource =
206 | typeof providedConnectionStorageLayer
207 | typeof Runtime.runtimeContextLayer
208 | typeof connectivityLayer
209 | typeof wakeupsLayer
210 | typeof providedCapabilitiesLayer
211 | typeof platformConnectionSourceLayer
212 | typeof environmentOwnedDataCleanupLayer;
213
214export const connectionPlatformLayer: Layer.Layer<
215 Layer.Success<ConnectionPlatformLayerSource>,
216 Layer.Error<ConnectionPlatformLayerSource>,
217 Layer.Services<ConnectionPlatformLayerSource>
218> = Layer.mergeAll(
219 providedConnectionStorageLayer,
220 Runtime.runtimeContextLayer,
221 connectivityLayer,
222 wakeupsLayer,
223 providedCapabilitiesLayer,
224 platformConnectionSourceLayer,
225 environmentOwnedDataCleanupLayer,
226);