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;
27const LEASE_TTL_MS = 45_000;
28const BASELINE_SCOPES: ReadonlyArray<BackgroundScope> = [{ type: "provider-status" }];
29
30function normalizeAppState(
31 state: string | null | undefined,
32): NonNullable<ClientActivityReportInput["appState"]> {
33 if (state === "active" || state === "inactive" || state === "background") return state;
34 return "unknown";
35}
36
37export const layerObserver = Layer.succeed(
38 EnvironmentRpcSubscriptionObserver,
39 EnvironmentRpcSubscriptionObserver.of({
40 observe: observeMobileBackgroundActivitySubscription,
41 }),
42);
43
44export const layerReporter = Layer.effectDiscard(
45 Effect.gen(function* () {
46 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
47 const storage = yield* MobileStorage.MobileStorage;
48 const clientId = yield* storage.loadOrCreateAgentAwarenessDeviceId.pipe(
49 Effect.map((deviceId) => `mobile-${deviceId}`),
50 Effect.orElseSucceed(() => "ephemeral-mobile-client"),
51 );
52 const reportRequests = yield* Queue.sliding<void>(1);
53 const requestReport = () => Queue.offerUnsafe(reportRequests, undefined);
54 let appState = AppState.currentState;
55
56 const report = Effect.gen(function* () {
57 const observedAtMs = yield* Clock.currentTimeMillis;
58 const active = appState === "active";
59 const entries = yield* SubscriptionRef.get(registry.entries);
60 yield* Effect.forEach(
61 entries.keys(),
62 (environmentId) =>
63 registry
64 .run(
65 environmentId,
66 request(WS_METHODS.serverReportClientActivity, {
67 environmentId: environmentId as EnvironmentId,
68 clientId,
69 clientKind: "mobile",
70 visible: active,
71 focused: active,
72 recentlyInteracted: active,
73 appState: normalizeAppState(appState),
74 scopes: [
75 ...BASELINE_SCOPES,
76 ...retainedMobileBackgroundScopes(environmentId as EnvironmentId),
77 ],
78 ttlMs: LEASE_TTL_MS,
79 observedAt: DateTime.makeUnsafe(observedAtMs),
80 }),
81 )
82 // Not `ignore`: tearing down an environment mid-request interrupts its report,
83 // and an interrupt leaking out here would end the reporting loop for good.
84 .pipe(Effect.ignoreCause),
85 { concurrency: "unbounded", discard: true },
86 );
87 }).pipe(Effect.withSpan("mobile.backgroundActivity.report"));
88
89 yield* Effect.acquireRelease(
90 Effect.sync(() => {
91 const removeScopeListener = onRetainedMobileBackgroundScopesChange(requestReport);
92 const subscription = AppState.addEventListener("change", (nextState) => {
93 appState = nextState;
94 requestReport();
95 });
96 return { removeScopeListener, subscription };
97 }),
98 ({ removeScopeListener, subscription }) =>
99 Effect.sync(() => {
100 removeScopeListener();
101 subscription.remove();
102 }),
103 );
104 yield* SubscriptionRef.changes(registry.entries).pipe(
105 Stream.runForEach(() => Effect.sync(requestReport)),
106 Effect.forkScoped,
107 );
108 yield* Stream.fromQueue(reportRequests).pipe(
109 Stream.debounce("250 millis"),
110 Stream.runForEach(() => report),
111 Effect.forkScoped,
112 );
113 yield* Effect.sync(requestReport).pipe(
114 Effect.repeat(Schedule.spaced(`${REPORT_INTERVAL_MS} millis`)),
115 Effect.forkScoped,
116 );
117 }),
118);