Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- Fixed host details and the Welcome to Fleet card scheduling an extra polling loop on every tab switch during a refetch.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- Fixed host details and the Welcome to Fleet card restarting a refetch and repeating the timeout toast when the tab regained focus after a refetch had already timed out.
Original file line number Diff line number Diff line change
Expand Up @@ -112,4 +112,82 @@ describe("WelcomeHost - refetch give-up state", () => {
// Still only the one call from the original give-up -- not a second one.
expect(notify.error).toHaveBeenCalledTimes(1);
});

// Each tab-focus re-entry into onSuccess used to schedule a fresh setTimeout
// next to the one already pending, so polling sped up.
it("does not stack polling loops when the tab regains focus mid-refetch", async () => {
jest.useFakeTimers({ doNotFake: ["queueMicrotask"] });
let now = 1_700_000_000_000;
jest.spyOn(Date, "now").mockImplementation(() => now);

(hostAPI.loadHostDetails as jest.Mock).mockResolvedValue({
host: mockOnlineStuckRefetchHost(),
});

renderWelcomeHost();
await screen.findByText("Antivirus healthy");

for (let i = 0; i < 3; i += 1) {
// eslint-disable-next-line no-await-in-loop
await act(async () => {
window.dispatchEvent(new Event("focus"));
window.dispatchEvent(new Event("visibilitychange"));
await jest.advanceTimersByTimeAsync(0);
});
}

const callsBeforeAdvance = (hostAPI.loadHostDetails as jest.Mock).mock.calls
.length;

now += 1000;
await act(async () => {
await jest.advanceTimersByTimeAsync(1000);
});

const pollsInOneInterval =
(hostAPI.loadHostDetails as jest.Mock).mock.calls.length -
callsBeforeAdvance;
expect(pollsInOneInterval).toBe(1);
});

// After give-up, a focus-triggered onSuccess used to re-enter the "timer
// just started" branch, open a fresh 60s cycle, and fire the toast again
// 60s later.
it("doesn't restart the refetch window after a timeout when the tab regains focus", async () => {
jest.useFakeTimers({ doNotFake: ["queueMicrotask"] });
let now = 1_700_000_000_000;
jest.spyOn(Date, "now").mockImplementation(() => now);

(hostAPI.loadHostDetails as jest.Mock).mockResolvedValue({
host: mockOnlineStuckRefetchHost(),
});

renderWelcomeHost();
await screen.findByText("Antivirus healthy");

// Trip the give-up branch on the first polling tick.
now += 61000;
await act(async () => {
await jest.advanceTimersByTimeAsync(1000);
});

await waitFor(() => {
expect(notify.error).toHaveBeenCalledTimes(1);
});

// Tab switch, then let a full fresh 60s window elapse. Without the fix,
// the focus-triggered onSuccess restarts a new cycle and the toast fires
// a second time around now.
await act(async () => {
window.dispatchEvent(new Event("focus"));
window.dispatchEvent(new Event("visibilitychange"));
await jest.advanceTimersByTimeAsync(0);
});
now += 65000;
await act(async () => {
await jest.advanceTimersByTimeAsync(1000);
});

expect(notify.error).toHaveBeenCalledTimes(1);
});
});
85 changes: 57 additions & 28 deletions frontend/pages/DashboardPage/cards/WelcomeHost/WelcomeHost.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useState } from "react";
import React, { useRef, useState } from "react";
import { useQuery } from "react-query";

