recator placement of code
This commit is contained in:
10
backend/prodSql/prodSql.routes.ts
Normal file
10
backend/prodSql/prodSql.routes.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import type { Express } from "express";
|
||||
import restart from "./prodSqlRestart.route.js";
|
||||
import start from "./prodSqlStart.route.js";
|
||||
import stop from "./prodSqlStop.route.js";
|
||||
export const setupProdSqlRoutes = (baseUrl: string, app: Express) => {
|
||||
//setup all the routes
|
||||
app.use(`${baseUrl}/api/system/prodSql`, start);
|
||||
app.use(`${baseUrl}/api/system/prodSql`, stop);
|
||||
app.use(`${baseUrl}/api/system/prodSql`, restart);
|
||||
};
|
||||
157
backend/prodSql/prodSqlConnection.controller.ts
Normal file
157
backend/prodSql/prodSqlConnection.controller.ts
Normal file
@@ -0,0 +1,157 @@
|
||||
import sql from "mssql";
|
||||
import { prodSqlConfig } from "../configs/prodSql.config.js";
|
||||
import { createLogger } from "../logger/logger.controller.js";
|
||||
import { checkHostnamePort } from "../utils/checkHost.utils.js";
|
||||
import { returnFunc } from "../utils/returnHelper.utils.js";
|
||||
|
||||
export let pool: sql.ConnectionPool;
|
||||
export let connected: boolean = false;
|
||||
export let reconnecting = false;
|
||||
|
||||
export const connectProdSql = async () => {
|
||||
const serverUp = await checkHostnamePort(`${process.env.PROD_SERVER}:1433`);
|
||||
if (!serverUp) {
|
||||
// we will try to reconnect
|
||||
connected = false;
|
||||
return returnFunc({
|
||||
success: false,
|
||||
level: "error",
|
||||
module: "system",
|
||||
subModule: "db",
|
||||
message: "Prod server is offline or unreachable.",
|
||||
});
|
||||
}
|
||||
|
||||
// if we are trying to click restart from the api for some reason we want to kick back and say no
|
||||
if (connected) {
|
||||
return returnFunc({
|
||||
success: false,
|
||||
level: "error",
|
||||
module: "system",
|
||||
subModule: "db",
|
||||
message: "The Sql server is already connected.",
|
||||
});
|
||||
}
|
||||
|
||||
// try to connect to the sql server
|
||||
try {
|
||||
pool = new sql.ConnectionPool(prodSqlConfig);
|
||||
await pool.connect();
|
||||
connected = true;
|
||||
return returnFunc({
|
||||
success: true,
|
||||
level: "info",
|
||||
module: "system",
|
||||
subModule: "db",
|
||||
message: `${prodSqlConfig.server} is connected to ${prodSqlConfig.database}`,
|
||||
data: [],
|
||||
notify: false,
|
||||
});
|
||||
} catch (error) {
|
||||
return returnFunc({
|
||||
success: false,
|
||||
level: "error",
|
||||
module: "system",
|
||||
subModule: "db",
|
||||
message: "Failed to connect to the prod sql server.",
|
||||
data: [error],
|
||||
notify: false,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export const closePool = async () => {
|
||||
if (!connected) {
|
||||
return returnFunc({
|
||||
success: false,
|
||||
level: "error",
|
||||
module: "system",
|
||||
subModule: "db",
|
||||
message: "There is no connection to the prod server currently.",
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
await pool.close();
|
||||
connected = false;
|
||||
return returnFunc({
|
||||
success: true,
|
||||
level: "info",
|
||||
module: "system",
|
||||
subModule: "db",
|
||||
message: "The sql connection has been closed.",
|
||||
});
|
||||
} catch (error) {
|
||||
connected = false;
|
||||
|
||||
return returnFunc({
|
||||
success: false,
|
||||
level: "error",
|
||||
module: "system",
|
||||
subModule: "db",
|
||||
message: "There was an error closing the sql connection",
|
||||
data: [error],
|
||||
});
|
||||
}
|
||||
};
|
||||
export const reconnectToSql = async () => {
|
||||
const log = createLogger({
|
||||
module: "system",
|
||||
subModule: "db",
|
||||
});
|
||||
if (reconnecting) return;
|
||||
|
||||
//set reconnecting to true while we try to reconnect
|
||||
reconnecting = true;
|
||||
|
||||
// start the delay out as 2 seconds
|
||||
let delayStart = 2000;
|
||||
let attempt = 0;
|
||||
const maxAttempts = 10;
|
||||
|
||||
while (!connected && attempt < maxAttempts) {
|
||||
attempt++;
|
||||
log.info(
|
||||
`Reconnect attempt ${attempt}/${maxAttempts} in ${delayStart / 1000}s ...`,
|
||||
);
|
||||
|
||||
await new Promise((res) => setTimeout(res, delayStart));
|
||||
|
||||
const serverUp = await checkHostnamePort(`${process.env.PROD_SERVER}:1433`);
|
||||
|
||||
if (!serverUp) {
|
||||
delayStart = Math.min(delayStart * 2, 30000); // exponential backoff until up to 30000
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
pool = await sql.connect(prodSqlConfig);
|
||||
reconnecting = false;
|
||||
connected = true;
|
||||
log.info(
|
||||
`${prodSqlConfig.server} is connected to ${prodSqlConfig.database}`,
|
||||
);
|
||||
} catch (error) {
|
||||
delayStart = Math.min(delayStart * 2, 30000);
|
||||
return returnFunc({
|
||||
success: false,
|
||||
level: "error",
|
||||
module: "system",
|
||||
subModule: "db",
|
||||
message: "Failed to reconnect to the prod sql server.",
|
||||
data: [error],
|
||||
notify: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (!connected) {
|
||||
log.error(
|
||||
{ notify: true },
|
||||
"Max reconnect attempts reached on the prodSql server. Stopping retries.",
|
||||
);
|
||||
|
||||
reconnecting = false;
|
||||
// TODO: exit alert someone here
|
||||
}
|
||||
};
|
||||
97
backend/prodSql/prodSqlQuery.controller.ts
Normal file
97
backend/prodSql/prodSqlQuery.controller.ts
Normal file
@@ -0,0 +1,97 @@
|
||||
import { returnFunc } from "../utils/returnHelper.utils.js";
|
||||
import {
|
||||
connected,
|
||||
pool,
|
||||
reconnecting,
|
||||
reconnectToSql,
|
||||
} from "./prodSqlConnection.controller.js";
|
||||
|
||||
interface SqlError extends Error {
|
||||
code?: string;
|
||||
originalError?: {
|
||||
info?: { message?: string };
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Run a prod query
|
||||
* just pass over the query as a string and the name of the query.
|
||||
* Query should be like below.
|
||||
* * select * from AlplaPROD_test1.dbo.table
|
||||
* You must use test1 always as it will be changed via query
|
||||
*/
|
||||
export const prodQuery = async (queryToRun: string, name: string) => {
|
||||
if (!connected) {
|
||||
reconnectToSql();
|
||||
|
||||
if (reconnecting) {
|
||||
return returnFunc({
|
||||
success: false,
|
||||
level: "error",
|
||||
module: "system",
|
||||
subModule: "prodSql",
|
||||
message: `The sql ${process.env.PROD_PLANT_TOKEN} is trying to reconnect already`,
|
||||
data: [],
|
||||
notify: false,
|
||||
});
|
||||
} else {
|
||||
return returnFunc({
|
||||
success: false,
|
||||
level: "error",
|
||||
module: "system",
|
||||
subModule: "prodSql",
|
||||
message: `${process.env.PROD_PLANT_TOKEN} is not connected, and failed to connect.`,
|
||||
data: [],
|
||||
notify: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
//change to the correct server
|
||||
const query = queryToRun.replaceAll(
|
||||
"test1",
|
||||
`${process.env.PROD_PLANT_TOKEN}`,
|
||||
);
|
||||
|
||||
try {
|
||||
const result = await pool.request().query(query);
|
||||
return {
|
||||
success: true,
|
||||
message: `Query results for: ${name}`,
|
||||
data: result.recordset,
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
const err = error as SqlError;
|
||||
if (err.code === "ETIMEOUT") {
|
||||
return returnFunc({
|
||||
success: false,
|
||||
module: "system",
|
||||
subModule: "prodSql",
|
||||
level: "error",
|
||||
message: `${name} did not run due to a timeout.`,
|
||||
notify: false,
|
||||
data: [],
|
||||
});
|
||||
}
|
||||
|
||||
if (err.code === "EREQUEST") {
|
||||
return returnFunc({
|
||||
success: false,
|
||||
module: "system",
|
||||
subModule: "prodSql",
|
||||
level: "error",
|
||||
message: `${name} encountered an error ${err.originalError?.info?.message || "undefined error"}`,
|
||||
data: [],
|
||||
});
|
||||
}
|
||||
|
||||
return returnFunc({
|
||||
success: false,
|
||||
module: "system",
|
||||
subModule: "prodSql",
|
||||
level: "error",
|
||||
message: `${name} encountered an unknown error.`,
|
||||
data: [],
|
||||
});
|
||||
}
|
||||
};
|
||||
29
backend/prodSql/prodSqlQuerySelector.utils.ts
Normal file
29
backend/prodSql/prodSqlQuerySelector.utils.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
export type SqlQuery = {
|
||||
query: string;
|
||||
success: boolean;
|
||||
message: string;
|
||||
};
|
||||
|
||||
export const sqlQuerySelector = (name: string) => {
|
||||
try {
|
||||
const queryFile = readFileSync(
|
||||
new URL(`../prodSql/queries/${name}.sql`, import.meta.url),
|
||||
"utf8",
|
||||
);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: `Query for: ${name}`,
|
||||
query: queryFile,
|
||||
};
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
return {
|
||||
success: false,
|
||||
message:
|
||||
"Error getting the query file, please make sure you have the correct name.",
|
||||
};
|
||||
}
|
||||
};
|
||||
23
backend/prodSql/prodSqlRestart.route.ts
Normal file
23
backend/prodSql/prodSqlRestart.route.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { Router } from "express";
|
||||
import { apiReturn } from "../utils/returnHelper.utils.js";
|
||||
import { closePool, connectProdSql } from "./prodSqlConnection.controller.js";
|
||||
|
||||
const r = Router();
|
||||
|
||||
r.post("/restart", async (_, res) => {
|
||||
await closePool();
|
||||
|
||||
await new Promise((r) => setTimeout(r, 2000));
|
||||
|
||||
const connect = await connectProdSql();
|
||||
apiReturn(res, {
|
||||
success: connect.success,
|
||||
level: connect.success ? "info" : "error",
|
||||
module: "routes",
|
||||
subModule: "prodSql",
|
||||
message: "Sql Server has been restarted",
|
||||
data: connect.data,
|
||||
status: connect.success ? 200 : 400,
|
||||
});
|
||||
});
|
||||
export default r;
|
||||
20
backend/prodSql/prodSqlStart.route.ts
Normal file
20
backend/prodSql/prodSqlStart.route.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import { Router } from "express";
|
||||
import { apiReturn } from "../utils/returnHelper.utils.js";
|
||||
import { connectProdSql } from "./prodSqlConnection.controller.js";
|
||||
|
||||
const r = Router();
|
||||
|
||||
r.post("/start", async (_, res) => {
|
||||
const connect = await connectProdSql();
|
||||
apiReturn(res, {
|
||||
success: connect.success,
|
||||
level: connect.success ? "info" : "error",
|
||||
module: "routes",
|
||||
subModule: "prodSql",
|
||||
message: connect.message,
|
||||
data: connect.data,
|
||||
status: connect.success ? 200 : 400,
|
||||
});
|
||||
});
|
||||
|
||||
export default r;
|
||||
20
backend/prodSql/prodSqlStop.route.ts
Normal file
20
backend/prodSql/prodSqlStop.route.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import { Router } from "express";
|
||||
import { apiReturn } from "../utils/returnHelper.utils.js";
|
||||
import { closePool } from "./prodSqlConnection.controller.js";
|
||||
|
||||
const r = Router();
|
||||
|
||||
r.post("/stop", async (_, res) => {
|
||||
const connect = await closePool();
|
||||
apiReturn(res, {
|
||||
success: connect.success,
|
||||
level: connect.success ? "info" : "error",
|
||||
module: "routes",
|
||||
subModule: "prodSql",
|
||||
message: connect.message,
|
||||
data: connect.data,
|
||||
status: connect.success ? 200 : 400,
|
||||
});
|
||||
});
|
||||
|
||||
export default r;
|
||||
16
backend/prodSql/queries/prodSqlStats.sql
Normal file
16
backend/prodSql/queries/prodSqlStats.sql
Normal file
@@ -0,0 +1,16 @@
|
||||
|
||||
DECLARE @UptimeSeconds INT;
|
||||
DECLARE @StartTime DATETIME;
|
||||
|
||||
SELECT @StartTime = sqlserver_start_time FROM sys.dm_os_sys_info;
|
||||
SET @UptimeSeconds = DATEDIFF(SECOND, @StartTime, GETDATE());
|
||||
|
||||
SELECT
|
||||
@StartTime AS [Server Start Time],
|
||||
GETDATE() AS [Current Time],
|
||||
@UptimeSeconds AS [UptimeSeconds],
|
||||
@UptimeSeconds / 86400 AS [Days],
|
||||
(@UptimeSeconds % 86400) / 3600 AS [Hours],
|
||||
(@UptimeSeconds % 3600) / 60 AS [Minutes],
|
||||
(@UptimeSeconds % 60) AS [Seconds];
|
||||
|
||||
Reference in New Issue
Block a user