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

backgroundActivityReporter.ts

255 lines8.7 KB

1import { EnvironmentRegistry } from "@t3tools/client-runtime/connection";
2import {
3 EnvironmentRpcSubscriptionObserver,
4 request,
5 type EnvironmentRpcSubscriptionObservation,
6} from "@t3tools/client-runtime/rpc";
7import {
8 type BackgroundScope,
9 type ClientActivityReportInput,
10 type EnvironmentId,
11 WS_METHODS,
12} from "@t3tools/contracts";
13import * as Clock from "effect/Clock";
14import * as DateTime from "effect/DateTime";
15import * as Effect from "effect/Effect";
16import * as Layer from "effect/Layer";
17import * as Queue from "effect/Queue";
18import * as Schedule from "effect/Schedule";
19import * as Stream from "effect/Stream";
20import * as SubscriptionRef from "effect/SubscriptionRef";
21​
22import { randomUUID } from "./utils";
23​
24const CLIENT_ID_STORAGE_KEY = "t3.backgroundActivity.clientId";
25const REPORT_INTERVAL_MS = 25_000;
26const LEASE_TTL_MS = 45_000;
27const RECENT_INTERACTION_WINDOW_MS = LEASE_TTL_MS;
28const BASELINE_SCOPES: ReadonlyArray<BackgroundScope> = [{ type: "provider-status" }];
29​
30interface RetainedScope {
31 readonly environmentId: EnvironmentId;
32 readonly scope: BackgroundScope;
33 refCount: number;
35​
36const retainedScopes = new Map<string, RetainedScope>();
37const retainedScopeListeners = new Set<() => void>();
38​
39function notifyRetainedScopesChanged(): void {
40 for (const listener of retainedScopeListeners) {
41 try {
42 listener();
43 } catch {}
44 }
46​
47function stableScopeKey(environmentId: EnvironmentId, scope: BackgroundScope): string {
48 switch (scope.type) {
49 case "server-config":
50 case "diagnostics":
51 return JSON.stringify([environmentId, scope.type]);
52 case "provider-status":
53 return JSON.stringify([environmentId, scope.type, scope.instanceId ?? null]);
54 case "vcs-status":
55 case "git-refs":
56 return JSON.stringify([environmentId, scope.type, scope.cwd]);
57 case "thread":
58 return JSON.stringify([environmentId, scope.type, scope.threadId]);
59 }
61​
62function getClientId(): string {
63 try {
64 const existing = window.localStorage.getItem(CLIENT_ID_STORAGE_KEY);
65 if (existing) return existing;
66 const next = randomUUID();
67 window.localStorage.setItem(CLIENT_ID_STORAGE_KEY, next);
68 return next;
69 } catch {
70 return "ephemeral-browser-client";
71 }
73​
74function resolveClientKind(): ClientActivityReportInput["clientKind"] {
75 return window.desktopBridge ? "desktop-renderer" : "web";
77​
78export function wasRecentlyInteracted(lastInteractionAtMs: number, observedAtMs: number): boolean {
79 return (
80 lastInteractionAtMs <= observedAtMs &&
81 observedAtMs - lastInteractionAtMs <= RECENT_INTERACTION_WINDOW_MS
82 );
84​
85function createActivityReport(
86 environmentId: EnvironmentId,
87 lastInteractionAtMs: number,
88 observedAtMs: number,
89): ClientActivityReportInput {
90 const scopes = [...BASELINE_SCOPES];
91 for (const entry of retainedScopes.values()) {
92 if (entry.environmentId === environmentId) {
93 scopes.push(entry.scope);
94 }
95 }
96 return {
97 environmentId,
98 clientId: getClientId(),
99 clientKind: resolveClientKind(),
100 visible: document.visibilityState === "visible",
101 focused: document.hasFocus(),
102 recentlyInteracted: wasRecentlyInteracted(lastInteractionAtMs, observedAtMs),
103 appState: document.visibilityState === "visible" ? "active" : "background",
104 scopes,
105 ttlMs: LEASE_TTL_MS,
106 observedAt: DateTime.makeUnsafe(observedAtMs),
107 };
109​
110function scopeForSubscription(
111 observation: EnvironmentRpcSubscriptionObservation,
112): BackgroundScope | null {
113 if (observation.method === WS_METHODS.subscribeResourceTelemetry) {
114 return { type: "diagnostics" };
115 }
116 if (observation.method !== WS_METHODS.subscribeVcsStatus) {
117 return null;
118 }
119 const input = observation.input as { readonly cwd?: unknown; readonly includeRemote?: unknown };
120 if (input.includeRemote === false) return null;
121 return typeof input.cwd === "string" ? { type: "vcs-status", cwd: input.cwd } : null;
123​
124function retainBackgroundScope(environmentId: EnvironmentId, scope: BackgroundScope): () => void {
125 const key = stableScopeKey(environmentId, scope);
126 const existing = retainedScopes.get(key);
127 if (existing) {
128 existing.refCount += 1;
129 } else {
130 retainedScopes.set(key, { environmentId, scope, refCount: 1 });
131 notifyRetainedScopesChanged();
132 }
133​
134 return () => {
135 const current = retainedScopes.get(key);
136 if (!current) return;
137 current.refCount -= 1;
138 if (current.refCount <= 0) {
139 retainedScopes.delete(key);
140 notifyRetainedScopesChanged();
141 }
142 };
144​
145export function observeBackgroundActivitySubscription(
146 observation: EnvironmentRpcSubscriptionObservation,
147): Effect.Effect<Effect.Effect<void>> {
148 const scope = scopeForSubscription(observation);
149 if (scope === null) {
150 return Effect.succeed(Effect.void);
151 }
152 return Effect.sync(() => {
153 const release = retainBackgroundScope(observation.environmentId as EnvironmentId, scope);
154 return Effect.sync(release);
155 });
157​
158export function retainedBackgroundScopes(
159 environmentId: EnvironmentId,
160): ReadonlyArray<BackgroundScope> {
161 return Array.from(retainedScopes.values(), (entry) =>
162 entry.environmentId === environmentId ? entry.scope : null,
163 ).filter((scope): scope is BackgroundScope => scope !== null);
165​
166export const layerObserver = Layer.succeed(
167 EnvironmentRpcSubscriptionObserver,
168 EnvironmentRpcSubscriptionObserver.of({
169 observe: observeBackgroundActivitySubscription,
170 }),
171);
172​
173export const layer = Layer.effectDiscard(
174 Effect.gen(function* () {
175 if (typeof window === "undefined" || typeof document === "undefined") {
176 return;
177 }
178​
179 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
180 const clock = yield* Clock.Clock;
181 const reportRequests = yield* Queue.sliding<void>(1);
182 const requestReport = () => Queue.offerUnsafe(reportRequests, undefined);
183 let lastInteractionAtMs = clock.currentTimeMillisUnsafe();
184 const recordInteraction = () => {
185 const observedAtMs = clock.currentTimeMillisUnsafe();
186 const wasRecent = wasRecentlyInteracted(lastInteractionAtMs, observedAtMs);
187 lastInteractionAtMs = observedAtMs;
188 if (!wasRecent) {
189 requestReport();
190 }
191 };
192 const passiveListenerOptions = { passive: true } as const;
193​
194 const report = Effect.gen(function* () {
195 const observedAtMs = yield* Clock.currentTimeMillis;
196 const entries = yield* SubscriptionRef.get(registry.entries);
197 yield* Effect.forEach(
198 entries.keys(),
199 (environmentId) =>
200 registry
201 .run(
202 environmentId,
203 request(
204 WS_METHODS.serverReportClientActivity,
205 createActivityReport(environmentId, lastInteractionAtMs, observedAtMs),
206 ),
207 )
208 // Not `ignore`: tearing down an environment mid-request interrupts its report,
209 // and an interrupt leaking out here would end the reporting loop for good.
210 .pipe(Effect.ignoreCause),
211 { concurrency: "unbounded", discard: true },
212 );
213 }).pipe(Effect.withSpan("web.backgroundActivity.report"));
214​
215 yield* Effect.acquireRelease(
216 Effect.sync(() => {
217 retainedScopeListeners.add(requestReport);
218 document.addEventListener("visibilitychange", requestReport);
219 window.addEventListener("focus", requestReport);
220 window.addEventListener("blur", requestReport);
221 window.addEventListener("online", requestReport);
222 window.addEventListener("pointermove", recordInteraction);
223 window.addEventListener("keydown", recordInteraction);
224 window.addEventListener("wheel", recordInteraction, passiveListenerOptions);
225 window.addEventListener("touchstart", recordInteraction, passiveListenerOptions);
226 }),
227 () =>
228 Effect.sync(() => {
229 retainedScopeListeners.delete(requestReport);
230 document.removeEventListener("visibilitychange", requestReport);
231 window.removeEventListener("focus", requestReport);
232 window.removeEventListener("blur", requestReport);
233 window.removeEventListener("online", requestReport);
234 window.removeEventListener("pointermove", recordInteraction);
235 window.removeEventListener("keydown", recordInteraction);
236 window.removeEventListener("wheel", recordInteraction);
237 window.removeEventListener("touchstart", recordInteraction);
238 }),
239 );
240​
241 yield* SubscriptionRef.changes(registry.entries).pipe(
242 Stream.runForEach(() => Effect.sync(requestReport)),
243 Effect.forkScoped,
244 );
245 yield* Stream.fromQueue(reportRequests).pipe(
246 Stream.debounce("250 millis"),
247 Stream.runForEach(() => report),
248 Effect.forkScoped,
249 );
250 yield* Effect.sync(requestReport).pipe(
251 Effect.repeat(Schedule.spaced(`${REPORT_INTERVAL_MS} millis`)),
252 Effect.forkScoped,
253 );
254 }),
255);