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

platform.ts

257 lines8.1 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 identity: Effect.sync(() =>
122 Option.fromNullishOr(appAtomRegistry.get(managedRelaySessionAtom)),
123 ),
124 clerkToken: Effect.gen(function* () {
125 const session = appAtomRegistry.get(managedRelaySessionAtom);
126 if (session === null) {
127 return yield* new ConnectionBlockedError({
128 reason: "authentication",
129 detail: "Sign in to T3 Connect to connect this environment.",
130 });
131 }
132 const token = yield* session.readClerkToken().pipe(
133 Effect.mapError(
134 (error) =>
135 new ConnectionTransientError({
136 reason: "network",
137 detail: error.message,
138 }),
139 ),
140 );
141 if (token === null) {
142 return yield* new ConnectionBlockedError({
143 reason: "authentication",
144 detail: "The T3 Connect session is unavailable.",
145 });
146 }
147 return token;
148 }),
149 }),
150 ).pipe(
151 Context.add(
152 PrimaryEnvironmentAuth,
153 PrimaryEnvironmentAuth.of({ bearerToken: Effect.succeed(Option.none()) }),
154 ),
155 Context.add(
156 RelayDeviceIdentity,
157 RelayDeviceIdentity.of({
158 deviceId: storage.loadOrCreateAgentAwarenessDeviceId.pipe(
159 Effect.mapError(
160 (cause) =>
161 new ConnectionTransientError({
162 reason: "remote-unavailable",
163 detail: `Could not load the mobile device identity: ${String(cause)}`,
164 }),
165 ),
166 Effect.map(Option.some),
167 ),
168 }),
169 ),
170 Context.add(
171 ClientPresentation,
172 ClientPresentation.of({
173 metadata: authClientMetadata(Constants.expoConfig?.version),
174 scopes: AuthStandardClientScopes,
175 }),
176 ),
177 Context.add(
178 SshEnvironmentGateway,
179 SshEnvironmentGateway.of({
180 provision: () =>
181 Effect.fail(
182 new ConnectionBlockedError({
183 reason: "unsupported",
184 detail: "SSH environments are only available in the desktop app.",
185 }),
186 ),
187 prepare: () =>
188 Effect.fail(
189 new ConnectionBlockedError({
190 reason: "unsupported",
191 detail: "SSH environments are only available in the desktop app.",
192 }),
193 ),
194 disconnect: () => Effect.void,
195 }),
196 ),
197 );
198 }),
199);
200​
201const platformConnectionSourceLayer = Layer.succeed(
202 PlatformConnectionSource,
203 PlatformConnectionSource.of({
204 registrations: Stream.empty,
205 }),
206);
207​
208const providedConnectionStorageLayer = connectionStorageLayer.pipe(
209 Layer.provide(Runtime.runtimeContextLayer),
210);
211const providedCapabilitiesLayer = capabilitiesLayer.pipe(
212 Layer.provide(Runtime.runtimeContextLayer),
213);
214​
215const environmentOwnedDataCleanupLayer = Layer.succeed(
216 EnvironmentOwnedDataCleanup,
217 EnvironmentOwnedDataCleanup.of({
218 clear: (environmentId) =>
219 Effect.all(
220 [
221 Effect.promise(() => clearThreadOutboxEnvironment(environmentId)),
222 Effect.promise(() => clearComposerDraftsEnvironment(environmentId)),
223 ],
224 { concurrency: "unbounded", discard: true },
225 ).pipe(
226 Effect.catch((cause) =>
227 Effect.logWarning("Could not clear mobile environment-owned data.", {
228 environmentId,
229 cause,
230 }),
231 ),
232 ),
233 }),
234);
235​
236type ConnectionPlatformLayerSource =
237 | typeof providedConnectionStorageLayer
238 | typeof Runtime.runtimeContextLayer
239 | typeof connectivityLayer
240 | typeof wakeupsLayer
241 | typeof providedCapabilitiesLayer
242 | typeof platformConnectionSourceLayer
243 | typeof environmentOwnedDataCleanupLayer;
244​
245export const connectionPlatformLayer: Layer.Layer<
246 Layer.Success<ConnectionPlatformLayerSource>,
247 Layer.Error<ConnectionPlatformLayerSource>,
248 Layer.Services<ConnectionPlatformLayerSource>
249> = Layer.mergeAll(
250 providedConnectionStorageLayer,
251 Runtime.runtimeContextLayer,
252 connectivityLayer,
253 wakeupsLayer,
254 providedCapabilitiesLayer,
255 platformConnectionSourceLayer,
256 environmentOwnedDataCleanupLayer,
257);