-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
232 lines (204 loc) · 6.67 KB
/
server.js
File metadata and controls
232 lines (204 loc) · 6.67 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
#!/usr/bin/env node
/* AI Assistance Disclosure:
Tool: ChatGPT (model: GPT‑5) date: 2025‑10‑04
Scope:
- Expand 'connection' to include telemetry
Author review:
- Verified for correctness by running code
*/
// Env variables required:
// - HOST
// - PORT
import WebSocket from 'ws'
import http from 'http'
import * as number from 'lib0/number'
import { setupWSConnection, setPersistence, extractRoomName} from './utils.js'
import { mongoPersistence } from './persistence.js'
import url from 'url';
import jwt from 'jsonwebtoken'; // assuming you use jsonwebtoken lib
import express from 'express';
import IORedis from 'ioredis';
import path from 'path';
import { match } from 'assert';
import { promisify } from 'util';
import dotenv from "dotenv";
dotenv.config();
const wss = new WebSocket.Server({ noServer: true });
const host = process.env.COLLAB_HOST || '0.0.0.0';
const port = number.parseInt(process.env.COLLAB_PORT || '8081');
const redisOptions = {
host: process.env.REDIS_HOST,
port: Number(process.env.REDIS_PORT),
maxRetriesPerRequest: null
};
setPersistence(mongoPersistence);
const app = express();
const redis = new IORedis(redisOptions);
const server = http.createServer(app);
const jwtVerifyAsync = promisify(jwt.verify);
wss.on('connection', (conn, req) => {
// When client disconnects
conn.on('close', (code, reason) => {
console.log('Client disconnected');
console.log('Total connections:', wss.clients.size);
console.log(`Code: ${code}, Reason: ${reason}`);
});
if (!req.url) {
console.log("Empty url supplied");
conn.close(1007, "Connection is missing url");
return;
}
const { pathname, query } = url.parse(req.url, true);
if (!pathname) {
console.log("Connection is missing pathname")
conn.close(1007, "Connection is missing pathname");
return;
}
if (!query) {
console.log("Connection is missing query")
conn.close(1007, "Connection is missing query");
return;
}
const matchToken = extractRoomName(pathname);
if (! (typeof query.userId == "string")) {
console.log(`userId is of wrong type. Expected <string>, instead received: ${typeof query.userId}`);
conn.close(1007, "Invalid userId type");
return;
}
getMatchStatus(matchToken).then( (status) => {
if (!status) {
conn.close(3000, "Match has already terminated");
return;
}
}).catch( (error) => {
if (error instanceof URIError) {
}
})
// Print total open connections
console.log('Client connected');
console.log('Total connections:', wss.clients.size);
// Hand off to the default Yjs handler
setupWSConnection(conn, req, query.userId);
});
wss.on('error', (err) => {
console.error("WebSocket server error:", err);
});
server.on('upgrade', (request, socket, head) => {
// Expects ws connections on /room/:jwt?userId=<userId>s
// You may check auth of request here.
// Call `wss.HandleUpgrade` *after* you checked whether the client has access
// (e.g. by checking cookies, or url parameters).
// See https://github.com/websockets/ws#client-authentication
// console.log(request);
// console.log(head);
if (!request.url) {
socket.destroy();
return;
}
wss.handleUpgrade(request, socket, head, /** @param {any} ws */ ws => {
wss.emit('connection', ws, request)
});
})
app.get('/user/status/:userId', async (req, res) => {
//get from redis
const userId = req.params.userId;
try {
// Get all keys that match "match:*"
let cursor = '0';
const keys = [];
do {
const [nextCursor, batch] = await redis.scan(cursor, 'MATCH', 'match:*', 'COUNT', 100);
keys.push(...batch);
for(const key of keys) {
const matchDataString = await redis.get(key)
const matchData = matchDataString? JSON.parse(matchDataString) : [];
if (matchData.userA === userId || matchData.userB === userId) {
const matchId = key.split(':')[1];
return res.json({ status: 'in_match', matchId });
}
}
cursor = nextCursor;
} while (cursor !== '0');
res.json({ status: 'idle' });
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Server error' });
}
})
app.post('/match/start/:matchToken', async (req, res) => {
const matchToken = req.params.matchToken;
console.log(`Received Match Start Request for MatchId:${matchToken}`)
try {
// Verify JWT token
jwt.verify(matchToken, process.env.JWT_SECRET, async (err, decoded) => {
if (err) {
console.log('Auth failed during match start:', err.message);
// Reject connection
return res.status(400).json({ error: 'Invalid match token' });
}
await redis.set(`match:${matchToken}`, JSON.stringify(decoded));
return res.json({ success: true, matchToken: matchToken });
})
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Server error' });
}
})
app.get('/match/status/:matchToken', async (req, res) => {
const matchToken = req.params.matchToken;
console.log(`Status request received for match:${matchToken}`)
const status = await getMatchStatus(matchToken);
try{
if (status) {
return res.json({ status: 'in_match', matchToken: matchToken });
} else {
return res.json({ status: 'no_match', matchToken: matchToken });
}
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Server error' });
}
})
app.post('/match/stop/:matchToken', async (req, res) => {
const matchToken = req.params.matchToken;
try {
await stopMatch(matchToken);
return res.json({ success: true, matchToken: matchToken });
} catch (error) {
if (error instanceof URIError) {
return res.status(400).json({ error: 'Invalid match token' });
}
console.error(error);
return res.status(500).json({ error: 'Server error' });
}
})
export const stopMatch = async (matchToken) => {
try {
const decoded = await jwtVerifyAsync(matchToken, process.env.JWT_SECRET);
await redis.del(`match:${matchToken}`);
console.log(`Successfully stopped match with id ${matchToken}`);
} catch (err) {
// Safe type narrowing
if (err instanceof jwt.JsonWebTokenError) {
console.log('Auth failed during match end');
throw new URIError("Invalid matchToken");
}
console.error("Unexpected error during stopMatch:", err);
throw new Error("Server error when stopping match");
}
}
const getMatchStatus = async (matchToken) => {
try {
const data = await redis.get(`match:${matchToken}`);
if (!data) {
return false;
}
return true;
} catch (err) {
console.error("Error when getting Match Status");
throw err;
}
}
server.listen(port, host, () => {
console.log(`running at '${host}' on port ${port}`)
})