Store events that are to be broadcasted in the database, and fetch events to serve in the /api/event stream to the client from the database. This ensures that events are not lost if the operation to open the stream takes longer than usual, or the client was not connected at the time the event was broadcast. To ensure no events are lost in the transition from server generating the page to the client hydrating and establishing a connection with the event stream, the /api/last-event-id endpoint is first queried on the server before any other entities is fetched from the database. The client then passes this id when establishing the event stream, and receives all events greater than that id.
142 lines
4 KiB
TypeScript
142 lines
4 KiB
TypeScript
/*
|
|
SPDX-FileCopyrightText: © 2025 Hornwitser <code@hornwitser.no>
|
|
SPDX-License-Identifier: AGPL-3.0-or-later
|
|
*/
|
|
import type { ApiEvent, ApiEventStreamMessage } from "~/shared/types/api";
|
|
|
|
interface AppEventMap {
|
|
"open": Event,
|
|
"message": MessageEvent<ApiEventStreamMessage>,
|
|
"event": MessageEvent<ApiEvent>,
|
|
"error": Event,
|
|
"close": Event,
|
|
}
|
|
|
|
class AppEventSource extends EventTarget {
|
|
#source: EventSource | null = null;
|
|
#sourceSessionId: number | undefined = undefined;
|
|
|
|
#forwardEvent(type: string) {
|
|
this.#source!.addEventListener(type, event => {
|
|
console.log("AppEventSource", event.type, event.data);
|
|
if (type === "open" || type === "error") {
|
|
this.dispatchEvent(new Event(event.type));
|
|
} else if (type === "message") {
|
|
const data = event.data ? JSON.parse(event.data) as ApiEventStreamMessage : undefined;
|
|
if (data?.type === "connected") {
|
|
this.#sourceSessionId = data.session?.id;
|
|
}
|
|
this.dispatchEvent(new MessageEvent(event.type, {
|
|
data,
|
|
origin: event.origin,
|
|
lastEventId: event.lastEventId,
|
|
source: event.source,
|
|
ports: [...event.ports],
|
|
}));
|
|
} else {
|
|
const data = event.data ? JSON.parse(event.data) as ApiEvent : undefined;
|
|
this.dispatchEvent(new MessageEvent(event.type, {
|
|
data,
|
|
origin: event.origin,
|
|
lastEventId: event.lastEventId,
|
|
source: event.source,
|
|
ports: [...event.ports],
|
|
}));
|
|
}
|
|
});
|
|
}
|
|
|
|
open(sessionId: number | undefined, lastEventId: number) {
|
|
console.log("Opening event source sid:", sessionId);
|
|
this.#sourceSessionId = sessionId;
|
|
const query = new URLSearchParams({ lastEventId: String(lastEventId) });
|
|
this.#source = new EventSource(`/api/events?${query}`);
|
|
this.#forwardEvent("open");
|
|
this.#forwardEvent("message");
|
|
this.#forwardEvent("event");
|
|
this.#forwardEvent("error");
|
|
}
|
|
|
|
close() {
|
|
console.log("Closing event source sid:", this.#sourceSessionId);
|
|
this.#source!.close();
|
|
this.#source = null;
|
|
this.#sourceSessionId = undefined;
|
|
console.log("AppEventSource", "close");
|
|
this.dispatchEvent(new Event("close"));
|
|
}
|
|
|
|
#connectRefs = 0;
|
|
connect(sessionId: number | undefined, lastEventId: number) {
|
|
this.#connectRefs += 1;
|
|
if (this.#source && this.#sourceSessionId !== sessionId) {
|
|
this.close();
|
|
}
|
|
if (!this.#source) {
|
|
this.open(sessionId, lastEventId);
|
|
}
|
|
}
|
|
|
|
reconnect(sessionId: number | undefined, lastEventId: number) {
|
|
if (this.#source && this.#sourceSessionId !== sessionId) {
|
|
this.close();
|
|
this.open(sessionId, lastEventId);
|
|
}
|
|
}
|
|
|
|
disconnect() {
|
|
if (this.#connectRefs === 0) {
|
|
throw Error("Connection reference count already zero");
|
|
}
|
|
this.#connectRefs -= 1;
|
|
if (this.#connectRefs === 0 && this.#source) {
|
|
this.close();
|
|
}
|
|
}
|
|
|
|
override addEventListener<K extends keyof AppEventMap>(
|
|
type: K,
|
|
listener: (this: AppEventSource, ev: AppEventMap[K]) => any,
|
|
options?: boolean | AddEventListenerOptions
|
|
) {
|
|
super.addEventListener(type, listener as (ev: Event) => void, options);
|
|
}
|
|
|
|
override dispatchEvent<K extends keyof AppEventMap>(
|
|
event: AppEventMap[K],
|
|
) {
|
|
return super.dispatchEvent(event);
|
|
}
|
|
|
|
override removeEventListener<K extends keyof AppEventMap>(
|
|
type: K,
|
|
listener: (this: AppEventSource, ev: AppEventMap[K]) => any,
|
|
options?: boolean | EventListenerOptions
|
|
) {
|
|
return super.removeEventListener(type, listener as (ev: Event) => void, options);
|
|
}
|
|
}
|
|
|
|
// The event source exists only on the client.
|
|
export const appEventSource = import.meta.client ? new AppEventSource() : null;
|
|
|
|
export function useEventSource() {
|
|
const sessionStore = useSessionStore();
|
|
const eventsStore = useEventsStore();
|
|
onMounted(() => {
|
|
console.log("useEventSource onMounted", sessionStore.id);
|
|
appEventSource!.connect(sessionStore.id, eventsStore.lastEventId);
|
|
})
|
|
|
|
watch(() => sessionStore.id, () => {
|
|
console.log("useEventSource sessionStore.id change", sessionStore.id);
|
|
appEventSource!.reconnect(sessionStore.id, eventsStore.lastEventId);
|
|
})
|
|
|
|
onUnmounted(() => {
|
|
console.log("useEventSource onUnmounted");
|
|
appEventSource!.disconnect();
|
|
});
|
|
|
|
return appEventSource;
|
|
}
|