import Button from "components/buttons/Button";
Expand Down Expand Up @@ -37,6 +37,12 @@ const WelcomeHost = ({
const [showRefetchLoadingSpinner, setShowRefetchLoadingSpinner] = useState(
false
);
// Pending next-poll timer; cleared before scheduling a new one so a focus-triggered
// onSuccess re-entry replaces the pending poll instead of stacking.
const pollingTimerRef = useRef<NodeJS.Timeout | null>(null);
// True once the current refetch cycle has given up; blocks the restart path in
// onSuccess when the server still reports refetch_requested: true.
const didTimeOutRef = useRef(false);

/**
* Hides refetch spinner and resets refetch timer,
Expand All @@ -45,6 +51,20 @@ const WelcomeHost = ({
const resetHostRefetchStates = () => {
setShowRefetchLoadingSpinner(false);
setRefetchStartTime(null);
if (pollingTimerRef.current) {
clearTimeout(pollingTimerRef.current);
pollingTimerRef.current = null;
}
};

const scheduleNextPoll = (fn: () => void) => {
if (pollingTimerRef.current) {
clearTimeout(pollingTimerRef.current);
}
pollingTimerRef.current = setTimeout(() => {
pollingTimerRef.current = null;
fn();
}, 1000);
};

const {
Expand All @@ -59,43 +79,51 @@ const WelcomeHost = ({
retry: false,
select: (data: IHostResponse) => data.host,
onSuccess: (returnedHost) => {
setShowRefetchLoadingSpinner(returnedHost.refetch_requested);

const anyPassingOrFailingPolicy = returnedHost?.policies?.find(
(p) => p.response === POLICY_PASS || p.response === POLICY_FAIL
);
setIsPoliciesEmpty(typeof anyPassingOrFailingPolicy === "undefined");

if (returnedHost.refetch_requested) {
// Code duplicated from HostDetailsPage. See comments there.
if (!refetchStartTime) {
if (returnedHost.status === "online") {
setRefetchStartTime(Date.now());
setTimeout(() => {
fullyReloadHost();
}, 1000);
} else {
resetHostRefetchStates();
}
if (!returnedHost.refetch_requested) {
didTimeOutRef.current = false;
resetHostRefetchStates();
return;
}
Comment thread
Copilot marked this conversation as resolved.
Resolved

// Previous cycle gave up and server still reports refetch_requested: true.
// Skip the restart path so a focus-triggered re-entry doesn't open a fresh
// 60s window + repeat toast.
if (didTimeOutRef.current && !refetchStartTime) {
return;
}

setShowRefetchLoadingSpinner(true);

// Code duplicated from HostDetailsPage. See comments there.
if (!refetchStartTime) {
if (returnedHost.status === "online") {
setRefetchStartTime(Date.now());
scheduleNextPoll(fullyReloadHost);
} else {
const totalElapsedTime = Date.now() - refetchStartTime;
if (totalElapsedTime < 60000) {
if (returnedHost.status === "online") {
setTimeout(() => {
fullyReloadHost();
}, 1000);
} else {
notify.error(
`This host is offline. Please try refetching host vitals later.`
);
resetHostRefetchStates();
}
resetHostRefetchStates();
}
} else {
const totalElapsedTime = Date.now() - refetchStartTime;
if (totalElapsedTime < 60000) {
if (returnedHost.status === "online") {
scheduleNextPoll(fullyReloadHost);
} else {
notify.error(
`Refetch sent but vitals are taking longer than expected to load. You’ll see an update when the host responds.`
`This host is offline. Please try refetching host vitals later.`
);
resetHostRefetchStates();
}
} else {
notify.error(
`Refetch sent but vitals are taking longer than expected to load. You’ll see an update when the host responds.`
);
didTimeOutRef.current = true;
resetHostRefetchStates();
}
}
},
Expand All @@ -111,8 +139,9 @@ const WelcomeHost = ({

try {
await hostAPI.refetch(host).then(() => {
didTimeOutRef.current = false;
setRefetchStartTime(Date.now());
setTimeout(() => fullyReloadHost(), 1000);
scheduleNextPoll(fullyReloadHost);
});
} catch (error) {
console.error(error);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -479,6 +479,108 @@ describe("HostDetailsPage - disk encryption key rotation", () => {
});
});

describe("HostDetailsPage - refetch cycle on tab switch", () => {
const mockOnlineStuckHost = (): IHost =>
createMockHost({
id: 1,
platform: "darwin",
status: "online",
refetch_requested: true,
});

afterEach(() => {
jest.useRealTimers();
jest.restoreAllMocks();
jest.resetAllMocks();
});

// Each tab-focus re-entry into onSuccess used to schedule a fresh setTimeout
// next to the one already pending, so polling sped up.
it("does not stack polling loops when the tab regains focus mid-refetch", async () => {
stubQueries(mockOnlineStuckHost());

jest.useFakeTimers({ doNotFake: ["queueMicrotask"] });
const start = 1_700_000_000_000;
let now = start;
jest.spyOn(Date, "now").mockImplementation(() => now);

renderHostDetails();
await screen.findByText("Vitals");

// Dispatch three window-focus events (react-query's refetchOnWindowFocus
// trigger). Each one re-enters onSuccess.
for (let i = 0; i < 3; i += 1) {
// eslint-disable-next-line no-await-in-loop
await act(async () => {
window.dispatchEvent(new Event("focus"));
window.dispatchEvent(new Event("visibilitychange"));
await jest.advanceTimersByTimeAsync(0);
});
}

const callsBeforeAdvance = (hostAPI.loadHostDetails as jest.Mock).mock.calls
.length;

// One polling interval. With the fix, exactly one scheduled poll fires in
// this window. Without it, each stacked timer fires an extra request.
now += 2000;
await act(async () => {
await jest.advanceTimersByTimeAsync(2000);
});

const pollsInOneInterval =
(hostAPI.loadHostDetails as jest.Mock).mock.calls.length -
callsBeforeAdvance;
expect(pollsInOneInterval).toBe(1);
});

// After give-up, the server still reports refetch_requested: true, so a
// focus-triggered onSuccess used to re-enter the "timer just started" branch
// and run a fresh 60s cycle (new toast 60s later).
it("doesn't restart the refetch window after a timeout when the tab regains focus", async () => {
jest.useFakeTimers({ doNotFake: ["queueMicrotask"] });
const start = 1_700_000_000_000;
let now = start;
jest.spyOn(Date, "now").mockImplementation(() => now);

stubQueries(mockOnlineStuckHost());
(hostAPI.loadHostDetails as jest.Mock).mockResolvedValue({
host: mockOnlineStuckHost(),
});

renderHostDetails();
await screen.findByText("Vitals");

// Advance past the 60s give-up window so the next polling tick fires the toast.
now += 61000;
await act(async () => {
await jest.advanceTimersByTimeAsync(2000);
});

await waitFor(() => {
expect(notify.error).toHaveBeenCalledWith(
"Refetch sent but vitals are taking longer than expected to load. You’ll see an update when the host responds."
);
});
expect(notify.error).toHaveBeenCalledTimes(1);

// Simulate a tab switch and let a full fresh 60s + 2s poll interval pass.
// Without the fix, this re-enters the "timer just started" branch, opens a
// new 60s cycle, and 60s later shows the toast a second time.
await act(async () => {
window.dispatchEvent(new Event("focus"));
window.dispatchEvent(new Event("visibilitychange"));
await jest.advanceTimersByTimeAsync(0);
});
now += 65000;
await act(async () => {
await jest.advanceTimersByTimeAsync(2000);
});

expect(notify.error).toHaveBeenCalledTimes(1);
});
});

describe("HostDetailsPage - enrollment rejection details", () => {
afterEach(() => {
jest.resetAllMocks();
Expand Down
Loading
Loading