Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
271 lines (236 loc) · 8.5 KB
/
Copy pathserver.js
File metadata and controls
271 lines (236 loc) · 8.5 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
/**
* Minimal Node server: HTTP + WebSocket.
* Serves static files from deprecated/public/ and handles WS upgrade.
* Usage: node server.js
* Build UI: cd client && npm run build && cd ..
*/
const path = require('path');
const fs = require('fs');
const http = require('http');
const express = require('express');
const WebSocket = require('ws');
const uuid = require('uuid');
const querystring = require('querystring');
const app = express();
const PORT = process.env.PORT || 3000;
const publicDir = path.join(__dirname, 'deprecated', 'public');
const indexPath = path.join(publicDir, 'index.html');
if (!fs.existsSync(indexPath)) {
console.warn('No deprecated/public/index.html. Build the UI: cd client && npm run build && cd ..');
}
// Simple version check so you can verify deploy: GET /api/version
app.get('/api/version', (req, res) => {
res.json({
version: '0.0.1',
built: fs.existsSync(indexPath) ? 'yes' : 'no',
time: new Date().toISOString(),
});
});
app.use(express.static(publicDir));
app.get('*', (req, res) => {
res.sendFile(path.join(publicDir, 'index.html'));
});
const server = http.createServer(app);
// WebSocket: channels, broadcast, send to client/channel (inlined from ws-server.js)
const logger = console;
const wss = new WebSocket.Server({ noServer: true, clientTracking: true });
const channels = {};
function processQueryParams(url) {
if (url.indexOf('?') === -1) return {};
return querystring.parse(url.split('?')[1]);
}
function addToChannel(channel, client) {
channels[channel] = channels[channel]?.length
? Array.from(new Set([...channels[channel], client]))
: [client];
}
function removeFromChannel(channel, client) {
channels[channel] = channels[channel].filter((c) => c !== client);
if (!channels[channel].length) delete channels[channel];
}
function removeFromChannels(client) {
Object.keys(channels).forEach((ch) => removeFromChannel(ch, client));
}
function broadcastMessage(message, sender) {
wss.clients.forEach((client) => {
if (client !== sender && client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({ ...message, from: sender.id }));
}
});
}
function sendToClient(message, targetId, sender) {
if (sender.id === targetId) return;
for (const c of wss.clients) {
if (c.id === targetId && c.readyState === WebSocket.OPEN) {
c.send(JSON.stringify({ ...message, from: sender.id, directMessage: true }));
break;
}
}
}
function sendToClientOnChannel(message, targetId, channel, sender) {
if (!channels[channel]?.includes(sender)) return;
const target = channels[channel].find((c) => c.id === targetId);
if (target && target !== sender && target.readyState === WebSocket.OPEN) {
target.send(JSON.stringify({ ...message, channel, targetId, from: sender.id }));
wss.clients.forEach((c) => {
if (c.readyState === WebSocket.OPEN) {
c.send(JSON.stringify({ type: 'dataFlow', from: sender.id, to: targetId, channel }));
}
});
}
}
// One-way latency estimate (ms). Uses client-reported RTT/2 or default.
const DEFAULT_ONE_WAY_MS = 25;
const SYNC_BUFFER_MS = 30;
function getOneWayLatency(client) {
if (client.latencyRtt != null && typeof client.latencyRtt === 'number') {
return Math.max(1, Math.round(client.latencyRtt / 2));
}
return DEFAULT_ONE_WAY_MS;
}
function sendToChannel(message, channel, sender) {
if (!channels[channel]?.includes(sender)) return;
channels[channel].forEach((client) => {
if (client !== sender && client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({ ...message, channel, from: sender.id }));
}
});
wss.clients.forEach((c) => {
if (c.readyState === WebSocket.OPEN) {
c.send(JSON.stringify({ type: 'dataFlow', from: sender.id, to: null, channel }));
}
});
}
// Deliver to channel members at approximately the same wall-clock time by delaying each send.
function sendToChannelSync(message, channel, sender) {
if (!channels[channel]?.includes(sender)) return;
const recipients = channels[channel].filter((c) => c !== sender && c.readyState === WebSocket.OPEN);
if (recipients.length === 0) return;
const { syncDelivery, ...payload } = message;
const oneWayLatencies = recipients.map((c) => ({ client: c, ms: getOneWayLatency(c) }));
const maxOneWay = Math.max(...oneWayLatencies.map((o) => o.ms));
const targetTime = Date.now() + maxOneWay + SYNC_BUFFER_MS;
oneWayLatencies.forEach(({ client, ms }) => {
const sendAt = targetTime - ms;
const delay = Math.max(0, sendAt - Date.now());
setTimeout(() => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({ ...payload, channel, from: sender.id }));
}
}, delay);
});
wss.clients.forEach((c) => {
if (c.readyState === WebSocket.OPEN) {
c.send(JSON.stringify({ type: 'dataFlow', from: sender.id, to: null, channel }));
}
});
}
function sendToJoinedChannels(message, sender) {
Object.keys(channels).forEach((ch) => {
if (channels[ch].includes(sender)) sendToChannel(message, ch, sender);
});
}
function sendJoinedChannels(ws) {
ws.send(
JSON.stringify({
type: 'joinedChannels',
channels: Object.keys(channels)
.filter((ch) => channels[ch].includes(ws))
.map((ch) => ({ channel: ch, members: channels[ch].map((c) => c.id) })),
})
);
}
function sendAvailableChannels(ws) {
ws.send(
JSON.stringify({
type: 'availableChannels',
channels: Object.keys(channels).map((ch) => ({
channel: ch,
members: channels[ch].map((c) => c.id),
})),
})
);
}
function sendChannelMembershipUpdates(client) {
sendJoinedChannels(client);
sendAvailableChannels(client);
}
wss.on('connection', (client, req) => {
client.id = uuid.v4();
logger.log('new connection', client.id, '|', wss.clients.size, 'clients');
client.send(JSON.stringify({ type: 'id', id: client.id }));
broadcastMessage({ type: 'clientConnected' }, client);
const params = processQueryParams(req.url);
if (params.channels) {
params.channels.split(',').forEach((ch) => addToChannel(ch, client));
}
client.on('message', (data, binary) => {
try {
const message = binary ? data : JSON.parse(data);
if (binary) return;
switch (message.type) {
case 'joinChannel':
addToChannel(message.channel, client);
wss.clients.forEach(sendChannelMembershipUpdates);
break;
case 'leaveChannel':
removeFromChannel(message.channel, client);
wss.clients.forEach(sendChannelMembershipUpdates);
break;
case 'broadcast':
broadcastMessage(message, client);
break;
case 'joinedChannels':
sendJoinedChannels(client);
break;
case 'availableChannels':
sendAvailableChannels(client);
break;
case 'ping':
if (typeof message.ts === 'number') {
client.send(JSON.stringify({ type: 'pong', ts: message.ts }));
}
break;
case 'latencyReport':
if (typeof message.rtt === 'number' && message.rtt >= 0) {
client.latencyRtt = message.rtt;
logger.log('latencyReport', client.id, message.rtt, 'ms');
}
break;
default:
if (message.targetId) {
if (message.channel) sendToClientOnChannel(message, message.targetId, message.channel, client);
else sendToClient(message, message.targetId, client);
} else if (message.channel) {
if (message.syncDelivery) {
sendToChannelSync(message, message.channel, client);
} else {
sendToChannel(message, message.channel, client);
}
} else {
sendToJoinedChannels(message, client);
}
}
} catch (e) {
logger.log('error parsing message', e);
}
});
client.on('close', () => {
logger.log('connection closed', '|', wss.clients.size, 'clients');
removeFromChannels(client);
broadcastMessage({ type: 'clientDisconnected' }, client);
wss.clients.forEach(sendChannelMembershipUpdates);
});
wss.clients.forEach(sendChannelMembershipUpdates);
});
logger.log('wss_ready');
server.on('upgrade', (req, socket, head) => {
logger.log('ws upgrade request', req.headers.host || '(no host)', req.url);
socket.on('error', (err) => logger.log('ws upgrade socket error', err.message));
wss.handleUpgrade(req, socket, head, (ws) => {
wss.emit('connection', ws, req);
});
});
server.listen(PORT, () => {
console.log(`Server http://localhost:${PORT}`);
});