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