Compare commits

..

No commits in common. "f9d188b2ba36c4253e36c93d2774bfd1e7fdd1c1" and "0a0eb43d78f9cae9c7ea91e4812256519e06b7e3" have entirely different histories.

23 changed files with 147 additions and 329 deletions

View file

@ -11,10 +11,7 @@
import "~/assets/global.css";
const event = useRequestEvent();
const sessionStore = useSessionStore();
const eventsStore = useEventsStore();
const nuxtApp = useNuxtApp();
await callOnce("fetch-globals", async () => {
await callOnce("fetch-session", async () => {
await sessionStore.fetch(event);
await nuxtApp.runWithContext(eventsStore.fetchLastEventId);
})
</script>

View file

@ -61,7 +61,7 @@ const shifts = computed(() => {
});
</script>
<style scoped>
<style>
h2 {
margin-block-start: 0.2rem;
}

View file

@ -35,3 +35,7 @@ async function logIn() {
}
}
</script>
<style>
</style>

View file

@ -61,3 +61,7 @@
useEventSource();
const usersStore = useUsersStore();
</script>
<style>
</style>

View file

@ -2,12 +2,12 @@
SPDX-FileCopyrightText: © 2025 Hornwitser <code@hornwitser.no>
SPDX-License-Identifier: AGPL-3.0-or-later
*/
import type { ApiEvent, ApiEventStreamMessage } from "~/shared/types/api";
import type { ApiEvent } from "~/shared/types/api";
interface AppEventMap {
"open": Event,
"message": MessageEvent<ApiEventStreamMessage>,
"event": MessageEvent<ApiEvent>,
"message": MessageEvent<string>,
"update": MessageEvent<ApiEvent>,
"error": Event,
"close": Event,
}
@ -18,11 +18,12 @@ class AppEventSource extends EventTarget {
#forwardEvent(type: string) {
this.#source!.addEventListener(type, event => {
console.log("AppEventSource", event.type, event.data);
if (type === "open" || type === "error") {
if (type === "open" || type === "message" || type === "error") {
console.log("AppEventSource", event.type, event.data);
this.dispatchEvent(new Event(event.type));
} else if (type === "message") {
const data = event.data ? JSON.parse(event.data) as ApiEventStreamMessage : undefined;
} else {
const data = event.data ? JSON.parse(event.data) as ApiEvent : undefined;
console.log("AppEventSource", event.type, data);
if (data?.type === "connected") {
this.#sourceSessionId = data.session?.id;
}
@ -33,27 +34,17 @@ class AppEventSource extends EventTarget {
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) {
open(sessionId: number | undefined) {
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.#source = new EventSource("/api/events");
this.#forwardEvent("open");
this.#forwardEvent("message");
this.#forwardEvent("event");
this.#forwardEvent("update");
this.#forwardEvent("error");
}
@ -67,20 +58,20 @@ class AppEventSource extends EventTarget {
}
#connectRefs = 0;
connect(sessionId: number | undefined, lastEventId: number) {
connect(sessionId: number | undefined) {
this.#connectRefs += 1;
if (this.#source && this.#sourceSessionId !== sessionId) {
this.close();
}
if (!this.#source) {
this.open(sessionId, lastEventId);
this.open(sessionId);
}
}
reconnect(sessionId: number | undefined, lastEventId: number) {
reconnect(sessionId: number | undefined) {
if (this.#source && this.#sourceSessionId !== sessionId) {
this.close();
this.open(sessionId, lastEventId);
this.open(sessionId);
}
}
@ -122,15 +113,14 @@ 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);
appEventSource!.connect(sessionStore.id);
})
watch(() => sessionStore.id, () => {
console.log("useEventSource sessionStore.id change", sessionStore.id);
appEventSource!.reconnect(sessionStore.id, eventsStore.lastEventId);
appEventSource!.reconnect(sessionStore.id);
})
onUnmounted(() => {

View file

@ -11,9 +11,3 @@ To update in real time this application sends a `text/event-source` stream using
Upon connecting a `"connect"` event is emitted with the session the connection was made under. This is the primary mechanism a user agent discovers its own session having been rotated into a new one, which also happens when the access level of the account associated with the session changes.
After the `"connect"` event the user agent will start to receive updates to resources it has access to that has changed. There is no filtering for what resoucres the user agent receives updates for at the moment as there's not enough events to justify the complexity of server-side subscriptions and filtering.
## Id and order
Events are guaranteed to be delivered in order, and to maintain consistency the server provides the following guarantee: Any entities fetched after receiving a response from `/api/last-event-id` will include updates from all events up to and including the `id` received from the response.
This means that a client can fetch an up to date and live representation of any API entity by first fetching the last event from `/api/last-event-id`, and then in parallel fetch any entities as well as opening the `/api/events` stream with the `lastEventId` query param set to the value received from the `/api/last-event-id` endpoint.

View file

@ -109,3 +109,7 @@ const tabs = [
{ id: "database", title: "Database" },
];
</script>
<style>
</style>

View file

@ -84,7 +84,7 @@ const { pending, data, error } = await useFetch(() => `/api/users/${id.value}/de
const userDetails = data as Ref<ApiUserDetails | ApiTombstone>;
</script>
<style scoped>
<style>
dl {
display: grid;
grid-template-columns: auto 1fr;

View file

@ -2,7 +2,7 @@
SPDX-FileCopyrightText: © 2025 Hornwitser <code@hornwitser.no>
SPDX-License-Identifier: AGPL-3.0-or-later
*/
import { nextEventId, readSessions, readUsers, writeSessions, writeUsers } from "~/server/database";
import { readSessions, readUsers, writeSessions, writeUsers } from "~/server/database";
import { apiUserPatchSchema } from "~/shared/types/api";
import { z } from "zod/v4-mini";
import { broadcastEvent } from "~/server/streams";
@ -54,7 +54,6 @@ export default defineEventHandler(async (event) => {
user.updatedAt = new Date().toISOString();
await writeUsers(users);
broadcastEvent({
id: await nextEventId(),
type: "user-update",
data: serverUserToApi(user),
});
@ -67,7 +66,6 @@ export default defineEventHandler(async (event) => {
if (session.accountId === user.id) {
session.rotatesAtMs = nowMs;
broadcastEvent({
id: await nextEventId(),
type: "session-expired",
sessionId: session.id,
});

View file

@ -5,7 +5,6 @@
import {
readUsers, readSessions, readSubscriptions,
writeUsers, writeSessions, writeSubscriptions,
nextEventId,
} from "~/server/database";
import { broadcastEvent, cancelAccountStreams } from "~/server/streams";
@ -25,7 +24,6 @@ export default defineEventHandler(async (event) => {
) {
session.expiresAtMs = nowMs;
broadcastEvent({
id: await nextEventId(),
type: "session-expired",
sessionId: session.id,
});
@ -50,7 +48,6 @@ export default defineEventHandler(async (event) => {
account.updatedAt = now;
await writeUsers(users);
await broadcastEvent({
id: await nextEventId(),
type: "user-update",
data: {
id: account.id,

View file

@ -2,7 +2,7 @@
SPDX-FileCopyrightText: © 2025 Hornwitser <code@hornwitser.no>
SPDX-License-Identifier: AGPL-3.0-or-later
*/
import { readUsers, writeUsers, nextUserId, type ServerUser, readAuthenticationMethods, nextAuthenticationMethodId, writeAuthenticationMethods, nextEventId } from "~/server/database";
import { readUsers, writeUsers, nextUserId, type ServerUser, readAuthenticationMethods, nextAuthenticationMethodId, writeAuthenticationMethods } from "~/server/database";
import { broadcastEvent } from "~/server/streams";
import type { ApiSession } from "~/shared/types/api";
@ -88,7 +88,6 @@ export default defineEventHandler(async (event): Promise<ApiSession> => {
users.push(user);
await writeUsers(users);
await broadcastEvent({
id: await nextEventId(),
type: "user-update",
data: user,
});

View file

@ -3,46 +3,33 @@
SPDX-License-Identifier: AGPL-3.0-or-later
*/
import { pipeline } from "node:stream";
import { createEventStream } from "~/server/streams";
import { addStream, deleteStream } from "~/server/streams";
export default defineEventHandler(async (event) => {
const session = await getServerSession(event, false);
let lastEventId: number | undefined;
const lastEventIdHeader = event.headers.get("Last-Event-ID");
const lastEventIdQuery = getQuery(event)["lastEventId"];
if (lastEventIdHeader) {
if (!/^[0-9]{1,15}$/.test(lastEventIdHeader)) {
throw createError({
statusCode: 400,
statusMessage: "Bad Request",
message: "Malformed Last-Event-ID header",
});
const encoder = new TextEncoder();
const source = event.headers.get("x-forwarded-for");
console.log(`starting event stream for ${source}`)
const stream = new TransformStream<string, Uint8Array>({
transform(chunk, controller) {
controller.enqueue(encoder.encode(chunk));
},
flush(controller) {
console.log(`finished event stream for ${source}`);
deleteStream(stream.writable);
},
// @ts-expect-error experimental API
cancel(reason) {
console.log(`cancelled event stream for ${source}`);
deleteStream(stream.writable);
}
lastEventId = Number.parseInt(lastEventIdHeader, 10);
} else if (lastEventIdQuery) {
if (typeof lastEventIdQuery !== "string" || !/^[0-9]{1,15}$/.test(lastEventIdQuery)) {
throw createError({
statusCode: 400,
statusMessage: "Bad Request",
message: "Malformed lastEventId",
});
}
lastEventId = Number.parseInt(lastEventIdQuery, 10);
} else {
throw createError({
statusCode: 400,
statusMessage: "Bad Request",
message: "lastEventId is required",
});
}
const source = event.headers.get("x-forwarded-for") ?? "";
const stream = await createEventStream(event, source, lastEventId, session);
});
addStream(event, stream.writable, session);
// Workaround to properly handle stream errors. See https://github.com/unjs/h3/issues/986
setHeader(event, "Access-Control-Allow-Origin", "*");
setHeader(event, "Content-Type", "text/event-stream");
pipeline(stream as unknown as NodeJS.ReadableStream, event.node.res, (err) => { /* ignore */ });
pipeline(stream.readable as unknown as NodeJS.ReadableStream, event.node.res, (err) => { /* ignore */ });
event._handled = true;
});

View file

@ -1,11 +0,0 @@
/*
SPDX-FileCopyrightText: © 2025 Hornwitser <code@hornwitser.no>
SPDX-License-Identifier: AGPL-3.0-or-later
*/
import { readEvents } from "../database";
export default defineEventHandler(async (event) => {
const events = await readEvents();
return events[events.length - 1]?. id ?? 0;
});

View file

@ -3,7 +3,7 @@
SPDX-License-Identifier: AGPL-3.0-or-later
*/
import { z } from "zod/v4-mini";
import { nextEventId, readSchedule, writeSchedule } from "~/server/database";
import { readSchedule, writeSchedule } from "~/server/database";
import { broadcastEvent } from "~/server/streams";
import { apiScheduleSchema } from "~/shared/types/api";
import { applyUpdatesToArray } from "~/shared/utils/update";
@ -87,7 +87,6 @@ export default defineEventHandler(async (event) => {
await writeSchedule(schedule);
await broadcastEvent({
id: await nextEventId(),
type: "schedule-update",
updatedFrom,
data: update,

View file

@ -3,7 +3,7 @@
SPDX-License-Identifier: AGPL-3.0-or-later
*/
import { readFile, unlink, writeFile } from "node:fs/promises";
import type { ApiAuthenticationProvider, ApiEvent, ApiSchedule, ApiSubscription, ApiUserType } from "~/shared/types/api";
import type { ApiAuthenticationProvider, ApiSchedule, ApiSubscription, ApiUserType } from "~/shared/types/api";
import type { Id } from "~/shared/types/common";
export interface ServerSession {
@ -50,8 +50,6 @@ const sessionsPath = "data/sessions.json";
const nextSessionIdPath = "data/next-session-id.json";
const authMethodPath = "data/auth-method.json";
const nextAuthenticationMethodIdPath = "data/auth-method-id.json"
const nextEventIdPath = "data/next-event-id.json";
const eventsPath = "data/events.json";
async function remove(path: string) {
try {
@ -170,21 +168,3 @@ export async function readAuthenticationMethods() {
export async function writeAuthenticationMethods(authMethods: ServerAuthenticationMethod[]) {
await writeFile(authMethodPath, JSON.stringify(authMethods, undefined, "\t") + "\n", "utf-8");
}
export async function nextEventId() {
const nextId = await readJson(nextEventIdPath, 0);
await writeFile(nextEventIdPath, String(nextId + 1), "utf-8");
return nextId;
}
export async function writeNextEventId(nextId: number) {
await writeFile(nextEventIdPath, String(nextId), "utf-8");
}
export async function readEvents() {
return readJson<ApiEvent[]>(eventsPath, [])
}
export async function writeEvents(events: ApiEvent[]) {
await writeFile(eventsPath, JSON.stringify(events, undefined, "\t") + "\n", "utf-8");
}

View file

@ -2,134 +2,82 @@
SPDX-FileCopyrightText: © 2025 Hornwitser <code@hornwitser.no>
SPDX-License-Identifier: AGPL-3.0-or-later
*/
import { readEvents, writeEvents, readUsers, type ServerSession } from "~/server/database";
import type { ApiAccount, ApiDisconnected, ApiEvent, ApiEventStreamMessage, ApiUserType } from "~/shared/types/api";
import { readUsers, type ServerSession } from "~/server/database";
import type { ApiAccount, ApiEvent } from "~/shared/types/api";
import { serverSessionToApi } from "./utils/session";
import { H3Event } from "h3";
const keepaliveTimeoutMs = 45e3;
const eventUpdateTimeMs = 1e3;
class EventStream {
write!: (data: string) => void;
close!: (reason?: string) => void;
constructor(
public sessionId: number | undefined,
public accountId: number | undefined,
public userType: ApiUserType | undefined,
public rotatesAtMs: number ,
public lastKeepAliveMs: number,
public lastEventId: number,
) {
}
function sendMessage(
stream: WritableStream<string>,
message: string,
) {
const writer = stream.getWriter();
writer.ready
.then(() => writer.write(message))
.catch(console.error)
.finally(() => writer.releaseLock())
;
}
export async function createEventStream(
function sendMessageAndClose(
stream: WritableStream<string>,
message: string,
) {
const writer = stream.getWriter();
writer.ready
.then(() => {
writer.write(message);
writer.close();
}).catch(console.error)
.finally(() => writer.releaseLock())
;
}
const streams = new Map<WritableStream<string>, { sessionId?: number, accountId?: number, rotatesAtMs: number }>();
let keepaliveInterval: ReturnType<typeof setInterval> | null = null
export async function addStream(
event: H3Event,
source: string,
lastEventId: number,
stream: WritableStream<string>,
session?: ServerSession,
) {
const runtimeConfig = useRuntimeConfig(event);
const now = Date.now();
const events = (await readEvents()).filter(e => e.id > lastEventId);
const users = await readUsers();
const apiSession = session ? await serverSessionToApi(event, session) : undefined;
let userType: ApiAccount["type"] | undefined;
if (session?.accountId !== undefined) {
userType = users.find(a => !a.deleted && a.id === session.accountId)?.type
if (streams.size === 0) {
console.log("Starting keepalive")
keepaliveInterval = setInterval(sendKeepalive, 4000)
}
const stream = new EventStream(
session?.id,
session?.accountId,
userType,
session?.rotatesAtMs ?? now + runtimeConfig.sessionRotatesTimeout * 1000,
now,
events[events.length - 1]?.id ?? lastEventId,
);
const readableStream = new ReadableStream<Uint8Array>({
start(controller) {
const encoder = new TextEncoder();
stream.write = (data: string) => {
controller.enqueue(encoder.encode(data));
}
stream.close = (reason?: string) => {
const data: ApiDisconnected = {
type: "disconnect",
reason,
};
stream.write(`data: ${JSON.stringify(data)}\n\n`);
controller.close();
deleteStream(stream);
},
console.log(`Starting event stream for ${source}`)
addStream(stream);
},
cancel(reason) {
console.log(`Cancelled event stream for ${source}:`, reason);
deleteStream(stream);
}
const runtimeConfig = useRuntimeConfig(event);
streams.set(stream, {
sessionId: session?.id,
accountId: session?.accountId,
rotatesAtMs: session?.rotatesAtMs ?? Date.now() + runtimeConfig.sessionRotatesTimeout * 1000,
});
// Produce a response immediately to avoid the reply waiting for content.
const update: ApiEventStreamMessage = {
const update: ApiEvent = {
type: "connected",
session: apiSession,
session: session ? await serverSessionToApi(event, session) : undefined,
};
stream.write(`data: ${JSON.stringify(update)}\n\n`);
/*
Send events since the provided lastEventId
Warning: This have to happen either before addStream(stream) is
called, or as done here synchronously after it. Otherwise there's a
possibility of events being delivered out of order, which will break
the assumption made by the schedule updating logic.
*/
if (events.length)
console.log(`Sending ${events.length} event(s) to ${source}`);
for (const event of events) {
if (!sendEventToStream(stream, event)) {
break;
}
}
return readableStream;
sendMessage(stream, `event: update\ndata: ${JSON.stringify(update)}\n\n`);
}
let updateInterval: ReturnType<typeof setInterval> | null = null
const streams = new Set<EventStream>();
function addStream(
stream: EventStream,
) {
if (streams.size === 0) {
console.log("Starting event updates")
updateInterval = setInterval(sendEventUpdates, eventUpdateTimeMs)
}
streams.add(stream);
}
function deleteStream(stream: EventStream) {
export function deleteStream(stream: WritableStream<string>) {
streams.delete(stream);
if (streams.size === 0) {
console.log("Ending event updates")
clearInterval(updateInterval!);
updateInterval = null;
console.log("Ending keepalive")
clearInterval(keepaliveInterval!);
}
}
export function cancelAccountStreams(accountId: number) {
for (const stream of streams.values()) {
if (stream.accountId === accountId) {
stream.close("cancelled");
for (const [stream, data] of streams) {
if (data.accountId === accountId) {
sendMessageAndClose(stream, `data: cancelled\n\n`);
}
}
}
export function cancelSessionStreams(sessionId: number) {
for (const stream of streams.values()) {
if (stream.sessionId === sessionId) {
stream.close("cancelled");
for (const [stream, data] of streams) {
if (data.sessionId === sessionId) {
sendMessageAndClose(stream, `data: cancelled\n\n`);
}
}
}
@ -146,7 +94,6 @@ function encodeEvent(event: ApiEvent, userType: ApiAccount["type"] | undefined)
if (event.type === "schedule-update") {
if (!canSeeCrew(userType)) {
event = {
id: event.id,
type: event.type,
updatedFrom: event.updatedFrom,
data: filterSchedule(event.data),
@ -159,7 +106,6 @@ function encodeEvent(event: ApiEvent, userType: ApiAccount["type"] | undefined)
|| !event.data.deleted && event.data.type === "anonymous" && !canSeeAnonymous(userType)
) {
event = {
id: event.id,
type: event.type,
data: {
id: event.data.id,
@ -182,67 +128,44 @@ function encodeEvent(event: ApiEvent, userType: ApiAccount["type"] | undefined)
}
export async function broadcastEvent(event: ApiEvent) {
const events = await readEvents();
events.push(event);
await writeEvents(events);
}
const id = Date.now();
console.log(`broadcasting update to ${streams.size} clients`);
if (!streams.size) {
return;
}
function sendEventToStream(stream: EventStream, event: ApiEvent) {
// Session expiry events cause the streams belonging to that session to be terminated
if (event.type === "session-expired") {
if (stream.sessionId === event.sessionId) {
stream.close("session expired");
}
return false;
cancelSessionStreams(event.sessionId);
return;
}
// Account events are specially handled and only sent to the user they belong to.
if (event.type === "account-update") {
if (stream.accountId === event.data.id) {
stream.write(`id: ${event.id}\nevent: event\ndata: ${JSON.stringify(event)}\n\n`);
}
return true;
}
// All other events are encoded according to the user access level seeing it.
const data = encodeEvent(event, stream.userType)
stream.write(`id: ${event.id}\nevent: event\ndata: ${data}\n\n`);
return true;
}
async function sendEventUpdates() {
// Cancel streams that need to be rotated.
const now = Date.now();
for (const stream of streams.values()) {
if (stream.rotatesAtMs < now) {
stream.close("session rotation");
continue;
}
}
// Send events.
const skipEventId = Math.min(...[...streams.values()].map(s => s.lastEventId));
const events = (await readEvents()).filter(e => e.id > skipEventId);
if (events.length)
console.log(`broadcasting ${events.length} event(s) to ${streams.size} client(s)`);
for (const stream of streams.values()) {
for (const event of events) {
if (event.id > stream.lastEventId) {
stream.lastEventId = event.id;
stream.lastKeepAliveMs = now;
if (!sendEventToStream(stream, event)) {
break;
}
const users = await readUsers();
for (const [stream, streamData] of streams) {
// Account events are specially handled and only sent to the user they belong to.
if (event.type === "account-update") {
if (streamData.accountId === event.data.id) {
sendMessage(stream, `id: ${id}\nevent: update\ndata: ${JSON.stringify(event)}\n\n`);
}
}
}
// Send Keepalives to streams with no activity.
for (const stream of streams.values()) {
if (stream.lastKeepAliveMs + keepaliveTimeoutMs < now) {
stream.write(": keepalive\n");
stream.lastKeepAliveMs = now;
} else {
let userType: ApiAccount["type"] | undefined;
if (streamData.accountId !== undefined) {
userType = users.find(a => !a.deleted && a.id === streamData.accountId)?.type
}
const data = encodeEvent(event, userType)
sendMessage(stream, `id: ${id}\nevent: update\ndata: ${data}\n\n`);
}
}
}
function sendKeepalive() {
const now = Date.now();
for (const [stream, streamData] of streams) {
if (streamData.rotatesAtMs > now) {
sendMessage(stream, ": keepalive\n");
} else {
sendMessageAndClose(stream, `data: cancelled\n\n`);
}
}
}

View file

@ -2,7 +2,7 @@
SPDX-FileCopyrightText: © 2025 Hornwitser <code@hornwitser.no>
SPDX-License-Identifier: AGPL-3.0-or-later
*/
import { nextEventId, readSchedule, type ServerUser, writeSchedule } from '~/server/database';
import { readSchedule, type ServerUser, writeSchedule } from '~/server/database';
import { broadcastEvent } from '~/server/streams';
import type { ApiSchedule, ApiTombstone } from '~/shared/types/api';
@ -58,7 +58,6 @@ export async function updateScheduleInterestedCounts(users: ServerUser[]) {
schedule.updatedAt = updatedFrom;
await writeSchedule(schedule);
await broadcastEvent({
id: await nextEventId(),
type: "schedule-update",
updatedFrom,
data: update,

View file

@ -4,7 +4,6 @@
*/
import type { H3Event } from "h3";
import {
nextEventId,
nextSessionId,
readSessions,
readSubscriptions,
@ -35,7 +34,6 @@ async function clearServerSessionInternal(event: H3Event, sessions: ServerSessio
if (session) {
session.expiresAtMs = Date.now();
broadcastEvent({
id: await nextEventId(),
type: "session-expired",
sessionId,
});

View file

@ -155,26 +155,27 @@ export interface ApiUserDetails {
}
export interface ApiAccountUpdate {
id: Id,
type: "account-update",
data: ApiAccount,
}
export interface ApiConnected {
type: "connected",
session?: ApiSession,
}
export interface ApiScheduleUpdate {
id: Id,
type: "schedule-update",
updatedFrom?: string,
data: ApiSchedule | ApiTombstone,
}
export interface ApiSessionExpired {
id: Id,
type: "session-expired",
sessionId: Id,
}
export interface ApiUserUpdate {
id: Id,
type: "user-update",
updatedFrom?: string,
data: ApiUser | ApiTombstone,
@ -182,22 +183,8 @@ export interface ApiUserUpdate {
export type ApiEvent =
| ApiAccountUpdate
| ApiConnected
| ApiScheduleUpdate
| ApiSessionExpired
| ApiUserUpdate
;
export interface ApiConnected {
type: "connected",
session?: ApiSession,
}
export interface ApiDisconnected {
type: "disconnect",
reason?: string,
}
export type ApiEventStreamMessage =
| ApiConnected
| ApiDisconnected
;

View file

@ -1,31 +0,0 @@
/*
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,
};
});

View file

@ -96,7 +96,7 @@ export const useSchedulesStore = defineStore("schedules", () => {
}
})
appEventSource?.addEventListener("event", (event) => {
appEventSource?.addEventListener("update", (event) => {
if (event.data.type !== "schedule-update") {
return;
}

View file

@ -57,7 +57,7 @@ export const useSessionStore = defineStore("session", () => {
},
};
appEventSource?.addEventListener("message", (event) => {
appEventSource?.addEventListener("update", (event) => {
if (event.data.type !== "connected") {
return;
}

View file

@ -75,7 +75,7 @@ export const useUsersStore = defineStore("users", () => {
},
}
appEventSource?.addEventListener("event", (event) => {
appEventSource?.addEventListener("update", (event) => {
if (event.data.type !== "user-update") {
return;
}