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 @@ -15,13 +15,13 @@
*/
import { AxiosInstance } from 'axios';
import { sortBy } from 'lodash-es';
import { Observable, concat, from, ignoreElements } from 'rxjs';
import { Observable, from, switchMap } from 'rxjs';

import axios, {
addLanguageHeaderInterceptor,
redirectOn401,
} from '../utils/axios';
import waitForPolyfill from '../utils/eventsource-polyfill';
import loadEventSource from '../utils/eventsource';
import uri from '../utils/uri';
import Instance, { DOWN_STATES, UNKNOWN_STATES, UP_STATES } from './instance';

Expand Down Expand Up @@ -140,19 +140,21 @@ class Application {
}

static getStream(): Observable<ApplicationStream | unknown> {
return concat(
from(waitForPolyfill()).pipe(ignoreElements()),
Observable.create((observer) => {
const eventSource = new EventSource('applications');
eventSource.onmessage = (message) =>
observer.next({
...message,
data: Application._transformResponse(message.data),
} as ApplicationStream);

eventSource.onerror = (err) => observer.error(err);
return () => eventSource.close();
}),
return from(loadEventSource()).pipe(
switchMap(
(openEventSource) =>
new Observable((observer) => {
const eventSource = openEventSource('applications');
eventSource.onmessage = (message) =>
observer.next({
...message,
data: Application._transformResponse(message.data),
} as ApplicationStream);

eventSource.onerror = (err) => observer.error(err);
return () => eventSource.close();
}),
),
);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import Application from './application';
import Instance from './instance';

type FakeEventSource = {
url: string;
onmessage: ((message: { data: string }) => void) | null;
onerror: ((error: unknown) => void) | null;
close: ReturnType<typeof vi.fn>;
};

const sources: FakeEventSource[] = [];

vi.mock('event-source-polyfill', () => ({
EventSourcePolyfill: vi.fn().mockImplementation(function (url: string) {
const source: FakeEventSource = {
url,
onmessage: null,
onerror: null,
close: vi.fn(),
};
sources.push(source);
return source;
}),
}));

const opened = async () => {
await vi.waitFor(() => expect(sources.length).toBeGreaterThan(0));
return sources[sources.length - 1];
};

describe.each([
['Application.getStream', 'applications', () => Application.getStream()],
[
'Instance.getEventStream',
'instances/events',
() => Instance.getEventStream(),
],
])('%s', (_name, url, createStream) => {
beforeEach(() => {
sources.length = 0;
});

afterEach(() => {
vi.restoreAllMocks();
});

it('connects to the event stream', async () => {
const subscription = createStream().subscribe();

const source = await opened();

expect(source.url).toBe(url);
subscription.unsubscribe();
});

it('emits an error when the connection reports one, e.g. the heartbeat timeout of a silent connection', async () => {
const error = vi.fn();
const subscription = createStream().subscribe({ error });

const source = await opened();
const timeout = new Error('No activity within 30000 milliseconds.');
source.onerror?.(timeout);

expect(error).toHaveBeenCalledWith(timeout);
expect(source.close).toHaveBeenCalled();
subscription.unsubscribe();
});

it('closes the connection when unsubscribing', async () => {
const subscription = createStream().subscribe();

const source = await opened();
subscription.unsubscribe();

expect(source.close).toHaveBeenCalledTimes(1);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,14 @@
*/
import { AxiosError, AxiosInstance, AxiosResponse } from 'axios';
import saveAs from 'file-saver';
import { Observable, concat, from, ignoreElements } from 'rxjs';
import { Observable, from, switchMap } from 'rxjs';

import axios, {
addLanguageHeaderInterceptor,
redirectOn401,
registerErrorToastInterceptor,
} from '../utils/axios';
import waitForPolyfill from '../utils/eventsource-polyfill';
import loadEventSource from '../utils/eventsource';
import logtail, { getLogfileWindowMetadata } from '../utils/logtail';
import uri from '../utils/uri';

Expand Down Expand Up @@ -95,20 +95,22 @@ class Instance {
}

static getEventStream() {
return concat(
from(waitForPolyfill()).pipe(ignoreElements()),
Observable.create((observer) => {
const eventSource = new EventSource('instances/events');
eventSource.onmessage = (message) =>
observer.next({
...message,
data: JSON.parse(message.data),
});
eventSource.onerror = (err) => observer.error(err);
return () => {
eventSource.close();
};
}),
return from(loadEventSource()).pipe(
switchMap(
(openEventSource) =>
new Observable((observer) => {
const eventSource = openEventSource('instances/events');
eventSource.onmessage = (message) =>
observer.next({
...message,
data: JSON.parse(message.data),
});
eventSource.onerror = (err) => observer.error(err);
return () => {
eventSource.close();
};
}),
),
);
}

Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';

import loadEventSource, { HEARTBEAT_TIMEOUT } from './eventsource';

const created: Array<{ url: string; options: any }> = [];

vi.mock('event-source-polyfill', () => ({
EventSourcePolyfill: vi.fn().mockImplementation(function (url, options) {
created.push({ url, options });
return { close: vi.fn() };
}),
}));

describe('loadEventSource', () => {
beforeEach(() => {
created.length = 0;
});

it('opens the stream with the heartbeat timeout, so a silent connection is detected', async () => {
const open = await loadEventSource();

open('applications');

expect(created).toEqual([
{
url: 'applications',
options: { heartbeatTimeout: HEARTBEAT_TIMEOUT },
},
]);
});

it('uses a timeout that tolerates a missed ping of the server (every 10s) but not more', () => {
expect(HEARTBEAT_TIMEOUT).toBeGreaterThan(20_000);
expect(HEARTBEAT_TIMEOUT).toBeLessThanOrEqual(45_000);
});

it('allows to override the heartbeat timeout', async () => {
const open = await loadEventSource(5_000);

open('instances/events');

expect(created[0].options).toEqual({ heartbeatTimeout: 5_000 });
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/**
* The server sends a ":ping" comment every 10 seconds on every event stream. The native EventSource never exposes
* comments to JavaScript, so a connection that silently stops delivering data (dropped by a NAT, firewall or route
* without any close or error) can't be detected with it, and the UI would show stale data forever.
*
* The polyfill counts comments as activity and aborts and reports an error if nothing arrives within
* `heartbeatTimeout`, so the caller can reconnect. It is used in all browsers for that reason.
*/
export const HEARTBEAT_TIMEOUT = 30_000;

export type EventSourceFactory = (url: string) => EventSource;

export default async function loadEventSource(
heartbeatTimeout = HEARTBEAT_TIMEOUT,
): Promise<EventSourceFactory> {
const { EventSourcePolyfill } = await import('event-source-polyfill');
return (url) =>
new EventSourcePolyfill(url, {
heartbeatTimeout,
}) as unknown as EventSource;
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@
*/
import { fireEvent, screen, waitFor } from '@testing-library/vue';
import { HttpResponse, http } from 'msw';
import { Subject } from 'rxjs';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { Observable, Subject } from 'rxjs';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { ref } from 'vue';

import JournalView from './index.vue';
Expand Down Expand Up @@ -164,4 +164,79 @@ describe('Journal View', () => {
const appTwoText = await screen.findAllByText('App Two Updated');
expect(appTwoText).toBeDefined();
});

describe('when the event stream breaks', () => {
const registered = (name: string, version: number) => ({
instance: 'instance-1',
version,
type: InstanceEventType.REGISTERED,
timestamp: new Date('2023-01-01T10:00:00Z'),
registration: { name },
});

afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
});

it('reconnects and loads the events that were missed meanwhile', async () => {
let history = [registered('BEFORE OUTAGE', 1)];
server.use(
http.get('**/instances/events', () => HttpResponse.json(history)),
);

const connections: Array<(event: unknown) => void> = [];
let failing: (error: Error) => void = () => {};
vi.spyOn(Instance, 'getEventStream').mockImplementation(
() =>
new Observable((observer) => {
failing = (error) => observer.error(error);
connections.push((event) => observer.next({ data: event }));
}) as any,
);

vi.useFakeTimers({ shouldAdvanceTime: true });
render(JournalView, {
global: {
stubs: {
JournalTable: {
props: ['events'],
template:
'<ul><li v-for="event in events" :key="event.key">{{event.version}}</li></ul>',
},
},
},
});
await screen.findByText('1');
expect(connections).toHaveLength(1);

history = [registered('BEFORE OUTAGE', 1), registered('MISSED', 2)];
failing(new Error('No activity within 30000 milliseconds.'));
await vi.advanceTimersByTimeAsync(5000);

await vi.waitFor(() => expect(connections).toHaveLength(2));
await screen.findByText('2');

connections[1](registered('AFTER RECONNECT', 3));
await screen.findByText('3');
});

it('keeps trying while the server is not reachable', async () => {
server.use(http.get('**/instances/events', () => HttpResponse.json([])));
let attempts = 0;
vi.spyOn(Instance, 'getEventStream').mockImplementation(
() =>
new Observable((observer) => {
attempts += 1;
observer.error(new Error('connection refused'));
}) as any,
);

vi.useFakeTimers({ shouldAdvanceTime: true });
render(JournalView);
await vi.advanceTimersByTimeAsync(5000 * 3 + 100);

expect(attempts).toBeGreaterThanOrEqual(3);
});
});
});
Loading
Loading