Open History to see the last commit
1import {
2 type AuthSessionId,
3 type BackgroundPolicySnapshot,
4 type BackgroundScope,
5 type ClientActivityLease,
6 type ClientActivityReportInput,
7 type HostPowerSnapshot,
8 type RpcClientId,
9} from "@t3tools/contracts";
10import {
11 getBackgroundActivityPresetSettings,
12 resolveServerBackgroundActivitySettings,
13 type ResolvedBackgroundActivitySettings,
14} from "@t3tools/shared/backgroundActivitySettings";
15import * as DateTime from "effect/DateTime";
16import * as Context from "effect/Context";
17import * as Effect from "effect/Effect";
18import * as Layer from "effect/Layer";
19import * as PubSub from "effect/PubSub";
20import * as Ref from "effect/Ref";
21import * as Scope from "effect/Scope";
22import * as Semaphore from "effect/Semaphore";
23import * as Stream from "effect/Stream";
24
25import { ServerSettingsService } from "../serverSettings.ts";
26import { subscribeBeforeSnapshot } from "../utils/subscribeBeforeSnapshot.ts";
27import * as HostPowerMonitor from "./HostPowerMonitor.ts";
28
29export class BackgroundPolicy extends Context.Service<
30 BackgroundPolicy,
31 {
32 readonly reportClientActivity: (
33 sessionId: AuthSessionId,
34 rpcClientId: RpcClientId,
35 input: ClientActivityReportInput,
36 ) => Effect.Effect<void>;
37 readonly removeRpcClient: (
38 sessionId: AuthSessionId,
39 rpcClientId: RpcClientId,
40 ) => Effect.Effect<void>;
41 readonly reportHostPowerState: (snapshot: HostPowerSnapshot) => Effect.Effect<void>;
42 readonly snapshot: Effect.Effect<BackgroundPolicySnapshot>;
43 readonly streamChanges: Stream.Stream<BackgroundPolicySnapshot>;
44 readonly subscribe: Effect.Effect<
45 {
46 readonly latest: BackgroundPolicySnapshot;
47 readonly changes: Stream.Stream<BackgroundPolicySnapshot>;
48 },
49 never,
50 Scope.Scope
51 >;
52 readonly hasDemand: (scope: BackgroundScope) => Effect.Effect<boolean>;
53 readonly shouldRunScopeWork: (scope: BackgroundScope) => Effect.Effect<boolean>;
54 readonly shouldRunOpportunisticWork: Effect.Effect<boolean>;
55 }
56>()("t3/background/BackgroundPolicy") {}
57
58const DEFAULT_LEASE_TTL_MS = 45_000;
59const MAX_LEASE_TTL_MS = 120_000;
60export const MAX_CLIENT_ACTIVITY_LEASES_PER_RPC_CLIENT = 16;
61
62function scopeKey(scope: BackgroundScope): string {
63 switch (scope.type) {
64 case "server-config":
65 case "diagnostics":
66 return scope.type;
67 case "provider-status":
68 return scope.instanceId ? `${scope.type}:${scope.instanceId}` : scope.type;
69 case "vcs-status":
70 case "git-refs":
71 return `${scope.type}:${scope.cwd}`;
72 case "thread":
73 return `${scope.type}:${scope.threadId}`;
74 }
75}
76
77function isLeaseActive(lease: ClientActivityLease, now: DateTime.Utc): boolean {
78 return DateTime.isGreaterThan(lease.expiresAt, now);
79}
80
81function leaseKey(lease: Pick<ClientActivityLease, "sessionId" | "rpcClientId" | "clientId">) {
82 return JSON.stringify([lease.sessionId, lease.rpcClientId, lease.clientId]);
83}
84
85export function upsertClientActivityLease(
86 leases: ReadonlyMap<string, ClientActivityLease>,
87 lease: ClientActivityLease,
88 now: DateTime.Utc,
89): Map<string, ClientActivityLease> {
90 const next = new Map(leases);
91 for (const [key, current] of next) {
92 if (!isLeaseActive(current, now)) {
93 next.delete(key);
94 }
95 }
96
97 const key = leaseKey(lease);
98 if (!next.has(key)) {
99 let connectionLeaseCount = 0;
100 let oldestConnectionLease:
101 | {
102 readonly key: string;
103 readonly updatedAtMs: number;
104 }
105 | undefined;
106 for (const [currentKey, current] of next) {
107 if (current.sessionId !== lease.sessionId || current.rpcClientId !== lease.rpcClientId) {
108 continue;
109 }
110 connectionLeaseCount += 1;
111 const updatedAtMs = DateTime.toEpochMillis(current.updatedAt);
112 if (oldestConnectionLease === undefined || updatedAtMs < oldestConnectionLease.updatedAtMs) {
113 oldestConnectionLease = { key: currentKey, updatedAtMs };
114 }
115 }
116 if (
117 connectionLeaseCount >= MAX_CLIENT_ACTIVITY_LEASES_PER_RPC_CLIENT &&
118 oldestConnectionLease !== undefined
119 ) {
120 next.delete(oldestConnectionLease.key);
121 }
122 }
123
124 next.set(key, lease);
125 return next;
126}
127
128function isForegroundLease(lease: ClientActivityLease, now: DateTime.Utc): boolean {
129 return isLeaseActive(lease, now) && lease.visible && (lease.focused || lease.recentlyInteracted);
130}
131
132function leaseHasScope(lease: ClientActivityLease, scope: BackgroundScope): boolean {
133 const key = scopeKey(scope);
134 return lease.scopes.some((leaseScope) => scopeKey(leaseScope) === key);
135}
136
137function hasThermalPressure(hostPower: HostPowerSnapshot): boolean {
138 return hostPower.thermalState === "serious" || hostPower.thermalState === "critical";
139}
140
141function isHostConstrained(
142 hostPower: HostPowerSnapshot,
143 settings: ResolvedBackgroundActivitySettings,
144): boolean {
145 if (hostPower.stale) return false;
146 if (
147 hostPower.suspended ||
148 (settings.pauseWhenHostLocked && hostPower.locked === "true") ||
149 hasThermalPressure(hostPower)
150 ) {
151 return true;
152 }
153 if (settings.pauseWhenHostLowPower && hostPower.lowPowerMode === "true") return true;
154 return settings.pauseWhenOnBattery && hostPower.onBattery === "true";
155}
156
157function isClientConstrained(
158 lease: ClientActivityLease,
159 settings: ResolvedBackgroundActivitySettings,
160): boolean {
161 if (settings.pauseWhenClientLowPower && lease.lowPowerMode === "true") return true;
162 return settings.pauseWhenOnBattery && lease.batteryState === "unplugged";
163}
164
165function leaseMayRunScopedWork(
166 lease: ClientActivityLease,
167 scope: BackgroundScope,
168 now: DateTime.Utc,
169 settings: ResolvedBackgroundActivitySettings,
170): boolean {
171 const activeWithScope = isLeaseActive(lease, now) && leaseHasScope(lease, scope);
172 if (!activeWithScope || isClientConstrained(lease, settings)) {
173 return false;
174 }
175 if (settings.profile === "performance") {
176 return true;
177 }
178 return isForegroundLease(lease, now);
179}
180
181function computeSnapshot(input: {
182 readonly hostPower: HostPowerSnapshot;
183 readonly leases: ReadonlyMap<string, ClientActivityLease>;
184 readonly now: DateTime.Utc;
185 readonly settings: ResolvedBackgroundActivitySettings;
186 readonly updatedAt: DateTime.Utc;
187}): BackgroundPolicySnapshot {
188 const activeLeases = [...input.leases.values()].filter((lease) =>
189 isLeaseActive(lease, input.now),
190 );
191 const foregroundLeases = activeLeases.filter((lease) => isForegroundLease(lease, input.now));
192 const activeScopeKeys = new Set<string>();
193 for (const lease of activeLeases) {
194 for (const scope of lease.scopes) {
195 activeScopeKeys.add(scopeKey(scope));
196 }
197 }
198
199 return {
200 hostPower: input.hostPower,
201 leases: activeLeases,
202 activeForegroundLeaseCount: foregroundLeases.length,
203 activeScopeKeys: [...activeScopeKeys].toSorted(),
204 shouldRunOpportunisticWork:
205 foregroundLeases.some((lease) => !isClientConstrained(lease, input.settings)) &&
206 !isHostConstrained(input.hostPower, input.settings),
207 updatedAt: input.updatedAt,
208 };
209}
210
211export const make = Effect.fn("background.policy.make")(function* () {
212 const hostPowerMonitor = yield* HostPowerMonitor.HostPowerMonitor;
213 const serverSettings = yield* ServerSettingsService;
214 const leasesRef = yield* Ref.make(new Map<string, ClientActivityLease>());
215 const changes = yield* PubSub.sliding<BackgroundPolicySnapshot>(1);
216 const publishMutex = yield* Semaphore.make(1);
217
218 const backgroundActivitySettings = serverSettings.getSettings.pipe(
219 Effect.map(resolveServerBackgroundActivitySettings),
220 Effect.orElseSucceed(() => getBackgroundActivityPresetSettings("balanced")),
221 );
222
223 const snapshot = Effect.gen(function* () {
224 const [hostPower, leases, now, settings] = yield* Effect.all([
225 hostPowerMonitor.snapshot,
226 Ref.get(leasesRef),
227 DateTime.now,
228 backgroundActivitySettings,
229 ]);
230 return computeSnapshot({ hostPower, leases, now, settings, updatedAt: now });
231 });
232
233 const publishSnapshotUnlocked = snapshot.pipe(
234 Effect.flatMap((next) => PubSub.publish(changes, next)),
235 );
236 const publishSnapshot = publishMutex.withPermits(1)(publishSnapshotUnlocked);
237
238 const reportClientActivity: BackgroundPolicy["Service"]["reportClientActivity"] = (
239 sessionId,
240 rpcClientId,
241 input,
242 ) =>
243 publishMutex.withPermits(1)(
244 Effect.gen(function* () {
245 const ttlMs = Math.min(
246 Math.max(input.ttlMs ?? DEFAULT_LEASE_TTL_MS, 1_000),
247 MAX_LEASE_TTL_MS,
248 );
249 const now = yield* DateTime.now;
250 const expiresAt = DateTime.add(now, { milliseconds: ttlMs });
251 const lease: ClientActivityLease = {
252 sessionId,
253 rpcClientId,
254 clientId: input.clientId,
255 clientKind: input.clientKind,
256 visible: input.visible,
257 focused: input.focused,
258 recentlyInteracted: input.recentlyInteracted,
259 ...(input.appState !== undefined ? { appState: input.appState } : {}),
260 ...(input.lowPowerMode !== undefined ? { lowPowerMode: input.lowPowerMode } : {}),
261 ...(input.batteryState !== undefined ? { batteryState: input.batteryState } : {}),
262 ...(input.networkType !== undefined ? { networkType: input.networkType } : {}),
263 scopes: input.scopes,
264 updatedAt: now,
265 expiresAt,
266 };
267 yield* Ref.update(leasesRef, (leases) => upsertClientActivityLease(leases, lease, now));
268 yield* publishSnapshotUnlocked;
269 }),
270 );
271
272 const removeRpcClient: BackgroundPolicy["Service"]["removeRpcClient"] = (
273 sessionId,
274 rpcClientId,
275 ) =>
276 publishMutex.withPermits(1)(
277 Ref.update(leasesRef, (leases) => {
278 const next = new Map(leases);
279 for (const [key, lease] of next) {
280 if (lease.sessionId === sessionId && lease.rpcClientId === rpcClientId) {
281 next.delete(key);
282 }
283 }
284 return next;
285 }).pipe(Effect.andThen(publishSnapshotUnlocked), Effect.asVoid),
286 );
287
288 const hasDemand: BackgroundPolicy["Service"]["hasDemand"] = (scope) =>
289 Effect.map(snapshot, (current) => current.activeScopeKeys.includes(scopeKey(scope)));
290
291 const shouldRunScopeWork: BackgroundPolicy["Service"]["shouldRunScopeWork"] = (scope) =>
292 Effect.gen(function* () {
293 const [current, settings] = yield* Effect.all([snapshot, backgroundActivitySettings]);
294 if (isHostConstrained(current.hostPower, settings)) {
295 return false;
296 }
297 return current.leases.some((lease) =>
298 leaseMayRunScopedWork(lease, scope, current.updatedAt, settings),
299 );
300 });
301
302 const shouldRunOpportunisticWork = Effect.map(
303 snapshot,
304 (current) => current.shouldRunOpportunisticWork,
305 );
306
307 yield* Stream.runForEach(hostPowerMonitor.streamChanges, () => publishSnapshot).pipe(
308 Effect.forkScoped,
309 );
310 yield* Stream.runForEach(serverSettings.streamChanges, () => publishSnapshot).pipe(
311 Effect.forkScoped,
312 );
313
314 yield* Effect.forever(
315 Effect.sleep("15 seconds").pipe(
316 Effect.andThen(
317 publishMutex.withPermits(1)(
318 Effect.gen(function* () {
319 const now = yield* DateTime.now;
320 yield* Ref.update(leasesRef, (leases) => {
321 const next = new Map(leases);
322 for (const [key, lease] of next) {
323 if (!isLeaseActive(lease, now)) {
324 next.delete(key);
325 }
326 }
327 return next;
328 });
329 yield* publishSnapshotUnlocked;
330 }),
331 ),
332 ),
333 ),
334 ).pipe(Effect.forkScoped);
335
336 return BackgroundPolicy.of({
337 reportClientActivity,
338 removeRpcClient,
339 reportHostPowerState: hostPowerMonitor.report,
340 snapshot,
341 streamChanges: Stream.fromPubSub(changes),
342 subscribe: subscribeBeforeSnapshot(changes, snapshot, publishMutex),
343 hasDemand,
344 shouldRunScopeWork,
345 shouldRunOpportunisticWork,
346 });
347});
348
349export const layer = Layer.effect(BackgroundPolicy, make());