-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstart-desktop.js
More file actions
297 lines (244 loc) Β· 9.2 KB
/
Copy pathstart-desktop.js
File metadata and controls
297 lines (244 loc) Β· 9.2 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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
#!/usr/bin/env node
/**
* LPS Crawler Real Desktop Application Launcher
* Production-grade launcher with comprehensive error handling and system integration
*
* @author Production-Grade Implementer
* @version 1.0.0
*/
const { spawn } = require('child_process');
const path = require('path');
const os = require('os');
const fs = require('fs');
class DesktopLauncher {
constructor() {
this.desktopProcess = null;
this.startTime = Date.now();
this.isRestarting = false;
this.maxRestarts = 3;
this.restartCount = 0;
this.initializeLauncher();
}
initializeLauncher() {
console.log('π LPS Crawler Real Desktop Application Launcher');
console.log('π― Production-Grade Web Scraping Tool');
console.log('');
// Display system information
this.displaySystemInfo();
// Check prerequisites
this.checkPrerequisites();
// Setup signal handlers
this.setupSignalHandlers();
// Start the desktop application
this.startDesktopApp();
}
displaySystemInfo() {
console.log('π SYSTEM INFORMATION:');
console.log(` β’ Platform: ${os.platform()} ${os.arch()}`);
console.log(` β’ Node.js: ${process.version}`);
console.log(` β’ Memory: ${Math.round(os.totalmem() / 1024 / 1024 / 1024)}GB total`);
console.log(` β’ CPUs: ${os.cpus().length} cores`);
console.log(` β’ Working Directory: ${process.cwd()}`);
console.log('');
}
checkPrerequisites() {
console.log('π CHECKING PREREQUISITES...');
const requiredFiles = [
path.join(__dirname, 'desktop', 'main.js'),
path.join(__dirname, 'serve-gui.js'),
path.join(__dirname, 'index.html')
];
let allFilesExist = true;
requiredFiles.forEach(filePath => {
if (fs.existsSync(filePath)) {
// console.log(` β
${path.basename(filePath)}`);
} else {
console.log(` β ${path.basename(filePath)} - MISSING`);
allFilesExist = false;
}
});
if (!allFilesExist) {
console.error('β Missing required files.');
process.exit(1);
}
console.log('β
Prerequisites satisfied.');
}
setupSignalHandlers() {
['SIGINT', 'SIGTERM'].forEach(signal => {
process.on(signal, () => {
console.log(`\nπ Received ${signal}, shutting down...`);
this.shutdown();
});
});
process.on('uncaughtException', (error) => {
console.error('π¨ Uncaught Exception:', error);
this.shutdown();
process.exit(1);
});
if (os.platform() === 'win32') {
const readline = require('readline');
readline.createInterface({
input: process.stdin,
output: process.stdout
}).on('SIGINT', () => {
process.emit('SIGINT');
});
}
}
startDesktopApp() {
console.log('π₯οΈ Starting Desktop App...');
const desktopAppPath = path.join(__dirname, 'desktop', 'main.js');
const nodeArgs = [desktopAppPath];
if (process.env.NODE_ENV === 'development') {
nodeArgs.unshift('--inspect');
}
this.desktopProcess = spawn('node', nodeArgs, {
stdio: 'inherit',
env: {
...process.env,
NODE_ENV: process.env.NODE_ENV || 'production',
ELECTRON_ENABLE_LOGGING: 'true'
},
detached: false
});
// Setup process event handlers
this.setupProcessHandlers();
// Monitor process health
this.startHealthMonitoring();
}
setupProcessHandlers() {
if (!this.desktopProcess) return;
this.desktopProcess.on('error', (error) => {
console.error('π¨ Failed to start desktop app:', error);
this.handleProcessError(error);
});
this.desktopProcess.on('exit', (code, signal) => {
const uptime = ((Date.now() - this.startTime) / 1000).toFixed(1);
if (code === 0) {
console.log(`β
Desktop app closed successfully (uptime: ${uptime}s)`);
this.handleGracefulExit();
} else {
console.error(`β Desktop app exited with code ${code}, signal: ${signal} (uptime: ${uptime}s)`);
this.handleProcessCrash(code, signal);
}
});
this.desktopProcess.on('disconnect', () => {
console.warn('π Desktop app process disconnected');
});
// Handle stdout/stderr if not using inherit
if (this.desktopProcess.stdout) {
this.desktopProcess.stdout.on('data', (data) => {
console.log(`π€ Desktop: ${data}`);
});
}
if (this.desktopProcess.stderr) {
this.desktopProcess.stderr.on('data', (data) => {
console.error(`π₯ Desktop Error: ${data}`);
});
}
}
handleProcessError(error) {
console.error('π¨ Process Error Details:', error);
if (error.code === 'ENOENT') {
console.error('β Node.js executable not found. Please ensure Node.js is installed.');
} else if (error.code === 'EACCES') {
console.error('β Permission denied. Please check file permissions.');
} else {
console.error('β Unknown process error occurred.');
}
// Attempt restart if under limit
if (this.restartCount < this.maxRestarts && !this.isRestarting) {
this.attemptRestart();
} else {
this.shutdown();
process.exit(1);
}
}
handleProcessCrash(code, signal) {
// Log crash details for debugging
const crashReport = {
timestamp: new Date().toISOString(),
exitCode: code,
signal: signal,
uptime: Date.now() - this.startTime,
restartCount: this.restartCount,
platform: os.platform(),
nodeVersion: process.version
};
try {
const crashLogPath = path.join(__dirname, 'crash-reports', `crash-${Date.now()}.json`);
const crashDir = path.dirname(crashLogPath);
if (!fs.existsSync(crashDir)) {
fs.mkdirSync(crashDir, { recursive: true });
}
fs.writeFileSync(crashLogPath, JSON.stringify(crashReport, null, 2));
console.log(`π Crash report saved: ${crashLogPath}`);
} catch (error) {
console.error('β Failed to save crash report:', error);
}
// Attempt restart if under limit
if (this.restartCount < this.maxRestarts && !this.isRestarting) {
this.attemptRestart();
} else {
console.error('β Max restart attempts reached. Shutting down.');
this.shutdown();
process.exit(1);
}
}
handleGracefulExit() {
console.log('π Desktop application terminated gracefully');
this.shutdown();
process.exit(0);
}
attemptRestart() {
this.isRestarting = true;
this.restartCount++;
console.log(`π Attempting restart ${this.restartCount}/${this.maxRestarts}...`);
// Wait before restart to avoid rapid restart loops
setTimeout(() => {
this.isRestarting = false;
this.startTime = Date.now();
this.startDesktopApp();
}, 3000);
}
startHealthMonitoring() {
// Monitor system resources every 30 seconds
setInterval(() => {
const memUsage = process.memoryUsage();
const uptime = ((Date.now() - this.startTime) / 1000).toFixed(1);
// Log resource usage in development mode
if (process.env.NODE_ENV === 'development') {
console.log(`π Health Check - Uptime: ${uptime}s, Memory: ${Math.round(memUsage.heapUsed / 1024 / 1024)}MB used`);
}
// Check for memory leaks (if using more than 1GB)
if (memUsage.heapUsed > 1024 * 1024 * 1024) {
console.warn('β οΈ High memory usage detected');
}
}, 30000);
}
shutdown() {
console.log('π§Ή Shutting down launcher...');
if (this.desktopProcess && !this.desktopProcess.killed) {
console.log('π Terminating desktop application...');
this.desktopProcess.kill('SIGTERM');
// Force kill after timeout
setTimeout(() => {
if (this.desktopProcess && !this.desktopProcess.killed) {
console.log('β οΈ Force terminating desktop application...');
this.desktopProcess.kill('SIGKILL');
}
}, 5000);
}
console.log('β
Launcher shutdown complete');
}
}
// Application entry point
if (require.main === module) {
try {
new DesktopLauncher();
} catch (error) {
console.error('π¨ Fatal launcher error:', error);
process.exit(1);
}
}
module.exports = DesktopLauncher;