Skip to content

Commit

Permalink
switch to websockets for reading logs
Browse files Browse the repository at this point in the history
  • Loading branch information
howardchung committed Dec 4, 2023
1 parent db7dc05 commit bd720c9
Show file tree
Hide file tree
Showing 3 changed files with 77 additions and 31 deletions.
71 changes: 62 additions & 9 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,8 @@
"steam-resources": "github:odota/node-steam-resources",
"stripe": "^9.12.0",
"supertest": "^4.0.2",
"uuid": "^3.3.3"
"uuid": "^3.3.3",
"ws": "^8.14.2"
},
"devDependencies": {
"@apidevtools/swagger-parser": "^10.0.2",
Expand Down
34 changes: 13 additions & 21 deletions svc/web.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import cors from 'cors';
import bodyParser from 'body-parser';
import stripeLib from 'stripe';
import Redis from 'ioredis';
import uuid from 'uuid';
import { WebSocketServer } from 'ws';
import keys from '../routes/keyManagement.mjs';
import api from '../routes/api.mjs';
import queries from '../store/queries.mjs';
Expand Down Expand Up @@ -338,26 +338,6 @@ app.route('/manageSub').post(async (req, res) => {
return res.json(session);
});
app.use('/api', api);
const logReaders = {};
const logSub = new Redis(config.REDIS_URL);
logSub.subscribe(['api', 'parsed', 'gcdata']);
logSub.on('message', (channel, message) => {
// Emit it to all the connected logs
Object.values(logReaders).forEach(([req, res]) => {
const matched =
Array.isArray(req.query.channel) && req.query.channel?.includes(channel);
if (!req.query.channel || req.query.channel === channel || matched) {
res.write(message + '\n');
}
});
});
app.get('/logs', (req, res) => {
const id = uuid.v4();
logReaders[id] = [req, res];
req.on('close', () => {
delete logReaders[id];
});
});
// CORS Preflight for API keys
// NB: make sure UI_HOST is set e.g. http://localhost:3000 otherwise CSRF check above will stop preflight from working
app.options('/keys', cors());
Expand Down Expand Up @@ -385,6 +365,18 @@ const port = config.PORT || config.FRONTEND_PORT;
const server = app.listen(port, () => {
console.log('[WEB] listening on %s', port);
});
const wss = new WebSocketServer({ server });
const logSub = new Redis(config.REDIS_URL);
logSub.subscribe(['api', 'parsed', 'gcdata']);
logSub.on('message', (channel, message) => {
// Emit it to all the connected websockets
// Can we let the user choose channels to sub to?
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
/**
* Wait for connections to end, then shut down
* */
Expand Down

0 comments on commit bd720c9

Please sign in to comment.