Repository navigation
Expand file tree
/
Copy pathbackgroundActivityReporter.ts
More file actions
258 lines (237 loc) · 8.95 KB
/
Copy pathbackgroundActivityReporter.ts
File metadata and controls
258 lines (237 loc) · 8.95 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
import { EnvironmentRegistry } from "@t3tools/client-runtime/connection";
import {
EnvironmentRpcSubscriptionObserver,
request,
type EnvironmentRpcSubscriptionObservation,
} from "@t3tools/client-runtime/rpc";
import {
type BackgroundScope,
type ClientActivityReportInput,
type EnvironmentId,
WS_METHODS,
} from "@t3tools/contracts";
import * as Clock from "effect/Clock";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Queue from "effect/Queue";
import * as Schedule from "effect/Schedule";
import * as Stream from "effect/Stream";
import * as SubscriptionRef from "effect/SubscriptionRef";
import { randomUUID } from "./utils";
const CLIENT_ID_STORAGE_KEY = "t3.backgroundActivity.clientId";
const REPORT_INTERVAL_MS = 25_000;
// Shorter than the interval, so a report that never settles cannot hold up the next one.
const REPORT_TIMEOUT_MS = 15_000;
const LEASE_TTL_MS = 45_000;
const RECENT_INTERACTION_WINDOW_MS = LEASE_TTL_MS;
const BASELINE_SCOPES: ReadonlyArray<BackgroundScope> = [{ type: "provider-status" }];
interface RetainedScope {
readonly environmentId: EnvironmentId;
readonly scope: BackgroundScope;
refCount: number;
}
const retainedScopes = new Map<string, RetainedScope>();
const retainedScopeListeners = new Set<() => void>();
function notifyRetainedScopesChanged(): void {
for (const listener of retainedScopeListeners) {
try {
listener();
} catch {}
}
}
function stableScopeKey(environmentId: EnvironmentId, scope: BackgroundScope): string {
switch (scope.type) {
case "server-config":
case "diagnostics":
return JSON.stringify([environmentId, scope.type]);
case "provider-status":
return JSON.stringify([environmentId, scope.type, scope.instanceId ?? null]);
case "vcs-status":
case "git-refs":
return JSON.stringify([environmentId, scope.type, scope.cwd]);
case "thread":
return JSON.stringify([environmentId, scope.type, scope.threadId]);
}
}
function getClientId(): string {
try {
const existing = window.localStorage.getItem(CLIENT_ID_STORAGE_KEY);
if (existing) return existing;
const next = randomUUID();
window.localStorage.setItem(CLIENT_ID_STORAGE_KEY, next);
return next;
} catch {
return "ephemeral-browser-client";
}
}
function resolveClientKind(): ClientActivityReportInput["clientKind"] {
return window.desktopBridge ? "desktop-renderer" : "web";
}
function wasRecentlyInteracted(lastInteractionAtMs: number, observedAtMs: number): boolean {
return (
lastInteractionAtMs <= observedAtMs &&
observedAtMs - lastInteractionAtMs <= RECENT_INTERACTION_WINDOW_MS
);
}
function createActivityReport(
environmentId: EnvironmentId,
lastInteractionAtMs: number,
observedAtMs: number,
): ClientActivityReportInput {
const scopes = [...BASELINE_SCOPES];
for (const entry of retainedScopes.values()) {
if (entry.environmentId === environmentId) {
scopes.push(entry.scope);
}
}
return {
environmentId,
clientId: getClientId(),
clientKind: resolveClientKind(),
visible: document.visibilityState === "visible",
focused: document.hasFocus(),
recentlyInteracted: wasRecentlyInteracted(lastInteractionAtMs, observedAtMs),
appState: document.visibilityState === "visible" ? "active" : "background",
scopes,
ttlMs: LEASE_TTL_MS,
observedAt: DateTime.makeUnsafe(observedAtMs),
};
}
function scopeForSubscription(
observation: EnvironmentRpcSubscriptionObservation,
): BackgroundScope | null {
if (observation.method === WS_METHODS.subscribeResourceTelemetry) {
return { type: "diagnostics" };
}
if (observation.method !== WS_METHODS.subscribeVcsStatus) {
return null;
}
const input = observation.input as { readonly cwd?: unknown; readonly includeRemote?: unknown };
if (input.includeRemote === false) return null;
return typeof input.cwd === "string" ? { type: "vcs-status", cwd: input.cwd } : null;
}
function retainBackgroundScope(environmentId: EnvironmentId, scope: BackgroundScope): () => void {
const key = stableScopeKey(environmentId, scope);
const existing = retainedScopes.get(key);
if (existing) {
existing.refCount += 1;
} else {
retainedScopes.set(key, { environmentId, scope, refCount: 1 });
notifyRetainedScopesChanged();
}
return () => {
const current = retainedScopes.get(key);
if (!current) return;
current.refCount -= 1;
if (current.refCount <= 0) {
retainedScopes.delete(key);
notifyRetainedScopesChanged();
}
};
}
export function observeBackgroundActivitySubscription(
observation: EnvironmentRpcSubscriptionObservation,
): Effect.Effect<Effect.Effect<void>> {
const scope = scopeForSubscription(observation);
if (scope === null) {
return Effect.succeed(Effect.void);
}
return Effect.sync(() => {
const release = retainBackgroundScope(observation.environmentId as EnvironmentId, scope);
return Effect.sync(release);
});
}
export function retainedBackgroundScopes(
environmentId: EnvironmentId,
): ReadonlyArray<BackgroundScope> {
return Array.from(retainedScopes.values(), (entry) =>
entry.environmentId === environmentId ? entry.scope : null,
).filter((scope): scope is BackgroundScope => scope !== null);
}
export const layerObserver = Layer.succeed(
EnvironmentRpcSubscriptionObserver,
EnvironmentRpcSubscriptionObserver.of({
observe: observeBackgroundActivitySubscription,
}),
);
export const layer = Layer.effectDiscard(
Effect.gen(function* () {
if (typeof window === "undefined" || typeof document === "undefined") {
return;
}
const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
const clock = yield* Clock.Clock;
const reportRequests = yield* Queue.sliding<void>(1);
const requestReport = () => Queue.offerUnsafe(reportRequests, undefined);
let lastInteractionAtMs = clock.currentTimeMillisUnsafe();
const recordInteraction = () => {
const observedAtMs = clock.currentTimeMillisUnsafe();
const wasRecent = wasRecentlyInteracted(lastInteractionAtMs, observedAtMs);
lastInteractionAtMs = observedAtMs;
if (!wasRecent) {
requestReport();
}
};
const passiveListenerOptions = { passive: true } as const;
const report = Effect.gen(function* () {
const observedAtMs = yield* Clock.currentTimeMillis;
const entries = yield* SubscriptionRef.get(registry.entries);
yield* Effect.forEach(
entries.keys(),
(environmentId) =>
registry
.run(
environmentId,
request(
WS_METHODS.serverReportClientActivity,
createActivityReport(environmentId, lastInteractionAtMs, observedAtMs),
),
)
// Not `ignore`: tearing down an environment mid-request interrupts its report,
// and an interrupt leaking out here would end the reporting loop for good.
// The timeout covers a live connection that never answers, which would stall it.
.pipe(Effect.timeout(`${REPORT_TIMEOUT_MS} millis`), Effect.ignoreCause),
{ concurrency: "unbounded", discard: true },
);
}).pipe(Effect.withSpan("web.backgroundActivity.report"));
yield* Effect.acquireRelease(
Effect.sync(() => {
retainedScopeListeners.add(requestReport);
document.addEventListener("visibilitychange", requestReport);
window.addEventListener("focus", requestReport);
window.addEventListener("blur", requestReport);
window.addEventListener("online", requestReport);
window.addEventListener("pointermove", recordInteraction);
window.addEventListener("keydown", recordInteraction);
window.addEventListener("wheel", recordInteraction, passiveListenerOptions);
window.addEventListener("touchstart", recordInteraction, passiveListenerOptions);
}),
() =>
Effect.sync(() => {
retainedScopeListeners.delete(requestReport);
document.removeEventListener("visibilitychange", requestReport);
window.removeEventListener("focus", requestReport);
window.removeEventListener("blur", requestReport);
window.removeEventListener("online", requestReport);
window.removeEventListener("pointermove", recordInteraction);
window.removeEventListener("keydown", recordInteraction);
window.removeEventListener("wheel", recordInteraction);
window.removeEventListener("touchstart", recordInteraction);
}),
);
yield* SubscriptionRef.changes(registry.entries).pipe(
Stream.runForEach(() => Effect.sync(requestReport)),
Effect.forkScoped,
);
yield* Stream.fromQueue(reportRequests).pipe(
Stream.debounce("250 millis"),
Stream.runForEach(() => report),
Effect.forkScoped,
);
yield* Effect.sync(requestReport).pipe(
Effect.repeat(Schedule.spaced(`${REPORT_INTERVAL_MS} millis`)),
Effect.forkScoped,
);
}),
);