dsql-admin/dsql-app/deploy/index.ts
Benjamin Toby a3440692a9 Updates
2025-01-13 22:50:42 +01:00

96 lines
3.4 KiB
TypeScript
Executable File

// @ts-check
import http from "http";
import path from "path";
import childProcess, { ChildProcess } from "child_process";
const { spawn, spawnSync, execSync } = childProcess;
require("dotenv").config({
path: path.resolve(__dirname, "../.env"),
});
const environment = process.env.NODE_ENVIRONMENT;
const workingDirectory = path.resolve(__dirname, "../");
// process.stdin.addListener("data", (message) => {
// console.log("MEssage received =>", message);
// });
process.on("message", (message) => {
console.log("Message received =>", message);
if (message == "exit") {
process.exit();
}
});
const args = environment?.match(/prod/i) ? ["start"] : ["run", "dev"];
let child: ChildProcess = spawn("bun", args, {
cwd: workingDirectory,
stdio: "inherit",
shell: environment?.match(/prod/i) ? undefined : "bash.exe",
});
const PORT = process.env.DSQL_DEPLOY_SERVER_PORT || 1276;
// deepcode ignore NoRateLimitingForExpensiveWebOperation: <Web Server is only accessible locally>, deepcode ignore HttpToHttps: <Server is not exposed to the web>
http.createServer((req, res) => {
if (req.url == "/" + process.env.DEPLOY_ROUTE) {
async function redeploy() {
/** @type {import("child_process").SpawnSyncOptionsWithBufferEncoding} */
const options: import("child_process").SpawnSyncOptionsWithBufferEncoding =
{
cwd: workingDirectory,
stdio: "inherit",
};
if (process.platform?.match(/win/i)) {
options.shell = "bash.exe";
}
if (environment?.match(/prod/i)) {
spawnSync("git", ["checkout", "."], options);
spawnSync("git", ["pull"], options);
spawnSync("bun", ["install"], options);
spawnSync("bun", ["run", "build"], options);
try {
child.kill();
const existingProcessId = execSync(
`lsof -i :2763 | grep LISTEN | awk '{print $2}'`
);
console.log(
"Existing Process Id GREPED",
existingProcessId.toString()
);
execSync(`kill ${existingProcessId.toString()}`);
// spawnSync("kill", [existingProcessId.toString()], options);
// spawnSync("kill", [`${child.pid}`], options);
} catch (/** @type {any} */ error: any) {
console.log("Error killing child process", error.message);
}
child = spawn("bun", args, {
cwd: workingDirectory,
stdio: "inherit",
shell: environment?.match(/prod/i) ? undefined : "bash.exe",
});
} else {
spawnSync("git", ["status"], options);
spawnSync("bun", ["list", "next"], options);
console.log("Not in production, Continuing ...");
}
}
redeploy();
res.statusCode = 200;
res.end("Deployed");
} else {
res.statusCode = 402;
res.end("Unauthorized");
}
}).listen(PORT, () => console.log("Deployment Server Started on Port", PORT));