Skip to content

Commit

Permalink
feat: Add metrics endpoint to publish socket.io metrics to prometheus
Browse files Browse the repository at this point in the history
Signed-off-by: Julius Härtl <[email protected]>
  • Loading branch information
juliusknorr committed Jul 5, 2024
1 parent 7cd17c0 commit 6847428
Show file tree
Hide file tree
Showing 5 changed files with 60 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,7 @@ TLS=false
TLS_KEY=
TLS_CERT=
JWT_SECRET_KEY=your_secret_key

# Prometheus metrics endpoint
# Set this to access the monitoring endpoint at /metrics
# METRICS_TOKEN=
38 changes: 38 additions & 0 deletions package-lock.json

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

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,12 @@
"jsonwebtoken": "^9.0.2",
"lodash": "^4.17.21",
"node-fetch": "^3.3.2",
"prom-client": "^14.2.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"socket.io": "^4.7.5",
"socket.io-client": "^4.7.5",
"socket.io-prometheus": "^0.3.0",
"vue": "^2.7.14"
},
"devDependencies": {
Expand Down
13 changes: 13 additions & 0 deletions websocket_server/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,24 @@
*/

import express from 'express'
import { register } from 'prom-client'

const METRICS_TOKEN = process.env.METRICS_TOKEN

const app = express()

app.get('/', (req, res) => {
res.send('Excalidraw collaboration server is up :)')
})

app.get('/metrics', async (req, res) => {
const token = req.headers.authorization?.split(' ')[1] || req.query.token
if (!METRICS_TOKEN || token !== METRICS_TOKEN) {
return res.status(403).send('Unauthorized')
}
const metrics = await register.metrics()
res.set('Content-Type', register.contentType)
res.end(metrics)
})

export default app
3 changes: 3 additions & 0 deletions websocket_server/socket.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
*/

import { Server as SocketIO } from 'socket.io'
import prometheusMetrics from 'socket.io-prometheus'
import jwt from 'jsonwebtoken'
import { getRoomDataFromFile, roomDataStore, saveRoomDataToFile } from './roomData.js'
import { convertArrayBufferToString, convertStringToArrayBuffer } from './utils.js'
Expand Down Expand Up @@ -42,6 +43,8 @@ export const initSocket = (server) => {

io.use(socketAuthenticateHandler)

prometheusMetrics(io)

io.on('connection', (socket) => {
setupSocketEvents(socket, io)
})
Expand Down

0 comments on commit 6847428

Please sign in to comment.