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

platform.ts

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