Open History to see the last commit
1import { EnvironmentRegistry } from "@t3tools/client-runtime/connection";
2import { EnvironmentRpcSubscriptionObserver, request } from "@t3tools/client-runtime/rpc";
3import {
4 type BackgroundScope,
5 type ClientActivityReportInput,
6 type EnvironmentId,
7 WS_METHODS,
8} from "@t3tools/contracts";
9import * as Clock from "effect/Clock";
10import * as DateTime from "effect/DateTime";
11import * as Effect from "effect/Effect";
12import * as Layer from "effect/Layer";
13import * as Queue from "effect/Queue";
14import * as Schedule from "effect/Schedule";
15import * as Stream from "effect/Stream";
16import * as SubscriptionRef from "effect/SubscriptionRef";
17import { AppState } from "react-native";
18
19import * as MobileStorage from "../persistence/mobile-storage";
20import {
21 observeMobileBackgroundActivitySubscription,
22 onRetainedMobileBackgroundScopesChange,
23 retainedMobileBackgroundScopes,
24} from "./background-activity-scopes";
25
26const REPORT_INTERVAL_MS = 25_000;
27// Shorter than the interval, so a report that never settles cannot hold up the next one.
28const REPORT_TIMEOUT_MS = 15_000;
29const LEASE_TTL_MS = 45_000;
30const BASELINE_SCOPES: ReadonlyArray<BackgroundScope> = [{ type: "provider-status" }];
31
32function normalizeAppState(
33 state: string | null | undefined,
34): NonNullable<ClientActivityReportInput["appState"]> {
35 if (state === "active" || state === "inactive" || state === "background") return state;
36 return "unknown";
37}
38
39// Control Center, alerts, and the app switcher leave the app on screen as `inactive`.
40function isForeground(state: string | null | undefined): boolean {
41 return state === "active" || state === "inactive";
42}
43
44export const layerObserver = Layer.succeed(
45 EnvironmentRpcSubscriptionObserver,
46 EnvironmentRpcSubscriptionObserver.of({
47 observe: observeMobileBackgroundActivitySubscription,
48 }),
49);
50
51export const layerReporter = Layer.effectDiscard(
52 Effect.gen(function* () {
53 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
54 const storage = yield* MobileStorage.MobileStorage;
55 const clientId = yield* storage.loadOrCreateAgentAwarenessDeviceId.pipe(
56 Effect.map((deviceId) => `mobile-${deviceId}`),
57 Effect.orElseSucceed(() => "ephemeral-mobile-client"),
58 );
59 const reportRequests = yield* Queue.sliding<void>(1);
60 const requestReport = () => Queue.offerUnsafe(reportRequests, undefined);
61 let appState = AppState.currentState;
62
63 const report = Effect.gen(function* () {
64 const observedAtMs = yield* Clock.currentTimeMillis;
65 const foreground = isForeground(appState);
66 const entries = yield* SubscriptionRef.get(registry.entries);
67 yield* Effect.forEach(
68 entries.keys(),
69 (environmentId) =>
70 registry
71 .run(
72 environmentId,
73 request(WS_METHODS.serverReportClientActivity, {
74 environmentId: environmentId as EnvironmentId,
75 clientId,
76 clientKind: "mobile",
77 visible: foreground,
78 focused: foreground,
79 recentlyInteracted: foreground,
80 appState: normalizeAppState(appState),
81 scopes: [
82 ...BASELINE_SCOPES,
83 ...retainedMobileBackgroundScopes(environmentId as EnvironmentId),
84 ],
85 ttlMs: LEASE_TTL_MS,
86 observedAt: DateTime.makeUnsafe(observedAtMs),
87 }),
88 )
89 // Not `ignore`: tearing down an environment mid-request interrupts its report,
90 // and an interrupt leaking out here would end the reporting loop for good.
91 // The timeout covers a live connection that never answers, which would stall it.
92 .pipe(Effect.timeout(`${REPORT_TIMEOUT_MS} millis`), Effect.ignoreCause),
93 { concurrency: "unbounded", discard: true },
94 );
95 }).pipe(Effect.withSpan("mobile.backgroundActivity.report"));
96
97 yield* Effect.acquireRelease(
98 Effect.sync(() => {
99 const removeScopeListener = onRetainedMobileBackgroundScopesChange(requestReport);
100 const subscription = AppState.addEventListener("change", (nextState) => {
101 const changed = isForeground(appState) !== isForeground(nextState);
102 appState = nextState;
103 if (changed) requestReport();
104 });
105 return { removeScopeListener, subscription };
106 }),
107 ({ removeScopeListener, subscription }) =>
108 Effect.sync(() => {
109 removeScopeListener();
110 subscription.remove();
111 }),
112 );
113 yield* SubscriptionRef.changes(registry.entries).pipe(
114 Stream.runForEach(() => Effect.sync(requestReport)),
115 Effect.forkScoped,
116 );
117 yield* Stream.fromQueue(reportRequests).pipe(
118 Stream.debounce("250 millis"),
119 Stream.runForEach(() => report),
120 Effect.forkScoped,
121 );
122 yield* Effect.sync(() => {
123 if (isForeground(appState)) requestReport();
124 }).pipe(Effect.repeat(Schedule.spaced(`${REPORT_INTERVAL_MS} millis`)), Effect.forkScoped);
125 }),
126);