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
19 changes: 17 additions & 2 deletions webapp/frontend/src/lib/mlog_watcher/channel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,25 @@ export type MlogWatcherChannelError = {
[mlogWatcherChannelErrorTag]: true;
} & ({ type: 'disconnected' } | { type: 'connectionError' });

export interface MlogWatcherChannelClosedEvent {
code: number;
wasOpen: boolean;
}

export class MlogWatcherChannel {
private nextId = 0;
private pendingInvocations = new Map<number, Completer<unknown>>();
private socket: WebSocket;
private isOpen = false;
ready: Promise<void>;
closed: Promise<MlogWatcherChannelClosedEvent>;

constructor(port: number) {
this.socket = new WebSocket(`ws://localhost:${port}/v1`);

this.ready = new Promise((resolve, reject) => {
this.socket.onopen = () => {
this.isOpen = true;
resolve();
};

Expand All @@ -42,7 +50,6 @@ export class MlogWatcherChannel {
};

this.socket.onmessage = (event) => {
console.log(event.data);
const response: MlogWatcherResponse<unknown, unknown> = JSON.parse(event.data);
const completer = this.pendingInvocations.get(response.invocation_id);
if (!completer) {
Expand All @@ -54,6 +61,15 @@ export class MlogWatcherChannel {
this.pendingInvocations.delete(response.invocation_id);
};
});

this.closed = new Promise((resolve) => {
this.socket.addEventListener('close', (event) => {
resolve({
code: event.code,
wasOpen: this.isOpen
});
});
});
}

private assertSocketOpen(socket: WebSocket) {
Expand All @@ -78,7 +94,6 @@ export class MlogWatcherChannel {
const completer = new Completer();
this.pendingInvocations.set(invocation.invocation_id, completer);
const content = JSON.stringify(invocation);
console.log('Sending invocation:', content);
this.socket.send(content);
return completer.promise as Promise<Response>;
}
Expand Down
14 changes: 14 additions & 0 deletions webapp/frontend/src/lib/mlog_watcher/store.svelte.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export class MlogWatcherStore {
channel.ready.catch((error) => {
this.channel = new Completer();
this.#initialized = false;

toast.error(
'Mlog Watcher connection failed. Please ensure the Mlog Watcher server is running and the port is correct.'
);
Expand All @@ -37,6 +38,19 @@ export class MlogWatcherStore {
}
});

channel.closed.then((e) => {
if (!e.wasOpen) return;

this.channel = new Completer();
this.#initialized = false;

if (e.code !== 1000) {
toast.error(
`Mlog Watcher connection closed unexpectedly. Websocket close code: ${e.code}`
);
}
});

return () => {
channel.close();
this.channel = new Completer();
Expand Down
Loading