Skip to content

Commit 27d81fa

Browse files
committed
feat: add status ping
1 parent 8b6dfe7 commit 27d81fa

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

app/controllers/api/v1/sse.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,26 @@
11
async function connect(ctx) {
22
if (ctx.sse) {
3+
// likely not the best way to do this
4+
// TODO: fork koa-sse and move this into the ping interval
5+
// runs every 60s
6+
const interval = setInterval(() => {
7+
const connected = ctx.sse.send({
8+
event: 'status',
9+
data: isActive(ctx)
10+
});
11+
12+
console.log('connected');
13+
14+
// clear the interval if the client is disconnected
15+
if (!connected) {
16+
clearInterval(interval);
17+
}
18+
}, 60_000);
19+
ctx.sse.send({
20+
event: 'status',
21+
data: isActive(ctx)
22+
});
23+
324
// send bree events over sse
425
for (const event of ['worker created', 'worker deleted']) {
526
ctx.bree.on(event, (name) => {
@@ -9,8 +30,18 @@ async function connect(ctx) {
930

1031
ctx.sse.on('close', () => {
1132
ctx.logger.error('SSE closed');
33+
34+
clearInterval(interval);
1235
});
1336
}
1437
}
1538

39+
function isActive(ctx) {
40+
return Boolean(
41+
ctx.bree.workers.size > 0 ||
42+
ctx.bree.timeouts.size > 0 ||
43+
ctx.bree.intervals.size > 0
44+
);
45+
}
46+
1647
module.exports = { connect };

0 commit comments

Comments
 (0)