Skip to content

Commit

Permalink
feat(backend): add /version endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
davidyuk committed Jan 21, 2024
1 parent e4ce907 commit ac44137
Show file tree
Hide file tree
Showing 5 changed files with 244 additions and 1,980 deletions.
1 change: 1 addition & 0 deletions babel.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@ module.exports = {
module: 'bluebird',
method: 'coroutine',
}],
['@babel/plugin-syntax-import-attributes'],
],
};
5 changes: 4 additions & 1 deletion backend/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
FROM node:18-alpine
FROM node:20-alpine
WORKDIR /app

COPY package*.json ./
Expand All @@ -8,4 +8,7 @@ COPY src src
EXPOSE 80
ENV PORT=80

ARG REVISION
ENV REVISION $REVISION

CMD [ "node", "src/main.js" ]
38 changes: 33 additions & 5 deletions backend/src/server.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,28 @@
import http from 'http';
import { Server } from 'socket.io';
import sendPushNotification from './send-push-notification.js';
import pkg from '../package.json' with { type: 'json' };

export default (port, log = () => {}) => {
const io = new Server(port, {
let getStats;

const server = http.createServer((request, response) => {
if (request.url === '/version' && request.method === 'GET') {
response.setHeader('Content-Type', 'application/json');
const json = JSON.stringify({
version: pkg.version,
revision: process.env.REVISION || 'local',
...getStats(),
}, null, 2);
response.write(json);
response.end();
return;
}
response.writeHead(404);
response.end();
});

const io = new Server(server, {
cors: { origin: '*' },
});

Expand All @@ -11,6 +31,13 @@ export default (port, log = () => {}) => {
const leaderPushApiSubscriptions = {};
const leaderMessages = {};

getStats = () => {
const clients = io.engine.clientsCount;
const leaders = Object.keys(leaderPushApiSubscriptions).length;
const followers = Object.keys(leaderKeys).length;
return { clients, leaders, followers };
};

io.sockets.use((socket, next) => {
const { key } = socket.handshake.auth;
if (!key) next(new Error('Key is missed'));
Expand Down Expand Up @@ -130,12 +157,13 @@ export default (port, log = () => {}) => {
}
});

log(`Listening on ${port} port`);
server.listen(port, () => {
log(`Listening on ${port} port`);
});

const interval = setInterval(() => {
const leaders = Object.keys(leaderPushApiSubscriptions).length;
const followers = Object.keys(leaderKeys).length;
log(`Connected ${io.engine.clientsCount} clients, recorded ${leaders} leaders, ${followers} followers`);
const s = getStats();
log(`Connected ${s.clients} clients, recorded ${s.leaders} leaders, ${s.followers} followers`);
}, 20000);
const ioClose = io.close;
io.close = function closeHandler(...args) {
Expand Down

0 comments on commit ac44137

Please sign in to comment.