Cosmostat Init Commit

This commit is contained in:
2026-03-09 16:32:43 -07:00
commit 298d7432a7
23 changed files with 1707 additions and 0 deletions

View File

@ -0,0 +1,18 @@
# Use an official Node runtime
FROM node:20-alpine
# Create app directory
WORKDIR /usr/src/app
# Install dependencies
COPY package.json .
RUN npm install --only=production
# Copy app source
COPY . .
# Expose the port that the app listens on
EXPOSE 3000
# Start the server
CMD ["node", "server.js"]

View File

@ -0,0 +1,13 @@
{
"name": "redis-table-demo",
"version": "1.0.0",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"dependencies": {
"express": "^4.18.2",
"socket.io": "^4.7.2",
"redis": "^4.6.7"
}
}

View File

@ -0,0 +1,70 @@
// server.js
const http = require('http');
const express = require('express');
const { createClient } = require('redis');
const { Server } = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = new Server(server);
// Serve static files (index.html)
app.use(express.static('public'));
// ---------- Redis subscriber ----------
const redisClient = createClient({
url: 'redis://172.17.0.1:6379'
});
redisClient.on('error', err => console.error('Redis error', err));
(async () => {
await redisClient.connect();
const sub = redisClient.duplicate(); // duplicate to keep separate pub/sub
await sub.connect();
// Subscribe to the channel that sends host stats
await sub.subscribe(
['host_stats'],
(message, channel) => { // <-- single handler
let payload;
try {
payload = JSON.parse(message); // message is a JSON string
} catch (e) {
console.error(`Failed to parse ${channel}`, e);
return;
}
io.emit(channel, payload);
}
);
// Subscribe to the channel that sends history stats
await sub.subscribe(
['history_stats'],
(message, channel) => {
let payload;
try {
payload = JSON.parse(message); // message is a JSON string
} catch (e) {
console.error(`Failed to parse ${channel}`, e);
return;
}
io.emit(channel, payload);
}
);
sub.on('error', err => console.error('Subscriber error', err));
})();
// ---------- Socket.io ----------
io.on('connection', socket => {
console.log('client connected:', socket.id);
// Optional: send the current state on connect if you keep it cached
});
// ---------- Start ----------
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server listening on http://localhost:${PORT}`);
});