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
Expand Up @@ -13,12 +13,21 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Subject } from 'rxjs';

export default {
data() {
return {
destroy$: new Subject<void>(),
};
},
created() {
this.subscribe();
},
beforeUnmount() {
// Emit to signal all subscriptions to complete
this.destroy$.next();
this.destroy$.complete();
this.unsubscribe();
},
methods: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ class Instance {
public availableMetrics: string[] = [];
public tags: { [key: string]: string }[];
public statusTimestamp: string;
public version?: number;
public buildVersion: string;
public statusInfo: StatusInfo;

Expand Down Expand Up @@ -534,6 +535,7 @@ type StatusInfo = {

type InstanceData = {
id: string;
version?: number;
registration: Registration;
endpoints?: Endpoint[];
availableMetrics?: string[];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -229,4 +229,39 @@ describe('DetailsCache', () => {
expect(queryByText(`${HITS[0]}`)).not.toBeInTheDocument();
});
});

it('should reinitialize metrics when instance version changes (SSE update)', async () => {
const application = new Application(applications[0]);
const instance1 = application.instances[0];

const { getByText, rerender, queryByText } = await render(DetailsCache, {
props: {
instance: instance1,
cacheName: CACHE_NAME,
index: 0,
},
});

// wait until initial fetch rendered a numeric value
await waitFor(() => {
expect(getByText(`${HITS[0]}`)).toBeTruthy();
});

const instance2 = new Application({
...application,
instances: [
{
...instance1,
id: instance1.id,
version: (instance1.version ?? 0) + 1,
},
],
}).instances[0];

await rerender({ instance: instance2, cacheName: CACHE_NAME, index: 0 });

await waitFor(() => {
expect(queryByText(`${HITS[0]}`)).not.toBeInTheDocument();
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,8 @@

<script>
import moment from 'moment';
import { take } from 'rxjs/operators';
import { Subject } from 'rxjs';
import { take, takeUntil } from 'rxjs/operators';

import SbaAccordion from '@/components/sba-accordion.vue';
import sbaAlert from '@/components/sba-alert.vue';
Expand Down Expand Up @@ -116,6 +117,7 @@ export default {
shouldFetchCacheMisses: true,
chartData: [],
currentInstanceId: null,
currentInstanceUpdateKey: null,
}),
computed: {
ratio() {
Expand All @@ -139,15 +141,33 @@ export default {
},
methods: {
initCacheMetrics() {
if (this.instance.id !== this.currentInstanceId) {
const updateKey =
this.instance.version ??
this.instance.statusTimestamp ??
this.instance.id;
const firstInit = this.currentInstanceId === null;
if (
this.instance.id !== this.currentInstanceId ||
updateKey !== this.currentInstanceUpdateKey
) {
this.currentInstanceId = this.instance.id;
this.currentInstanceUpdateKey = updateKey;
this.hasLoaded = false;
this.error = null;
this.current = null;
this.chartData = [];
this.shouldFetchCacheSize = true;
this.shouldFetchCacheHits = true;
this.shouldFetchCacheMisses = true;

// Restart polling immediately so SSE updates refresh the view.
if (!firstInit) {
// Stop old subscription and start fresh
this.unsubscribe();
// Recreate destroy$ so new subscription can use takeUntil properly
this.destroy$ = new Subject();
this.subscribe();
}
}
},
async fetchMetrics() {
Expand Down Expand Up @@ -235,6 +255,8 @@ export default {
.pipe(
concatMap(this.fetchMetrics),
map(this.calculateMetricsPerInterval),
// Stop polling when destroy$ emits (on unmount or instance update)
takeUntil(this.destroy$),
retryWhen((err) => {
return err.pipe(delay(1000), take(5));
}),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -163,4 +163,37 @@ describe('DetailsDatasource', () => {
expect(screen.queryByText(`${ACTIVE[0]}`)).not.toBeInTheDocument();
});
});

it('should reinitialize metrics when instance version changes (SSE update)', async () => {
const application = new Application(applications[0]);
const instance1 = application.instances[0];

const { rerender } = await render(DetailsDatasource, {
props: {
instance: instance1,
dataSource: DATA_SOURCE,
},
});

await waitFor(() => {
expect(screen.getByText(`${ACTIVE[0]}`)).toBeVisible();
});

const instance2 = new Application({
...application,
instances: [
{
...instance1,
id: instance1.id,
version: (instance1.version ?? 0) + 1,
},
],
}).instances[0];

await rerender({ instance: instance2, dataSource: DATA_SOURCE });

await waitFor(() => {
expect(screen.queryByText(`${ACTIVE[0]}`)).not.toBeInTheDocument();
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@

<script>
import moment from 'moment';
import { concatMap, delay, retryWhen, timer } from 'rxjs';
import { Subject, concatMap, delay, retryWhen, takeUntil, timer } from 'rxjs';
import { take } from 'rxjs/operators';

import SbaAccordion from '@/components/sba-accordion.vue';
Expand Down Expand Up @@ -96,6 +96,7 @@ export default {
current: null,
chartData: [],
currentInstanceId: null,
currentInstanceUpdateKey: null,
}),
watch: {
instance: {
Expand All @@ -105,12 +106,30 @@ export default {
},
methods: {
initDatasourceMetrics() {
if (this.instance.id !== this.currentInstanceId) {
const updateKey =
this.instance.version ??
this.instance.statusTimestamp ??
this.instance.id;
const firstInit = this.currentInstanceId === null;
if (
this.instance.id !== this.currentInstanceId ||
updateKey !== this.currentInstanceUpdateKey
) {
this.currentInstanceId = this.instance.id;
this.currentInstanceUpdateKey = updateKey;
this.hasLoaded = false;
this.error = null;
this.current = null;
this.chartData = [];

// Restart polling immediately so SSE updates refresh the view.
if (!firstInit) {
// Stop old subscription and start fresh
this.unsubscribe();
// Recreate destroy$ so new subscription can use takeUntil properly
this.destroy$ = new Subject();
this.subscribe();
}
}
},
async fetchMetrics() {
Expand All @@ -135,6 +154,8 @@ export default {
return timer(0, sbaConfig.uiSettings.pollTimer.datasource)
.pipe(
concatMap(this.fetchMetrics),
// Stop polling when destroy$ emits (on unmount or instance update)
takeUntil(this.destroy$),
retryWhen((err) => {
return err.pipe(delay(1000), take(5));
}),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,32 @@
import userEvent from '@testing-library/user-event';
import { screen, waitFor } from '@testing-library/vue';
import { HttpResponse, http } from 'msw';
import { beforeEach, describe, expect, it } from 'vitest';
import { beforeEach, describe, expect, it, vi } from 'vitest';

import { applications } from '@/mocks/applications/data';
import { server } from '@/mocks/server';
import Application from '@/services/application';
import { render } from '@/test-utils';
import DetailsHealth from '@/views/instances/details/details-health.vue';

function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (reason?: any) => void;
const promise = new Promise<T>((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve, reject };
}

describe('DetailsHealth', () => {
const healthHandlerSpy = vi.fn();

beforeEach(() => {
healthHandlerSpy.mockReset();
server.use(
http.get('/instances/:instanceId/actuator/health', () => {
healthHandlerSpy();
return HttpResponse.json({
instance: 'UP',
groups: ['liveness'],
Expand Down Expand Up @@ -112,6 +126,94 @@ describe('DetailsHealth', () => {
);
});

it('should refetch health when instance version changes (SSE update)', async () => {
const application = new Application(applications[0]);
const instance1 = application.instances[0];

const { rerender } = render(DetailsHealth, {
props: {
instance: instance1,
},
});

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

const instance2 = new Application({
...application,
instances: [
{
...instance1,
id: instance1.id,
version: (instance1.version ?? 0) + 1,
},
],
}).instances[0];

await rerender({ instance: instance2 });

await waitFor(() => {
expect(healthHandlerSpy).toHaveBeenCalledTimes(2);
});
});

it('should ignore stale health response when instance updates quickly', async () => {
const application = new Application(applications[0]);
const instance1 = application.instances[0];

const p1 = deferred<{ data: any }>();
const p2 = deferred<{ data: any }>();
const fetchHealthSpy = vi
.fn()
.mockReturnValueOnce(p1.promise)
.mockReturnValueOnce(p2.promise);
instance1.fetchHealth = fetchHealthSpy;
instance1.fetchHealthGroup = vi.fn().mockResolvedValue({ data: {} });

const { rerender } = render(DetailsHealth, {
props: {
instance: instance1,
},
});

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

const instance2 = new Application({
...application,
instances: [
{
...instance1,
id: instance1.id,
version: (instance1.version ?? 0) + 1,
},
],
}).instances[0];
instance2.fetchHealth = fetchHealthSpy;
instance2.fetchHealthGroup = instance1.fetchHealthGroup;

await rerender({ instance: instance2 });

await waitFor(() => {
expect(fetchHealthSpy).toHaveBeenCalledTimes(2);
});

// Resolve second (newer) response first.
p2.resolve({ data: { status: 'UP', groups: [] } });
await waitFor(() => {
expect(screen.getByText('UP')).toBeInTheDocument();
});

// Resolve first (older) response afterwards; UI must not regress.
p1.resolve({ data: { status: 'DOWN', groups: [] } });
await waitFor(() => {
expect(screen.queryByText('DOWN')).not.toBeInTheDocument();
});
expect(screen.getByText('UP')).toBeInTheDocument();
});

it('should not display health group button if no groups are present', async () => {
server.use(
http.get('/instances/:instanceId/actuator/health', () => {
Expand Down Expand Up @@ -140,4 +242,27 @@ describe('DetailsHealth', () => {
}),
).toBeNull();
});

it('should fetch health details only once on startup', async () => {
const application = new Application(applications[0]);
const instance = application.instances[0];

render(DetailsHealth, {
props: {
instance,
},
});

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

// Verify that the handler is not called again after the initial fetch
await waitFor(
() => {
expect(healthHandlerSpy).toHaveBeenCalledTimes(1);
},
{ timeout: 1000 },
);
});
});
Loading
Loading