perf(server): cut idle preview port scans by 85% #4187
ClosedQuicksaver(GitHub profile, opens in a new tab)wants to merge 88 commits into
main fromrefs/pull/4187/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
- apps/server/src/preview/PortScanner.ts line 351OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -334 +351 @@334351 const subscribe: PortDiscovery["Service"]["subscribe"] = Effect.fn("PortDiscovery.subscribe")(
- apps/server/src/preview/PortScanner.ts line 374OutdatedResolvedby Quicksaver(GitHub profile, opens in a new tab)@@ -334,7 +363,12 @@334363 const subscribe: PortDiscovery["Service"]["subscribe"] = Effect.fn("PortDiscovery.subscribe")(335364 (listener) =>336365 Effect.acquireRelease(337- Ref.update(stateRef, (state) => ({338- ...state,339- listeners: new Set([...state.listeners, listener]),340- })),366+ notificationLock.withPermit(367+ Ref.modify(stateRef, (state) => [368+ state.lastSnapshot,369+ {370+ ...state,371+ listeners: new Set([...state.listeners, listener]),372+ },373+ ]).pipe(Effect.tap(listener)),374+ ),
- apps/server/src/preview/PortScanner.ts line 319OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -295,10 +305,15 @@305+ const changed = yield* Ref.modify(stateRef, (state) =>306+ serversEqual(state.lastSnapshot, next)307+ ? [false, state]308+ : [true, { ...state, lastSnapshot: next }],309+ );310+ if (changed) yield* broadcast(next);311+ }),312+ );313+ });314+295315 const pollTick = Effect.fn("PortDiscovery.pollTick")(296316 function* () {297317 if ((yield* Ref.get(stateRef)).retainCount <= 0) return;298318 const next = yield* scanOnce();299- const changed = yield* Ref.modify(stateRef, (state) =>300- serversEqual(state.lastSnapshot, next)301- ? [false, state]302- : [true, { ...state, lastSnapshot: next }],303- );304- if (changed) yield* broadcast(next);319+ yield* publishSnapshot(next);
- apps/web/src/components/BranchToolbarBranchSelector.tsx line 515OutdatedResolvedby Quicksaver(GitHub profile, opens in a new tab)@@ -500,6 +511,5 @@500511 setIsBranchMenuOpen(open);501512 if (!open) {502513 setBranchQuery("");503- return;504514 }505- branchRefState.refresh();515+ refreshVcsRefsOnMenuOpen(open, () =>apps/server/src/preview/PortScanner.ts line 389OutdatedResolvedby Quicksaver(GitHub profile, opens in a new tab)@@ -323,9 +374,16 @@323374 yield* pollTick();375+ yield* wakePollSchedule;324376 }325377 });326378327- const retain: PortDiscovery["Service"]["retain"] = Effect.acquireRelease(acquireRetention(), () =>328- Ref.update(stateRef, (state) => ({329- ...state,330- retainCount: Math.max(0, state.retainCount - 1),331- })),379+ const releaseRetention = Effect.fn("PortDiscovery.releaseRetention")(function* () {380+ const becameIdle = yield* Ref.modify(stateRef, (state) => {381+ const retainCount = Math.max(0, state.retainCount - 1);382+ return [state.retainCount > 0 && retainCount === 0, { ...state, retainCount }] as const;383+ });384+ if (becameIdle) yield* wakePollSchedule;385+ });386+387+ const retain: PortDiscovery["Service"]["retain"] = Effect.acquireRelease(388+ acquireRetention(),389+ releaseRetention,
- apps/web/src/components/BranchToolbarBranchSelector.tsx line 245OutdatedResolvedby Quicksaver(GitHub profile, opens in a new tab)@@ -232,3 +236,10 @@232236 branchRefState.data?.nextCursor !== null && branchRefState.data?.nextCursor !== undefined;233237 const isFetchingNextPage = branchRefState.isPending && branchRefState.data !== null;234238 const isInitialBranchesLoadPending = branchRefState.isPending && branchRefState.data === null;239+ useEffect(() => {240+ if (!shouldRefreshBranchRefsAfterQueryReset || deferredTrimmedBranchQuery.length > 0) {241+ return;242+ }243+ setShouldRefreshBranchRefsAfterQueryReset(false);244+ branchRefState.refresh();245+ }, [branchRefState.refresh, deferredTrimmedBranchQuery, shouldRefreshBranchRefsAfterQueryReset]);
- apps/server/src/preview/PortScanner.ts line 378OutdatedResolvedby Quicksaver(GitHub profile, opens in a new tab)@@ -292,0 +358,21 @@358+ deliveries.push(deliveryResult);359+ yield* Queue.offer(registration.notifications, {360+ _tag: "Snapshot",361+ servers: next,362+ deliveryResult,363+ isReplay: false,364+ });365+ }),366+ { discard: true },367+ );368+ }369+ return { pollIntervalChanged: result.pollIntervalChanged, deliveries };370+ }),371+ );372+ if (result.pollIntervalChanged) yield* wakePollSchedule;373+ if (currentListener === undefined) {374+ yield* Effect.forEach(result.deliveries, Deferred.await, {375+ concurrency: "unbounded",376+ discard: true,377+ });378+ }
- apps/server/src/preview/PortScanner.ts line 542OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -347,0 +522,21 @@522+ const replayResult = yield* Deferred.make<Exit.Exit<void>>();523+ const registration = { listener, notifications };524+ yield* notificationLock.withPermit(525+ Effect.gen(function* () {526+ const snapshot = yield* Ref.modify(stateRef, (state) => [527+ state.lastSnapshot,528+ {529+ ...state,530+ listeners: new Set([...state.listeners, registration]),531+ },532+ ]);533+ yield* Queue.offer(notifications, {534+ _tag: "Snapshot",535+ servers: snapshot,536+ deliveryResult: replayResult,537+ isReplay: true,538+ });539+ }),540+ );541+ yield* Effect.forkScoped(runListenerNotifications(registration));542+ const replayExit = yield* Deferred.await(replayResult);apps/server/src/preview/PortScanner.ts line 796Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -332,2 +454,21 @@454+ const releaseRetention = Effect.fn("PortDiscovery.releaseRetention")(function* () {455+ const becameIdle = yield* Ref.modify(stateRef, (state) => {456+ const retainCount = Math.max(0, state.retainCount - 1);457+ return [state.retainCount > 0 && retainCount === 0, { ...state, retainCount }] as const;458+ });459+ if (becameIdle) yield* wakePollSchedule;460+ });461+462+ const retain: PortDiscovery["Service"]["retain"] = Effect.acquireRelease(463+ acquireRetention(),464+ releaseRetention,332465 );333466467+ const removeListener = (registration: ListenerRegistration) =>468+ Ref.update(stateRef, (state) => {469+ const listeners = new Set(state.listeners);470+ listeners.delete(registration);471+ return { ...state, listeners };472+ });473+474+ const stopListener = Effect.fn("PortDiscovery.stopListener")(function* (
- apps/server/src/preview/PortScanner.ts line 510OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -333,0 +490,21 @@490+ yield* Queue.shutdown(registration.notifications);491+ });492+493+ const runListenerNotifications = Effect.fn("PortDiscovery.runListenerNotifications")(function* (494+ registration: ListenerRegistration,495+ ) {496+ let replayFailed = false;497+ while (true) {498+ const notification = yield* Queue.take(registration.notifications);499+ if (replayFailed) {500+ yield* Deferred.succeed(notification.deliveryResult, Exit.void).pipe(Effect.ignore);501+ continue;502+ }503+ const delivery = yield* registration.listener(notification.servers).pipe(504+ Effect.provideService(CurrentListenerRegistration, registration),505+ Effect.onInterrupt(() =>506+ Deferred.succeed(notification.deliveryResult, Exit.interrupt()).pipe(Effect.asVoid),507+ ),508+ Effect.exit,509+ );510+ yield* Deferred.succeed(notification.deliveryResult, delivery).pipe(Effect.ignore);
Quicksaver(GitHub profile, opens in a new tab) changed the title
- apps/server/src/preview/PortScanner.ts line 588OutdatedResolvedby Quicksaver(GitHub profile, opens in a new tab)@@ -356,13 +570,19 @@356570 const processIds = new Set(357571 input.processIds.filter((processId) => Number.isInteger(processId) && processId > 0),358572 );359- yield* Ref.update(stateRef, (state) => {573+ const changed = yield* Ref.modify(stateRef, (state) => {360574 const terminalProcesses = new Map(state.terminalProcesses);361575 const key = terminalOwnerKey(owner);576+ const existing = terminalProcesses.get(key);577+ if (existing && processIdsEqual(existing.processIds, processIds)) {578+ return [false, state] as const;579+ }362580 if (processIds.size === 0) {581+ if (!existing) return [false, state] as const;363582 terminalProcesses.delete(key);364583 } else {365584 terminalProcesses.set(key, { owner, processIds });366585 }367- return { ...state, terminalProcesses };586+ return [true, { ...state, terminalProcesses }] as const;368587 });588+ if (changed) yield* pollAfterTerminalChange();
- apps/server/src/preview/PortScanner.ts line 927Resolvedby Quicksaver(GitHub profile, opens in a new tab)@@ -359,10 +574,18 @@359- yield* Ref.update(stateRef, (state) => {574+ const shouldScan = yield* Ref.modify(stateRef, (state) => {360575 const terminalProcesses = new Map(state.terminalProcesses);361576 const key = terminalOwnerKey(owner);577+ const existing = terminalProcesses.get(key);578+ if (existing && processIdsEqual(existing.processIds, processIds)) {579+ if (!existing.needsSettleScan) return [false, state] as const;580+ terminalProcesses.set(key, { ...existing, needsSettleScan: false });581+ return [true, { ...state, terminalProcesses }] as const;582+ }362583 if (processIds.size === 0) {584+ if (!existing) return [false, state] as const;363585 terminalProcesses.delete(key);364586 } else {365- terminalProcesses.set(key, { owner, processIds });587+ terminalProcesses.set(key, { owner, processIds, needsSettleScan: true });366588 }367- return { ...state, terminalProcesses };589+ return [true, { ...state, terminalProcesses }] as const;368590 });591+ if (shouldScan) yield* pollAfterTerminalChange();
- apps/server/src/preview/PortScanner.ts line 648OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -555,20 +648 @@555- [...(yield* Ref.get(stateRef)).listeners.values()].flatMap(556- (subscription) => subscription.configuredUrls,557- ),558- ),559- ];560- const snapshot = yield* scanSnapshot(configuredUrls);561- const notifications = yield* Ref.modify(stateRef, (state) => {562- const listeners = new Map(state.listeners);563- const changed: Array<readonly [Listener, ReadonlyArray<DiscoveredLocalServer>]> = [];564- for (const [listener, subscription] of listeners) {565- const next = projectWebProbeSnapshot(snapshot, subscription.configuredUrls);566- if (serversEqual(subscription.lastSnapshot, next)) continue;567- listeners.set(listener, { ...subscription, lastSnapshot: next });568- changed.push([listener, next]);569- }570- return [changed, { ...state, listeners }];571- });572- yield* Effect.forEach(notifications, ([listener, servers]) => listener(servers), {573- discard: true,574- });648+ yield* scanLock.withPermit(
- apps/server/src/preview/PortScanner.ts line 742Resolvedby Quicksaver(GitHub profile, opens in a new tab)@@ -613,0 +723,21 @@723+ (retainedConfiguredUrls.get(configuredUrl) ?? 0) + 1,724+ );725+ }726+ return [727+ {728+ shouldScan:729+ state.retainCount === 0 ||730+ configuredUrls.some((url) => !state.lastScanConfiguredUrls.has(url)),731+ wasIdle: state.retainCount === 0,732+ },733+ {734+ ...state,735+ retainCount: state.retainCount + 1,736+ retainedConfiguredUrls,737+ },738+ ];739+ });740+ if (shouldScan) {741+ // Run an immediate scan + broadcast so the new retainer doesn't have742+ // to wait for the periodic safety-net scan.743+ yield* pollTick();
- apps/server/src/preview/PortScanner.ts line 752OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -613,0 +732,21 @@732+ {733+ ...state,734+ retainCount: state.retainCount + 1,735+ retainedConfiguredUrls,736+ },737+ ];738+ });739+ if (shouldScan) {740+ // Run an immediate scan + broadcast so the new retainer doesn't have741+ // to wait for the periodic safety-net scan.742+ yield* pollTick();743+ }744+ if (wasIdle) {745+ yield* wakePollSchedule;746+ }747+ });748+749+ const releaseRetention = Effect.fn("PortDiscovery.releaseRetention")(function* (750+ configuredUrls: ReadonlyArray<string>,751+ ) {752+ const becameIdle = yield* Ref.modify(stateRef, (state) => {apps/server/src/preview/PortScanner.ts line 824OutdatedResolvedby Quicksaver(GitHub profile, opens in a new tab)@@ -613,0 +804,21 @@804+ Effect.gen(function* () {805+ yield* removeListener(registration);806+ return yield* Queue.clear(registration.notifications);807+ }),808+ );809+ yield* Effect.forEach(810+ pending,811+ (notification) =>812+ Deferred.succeed(notification.deliveryResult, Exit.void).pipe(Effect.ignore),813+ { discard: true },814+ );815+ yield* Fiber.interrupt(worker);816+ yield* Queue.shutdown(registration.notifications);817+ });818+819+ const runListenerNotifications = Effect.fn("PortDiscovery.runListenerNotifications")(function* (820+ registration: ListenerRegistration,821+ ) {822+ let replayFailed = false;823+ while (true) {824+ const notification = yield* Queue.take(registration.notifications);
Quicksaver(GitHub profile, opens in a new tab) changed the title
- apps/server/src/preview/PortScanner.ts line 683Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -584,10 +671,13 @@671+ while (true) {672+ yield* Queue.take(reentrantScanRequests);673+ yield* pollTick();674+ }675+ }),676+ );584677585- const acquireRetention = Effect.fn("PortDiscovery.retain")(function* () {586- const wasIdle = yield* Ref.modify(stateRef, (state) => [587- state.retainCount === 0,588- { ...state, retainCount: state.retainCount + 1 },589- ]);590- if (wasIdle) {591- // Run an immediate scan + broadcast so the new retainer doesn't have592- // to wait up to POLL_INTERVAL for the first emission.678+ const pollAfterTerminalChange = Effect.fn("PortDiscovery.pollAfterTerminalChange")(function* () {679+ const currentListener = yield* CurrentListenerRegistration;680+ if (currentListener === undefined) {593681 yield* pollTick();682+ } else {683+ yield* Queue.offer(reentrantScanRequests, undefined);
Quicksaver(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.


Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID:
32c5c6e8-81b0-4987-b0a9-6477ec11b8d3You can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
✨ Finishing Touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share