Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

platform.ts

254 lines7.9 KB

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