-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
159 lines (135 loc) · 5.16 KB
/
server.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
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
const { createServer } = require('http');
const { parse } = require('url');
const next = require('next');
const { Server } = require("socket.io");
const fetch = require('node-fetch');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
// Track active executions
const activeExecutions = new Map();
app.prepare().then(() => {
const server = createServer((req, res) => {
const parsedUrl = parse(req.url, true);
handle(req, res, parsedUrl);
});
const io = new Server(server, {
cors: {
origin: ["http://localhost:3000", "http://127.0.0.1:3000"],
methods: ["GET", "POST"],
credentials: true,
transports: ['websocket', 'polling']
},
pingTimeout: 120000,
pingInterval: 30000,
connectTimeout: 60000,
allowEIO3: true
});
// Create notebook namespace
const notebookNamespace = io.of('/notebook');
notebookNamespace.on('connection', (socket) => {
console.log('Notebook client connected:', socket.id);
// Handle reconnection - resend any pending results
const pendingResults = Array.from(activeExecutions.entries())
.filter(([_, data]) => data.socketId === socket.id)
.map(([executionId, data]) => ({ executionId, result: data.result }));
if (pendingResults.length > 0) {
console.log(`Resending ${pendingResults.length} pending results for socket ${socket.id}`);
}
pendingResults.forEach(({ executionId, result }) => {
socket.emit(`execution_result_${executionId}`, result);
socket.emit('execution_result', result);
activeExecutions.delete(executionId);
});
socket.on('execute', async (data) => {
console.log(`Received execute request from ${socket.id}:`, data);
if (!data.content) {
const errorResponse = {
status: 'error',
error: 'No code content provided'
};
socket.emit('execution_result', errorResponse);
return;
}
// Store the execution request
const executionId = data.executionId || Date.now().toString();
activeExecutions.set(executionId, { socketId: socket.id });
try {
const pythonResponse = await fetch('http://localhost:8000/execute', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
type: 'execute',
content: data.content,
session_id: socket.id
}),
});
if (!pythonResponse.ok) {
throw new Error(`Python server error: ${pythonResponse.statusText}`);
}
const result = await pythonResponse.json();
console.log('Raw Python response:', result); // Debug log
// Store the result
activeExecutions.set(executionId, {
socketId: socket.id,
result
});
// Emit both specific and general results
if (socket.connected) {
console.log('Emitting result to client:', result); // Debug log
socket.emit(`execution_result_${executionId}`, result);
socket.emit('execution_result', result);
} else {
console.log(`Socket ${socket.id} disconnected before receiving result`);
}
} catch (error) {
console.error(`Error executing code for ${socket.id}:`, error);
const errorResponse = {
status: 'error',
error: error.message || 'Failed to execute code'
};
if (socket.connected) {
socket.emit(`execution_result_${executionId}`, errorResponse);
socket.emit('execution_result', errorResponse);
}
} finally {
// Clean up after sending the response
setTimeout(() => {
activeExecutions.delete(executionId);
}, socket.connected ? 5000 : 30000); // Keep longer if disconnected
}
});
socket.on('disconnect', (reason) => {
console.log(`Client ${socket.id} disconnected. Reason:`, reason);
if (reason === 'transport close' || reason === 'ping timeout') {
const clientExecutions = Array.from(activeExecutions.entries())
.filter(([_, data]) => data.socketId === socket.id);
if (clientExecutions.length > 0) {
console.log(`Preserving ${clientExecutions.length} executions for ${socket.id}`);
}
clientExecutions.forEach(([executionId, data]) => {
setTimeout(() => {
if (activeExecutions.has(executionId)) {
console.log(`Cleaning up execution ${executionId} for ${socket.id}`);
activeExecutions.delete(executionId);
}
}, 30000);
});
} else {
// Clean up immediately for intentional disconnects
const clientExecutions = Array.from(activeExecutions.entries())
.filter(([_, data]) => data.socketId === socket.id)
.forEach(([executionId, _]) => activeExecutions.delete(executionId));
}
});
socket.on('error', (error) => {
console.error(`Socket error for ${socket.id}:`, error);
});
});
server.listen(3000, (err) => {
if (err) throw err;
console.log('> Ready on http://localhost:3000');
});
});