Skip to content

Commit

Permalink
feat(sse): add log listeners for SSE
Browse files Browse the repository at this point in the history
  • Loading branch information
shadowgate15 committed Aug 2, 2022
1 parent 5908aaa commit fcdb64e
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 1 deletion.
24 changes: 24 additions & 0 deletions app/controllers/api/v1/sse.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
const { conns } = require('../../../../helpers/bree-hooks');

let uuid = 0;

async function connect(ctx) {
if (ctx.sse) {
// likely not the best way to do this
Expand All @@ -21,18 +25,38 @@ async function connect(ctx) {
data: isActive(ctx)
});

conns.push({ id: uuid, sse: ctx.sse });

// send bree events over sse
for (const event of ['worker created', 'worker deleted']) {
ctx.bree.on(event, (name) => {
ctx.sse.send({ event, data: name });
});
}

ctx.bree.on('worker message', (data) => {
ctx.sse.send({ event: 'worker message', data: JSON.stringify(data) });
});

ctx.bree.on('worker error', (data) => {
ctx.sse.send({ event: 'worker error', data: JSON.stringify(data) });
});

ctx.sse.on('close', () => {
ctx.logger.error('SSE closed');

// remove from conns array)
const idx = conns.findIndex((conn) => conn.id === uuid);

if (idx > 0) {
conns.splice(idx, 1);
}

clearInterval(interval);
});

// bump uuid
uuid++;
}
}

Expand Down
31 changes: 30 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,36 @@ function plugin(opts, Bree) {
const oldInit = Bree.prototype.init;

Bree.prototype.init = async function () {
await oldInit.bind(this)();
// hook error handler and message handler
const oldErrorHandler = this.config.errorHandler;
const oldWorkerMessageHandler = this.config.workerMessageHandler;

this.config.errorHandler = function (error, data) {
if (oldErrorHandler) {
oldErrorHandler.call(this, error, data);
}

this.emit('worker error', {
error,
name: data?.name,
data: data ? JSON.stringify(data) : undefined
});
};

this.config.errorHandler = this.config.errorHandler.bind(this);

this.config.workerMessageHandler = function (data) {
if (oldWorkerMessageHandler) {
oldWorkerMessageHandler.call(this, data);
}

this.emit('worker message', data);
};

this.config.workerMessageHandler =
this.config.workerMessageHandler.bind(this);

await oldInit.call(this);

// assign bree to the context
api.app.context.bree = this;
Expand Down

0 comments on commit fcdb64e

Please sign in to comment.