Refactor to persist and reliably deliver events

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.
This commit is contained in:
Hornwitser 2025-09-20 20:11:58 +02:00
parent 0a0eb43d78
commit 753da6d3d4
18 changed files with 326 additions and 132 deletions

31
stores/events.ts Normal file
View file

@ -0,0 +1,31 @@
/*
SPDX-FileCopyrightText: © 2025 Hornwitser <code@hornwitser.no>
SPDX-License-Identifier: AGPL-3.0-or-later
*/
export const useEventsStore = defineStore("events", () => {
const state = {
lastEventId: ref(0),
};
const getters = {
}
const actions = {
async fetchLastEventId() {
const requestFetch = useRequestFetch();
state.lastEventId.value = await requestFetch("/api/last-event-id");
}
}
appEventSource?.addEventListener("event", (event) => {
if (event.data.id !== undefined) {
state.lastEventId.value = event.data.id
return;
}
});
return {
...state,
...getters,
...actions,
};
});