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

platform.ts

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