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

VcsStatusBroadcaster.test.ts

820 lines29.1 KB

1import { assert, it, describe } from "@effect/vitest";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import * as Cause from "effect/Cause";
4import * as Deferred from "effect/Deferred";
5import * as DateTime from "effect/DateTime";
6import * as Duration from "effect/Duration";
7import * as Effect from "effect/Effect";
8import * as Exit from "effect/Exit";
9import * as FileSystem from "effect/FileSystem";
10import * as Layer from "effect/Layer";
11import * as Logger from "effect/Logger";
12import * as Option from "effect/Option";
13import * as Path from "effect/Path";
14import * as Scope from "effect/Scope";
15import * as Stream from "effect/Stream";
16import * as TestClock from "effect/testing/TestClock";
17import type {
18 BackgroundScope,
19 VcsStatusLocalResult,
20 VcsStatusRemoteResult,
21 VcsStatusResult,
22 VcsStatusStreamEvent,
23} from "@t3tools/contracts";
24import { GitManagerError } from "@t3tools/contracts";
25​
26import * as VcsStatusBroadcaster from "./VcsStatusBroadcaster.ts";
27import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
28import * as GitWorkflowService from "../git/GitWorkflowService.ts";
29​
30const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
31​
32const baseLocalStatus: VcsStatusLocalResult = {
33 isRepo: true,
34 sourceControlProvider: {
35 kind: "github",
36 name: "GitHub",
37 baseUrl: "https://github.com",
38 },
39 hasPrimaryRemote: true,
40 isDefaultRef: false,
41 refName: "feature/status-broadcast",
42 hasWorkingTreeChanges: false,
43 workingTree: { files: [], insertions: 0, deletions: 0 },
44};
45​
46const baseRemoteStatus: VcsStatusRemoteResult = {
47 hasUpstream: true,
48 aheadCount: 0,
49 behindCount: 0,
50 pr: null,
51};
52​
53const remoteStatusWithPr: VcsStatusRemoteResult = {
54 ...baseRemoteStatus,
55 pr: {
56 number: 2978,
57 title: "[codex] Rewrite client connection architecture",
58 url: "https://github.com/pingdotgg/t3code/pull/2978",
59 baseRef: "main",
60 headRef: "codex/connection-state-audit",
61 state: "open",
62 },
63};
64​
65const baseStatus: VcsStatusResult = {
66 ...baseLocalStatus,
67 ...baseRemoteStatus,
68};
69​
70function makeTestLayer(state: {
71 currentLocalStatus: VcsStatusLocalResult;
72 currentRemoteStatus: VcsStatusRemoteResult | null;
73 localStatusCalls: number;
74 remoteStatusCalls: number;
75 localInvalidationCalls: number;
76 remoteInvalidationCalls: number;
77 remoteStatusRefreshUpstreamValues?: Array<boolean | undefined>;
78}) {
79 return VcsStatusBroadcaster.layer.pipe(
80 Layer.provideMerge(NodeServices.layer),
81 Layer.provide(makeBackgroundPolicyLayer(() => true)),
82 Layer.provide(
83 Layer.mock(GitWorkflowService.GitWorkflowService)({
84 localStatus: () =>
85 Effect.sync(() => {
86 state.localStatusCalls += 1;
87 return state.currentLocalStatus;
88 }),
89 remoteStatus: (_input, options) =>
90 Effect.sync(() => {
91 state.remoteStatusCalls += 1;
92 state.remoteStatusRefreshUpstreamValues?.push(options?.refreshUpstream);
93 return state.currentRemoteStatus;
94 }),
95 invalidateLocalStatus: () =>
96 Effect.sync(() => {
97 state.localInvalidationCalls += 1;
98 }),
99 invalidateRemoteStatus: () =>
100 Effect.sync(() => {
101 state.remoteInvalidationCalls += 1;
102 }),
103 invalidateStatus: () =>
104 Effect.sync(() => {
105 state.localInvalidationCalls += 1;
106 state.remoteInvalidationCalls += 1;
107 }),
108 }),
109 ),
110 );
112​
113function makeBackgroundPolicyLayer(shouldRunScopeWork: (scope: BackgroundScope) => boolean) {
114 return Layer.mock(BackgroundPolicy.BackgroundPolicy)({
115 reportClientActivity: () => Effect.void,
116 removeRpcClient: () => Effect.void,
117 reportHostPowerState: () => Effect.void,
118 snapshot: Effect.succeed({
119 hostPower: {
120 source: "unknown",
121 idle: "unknown",
122 idleSeconds: null,
123 locked: "unknown",
124 suspended: false,
125 onBattery: "unknown",
126 lowPowerMode: "unknown",
127 thermalState: "unknown",
128 stale: true,
129 updatedAt: TEST_EPOCH,
130 },
131 leases: [],
132 activeForegroundLeaseCount: 0,
133 activeScopeKeys: [],
134 shouldRunOpportunisticWork: false,
135 updatedAt: TEST_EPOCH,
136 }),
137 streamChanges: Stream.empty,
138 hasDemand: () => Effect.succeed(true),
139 shouldRunScopeWork: (scope) => Effect.sync(() => shouldRunScopeWork(scope)),
140 shouldRunOpportunisticWork: Effect.succeed(true),
141 });
143​
144describe("VcsStatusBroadcaster", () => {
145 it.effect("reuses the cached VCS status across repeated reads", () => {
146 const state = {
147 currentLocalStatus: baseLocalStatus,
148 currentRemoteStatus: baseRemoteStatus,
149 localStatusCalls: 0,
150 remoteStatusCalls: 0,
151 localInvalidationCalls: 0,
152 remoteInvalidationCalls: 0,
153 };
154​
155 return Effect.gen(function* () {
156 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
157​
158 const first = yield* broadcaster.getStatus({ cwd: "/repo" });
159 const second = yield* broadcaster.getStatus({ cwd: "/repo" });
160​
161 assert.deepStrictEqual(first, baseStatus);
162 assert.deepStrictEqual(second, baseStatus);
163 assert.equal(state.localStatusCalls, 1);
164 assert.equal(state.remoteStatusCalls, 1);
165 assert.equal(state.localInvalidationCalls, 0);
166 assert.equal(state.remoteInvalidationCalls, 0);
167 }).pipe(Effect.provide(makeTestLayer(state)));
168 });
169​
170 it.effect("refreshes the cached snapshot after explicit invalidation", () => {
171 const state = {
172 currentLocalStatus: baseLocalStatus,
173 currentRemoteStatus: baseRemoteStatus,
174 localStatusCalls: 0,
175 remoteStatusCalls: 0,
176 localInvalidationCalls: 0,
177 remoteInvalidationCalls: 0,
178 };
179​
180 return Effect.gen(function* () {
181 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
182 const initial = yield* broadcaster.getStatus({ cwd: "/repo" });
183​
184 state.currentLocalStatus = {
185 ...baseLocalStatus,
186 refName: "feature/updated-status",
187 };
188 state.currentRemoteStatus = {
189 ...baseRemoteStatus,
190 aheadCount: 2,
191 };
192 const refreshed = yield* broadcaster.refreshStatus("/repo");
193 const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
194​
195 assert.deepStrictEqual(initial, baseStatus);
196 assert.deepStrictEqual(refreshed, {
197 ...state.currentLocalStatus,
198 ...state.currentRemoteStatus,
199 });
200 assert.deepStrictEqual(cached, {
201 ...state.currentLocalStatus,
202 ...state.currentRemoteStatus,
203 });
204 assert.equal(state.localStatusCalls, 2);
205 assert.equal(state.remoteStatusCalls, 2);
206 assert.equal(state.localInvalidationCalls, 1);
207 assert.equal(state.remoteInvalidationCalls, 1);
208 }).pipe(Effect.provide(makeTestLayer(state)));
209 });
210​
211 it.effect("keeps the cached snapshot unchanged when a refresh branch fails", () => {
212 const state = {
213 currentLocalStatus: baseLocalStatus,
214 currentRemoteStatus: baseRemoteStatus,
215 localStatusCalls: 0,
216 remoteStatusCalls: 0,
217 localInvalidationCalls: 0,
218 remoteInvalidationCalls: 0,
219 failRemoteStatus: false,
220 };
221 const testLayer = VcsStatusBroadcaster.layer.pipe(
222 Layer.provideMerge(NodeServices.layer),
223 Layer.provide(makeBackgroundPolicyLayer(() => true)),
224 Layer.provide(
225 Layer.mock(GitWorkflowService.GitWorkflowService)({
226 localStatus: () =>
227 Effect.sync(() => {
228 state.localStatusCalls += 1;
229 return state.currentLocalStatus;
230 }),
231 remoteStatus: () =>
232 Effect.suspend(() => {
233 state.remoteStatusCalls += 1;
234 return state.failRemoteStatus
235 ? Effect.fail(
236 new GitManagerError({
237 operation: "VcsStatusBroadcaster.test",
238 cwd: "/repo",
239 detail: "remote status failed",
240 }),
241 )
242 : Effect.succeed(state.currentRemoteStatus);
243 }),
244 invalidateLocalStatus: () =>
245 Effect.sync(() => {
246 state.localInvalidationCalls += 1;
247 }),
248 invalidateRemoteStatus: () =>
249 Effect.sync(() => {
250 state.remoteInvalidationCalls += 1;
251 }),
252 invalidateStatus: () =>
253 Effect.sync(() => {
254 state.localInvalidationCalls += 1;
255 state.remoteInvalidationCalls += 1;
256 }),
257 }),
258 ),
259 );
260​
261 return Effect.gen(function* () {
262 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
263 yield* broadcaster.getStatus({ cwd: "/repo" });
264​
265 state.currentLocalStatus = {
266 ...baseLocalStatus,
267 refName: "feature/partial-refresh",
268 };
269 state.currentRemoteStatus = {
270 ...baseRemoteStatus,
271 aheadCount: 3,
272 };
273 state.failRemoteStatus = true;
274​
275 const refreshExit = yield* broadcaster.refreshStatus("/repo").pipe(Effect.exit);
276 const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
277​
278 assert.isTrue(Exit.isFailure(refreshExit));
279 assert.deepStrictEqual(cached, baseStatus);
280 }).pipe(Effect.provide(testLayer));
281 });
282​
283 it.effect("refreshes only the cached local snapshot when requested", () => {
284 const state = {
285 currentLocalStatus: baseLocalStatus,
286 currentRemoteStatus: baseRemoteStatus,
287 localStatusCalls: 0,
288 remoteStatusCalls: 0,
289 localInvalidationCalls: 0,
290 remoteInvalidationCalls: 0,
291 };
292​
293 return Effect.gen(function* () {
294 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
295 const initial = yield* broadcaster.getStatus({ cwd: "/repo" });
296​
297 state.currentLocalStatus = {
298 ...baseLocalStatus,
299 refName: "feature/local-only-refresh",
300 hasWorkingTreeChanges: true,
301 };
302​
303 const refreshedLocal = yield* broadcaster.refreshLocalStatus("/repo");
304 const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
305​
306 assert.deepStrictEqual(initial, baseStatus);
307 assert.deepStrictEqual(refreshedLocal, state.currentLocalStatus);
308 assert.deepStrictEqual(cached, {
309 ...state.currentLocalStatus,
310 ...baseRemoteStatus,
311 });
312 assert.equal(state.localStatusCalls, 2);
313 assert.equal(state.remoteStatusCalls, 1);
314 assert.equal(state.localInvalidationCalls, 1);
315 assert.equal(state.remoteInvalidationCalls, 0);
316 }).pipe(Effect.provide(makeTestLayer(state)));
317 });
318​
319 it.effect("normalizes symlinked CWDs before cache lookup and workflow calls", () => {
320 const seenCwds: string[] = [];
321 const state = {
322 currentLocalStatus: baseLocalStatus,
323 currentRemoteStatus: baseRemoteStatus,
324 localStatusCalls: 0,
325 remoteStatusCalls: 0,
326 localInvalidationCalls: 0,
327 remoteInvalidationCalls: 0,
328 };
329 const testLayer = VcsStatusBroadcaster.layer.pipe(
330 Layer.provideMerge(NodeServices.layer),
331 Layer.provide(makeBackgroundPolicyLayer(() => true)),
332 Layer.provide(
333 Layer.mock(GitWorkflowService.GitWorkflowService)({
334 localStatus: (input) =>
335 Effect.sync(() => {
336 seenCwds.push(input.cwd);
337 state.localStatusCalls += 1;
338 return state.currentLocalStatus;
339 }),
340 remoteStatus: (input) =>
341 Effect.sync(() => {
342 seenCwds.push(input.cwd);
343 state.remoteStatusCalls += 1;
344 return state.currentRemoteStatus;
345 }),
346 invalidateLocalStatus: () =>
347 Effect.sync(() => {
348 state.localInvalidationCalls += 1;
349 }),
350 invalidateRemoteStatus: () =>
351 Effect.sync(() => {
352 state.remoteInvalidationCalls += 1;
353 }),
354 } satisfies Partial<GitWorkflowService.GitWorkflowService["Service"]>),
355 ),
356 );
357​
358 return Effect.gen(function* () {
359 const fileSystem = yield* FileSystem.FileSystem;
360 const path = yield* Path.Path;
361 const realDir = yield* fileSystem.makeTempDirectoryScoped({
362 prefix: "t3-vcs-status-real-",
363 });
364 const linkParent = yield* fileSystem.makeTempDirectoryScoped({
365 prefix: "t3-vcs-status-link-",
366 });
367 const linkDir = path.join(linkParent, "repo-link");
368 yield* fileSystem.symlink(realDir, linkDir);
369 const realPath = yield* fileSystem.realPath(realDir);
370​
371 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
372 yield* broadcaster.getStatus({ cwd: linkDir });
373 yield* broadcaster.getStatus({ cwd: realDir });
374​
375 assert.deepStrictEqual(seenCwds, [realPath, realPath]);
376 assert.equal(state.localStatusCalls, 1);
377 assert.equal(state.remoteStatusCalls, 1);
378 }).pipe(Effect.provide(testLayer));
379 });
380​
381 it.effect("streams a local snapshot first and remote updates later", () => {
382 const state = {
383 currentLocalStatus: baseLocalStatus,
384 currentRemoteStatus: baseRemoteStatus,
385 localStatusCalls: 0,
386 remoteStatusCalls: 0,
387 localInvalidationCalls: 0,
388 remoteInvalidationCalls: 0,
389 };
390​
391 return Effect.gen(function* () {
392 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
393 const snapshotDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
394 const remoteUpdatedDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
395 yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) => {
396 if (event._tag === "snapshot") {
397 return Deferred.succeed(snapshotDeferred, event).pipe(Effect.ignore);
398 }
399 if (event._tag === "remoteUpdated") {
400 return Deferred.succeed(remoteUpdatedDeferred, event).pipe(Effect.ignore);
401 }
402 return Effect.void;
403 }).pipe(Effect.forkScoped);
404​
405 const snapshot = yield* Deferred.await(snapshotDeferred);
406 yield* broadcaster.refreshStatus("/repo");
407 const remoteUpdated = yield* Deferred.await(remoteUpdatedDeferred);
408​
409 assert.deepStrictEqual(snapshot, {
410 _tag: "snapshot",
411 local: baseLocalStatus,
412 remote: null,
413 } satisfies VcsStatusStreamEvent);
414 assert.deepStrictEqual(remoteUpdated, {
415 _tag: "remoteUpdated",
416 remote: baseRemoteStatus,
417 } satisfies VcsStatusStreamEvent);
418 }).pipe(Effect.provide(makeTestLayer(state)));
419 });
420​
421 it.effect("loads remote status once when periodic refreshes are disabled", () => {
422 const state = {
423 currentLocalStatus: baseLocalStatus,
424 currentRemoteStatus: remoteStatusWithPr,
425 localStatusCalls: 0,
426 remoteStatusCalls: 0,
427 localInvalidationCalls: 0,
428 remoteInvalidationCalls: 0,
429 remoteStatusRefreshUpstreamValues: [] as Array<boolean | undefined>,
430 };
431​
432 return Effect.gen(function* () {
433 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
434 const scope = yield* Scope.make();
435 const snapshotDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
436 const remoteUpdatedDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
437 yield* Stream.runForEach(
438 broadcaster.streamStatus(
439 { cwd: "/repo" },
440 { automaticRemoteRefreshInterval: Effect.succeed(Duration.zero) },
441 ),
442 (event) => {
443 if (event._tag === "snapshot") {
444 return Deferred.succeed(snapshotDeferred, event).pipe(Effect.ignore);
445 }
446 if (event._tag === "remoteUpdated") {
447 return Deferred.succeed(remoteUpdatedDeferred, event).pipe(Effect.ignore);
448 }
449 return Effect.void;
450 },
451 ).pipe(Effect.forkIn(scope));
452​
453 const snapshot = yield* Deferred.await(snapshotDeferred);
454 const remoteUpdated = yield* Deferred.await(remoteUpdatedDeferred);
455​
456 assert.deepStrictEqual(snapshot, {
457 _tag: "snapshot",
458 local: baseLocalStatus,
459 remote: null,
460 } satisfies VcsStatusStreamEvent);
461 assert.deepStrictEqual(remoteUpdated, {
462 _tag: "remoteUpdated",
463 remote: remoteStatusWithPr,
464 } satisfies VcsStatusStreamEvent);
465 assert.equal(state.remoteStatusCalls, 1);
466 assert.equal(state.remoteInvalidationCalls, 0);
467 assert.deepStrictEqual(state.remoteStatusRefreshUpstreamValues, [false]);
468​
469 yield* TestClock.adjust(Duration.minutes(2));
470 assert.equal(state.remoteStatusCalls, 1);
471 assert.equal(state.remoteInvalidationCalls, 0);
472​
473 yield* Scope.close(scope, Exit.void);
474 }).pipe(Effect.provide(Layer.merge(makeTestLayer(state), TestClock.layer())));
475 });
476​
477 it.effect("retries the initial remote load when periodic refreshes are disabled", () => {
478 const state = {
479 currentLocalStatus: baseLocalStatus,
480 localStatusCalls: 0,
481 remoteStatusCalls: 0,
482 localInvalidationCalls: 0,
483 remoteInvalidationCalls: 0,
484 remoteStatusRefreshUpstreamValues: [] as Array<boolean | undefined>,
485 };
486 const privateCwd = "/private/user/workspace/repo";
487 const nestedCause = new Error("private nested VCS failure");
488 const messages: Array<ReadonlyArray<unknown>> = [];
489 const logger = Logger.make<unknown, void>(({ message }) => {
490 messages.push(message as ReadonlyArray<unknown>);
491 });
492 let firstRemoteAttemptDeferred: Deferred.Deferred<void> | null = null;
493 const testLayer = VcsStatusBroadcaster.layer.pipe(
494 Layer.provideMerge(NodeServices.layer),
495 Layer.provide(makeBackgroundPolicyLayer(() => true)),
496 Layer.provide(
497 Layer.mock(GitWorkflowService.GitWorkflowService)({
498 localStatus: () =>
499 Effect.sync(() => {
500 state.localStatusCalls += 1;
501 return state.currentLocalStatus;
502 }),
503 remoteStatus: (_input, options) =>
504 Effect.suspend(() => {
505 state.remoteStatusCalls += 1;
506 state.remoteStatusRefreshUpstreamValues.push(options?.refreshUpstream);
507 if (state.remoteStatusCalls === 1) {
508 return Effect.fail(
509 new GitManagerError({
510 operation: "VcsStatusBroadcaster.test",
511 cwd: privateCwd,
512 detail: "private initial remote status failure",
513 cause: nestedCause,
514 }),
515 ).pipe(
516 Effect.ensuring(
517 firstRemoteAttemptDeferred
518 ? Deferred.succeed(firstRemoteAttemptDeferred, undefined).pipe(Effect.ignore)
519 : Effect.void,
520 ),
521 );
522 }
523 return Effect.succeed(remoteStatusWithPr);
524 }),
525 invalidateLocalStatus: () =>
526 Effect.sync(() => {
527 state.localInvalidationCalls += 1;
528 }),
529 invalidateRemoteStatus: () =>
530 Effect.sync(() => {
531 state.remoteInvalidationCalls += 1;
532 }),
533 }),
534 ),
535 );
536​
537 return Effect.gen(function* () {
538 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
539 const scope = yield* Scope.make();
540 firstRemoteAttemptDeferred = yield* Deferred.make<void>();
541 const remoteUpdatedDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
542 yield* Stream.runForEach(
543 broadcaster.streamStatus(
544 { cwd: privateCwd },
545 { automaticRemoteRefreshInterval: Effect.succeed(Duration.zero) },
546 ),
547 (event) =>
548 event._tag === "remoteUpdated"
549 ? Deferred.succeed(remoteUpdatedDeferred, event).pipe(Effect.ignore)
550 : Effect.void,
551 ).pipe(Effect.forkIn(scope));
552​
553 yield* Deferred.await(firstRemoteAttemptDeferred);
554 yield* Effect.yieldNow;
555 assert.equal(state.remoteStatusCalls, 1);
556 assert.deepStrictEqual(
557 messages.find((message) => message[0] === "VCS remote status refresh failed"),
558 [
559 "VCS remote status refresh failed",
560 {
561 cwdLength: privateCwd.length,
562 reasonCount: 1,
563 failureCount: 1,
564 failureTags: ["GitManagerError"],
565 failureOperations: ["VcsStatusBroadcaster.test"],
566 defectCount: 0,
567 defectTags: [],
568 interruptionCount: 0,
569 consecutiveFailures: 1,
570 nextDelayMs: 30_000,
571 },
572 ],
573 );
574​
575 yield* TestClock.adjust(Duration.seconds(30));
576 const remoteUpdated = yield* Deferred.await(remoteUpdatedDeferred);
577​
578 assert.deepStrictEqual(remoteUpdated, {
579 _tag: "remoteUpdated",
580 remote: remoteStatusWithPr,
581 } satisfies VcsStatusStreamEvent);
582 assert.equal(state.remoteStatusCalls, 2);
583 assert.equal(state.remoteInvalidationCalls, 0);
584 assert.deepStrictEqual(state.remoteStatusRefreshUpstreamValues, [false, false]);
585​
586 yield* Scope.close(scope, Exit.void);
587 }).pipe(
588 Effect.provide(
589 Layer.mergeAll(
590 testLayer,
591 TestClock.layer(),
592 Logger.layer([logger], { mergeWithExisting: false }),
593 ),
594 ),
595 );
596 });
597​
598 it.effect("delays automatic refresh when a cached remote snapshot is available", () => {
599 const state = {
600 currentLocalStatus: baseLocalStatus,
601 currentRemoteStatus: baseRemoteStatus,
602 localStatusCalls: 0,
603 remoteStatusCalls: 0,
604 localInvalidationCalls: 0,
605 remoteInvalidationCalls: 0,
606 };
607​
608 return Effect.gen(function* () {
609 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
610 yield* broadcaster.getStatus({ cwd: "/repo" });
611 const scope = yield* Scope.make();
612 const snapshotDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
613 yield* Stream.runForEach(
614 broadcaster.streamStatus(
615 { cwd: "/repo" },
616 { automaticRemoteRefreshInterval: Effect.succeed(Duration.minutes(1)) },
617 ),
618 (event) =>
619 event._tag === "snapshot"
620 ? Deferred.succeed(snapshotDeferred, event).pipe(Effect.ignore)
621 : Effect.void,
622 ).pipe(Effect.forkIn(scope));
623​
624 yield* Deferred.await(snapshotDeferred);
625 assert.equal(state.remoteStatusCalls, 1);
626 assert.equal(state.remoteInvalidationCalls, 0);
627​
628 yield* TestClock.adjust(Duration.seconds(59));
629 assert.equal(state.remoteStatusCalls, 1);
630​
631 yield* TestClock.adjust(Duration.seconds(1));
632 yield* Effect.yieldNow;
633 assert.equal(state.remoteStatusCalls, 2);
634 assert.equal(state.remoteInvalidationCalls, 1);
635​
636 yield* Scope.close(scope, Exit.void);
637 }).pipe(Effect.provide(Layer.merge(makeTestLayer(state), TestClock.layer())));
638 });
639​
640 it("backs off remote refresh failures exponentially and honors larger configured intervals", () => {
641 assert.equal(
642 Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(1, Duration.seconds(1))),
643 30_000,
644 );
645 assert.equal(
646 Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(2, Duration.seconds(1))),
647 60_000,
648 );
649 assert.equal(
650 Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(3, Duration.seconds(1))),
651 120_000,
652 );
653 assert.equal(
654 Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(1, Duration.minutes(5))),
655 300_000,
656 );
657 assert.equal(
658 Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(20, Duration.seconds(1))),
659 900_000,
660 );
661 });
662​
663 it("summarizes refresh causes without exposing nested failure details", () => {
664 const nestedCause = new Error("private nested failure detail");
665 const failure = new GitManagerError({
666 operation: "VcsStatusBroadcaster.remoteStatus",
667 cwd: "/private/user/workspace/repo",
668 detail: "private Git failure detail",
669 cause: nestedCause,
670 });
671 const cause = Cause.combine(Cause.fail(failure), Cause.die(new TypeError("private defect")));
672​
673 assert.deepStrictEqual(VcsStatusBroadcaster.remoteRefreshFailureDiagnostics(cause), {
674 reasonCount: 2,
675 failureCount: 1,
676 failureTags: ["GitManagerError"],
677 failureOperations: ["VcsStatusBroadcaster.remoteStatus"],
678 defectCount: 1,
679 defectTags: ["TypeError"],
680 interruptionCount: 0,
681 });
682 });
683​
684 it.effect("does not start automatic remote refreshes without foreground client demand", () => {
685 const state = {
686 currentLocalStatus: baseLocalStatus,
687 currentRemoteStatus: baseRemoteStatus,
688 localStatusCalls: 0,
689 remoteStatusCalls: 0,
690 localInvalidationCalls: 0,
691 remoteInvalidationCalls: 0,
692 };
693 const testLayer = VcsStatusBroadcaster.layer.pipe(
694 Layer.provideMerge(NodeServices.layer),
695 Layer.provide(makeBackgroundPolicyLayer(() => false)),
696 Layer.provide(
697 Layer.mock(GitWorkflowService.GitWorkflowService)({
698 localStatus: () =>
699 Effect.sync(() => {
700 state.localStatusCalls += 1;
701 return state.currentLocalStatus;
702 }),
703 remoteStatus: () =>
704 Effect.sync(() => {
705 state.remoteStatusCalls += 1;
706 return state.currentRemoteStatus;
707 }),
708 invalidateLocalStatus: () =>
709 Effect.sync(() => {
710 state.localInvalidationCalls += 1;
711 }),
712 invalidateRemoteStatus: () =>
713 Effect.sync(() => {
714 state.remoteInvalidationCalls += 1;
715 }),
716 } satisfies Partial<GitWorkflowService.GitWorkflowService["Service"]>),
717 ),
718 );
719​
720 return Effect.gen(function* () {
721 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
722 const snapshot = yield* Stream.runHead(
723 broadcaster.streamStatus(
724 { cwd: "/repo" },
725 { automaticRemoteRefreshInterval: Effect.succeed(Duration.seconds(1)) },
726 ),
727 );
728​
729 assert.isTrue(Option.isSome(snapshot));
730 assert.equal(state.remoteStatusCalls, 0);
731 assert.equal(state.remoteInvalidationCalls, 0);
732 }).pipe(Effect.provide(testLayer));
733 });
734​
735 it.effect("stops the remote poller after the last stream subscriber disconnects", () => {
736 const state = {
737 currentLocalStatus: baseLocalStatus,
738 currentRemoteStatus: baseRemoteStatus,
739 localStatusCalls: 0,
740 remoteStatusCalls: 0,
741 localInvalidationCalls: 0,
742 remoteInvalidationCalls: 0,
743 };
744 let remoteInterruptedDeferred: Deferred.Deferred<void, never> | null = null;
745 let remoteStartedDeferred: Deferred.Deferred<void, never> | null = null;
746 const testLayer = VcsStatusBroadcaster.layer.pipe(
747 Layer.provideMerge(NodeServices.layer),
748 Layer.provide(makeBackgroundPolicyLayer(() => true)),
749 Layer.provide(
750 Layer.mock(GitWorkflowService.GitWorkflowService)({
751 localStatus: () =>
752 Effect.sync(() => {
753 state.localStatusCalls += 1;
754 return state.currentLocalStatus;
755 }),
756 remoteStatus: () =>
757 Effect.sync(() => {
758 state.remoteStatusCalls += 1;
759 }).pipe(
760 Effect.andThen(
761 remoteStartedDeferred
762 ? Deferred.succeed(remoteStartedDeferred, undefined).pipe(Effect.ignore)
763 : Effect.void,
764 ),
765 Effect.andThen(Effect.never as Effect.Effect<VcsStatusRemoteResult | null, never>),
766 Effect.onInterrupt(() =>
767 remoteInterruptedDeferred
768 ? Deferred.succeed(remoteInterruptedDeferred, undefined).pipe(Effect.ignore)
769 : Effect.void,
770 ),
771 ),
772 invalidateLocalStatus: () =>
773 Effect.sync(() => {
774 state.localInvalidationCalls += 1;
775 }),
776 invalidateRemoteStatus: () =>
777 Effect.sync(() => {
778 state.remoteInvalidationCalls += 1;
779 }),
780 } satisfies Partial<GitWorkflowService.GitWorkflowService["Service"]>),
781 ),
782 );
783​
784 return Effect.gen(function* () {
785 const remoteInterrupted = yield* Deferred.make<void>();
786 const remoteStarted = yield* Deferred.make<void>();
787 remoteInterruptedDeferred = remoteInterrupted;
788 remoteStartedDeferred = remoteStarted;
789​
790 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
791 const firstSnapshot = yield* Deferred.make<VcsStatusStreamEvent>();
792 const secondSnapshot = yield* Deferred.make<VcsStatusStreamEvent>();
793 const firstScope = yield* Scope.make();
794 const secondScope = yield* Scope.make();
795 yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) =>
796 event._tag === "snapshot"
797 ? Deferred.succeed(firstSnapshot, event).pipe(Effect.ignore)
798 : Effect.void,
799 ).pipe(Effect.forkIn(firstScope));
800 yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) =>
801 event._tag === "snapshot"
802 ? Deferred.succeed(secondSnapshot, event).pipe(Effect.ignore)
803 : Effect.void,
804 ).pipe(Effect.forkIn(secondScope));
805​
806 yield* Deferred.await(firstSnapshot);
807 yield* Deferred.await(secondSnapshot);
808 yield* Deferred.await(remoteStarted);
809​
810 assert.equal(state.remoteStatusCalls, 1);
811​
812 yield* Scope.close(firstScope, Exit.void);
813 assert.isTrue(Option.isNone(yield* Deferred.poll(remoteInterrupted)));
814​
815 yield* Scope.close(secondScope, Exit.void).pipe(Effect.forkScoped);
816 yield* Deferred.await(remoteInterrupted);
817 assert.isTrue(Option.isSome(yield* Deferred.poll(remoteInterrupted)));
818 }).pipe(Effect.provide(testLayer));
819 });
820});