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

BackgroundPolicy.test.ts

309 lines10.6 KB

1import { assert, describe, it } from "@effect/vitest";
2import {
3 AuthSessionId,
4 RpcClientId,
5 type HostPowerSnapshot,
6 type ClientActivityReportInput,
7} from "@t3tools/contracts";
8import * as DateTime from "effect/DateTime";
9import * as Deferred from "effect/Deferred";
10import * as Effect from "effect/Effect";
11import * as Fiber from "effect/Fiber";
12import * as Layer from "effect/Layer";
13import * as PubSub from "effect/PubSub";
14import * as Ref from "effect/Ref";
15import * as Stream from "effect/Stream";
16​
17import * as ServerSettings from "../serverSettings.ts";
18import * as BackgroundPolicy from "./BackgroundPolicy.ts";
19import * as HostPowerMonitor from "./HostPowerMonitor.ts";
20​
21const TEST_NOW = DateTime.makeUnsafe("2026-05-13T00:00:00.000Z");
22​
23const nominalHostPower: HostPowerSnapshot = {
24 source: "unknown",
25 idle: "unknown",
26 idleSeconds: null,
27 locked: "unknown",
28 suspended: false,
29 onBattery: "unknown",
30 lowPowerMode: "unknown",
31 thermalState: "unknown",
32 stale: true,
33 updatedAt: TEST_NOW,
34};
35​
36function makeReport(overrides: Partial<ClientActivityReportInput> = {}): ClientActivityReportInput {
37 return {
38 clientId: "client-1",
39 clientKind: "web",
40 visible: true,
41 focused: true,
42 recentlyInteracted: true,
43 scopes: [{ type: "vcs-status", cwd: "/repo" }],
44 ttlMs: 45_000,
45 observedAt: TEST_NOW,
46 ...overrides,
47 };
49​
50function layerFor(
51 hostPower: HostPowerSnapshot,
52 settingsOverrides: Parameters<typeof ServerSettings.layerTest>[0] = {},
53) {
54 const layerHost = Layer.effect(
55 HostPowerMonitor.HostPowerMonitor,
56 Effect.gen(function* () {
57 const changes = yield* PubSub.sliding<HostPowerSnapshot>(1);
58 let snapshot = hostPower;
59 return HostPowerMonitor.HostPowerMonitor.of({
60 snapshot: Effect.sync(() => snapshot),
61 report: (next) =>
62 Effect.sync(() => {
63 snapshot = next;
64 }).pipe(Effect.andThen(PubSub.publish(changes, next)), Effect.asVoid),
65 streamChanges: Stream.fromPubSub(changes),
66 });
67 }),
68 );
69 return BackgroundPolicy.layer.pipe(
70 Layer.provide(Layer.merge(layerHost, ServerSettings.layerTest(settingsOverrides))),
71 );
73​
74describe("BackgroundPolicy", () => {
75 it.effect("removes all leases for a disconnected websocket connection", () =>
76 Effect.gen(function* () {
77 const policy = yield* BackgroundPolicy.BackgroundPolicy;
78 yield* policy.reportClientActivity(
79 AuthSessionId.make("session-1"),
80 RpcClientId.make(1),
81 makeReport(),
82 );
83 yield* policy.removeRpcClient(AuthSessionId.make("session-1"), RpcClientId.make(1));
84​
85 const snapshot = yield* policy.snapshot;
86 assert.equal(snapshot.activeForegroundLeaseCount, 0);
87 assert.deepStrictEqual(snapshot.activeScopeKeys, []);
88 assert.equal(snapshot.shouldRunOpportunisticWork, false);
89 }).pipe(Effect.provide(layerFor(nominalHostPower))),
90 );
91​
92 it.effect("keeps leases from another session when rpc client ids are reused", () =>
93 Effect.gen(function* () {
94 const policy = yield* BackgroundPolicy.BackgroundPolicy;
95 const rpcClientId = RpcClientId.make(1);
96 yield* policy.reportClientActivity(
97 AuthSessionId.make("session-1"),
98 rpcClientId,
99 makeReport({ clientId: "client-1" }),
100 );
101 yield* policy.reportClientActivity(
102 AuthSessionId.make("session-2"),
103 rpcClientId,
104 makeReport({ clientId: "client-2" }),
105 );
106​
107 yield* policy.removeRpcClient(AuthSessionId.make("session-1"), rpcClientId);
108​
109 const snapshot = yield* policy.snapshot;
110 assert.equal(snapshot.activeForegroundLeaseCount, 1);
111 assert.equal(snapshot.leases[0]?.sessionId, AuthSessionId.make("session-2"));
112 assert.equal(snapshot.leases[0]?.clientId, "client-2");
113 }).pipe(Effect.provide(layerFor(nominalHostPower))),
114 );
115​
116 it.effect("serializes lease mutation publications", () =>
117 Effect.gen(function* () {
118 const firstSnapshotStarted = yield* Deferred.make<void>();
119 const releaseFirstSnapshot = yield* Deferred.make<void>();
120 const snapshotReads = yield* Ref.make(0);
121 const layerHost = Layer.succeed(
122 HostPowerMonitor.HostPowerMonitor,
123 HostPowerMonitor.HostPowerMonitor.of({
124 snapshot: Ref.updateAndGet(snapshotReads, (count) => count + 1).pipe(
125 Effect.flatMap((count) =>
126 count === 1
127 ? Deferred.succeed(firstSnapshotStarted, undefined).pipe(
128 Effect.andThen(Deferred.await(releaseFirstSnapshot)),
129 Effect.as(nominalHostPower),
130 )
131 : Effect.succeed(nominalHostPower),
132 ),
133 ),
134 report: () => Effect.void,
135 streamChanges: Stream.empty,
136 }),
137 );
138 const layer = BackgroundPolicy.layer.pipe(
139 Layer.provide(Layer.merge(layerHost, ServerSettings.layerTest())),
140 );
141​
142 yield* Effect.gen(function* () {
143 const policy = yield* BackgroundPolicy.BackgroundPolicy;
144 const updatesFiber = yield* policy.streamChanges.pipe(
145 Stream.take(2),
146 Stream.runCollect,
147 Effect.forkChild,
148 );
149 yield* Effect.yieldNow;
150 const reportFiber = yield* policy
151 .reportClientActivity(AuthSessionId.make("session-1"), RpcClientId.make(1), makeReport())
152 .pipe(Effect.forkChild);
153 yield* Deferred.await(firstSnapshotStarted);
154 const removeFiber = yield* policy
155 .removeRpcClient(AuthSessionId.make("session-1"), RpcClientId.make(1))
156 .pipe(Effect.forkChild);
157 yield* Effect.yieldNow;
158 yield* Deferred.succeed(releaseFirstSnapshot, undefined);
159 yield* Fiber.join(reportFiber);
160 yield* Fiber.join(removeFiber);
161 const updates = Array.from(yield* Fiber.join(updatesFiber));
162​
163 assert.equal(updates.at(-1)?.activeForegroundLeaseCount, 0);
164 assert.deepStrictEqual(updates.at(-1)?.activeScopeKeys, []);
165 }).pipe(Effect.provide(layer));
166 }),
167 );
168​
169 it.effect("bounds client-id churn for one websocket connection", () =>
170 Effect.gen(function* () {
171 const policy = yield* BackgroundPolicy.BackgroundPolicy;
172 const sessionId = AuthSessionId.make("session-1");
173 const rpcClientId = RpcClientId.make(1);
174 for (
175 let index = 0;
176 index <= BackgroundPolicy.MAX_CLIENT_ACTIVITY_LEASES_PER_RPC_CLIENT;
177 index += 1
178 ) {
179 yield* policy.reportClientActivity(
180 sessionId,
181 rpcClientId,
182 makeReport({ clientId: `client-${index}` }),
183 );
184 }
185​
186 const snapshot = yield* policy.snapshot;
187 assert.equal(
188 snapshot.leases.length,
189 BackgroundPolicy.MAX_CLIENT_ACTIVITY_LEASES_PER_RPC_CLIENT,
190 );
191 assert.isTrue(
192 snapshot.leases.some(
193 (lease) =>
194 lease.clientId ===
195 `client-${BackgroundPolicy.MAX_CLIENT_ACTIVITY_LEASES_PER_RPC_CLIENT}`,
196 ),
197 );
198 }).pipe(Effect.provide(layerFor(nominalHostPower))),
199 );
200​
201 it.effect("host suspension disables scoped and opportunistic work", () =>
202 Effect.gen(function* () {
203 const policy = yield* BackgroundPolicy.BackgroundPolicy;
204 yield* policy.reportClientActivity(
205 AuthSessionId.make("session-1"),
206 RpcClientId.make(1),
207 makeReport(),
208 );
209​
210 const snapshot = yield* policy.snapshot;
211 assert.equal(snapshot.activeForegroundLeaseCount, 1);
212 assert.equal(snapshot.shouldRunOpportunisticWork, false);
213 assert.equal(yield* policy.hasDemand({ type: "vcs-status", cwd: "/repo" }), true);
214 assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), false);
215 }).pipe(
216 Effect.provide(
217 layerFor({
218 ...nominalHostPower,
219 suspended: true,
220 stale: false,
221 }),
222 ),
223 ),
224 );
225​
226 it.effect("keeps background demand visible while preventing scoped work", () =>
227 Effect.gen(function* () {
228 const policy = yield* BackgroundPolicy.BackgroundPolicy;
229 yield* policy.reportClientActivity(
230 AuthSessionId.make("session-1"),
231 RpcClientId.make(1),
232 makeReport({ focused: false, visible: false }),
233 );
234​
235 const snapshot = yield* policy.snapshot;
236 assert.equal(snapshot.activeForegroundLeaseCount, 0);
237 assert.deepStrictEqual(snapshot.activeScopeKeys, ["vcs-status:/repo"]);
238 assert.equal(yield* policy.hasDemand({ type: "vcs-status", cwd: "/repo" }), true);
239 assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), false);
240 }).pipe(Effect.provide(layerFor(nominalHostPower))),
241 );
242​
243 it.effect("keeps scoped work active after a recently used visible window loses focus", () =>
244 Effect.gen(function* () {
245 const policy = yield* BackgroundPolicy.BackgroundPolicy;
246 yield* policy.reportClientActivity(
247 AuthSessionId.make("session-1"),
248 RpcClientId.make(1),
249 makeReport({ focused: false, recentlyInteracted: true }),
250 );
251​
252 const snapshot = yield* policy.snapshot;
253 assert.equal(snapshot.activeForegroundLeaseCount, 1);
254 assert.equal(snapshot.shouldRunOpportunisticWork, true);
255 assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), true);
256 }).pipe(Effect.provide(layerFor(nominalHostPower))),
257 );
258​
259 it.effect("battery saver profile pauses scoped work on battery", () =>
260 Effect.gen(function* () {
261 const policy = yield* BackgroundPolicy.BackgroundPolicy;
262 yield* policy.reportClientActivity(
263 AuthSessionId.make("session-1"),
264 RpcClientId.make(1),
265 makeReport(),
266 );
267​
268 assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), false);
269 }).pipe(
270 Effect.provide(
271 layerFor(
272 {
273 ...nominalHostPower,
274 onBattery: "true",
275 stale: false,
276 },
277 { backgroundActivityProfile: "battery-saver" },
278 ),
279 ),
280 ),
281 );
282​
283 it.effect("does not gate work on stale host power values", () =>
284 Effect.gen(function* () {
285 const policy = yield* BackgroundPolicy.BackgroundPolicy;
286 yield* policy.reportClientActivity(
287 AuthSessionId.make("session-1"),
288 RpcClientId.make(1),
289 makeReport(),
290 );
291​
292 assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), true);
293 }).pipe(
294 Effect.provide(
295 layerFor(
296 {
297 ...nominalHostPower,
298 locked: "true",
299 onBattery: "true",
300 lowPowerMode: "true",
301 thermalState: "critical",
302 stale: true,
303 },
304 { backgroundActivityProfile: "battery-saver" },
305 ),
306 ),
307 ),
308 );
309});