remove timer based kvstore status stragedy, only sse based now

This commit is contained in:
Soph :3 2026-01-04 20:41:49 +02:00
parent e64910d895
commit f1539bdffa
2 changed files with 40 additions and 60 deletions

View file

@ -1,3 +1,6 @@
import { Status } from '$lib';
import { kvStore } from '$lib/server/db/index.js';
interface SubscribedTo {
subscribed: string[];
userId: string;
@ -5,35 +8,63 @@ interface SubscribedTo {
}
export const _clients = new Map<string, SubscribedTo>();
export function _sendToSubscribers(userId: string, payload: unknown) {
for (const client of _clients) {
if (client[1].subscribed.includes(userId)) {
for (const [key, client] of _clients) {
if (client.subscribed.includes(userId)) {
try {
client[1].controller.enqueue(`data: ${JSON.stringify(payload)}\n\n`);
client.controller.enqueue(`data: ${JSON.stringify(payload)}\n\n`);
} catch {
_clients.delete(client[0]);
_clients.delete(key);
}
}
}
}
export function _isUserConnected(userId: string): boolean {
for (const client of _clients.values()) {
if (client.userId === userId) return true;
}
return false;
}
export async function GET({ locals, request }) {
if (!locals.user) {
return new Response('No authentication', { status: 401 });
}
const subscribed = locals.user.friends.map((z) => z.id);
const userId = locals.user.id;
//@TODO add more to subscribed eventually, server members, et cetera
const subscribed = locals.user.friends.map((f) => f.id);
const overwrite = locals.user.statusOverwrite;
const reqId = crypto.randomUUID();
const stream = new ReadableStream({
start(controller) {
_clients.set(reqId, { subscribed, userId: locals.user!.id, controller });
console.log(`SSE Client opened. ${_clients.size}`);
_clients.set(reqId, { subscribed, userId, controller });
console.log(`SSE Client opened. total: ${_clients.size}`);
controller.enqueue(`data: ${JSON.stringify({ type: 'connected' })}\n\n`);
if (overwrite === Status.DND) {
kvStore.set(`user-${userId}-state`, Status.DND);
_sendToSubscribers(userId, { type: 'status', id: userId, status: Status.DND });
} else {
kvStore.set(`user-${userId}-state`, Status.ONLINE);
_sendToSubscribers(userId, { type: 'status', id: userId, status: Status.ONLINE });
}
request.signal.addEventListener('abort', () => {
_clients.delete(reqId);
console.log(`SSE Client aborted. ${_clients.size}`);
console.log(`SSE Client aborted. total: ${_clients.size}`);
if (_isUserConnected(userId)) return;
if (overwrite === Status.OFFLINE) return;
kvStore.set(`user-${userId}-state`, Status.OFFLINE);
_sendToSubscribers(userId, { type: 'status', id: userId, status: Status.OFFLINE });
});
}
});