Restructure layout and add widget
This commit is contained in:
+24
-16
@@ -13,37 +13,40 @@ type ServerEventSource = {
|
||||
id: number;
|
||||
};
|
||||
|
||||
declare global {
|
||||
var sseList: ServerEventSource[];
|
||||
}
|
||||
|
||||
if (!globalThis.sseList) {
|
||||
globalThis.sseList = [];
|
||||
}
|
||||
|
||||
export class EventSourceManager {
|
||||
private list: ServerEventSource[] = [];
|
||||
private id = 0;
|
||||
new(
|
||||
topic = "_global",
|
||||
{ onDisconnect }: { onDisconnect?: () => void } = {},
|
||||
{
|
||||
onDisconnect,
|
||||
signal,
|
||||
}: { onDisconnect?: () => void; signal?: AbortSignal } = {},
|
||||
): Response {
|
||||
let timeout: NodeJS.Timeout | undefined;
|
||||
this.id++;
|
||||
if (this.id > 100000) this.id = 0;
|
||||
const id = this.id;
|
||||
console.log(` SUB ${topic}#${id}`);
|
||||
console.log(` SUB ${topic}#${id} (C${this.list.length})`);
|
||||
|
||||
const push = (s: ServerEventSource) => {
|
||||
globalThis.sseList.push(s);
|
||||
this.list.push(s);
|
||||
};
|
||||
const remove = (id: number) => {
|
||||
globalThis.sseList = globalThis.sseList.toSpliced(
|
||||
globalThis.sseList.findIndex((e) => e.id === id),
|
||||
if (this.list.findIndex((e) => e.id === id) < 0) return;
|
||||
console.log(` DSC ${topic}#${id}`);
|
||||
this.list = this.list.toSpliced(
|
||||
this.list.findIndex((e) => e.id === id),
|
||||
1,
|
||||
);
|
||||
onDisconnect?.();
|
||||
console.log(` DSC ${topic}#${id}`);
|
||||
};
|
||||
|
||||
signal?.addEventListener("abort", () => {
|
||||
clearInterval(timeout);
|
||||
remove(id);
|
||||
});
|
||||
|
||||
return new Response(
|
||||
new ReadableStream({
|
||||
start(controller) {
|
||||
@@ -66,6 +69,7 @@ export class EventSourceManager {
|
||||
id,
|
||||
};
|
||||
timeout = setInterval(() => {
|
||||
if (controller.desiredSize === null) return res.close();
|
||||
try {
|
||||
res.write(`:ping\n\n`);
|
||||
} catch {
|
||||
@@ -74,6 +78,10 @@ export class EventSourceManager {
|
||||
}, 5000);
|
||||
push(res);
|
||||
},
|
||||
cancel() {
|
||||
clearTimeout(timeout);
|
||||
remove(id);
|
||||
},
|
||||
}),
|
||||
{
|
||||
headers: {
|
||||
@@ -92,7 +100,7 @@ export class EventSourceManager {
|
||||
) {
|
||||
console.log(` PUB #${topic}`);
|
||||
setImmediate(() => {
|
||||
for (const s of globalThis.sseList) {
|
||||
for (const s of this.list) {
|
||||
if (s.topic !== topic) continue;
|
||||
try {
|
||||
s.send(data, event);
|
||||
@@ -102,7 +110,7 @@ export class EventSourceManager {
|
||||
}
|
||||
|
||||
count(topic = "_global") {
|
||||
return sseList.reduce((c, s) => c + (s.topic === topic ? 1 : 0), 0);
|
||||
return this.list.reduce((c, s) => c + (s.topic === topic ? 1 : 0), 0);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user