forked from jacktheboss220/WhatsAppBotMultiDevice
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconnection.js
More file actions
71 lines (59 loc) · 2.09 KB
/
connection.js
File metadata and controls
71 lines (59 loc) · 2.09 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
import NodeCache from "node-cache";
// Optimized cache with TTL and memory management
const cache = new NodeCache({
stdTTL: 600, // 10 minutes default TTL
checkperiod: 120, // Check every 2 minutes
useClones: false, // Avoid cloning for better memory usage
maxKeys: 1000, // Limit cache size
deleteOnExpire: true,
});
// Monitor cache memory usage
setInterval(() => {
const stats = cache.getStats();
if (stats.keys > 800) {
// When approaching limit
cache.flushAll(); // Clear cache to prevent memory issues
console.log("Cache cleared due to high memory usage");
}
}, 300000); // Check every 5 minutes
// Cleanup sessions more frequently during session issues
import socket from "./functions/getSocket.js";
import events from "./functions/getEvents.js";
let connectionAttempts = 0;
const MAX_CONNECTION_ATTEMPTS = 5;
let lastConnectionTime = 0;
const MIN_CONNECTION_INTERVAL = 10000; // 10 seconds minimum between attempts
const startSock = async (reason = "initial") => {
try {
const now = Date.now();
// Prevent too frequent reconnection attempts
if (now - lastConnectionTime < MIN_CONNECTION_INTERVAL) {
console.log("⏳ Connection attempt too soon, waiting...");
return null;
}
if (connectionAttempts >= MAX_CONNECTION_ATTEMPTS) {
console.log("❌ Max connection attempts reached. Performing emergency cleanup and resetting...");
connectionAttempts = 0; // Reset after cleanup
// Wait longer before allowing reconnection
setTimeout(() => {
connectionAttempts = 0;
}, 60000); // 1 minute reset
return null;
}
connectionAttempts++;
lastConnectionTime = now;
console.log(`🔄 Starting socket connection (attempt ${connectionAttempts}): ${reason}`);
// Perform comprehensive cleanup to prevent stale references
const sock = await socket();
if (sock) {
events(sock, startSock, cache);
connectionAttempts = 0; // Reset on successful connection
console.log("✅ Socket connection established successfully");
}
return sock;
} catch (error) {
console.error("❌ Error starting socket:", error.message);
return null;
}
};
export default startSock;