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

platform.ts

680 lines23.9 KB

1import {
2 ClientCapabilities,
3 PlatformConnectionSource,
4 Persistence,
5} from "@t3tools/client-runtime/platform";
6import {
7 BearerConnectionCredential,
8 BearerConnectionProfile,
9 BearerConnectionRegistration,
10 BearerConnectionTarget,
11 ConnectionBlockedError,
12 ConnectionTransientError,
13 Connectivity,
14 mapRemoteEnvironmentError,
15 type PlatformConnectionRegistration,
16 PrimaryConnectionRegistration,
17 PrimaryConnectionTarget,
18 Wakeups,
19} from "@t3tools/client-runtime/connection";
20import { bootstrapRemoteBearerSession } from "@t3tools/client-runtime/authorization";
21import { fetchRemoteEnvironmentDescriptor } from "@t3tools/client-runtime/environment";
22import { managedRelayAccountChanges, managedRelaySessionAtom } from "@t3tools/client-runtime/relay";
23import { EnvironmentRpcRequestObserver } from "@t3tools/client-runtime/rpc";
24import {
25 AuthStandardClientScopes,
26 type DesktopBridge,
27 type DesktopEnvironmentBootstrap,
28 type DesktopSshEnvironmentTarget,
29 type EnvironmentId,
30 PRIMARY_LOCAL_ENVIRONMENT_ID,
31} from "@t3tools/contracts";
32import * as Clock from "effect/Clock";
33import * as Context from "effect/Context";
34import * as Effect from "effect/Effect";
35import * as Layer from "effect/Layer";
36import * as Option from "effect/Option";
37import * as Queue from "effect/Queue";
38import * as Ref from "effect/Ref";
39import * as Stream from "effect/Stream";
40import { FetchHttpClient } from "effect/http";
41​
42import { APP_VERSION } from "../branding";
43import { readDesktopPrimaryBearerToken } from "../environments/primary/desktopAuth";
44import { primaryEnvironmentHttpLayer } from "../environments/primary/httpLayer";
45import {
46 readPrimaryEnvironmentTarget,
47 type PrimaryEnvironmentTarget,
48} from "../environments/primary/target";
49import { clearComposerDraftsEnvironment } from "../composerDraftStore";
50import { isHostedStaticApp } from "../hostedPairing";
51import { isLocalEnvironmentDisabled } from "../localEnvironment";
52import { appAtomRegistry } from "../rpc/atomRegistry";
53import { acknowledgeRpcRequest, trackRpcRequestSent } from "../rpc/requestLatencyState";
54import {
55 desktopLocalConnectionId,
56 readDesktopSecondaryBootstrapsResult,
57 type DesktopSecondaryBootstrapsRead,
58} from "./desktopLocal";
59import { connectionStorageLayer } from "./storage";
60import { clientPresentationMetadata } from "./clientMetadata";
61​
62let nextObservedRpcRequestId = 0;
63​
64function currentNetworkStatus(): "unknown" | "offline" | "online" {
65 if (typeof navigator === "undefined") {
66 return "unknown";
67 }
68 return navigator.onLine ? "online" : "offline";
70​
71const connectivityLayer = Connectivity.layer({
72 status: Effect.sync(currentNetworkStatus),
73 changes: Stream.callback((queue) =>
74 Effect.acquireRelease(
75 Effect.sync(() => {
76 const online = () => Queue.offerUnsafe(queue, "online");
77 const offline = () => Queue.offerUnsafe(queue, "offline");
78 window.addEventListener("online", online);
79 window.addEventListener("offline", offline);
80 return { online, offline };
81 }),
82 ({ online, offline }) =>
83 Effect.sync(() => {
84 window.removeEventListener("online", online);
85 window.removeEventListener("offline", offline);
86 }),
87 ).pipe(Effect.asVoid),
88 ),
89});
90​
91interface NetworkInformationLike extends EventTarget {
92 readonly type?: string;
94​
95/**
96 * Wakes connections when the browser reports a different network type, such
97 * as a laptop moving from Wi-Fi to a phone hotspot. `change` also fires for
98 * bandwidth and latency estimates on the same network, so only a type change
99 * counts. Browsers without `navigator.connection.type` rely on the periodic
100 * route check instead.
101 */
102const networkPathChanges = Stream.callback<"network-changed">((queue) =>
103 Effect.acquireRelease(
104 Effect.sync(() => {
105 const connection =
106 typeof navigator === "undefined"
107 ? undefined
108 : (navigator as Navigator & { readonly connection?: NetworkInformationLike }).connection;
109 if (connection?.type === undefined) return undefined;
110 let previous = connection.type;
111 const listener = () => {
112 const type = connection.type;
113 if (type === undefined || type === previous) return;
114 previous = type;
115 Queue.offerUnsafe(queue, "network-changed");
116 };
117 connection.addEventListener("change", listener);
118 return { connection, listener };
119 }),
120 (subscription) =>
121 Effect.sync(() =>
122 subscription?.connection.removeEventListener("change", subscription.listener),
123 ),
124 ).pipe(Effect.asVoid),
125);
126​
127const wakeupsLayer = Wakeups.layer({
128 changes: Stream.mergeAll(
129 [
130 Stream.callback<"application-active">((queue) =>
131 Effect.acquireRelease(
132 Effect.sync(() => {
133 const listener = () => {
134 if (document.visibilityState === "visible") {
135 Queue.offerUnsafe(queue, "application-active");
136 }
137 };
138 document.addEventListener("visibilitychange", listener);
139 return listener;
140 }),
141 (listener) =>
142 Effect.sync(() => {
143 document.removeEventListener("visibilitychange", listener);
144 }),
145 ).pipe(Effect.asVoid),
146 ),
147 managedRelayAccountChanges(appAtomRegistry).pipe(
148 Stream.map(() => "credentials-changed" as const),
149 ),
150 networkPathChanges,
151 ],
152 { concurrency: "unbounded" },
153 ),
154});
155​
156function clientMetadata() {
157 return clientPresentationMetadata({
158 appVersion: APP_VERSION,
159 hosted: isHostedStaticApp(),
160 identity: {
161 userAgent: navigator.userAgent,
162 platform: navigator.platform,
163 maxTouchPoints: navigator.maxTouchPoints,
164 },
165 desktopBridge: window.desktopBridge,
166 });
168​
169function sshPreparationError(cause: unknown) {
170 const message = cause instanceof Error ? cause.message : String(cause);
171 if (message.toLowerCase().includes("cancel")) {
172 return new ConnectionBlockedError({
173 reason: "authentication",
174 detail: message,
175 });
176 }
177 return new ConnectionTransientError({
178 reason: "remote-unavailable",
179 detail: `Could not prepare the SSH environment: ${message}`,
180 });
182​
183export const provisionDesktopSshEnvironment = Effect.fn(
184 "web.connectionPlatform.ssh.provisionDesktop",
185)(function* (
186 bridge: DesktopBridge,
187 target: DesktopSshEnvironmentTarget,
188 expectedEnvironmentId?: EnvironmentId,
189) {
190 const bootstrap = yield* Effect.tryPromise({
191 try: () =>
192 bridge.ensureSshEnvironment(target, {
193 issuePairingToken: true,
194 }),
195 catch: sshPreparationError,
196 });
197 const pairingToken = bootstrap.pairingToken;
198 if (pairingToken === null) {
199 return yield* new ConnectionBlockedError({
200 reason: "authentication",
201 detail: "The SSH environment did not issue a pairing credential.",
202 });
203 }
204 const descriptor = yield* Effect.tryPromise({
205 try: () => bridge.fetchSshEnvironmentDescriptor(bootstrap.httpBaseUrl),
206 catch: sshPreparationError,
207 });
208 if (expectedEnvironmentId !== undefined && descriptor.environmentId !== expectedEnvironmentId) {
209 return yield* new ConnectionBlockedError({
210 reason: "configuration",
211 detail: `That host reaches ${descriptor.label}, a different machine. Add it as its own environment instead.`,
212 });
213 }
214 const access = yield* Effect.tryPromise({
215 try: () => bridge.bootstrapSshBearerSession(bootstrap.httpBaseUrl, pairingToken),
216 catch: sshPreparationError,
217 });
218 return {
219 environmentId: descriptor.environmentId,
220 label: descriptor.label,
221 bootstrap,
222 bearerToken: access.access_token,
223 };
224});
225​
226const capabilitiesLayer = Layer.effectContext(
227 Effect.sync(() => {
228 const presentation = ClientCapabilities.ClientPresentation.of({
229 metadata: clientMetadata(),
230 scopes: AuthStandardClientScopes,
231 });
232 const cloudSession = ClientCapabilities.CloudSession.of({
233 identity: Effect.sync(() =>
234 Option.fromNullishOr(appAtomRegistry.get(managedRelaySessionAtom)),
235 ),
236 clerkToken: Effect.gen(function* () {
237 const session = appAtomRegistry.get(managedRelaySessionAtom);
238 if (session === null) {
239 return yield* new ConnectionBlockedError({
240 reason: "authentication",
241 detail: "Sign in to T3 Connect to connect this environment.",
242 });
243 }
244 const token = yield* session.readClerkToken().pipe(
245 Effect.mapError(
246 (error) =>
247 new ConnectionTransientError({
248 reason: "network",
249 detail: error.message,
250 }),
251 ),
252 );
253 if (token === null) {
254 return yield* new ConnectionBlockedError({
255 reason: "authentication",
256 detail: "The T3 Connect session is unavailable.",
257 });
258 }
259 return token;
260 }),
261 });
262 const identity = ClientCapabilities.RelayDeviceIdentity.of({
263 deviceId: Effect.succeedNone,
264 });
265 const primaryAuth = ClientCapabilities.PrimaryEnvironmentAuth.of({
266 bearerToken: Effect.tryPromise({
267 try: readDesktopPrimaryBearerToken,
268 catch: (cause) =>
269 new ConnectionTransientError({
270 reason: "remote-unavailable",
271 detail: `Could not load the desktop primary credential: ${String(cause)}`,
272 }),
273 }).pipe(Effect.map(Option.fromNullishOr)),
274 });
275 const ssh = ClientCapabilities.SshEnvironmentGateway.of({
276 provision: Effect.fn("web.connectionPlatform.ssh.provision")(
277 function* (target, expectedEnvironmentId) {
278 const bridge = window.desktopBridge;
279 if (bridge === undefined) {
280 return yield* new ConnectionBlockedError({
281 reason: "unsupported",
282 detail: "SSH environments are only available in the desktop app.",
283 });
284 }
285 return yield* provisionDesktopSshEnvironment(bridge, target, expectedEnvironmentId);
286 },
287 ),
288 prepare: Effect.fn("web.connectionPlatform.ssh.prepare")(function* (input) {
289 const bridge = window.desktopBridge;
290 if (bridge === undefined) {
291 return yield* new ConnectionBlockedError({
292 reason: "unsupported",
293 detail: "SSH environments are only available in the desktop app.",
294 });
295 }
296 const bootstrap = yield* Effect.tryPromise({
297 try: () =>
298 bridge.ensureSshEnvironment(input.target, {
299 issuePairingToken: true,
300 }),
301 catch: sshPreparationError,
302 });
303 if (bootstrap.pairingToken === null) {
304 return yield* new ConnectionBlockedError({
305 reason: "authentication",
306 detail: "The SSH environment did not issue a pairing credential.",
307 });
308 }
309 const access = yield* Effect.tryPromise({
310 try: () =>
311 bridge.bootstrapSshBearerSession(bootstrap.httpBaseUrl, bootstrap.pairingToken!),
312 catch: sshPreparationError,
313 });
314 return {
315 bootstrap,
316 bearerToken: access.access_token,
317 };
318 }),
319 disconnect: Effect.fn("web.connectionPlatform.ssh.disconnect")(function* (target) {
320 const bridge = window.desktopBridge;
321 if (bridge === undefined) {
322 return;
323 }
324 yield* Effect.tryPromise({
325 try: () => bridge.disconnectSshEnvironment(target),
326 catch: (cause) =>
327 new ConnectionTransientError({
328 reason: "remote-unavailable",
329 detail: `Could not disconnect the SSH environment: ${String(cause)}`,
330 }),
331 });
332 }),
333 });
334​
335 return Context.make(ClientCapabilities.CloudSession, cloudSession).pipe(
336 Context.add(ClientCapabilities.PrimaryEnvironmentAuth, primaryAuth),
337 Context.add(ClientCapabilities.RelayDeviceIdentity, identity),
338 Context.add(ClientCapabilities.ClientPresentation, presentation),
339 Context.add(ClientCapabilities.SshEnvironmentGateway, ssh),
340 );
341 }),
342);
343​
344const loadPrimaryConnectionRegistration = Effect.fn(
345 "web.connectionPlatform.loadPrimaryConnectionRegistration",
346)(function* (resolved: PrimaryEnvironmentTarget) {
347 const descriptor = yield* fetchRemoteEnvironmentDescriptor({
348 httpBaseUrl: resolved.target.httpBaseUrl,
349 }).pipe(Effect.provide(primaryEnvironmentHttpLayer), Effect.mapError(mapRemoteEnvironmentError));
350 return new PrimaryConnectionRegistration({
351 target: new PrimaryConnectionTarget({
352 environmentId: descriptor.environmentId,
353 label: descriptor.label,
354 httpBaseUrl: resolved.target.httpBaseUrl,
355 wsBaseUrl: resolved.target.wsBaseUrl,
356 }),
357 });
358});
359​
360// A desktop-local secondary backend (e.g. a parallel WSL backend) lives on its
361// own loopback origin, so — unlike the same-origin primary — it authenticates
362// with a bearer token minted from the bootstrap credential the desktop issues.
363const loadSecondaryConnectionRegistration = Effect.fn(
364 "web.connectionPlatform.loadSecondaryConnectionRegistration",
365)(function* (entry: DesktopEnvironmentBootstrap) {
366 if (
367 entry.httpBaseUrl === null ||
368 entry.wsBaseUrl === null ||
369 entry.bootstrapToken === undefined
370 ) {
371 return yield* new ConnectionTransientError({
372 reason: "endpoint-unavailable",
373 detail: `Desktop-local backend ${entry.id} is not ready yet.`,
374 });
375 }
376 const httpBaseUrl = entry.httpBaseUrl;
377 const wsBaseUrl = entry.wsBaseUrl;
378 const descriptor = yield* fetchRemoteEnvironmentDescriptor({ httpBaseUrl }).pipe(
379 Effect.mapError(mapRemoteEnvironmentError),
380 );
381 const issuedAtEpochMs = yield* Clock.currentTimeMillis;
382 const access = yield* bootstrapRemoteBearerSession({
383 httpBaseUrl,
384 credential: entry.bootstrapToken,
385 scopes: AuthStandardClientScopes,
386 clientMetadata: clientMetadata(),
387 }).pipe(Effect.mapError(mapRemoteEnvironmentError));
388 // Keep the desktop pool's stable backend id in the connection id. The
389 // descriptor environment id still scopes projects and RPC state, while the
390 // backend id lets desktop-only operations (notably the WSL folder picker)
391 // route back to the instance that owns the environment.
392 const connectionId = desktopLocalConnectionId(entry.id);
393 // Prefer the desktop's bootstrap label (it identifies the backend and distro,
394 // e.g. "WSL: Ubuntu") over the generic descriptor label, so consumers can show
395 // a meaningful name without recovering it from the bootstrap list later.
396 const label = entry.label || descriptor.label;
397 return {
398 registration: new BearerConnectionRegistration({
399 target: new BearerConnectionTarget({
400 environmentId: descriptor.environmentId,
401 label,
402 connectionId,
403 }),
404 profile: new BearerConnectionProfile({
405 connectionId,
406 environmentId: descriptor.environmentId,
407 label,
408 httpBaseUrl,
409 wsBaseUrl,
410 }),
411 credential: new BearerConnectionCredential({ token: access.access_token }),
412 }),
413 expiresAtEpochMs: secondaryBearerExpiresAtEpochMs(issuedAtEpochMs, access.expires_in),
414 refreshAtEpochMs: secondaryBearerRefreshAtEpochMs(issuedAtEpochMs, access.expires_in),
415 };
416});
417​
418// Poll cadence for the desktop bootstrap topology. There is no change event on
419// the bridge, so the renderer polls; successful registrations are cached by a
420// signature of their endpoint + token until bearer credentials approach expiry.
421const PLATFORM_POLL_INTERVAL = "3 seconds";
422const SECONDARY_BEARER_REFRESH_SKEW_MS = 5_000;
423​
424export function secondaryBearerExpiresAtEpochMs(
425 issuedAtEpochMs: number,
426 expiresInSeconds: number,
427): number {
428 return issuedAtEpochMs + Math.max(0, expiresInSeconds * 1_000);
430​
431export function secondaryBearerRefreshAtEpochMs(
432 issuedAtEpochMs: number,
433 expiresInSeconds: number,
434): number {
435 return Math.max(
436 issuedAtEpochMs,
437 secondaryBearerExpiresAtEpochMs(issuedAtEpochMs, expiresInSeconds) -
438 SECONDARY_BEARER_REFRESH_SKEW_MS,
439 );
441​
442interface CachedPlatformRegistration {
443 readonly signature: string;
444 readonly registration: PlatformConnectionRegistration;
445 readonly expiresAtEpochMs?: number;
446 readonly refreshAtEpochMs?: number;
448​
449export type PrimaryEnvironmentTargetRead =
450 | {
451 readonly _tag: "Success";
452 readonly target: PrimaryEnvironmentTarget | null;
453 }
454 | {
455 readonly _tag: "Failure";
456 readonly cause: unknown;
457 };
458​
459export function readPrimaryEnvironmentTargetResult(
460 readTarget: () => PrimaryEnvironmentTarget | null = readPrimaryEnvironmentTarget,
461): PrimaryEnvironmentTargetRead {
462 try {
463 return { _tag: "Success", target: readTarget() };
464 } catch (cause) {
465 return { _tag: "Failure", cause };
466 }
468​
469export function primaryRegistrationToRetainAfterTopologyRead(
470 previous: ReadonlyMap<string, CachedPlatformRegistration>,
471 topologyRead: PrimaryEnvironmentTargetRead,
472): CachedPlatformRegistration | undefined {
473 return topologyRead._tag === "Failure" ? previous.get(PRIMARY_LOCAL_ENVIRONMENT_ID) : undefined;
475​
476export function canReuseCachedPlatformRegistration(
477 cached: CachedPlatformRegistration,
478 signature: string,
479 nowEpochMs: number,
480): boolean {
481 return (
482 cached.signature === signature &&
483 (cached.refreshAtEpochMs === undefined || nowEpochMs < cached.refreshAtEpochMs)
484 );
486​
487export function canRetainCachedPlatformRegistrationAfterRefreshFailure(
488 cached: CachedPlatformRegistration,
489 signature: string,
490 nowEpochMs: number,
491): boolean {
492 return (
493 cached.signature === signature &&
494 cached.expiresAtEpochMs !== undefined &&
495 nowEpochMs < cached.expiresAtEpochMs
496 );
498​
499export function secondaryRegistrationsToRetainAfterTopologyRead(
500 previous: ReadonlyMap<string, CachedPlatformRegistration>,
501 topologyRead: DesktopSecondaryBootstrapsRead,
502 nowEpochMs: number,
503): ReadonlyMap<string, CachedPlatformRegistration> {
504 if (topologyRead._tag === "Success") {
505 return new Map();
506 }
507 return new Map(
508 [...previous].filter(
509 ([, cached]) => cached.expiresAtEpochMs !== undefined && nowEpochMs < cached.expiresAtEpochMs,
510 ),
511 );
513​
514const platformConnectionSourceLayer = Layer.effect(
515 PlatformConnectionSource.PlatformConnectionSource,
516 Effect.gen(function* () {
517 if (isHostedStaticApp() || isLocalEnvironmentDisabled()) {
518 return PlatformConnectionSource.PlatformConnectionSource.of({
519 registrations: Stream.empty,
520 });
521 }
522 const cacheRef = yield* Ref.make(new Map<string, CachedPlatformRegistration>());
523​
524 // Resolve the full set of platform-managed environments the host currently
525 // reports: the primary (same-origin cookie auth) plus any desktop-local
526 // backends running alongside it (bearer auth). Reused registrations come
527 // from the cache; a failed entry is skipped and retried on the next poll.
528 const buildPlatformRegistrations = Effect.gen(function* () {
529 const previous = yield* Ref.get(cacheRef);
530 const nowEpochMs = yield* Clock.currentTimeMillis;
531 const next = new Map<string, CachedPlatformRegistration>();
532 const registrations: Array<PlatformConnectionRegistration> = [];
533​
534 const primaryTopologyRead = readPrimaryEnvironmentTargetResult();
535 const retainedPrimary = primaryRegistrationToRetainAfterTopologyRead(
536 previous,
537 primaryTopologyRead,
538 );
539 if (retainedPrimary !== undefined) {
540 next.set(PRIMARY_LOCAL_ENVIRONMENT_ID, retainedPrimary);
541 registrations.push(retainedPrimary.registration);
542 }
543​
544 if (primaryTopologyRead._tag === "Failure") {
545 yield* Effect.logWarning("Could not read the primary environment topology.", {
546 cause: primaryTopologyRead.cause,
547 });
548 } else if (primaryTopologyRead.target !== null) {
549 const primaryTarget = primaryTopologyRead.target;
550 const signature = `primary|${primaryTarget.target.httpBaseUrl}|${primaryTarget.target.wsBaseUrl}`;
551 const cached = previous.get(PRIMARY_LOCAL_ENVIRONMENT_ID);
552 if (
553 cached !== undefined &&
554 canReuseCachedPlatformRegistration(cached, signature, nowEpochMs)
555 ) {
556 next.set(PRIMARY_LOCAL_ENVIRONMENT_ID, cached);
557 registrations.push(cached.registration);
558 } else {
559 const built = yield* loadPrimaryConnectionRegistration(primaryTarget).pipe(
560 Effect.tapError((error) =>
561 Effect.logWarning("Could not discover the primary environment.", { error }),
562 ),
563 Effect.option,
564 );
565 if (Option.isSome(built)) {
566 const cacheEntry = { signature, registration: built.value };
567 next.set(PRIMARY_LOCAL_ENVIRONMENT_ID, cacheEntry);
568 registrations.push(built.value);
569 }
570 }
571 }
572​
573 const topologyRead = readDesktopSecondaryBootstrapsResult();
574 for (const [id, cached] of secondaryRegistrationsToRetainAfterTopologyRead(
575 previous,
576 topologyRead,
577 nowEpochMs,
578 )) {
579 next.set(id, cached);
580 registrations.push(cached.registration);
581 }
582​
583 if (topologyRead._tag === "Failure") {
584 yield* Effect.logWarning("Could not read the desktop-local backend topology.", {
585 cause: topologyRead.cause,
586 });
587 } else {
588 for (const bootstrap of topologyRead.bootstraps) {
589 const signature = `${bootstrap.httpBaseUrl}|${bootstrap.wsBaseUrl}|${bootstrap.bootstrapToken ?? ""}`;
590 const cached = previous.get(bootstrap.id);
591 if (
592 cached !== undefined &&
593 canReuseCachedPlatformRegistration(cached, signature, nowEpochMs)
594 ) {
595 next.set(bootstrap.id, cached);
596 registrations.push(cached.registration);
597 continue;
598 }
599 const built = yield* loadSecondaryConnectionRegistration(bootstrap).pipe(
600 Effect.tapError((error) =>
601 Effect.logWarning("Could not connect a desktop-local backend.", {
602 id: bootstrap.id,
603 error,
604 }),
605 ),
606 Effect.option,
607 );
608 if (Option.isSome(built)) {
609 const cacheEntry = { signature, ...built.value };
610 next.set(bootstrap.id, cacheEntry);
611 registrations.push(built.value.registration);
612 } else if (
613 cached !== undefined &&
614 canRetainCachedPlatformRegistrationAfterRefreshFailure(cached, signature, nowEpochMs)
615 ) {
616 next.set(bootstrap.id, cached);
617 registrations.push(cached.registration);
618 }
619 }
620 }
621​
622 yield* Ref.set(cacheRef, next);
623 return registrations as ReadonlyArray<PlatformConnectionRegistration>;
624 }).pipe(Effect.provide(FetchHttpClient.layer));
625​
626 return PlatformConnectionSource.PlatformConnectionSource.of({
627 registrations: Stream.tick(PLATFORM_POLL_INTERVAL).pipe(
628 Stream.mapEffect(() => buildPlatformRegistrations),
629 ),
630 });
631 }),
632);
633​
634const environmentOwnedDataCleanupLayer = Layer.succeed(
635 Persistence.EnvironmentOwnedDataCleanup,
636 Persistence.EnvironmentOwnedDataCleanup.of({
637 clear: (environmentId) =>
638 Effect.sync(() => {
639 clearComposerDraftsEnvironment(environmentId);
640 }),
641 }),
642);
643​
644const rpcRequestObserverLayer = Layer.succeed(
645 EnvironmentRpcRequestObserver,
646 EnvironmentRpcRequestObserver.of({
647 observe: ({ environmentId, method }) =>
648 Effect.sync(() => {
649 nextObservedRpcRequestId += 1;
650 const requestId = `${environmentId}:${nextObservedRpcRequestId}`;
651 trackRpcRequestSent(requestId, method, `${method} · ${environmentId}`);
652 return Effect.sync(() => {
653 acknowledgeRpcRequest(requestId);
654 });
655 }),
656 }),
657);
658​
659type ConnectionPlatformLayerSource =
660 | typeof connectionStorageLayer
661 | typeof connectivityLayer
662 | typeof wakeupsLayer
663 | typeof capabilitiesLayer
664 | typeof platformConnectionSourceLayer
665 | typeof environmentOwnedDataCleanupLayer
666 | typeof rpcRequestObserverLayer;
667​
668export const connectionPlatformLayer: Layer.Layer<
669 Layer.Success<ConnectionPlatformLayerSource>,
670 Layer.Error<ConnectionPlatformLayerSource>,
671 Layer.Services<ConnectionPlatformLayerSource>
672> = Layer.mergeAll(
673 connectionStorageLayer,
674 connectivityLayer,
675 wakeupsLayer,
676 capabilitiesLayer,
677 platformConnectionSourceLayer,
678 environmentOwnedDataCleanupLayer,
679 rpcRequestObserverLayer,
680);