Repository navigation
Expand file tree
/
Copy pathplatform.ts
More file actions
297 lines (286 loc) · 9.8 KB
/
Copy pathplatform.ts
File metadata and controls
297 lines (286 loc) · 9.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
import {
ClientCapabilities,
PlatformConnectionSource,
Persistence,
} from "@t3tools/client-runtime/platform";
import {
ConnectionBlockedError,
ConnectionTransientError,
Connectivity,
Wakeups,
} from "@t3tools/client-runtime/connection";
import { managedRelayAccountChanges, managedRelaySessionAtom } from "@t3tools/client-runtime/relay";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
import * as Stream from "effect/Stream";
import Constants from "expo-constants";
import * as Network from "expo-network";
import { AppState } from "react-native";
import { authClientMetadata } from "../lib/authClientMetadata";
import * as Runtime from "../lib/runtime";
import * as MobileStorage from "../persistence/mobile-storage";
import { appAtomRegistry } from "../state/atom-registry";
import { clearThreadOutboxEnvironment } from "../state/thread-outbox-removal";
import { clearComposerDraftsEnvironment } from "../state/use-composer-drafts";
import { clearThreadComposerErrorsForEnvironment } from "../state/thread-composer-error";
import { mobileApplicationActiveWakeup } from "./app-state-wakeups";
import * as ConnectionStorage from "./storage";
function networkStatus(state: Network.NetworkState): "unknown" | "offline" | "online" {
if (state.isConnected === false) {
return "offline";
}
if (state.isConnected === true) {
return "online";
}
return "unknown";
}
const layerConnectivity = Connectivity.layer({
status: Effect.tryPromise({
try: () => Network.getNetworkStateAsync(),
catch: () => undefined,
}).pipe(
Effect.match({
onFailure: () => "unknown" as const,
onSuccess: networkStatus,
}),
),
changes: Stream.callback((queue) =>
Effect.acquireRelease(
Effect.sync(() => {
let active = true;
const networkSubscription = Network.addNetworkStateListener((state) => {
Queue.offerUnsafe(queue, networkStatus(state));
});
const appStateSubscription = AppState.addEventListener("change", (state) => {
if (state !== "active") {
return;
}
void Network.getNetworkStateAsync()
.then((current) => {
if (active) {
Queue.offerUnsafe(queue, networkStatus(current));
}
})
.catch(() => undefined);
});
return {
close: () => {
active = false;
networkSubscription.remove();
appStateSubscription.remove();
},
};
}),
({ close }) => Effect.sync(close),
).pipe(Effect.asVoid),
),
});
/**
* Wakes connections when the device moves between networks while staying
* online, such as Wi-Fi to cellular. Connectivity only reports online or
* offline, so leaving home on cellular would otherwise go unnoticed until the
* LAN socket times out.
*/
const networkPathChanges = Stream.callback<"network-changed">((queue) =>
Effect.acquireRelease(
Effect.sync(() => {
let active = true;
let previous: Network.NetworkStateType | undefined;
const record = (state: Network.NetworkState) => {
const type = state.isConnected === true ? state.type : undefined;
if (previous !== undefined && type !== undefined && type !== previous) {
Queue.offerUnsafe(queue, "network-changed");
}
previous = type ?? previous;
};
// The listener reports changes only, so seed the current type; without
// it the first Wi-Fi to cellular move would go unnoticed.
void Network.getNetworkStateAsync()
.then((state) => {
if (active && previous === undefined && state.isConnected === true) {
previous = state.type;
}
})
.catch(() => undefined);
const subscription = Network.addNetworkStateListener(record);
return {
remove: () => {
active = false;
subscription.remove();
},
};
}),
(subscription) => Effect.sync(() => subscription.remove()),
).pipe(Effect.asVoid),
);
const layerWakeups = Wakeups.layer({
changes: Stream.mergeAll(
[
Stream.callback<"application-active-probe" | "application-active-reconnect">((queue) =>
Effect.acquireRelease(
Effect.sync(() => {
let backgroundedAtMs = AppState.currentState === "background" ? Date.now() : null;
return AppState.addEventListener("change", (state) => {
if (state === "background") {
backgroundedAtMs = Date.now();
return;
}
if (state === "active") {
Queue.offerUnsafe(
queue,
mobileApplicationActiveWakeup(backgroundedAtMs, Date.now()),
);
backgroundedAtMs = null;
}
});
}),
(subscription) => Effect.sync(() => subscription.remove()),
).pipe(Effect.asVoid),
),
managedRelayAccountChanges(appAtomRegistry).pipe(
Stream.map(() => "credentials-changed" as const),
),
networkPathChanges,
],
{ concurrency: "unbounded" },
),
});
const layerCapabilities = Layer.effectContext(
Effect.gen(function* () {
const storage = yield* MobileStorage.MobileStorage;
return Context.make(
ClientCapabilities.CloudSession,
ClientCapabilities.CloudSession.of({
identity: Effect.sync(() =>
Option.fromNullishOr(appAtomRegistry.get(managedRelaySessionAtom)),
),
clerkToken: Effect.gen(function* () {
const session = appAtomRegistry.get(managedRelaySessionAtom);
if (session === null) {
return yield* new ConnectionBlockedError({
reason: "authentication",
detail: "Sign in to T3 Connect to connect this environment.",
});
}
const token = yield* session.readClerkToken().pipe(
Effect.mapError(
(error) =>
new ConnectionTransientError({
reason: "network",
detail: error.message,
}),
),
);
if (token === null) {
return yield* new ConnectionBlockedError({
reason: "authentication",
detail: "The T3 Connect session is unavailable.",
});
}
return token;
}),
}),
).pipe(
Context.add(
ClientCapabilities.PrimaryEnvironmentAuth,
ClientCapabilities.PrimaryEnvironmentAuth.of({
bearerToken: Effect.succeed(Option.none()),
}),
),
Context.add(
ClientCapabilities.RelayDeviceIdentity,
ClientCapabilities.RelayDeviceIdentity.of({
deviceId: storage.loadOrCreateAgentAwarenessDeviceId.pipe(
Effect.mapError(
(cause) =>
new ConnectionTransientError({
reason: "remote-unavailable",
detail: `Could not load the mobile device identity: ${String(cause)}`,
}),
),
Effect.map(Option.some),
),
}),
),
Context.add(
ClientCapabilities.ClientPresentation,
ClientCapabilities.ClientPresentation.of({
metadata: authClientMetadata(Constants.expoConfig?.version),
}),
),
Context.add(
ClientCapabilities.SshEnvironmentGateway,
ClientCapabilities.SshEnvironmentGateway.of({
provision: () =>
Effect.fail(
new ConnectionBlockedError({
reason: "unsupported",
detail: "SSH environments are only available in the desktop app.",
}),
),
prepare: () =>
Effect.fail(
new ConnectionBlockedError({
reason: "unsupported",
detail: "SSH environments are only available in the desktop app.",
}),
),
disconnect: () => Effect.void,
}),
),
);
}),
);
const layerPlatformConnectionSource = Layer.succeed(
PlatformConnectionSource.PlatformConnectionSource,
PlatformConnectionSource.PlatformConnectionSource.of({
registrations: Stream.empty,
}),
);
const layerProvidedConnectionStorage = ConnectionStorage.layer.pipe(Layer.provide(Runtime.layer));
const layerProvidedCapabilities = layerCapabilities.pipe(Layer.provide(Runtime.layer));
const layerEnvironmentOwnedDataCleanup = Layer.succeed(
Persistence.EnvironmentOwnedDataCleanup,
Persistence.EnvironmentOwnedDataCleanup.of({
clear: (environmentId) =>
Effect.all(
[
Effect.promise(() => clearThreadOutboxEnvironment(environmentId)),
Effect.promise(() => clearComposerDraftsEnvironment(environmentId)),
Effect.sync(() => clearThreadComposerErrorsForEnvironment(environmentId)),
],
{ concurrency: "unbounded", discard: true },
).pipe(
Effect.catch((cause) =>
Effect.logWarning("Could not clear mobile environment-owned data.", {
environmentId,
cause,
}),
),
),
}),
);
type ConnectionPlatformLayerSource =
| typeof layerProvidedConnectionStorage
| typeof Runtime.layer
| typeof layerConnectivity
| typeof layerWakeups
| typeof layerProvidedCapabilities
| typeof layerPlatformConnectionSource
| typeof layerEnvironmentOwnedDataCleanup;
export const layer: Layer.Layer<
Layer.Success<ConnectionPlatformLayerSource>,
Layer.Error<ConnectionPlatformLayerSource>,
Layer.Services<ConnectionPlatformLayerSource>
> = Layer.mergeAll(
layerProvidedConnectionStorage,
Runtime.layer,
layerConnectivity,
layerWakeups,
layerProvidedCapabilities,
layerPlatformConnectionSource,
layerEnvironmentOwnedDataCleanup,
);