-
Notifications
You must be signed in to change notification settings - Fork 17
/
siren.js
75 lines (64 loc) · 1.86 KB
/
siren.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
const express = require('express')
const next = require('next')
const EventSource = require('eventsource')
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
const PORT = process.env.PORT || 3000
require('dotenv').config()
const backendUrl = process.env.BACKEND_URL
const handleSSe = (res, req, url) => {
const cookies = req.headers.cookie;
let authToken = '';
if (cookies) {
cookies.split(';').forEach(cookie => {
const [name, value] = cookie.split('=').map(c => c.trim());
if (name === 'session-token') {
authToken = value;
}
});
}
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
'X-Accel-Buffering': 'no',
})
res.flushHeaders()
const eventSource = new EventSource(url, {
headers: {
'Authorization': `Bearer ${authToken}`
}
})
eventSource.onmessage = (e) => {
res.write(`data: ${e.data}\n\n`)
}
// Heartbeat mechanism
const heartbeatInterval = setInterval(() => {
res.write(': keep-alive\n\n')
}, 10000) // every 10 seconds
eventSource.onerror = (e) => {
console.error('EventSource failed:', e)
clearInterval(heartbeatInterval)
eventSource.close()
res.end()
}
req.on('close', () => {
clearInterval(heartbeatInterval)
eventSource.close()
res.end()
})
}
app.prepare().then(() => {
const server = express()
server.get('/validator-logs', (req, res) => handleSSe(res, req, `${backendUrl}/logs/validator`))
server.get('/beacon-logs', (req, res) => handleSSe(res, req, `${backendUrl}/logs/beacon`))
// Handling all other requests with Next.js
server.all('*', (req, res) => {
return handle(req, res)
})
server.listen(PORT, (err) => {
if (err) throw err
console.log(`> Ready on http://localhost:${PORT}`)
})
})