refactor: add close ws

This commit is contained in:
Mauricio Siu
2024-10-05 16:45:53 -06:00
parent 84009c5e9b
commit 24db4006cf

View File

@@ -48,39 +48,46 @@ export const setupDeploymentLogsWebSocketServer = (
if (!server.sshKeyId) return; if (!server.sshKeyId) return;
const client = new Client(); const client = new Client();
new Promise<void>((resolve, reject) => { client
client .on("ready", () => {
.on("ready", () => { const command = `
const command = `
tail -n +1 -f ${logPath}; tail -n +1 -f ${logPath};
`; `;
client.exec(command, (err, stream) => { client.exec(command, (err, stream) => {
if (err) { if (err) {
console.error("Execution error:", err); console.error("Execution error:", err);
reject(err); ws.close();
return; return;
} }
stream stream
.on("close", () => { .on("close", () => {
console.log("Connection closed ✅"); console.log("Connection closed ✅");
client.end(); client.end();
resolve(); ws.close();
}) })
.on("data", (data: string) => { .on("data", (data: string) => {
ws.send(data.toString()); ws.send(data.toString());
}) })
.stderr.on("data", (data) => { .stderr.on("data", (data) => {
ws.send(data.toString()); ws.send(data.toString());
}); });
});
})
.connect({
host: server.ipAddress,
port: server.port,
username: server.username,
privateKey: server.sshKey?.privateKey,
timeout: 99999,
}); });
})
.on("error", (err) => {
console.error("SSH connection error:", err);
ws.send(`SSH error: ${err.message}`);
ws.close(); // Cierra el WebSocket si hay un error con SSH
})
.connect({
host: server.ipAddress,
port: server.port,
username: server.username,
privateKey: server.sshKey?.privateKey,
});
ws.on("close", () => {
console.log("Connection closed ✅, From WS");
client.end();
}); });
} else { } else {
const tail = spawn("tail", ["-n", "+1", "-f", logPath]); const tail = spawn("tail", ["-n", "+1", "-f", logPath]);
@@ -92,6 +99,9 @@ export const setupDeploymentLogsWebSocketServer = (
tail.stderr.on("data", (data) => { tail.stderr.on("data", (data) => {
ws.send(new Error(`tail error: ${data.toString()}`).message); ws.send(new Error(`tail error: ${data.toString()}`).message);
}); });
tail.on("close", () => {
ws.close();
});
} }
} catch (error) { } catch (error) {
// @ts-ignore // @ts-ignore