diff options
Diffstat (limited to 'src-slowcord/status')
-rw-r--r-- | src-slowcord/status/src/gateway.ts | 51 | ||||
-rw-r--r-- | src-slowcord/status/src/index.ts | 140 | ||||
-rw-r--r-- | src-slowcord/status/tsconfig.json | 38 |
3 files changed, 138 insertions, 91 deletions
diff --git a/src-slowcord/status/src/gateway.ts b/src-slowcord/status/src/gateway.ts index 14944d09..bc00c2d4 100644 --- a/src-slowcord/status/src/gateway.ts +++ b/src-slowcord/status/src/gateway.ts @@ -5,14 +5,22 @@ import mysql from "mysql2"; import fetch from "node-fetch"; const dbConn = mysql.createConnection(process.env.DATABASE as string); -const executePromise = (sql: string, args: any[]) => new Promise((resolve, reject) => dbConn.execute(sql, args, (err, res) => { if (err) reject(err); else resolve(res); })); +const executePromise = (sql: string, args: any[]) => + new Promise((resolve, reject) => + dbConn.execute(sql, args, (err, res) => { + if (err) reject(err); + else resolve(res); + }), + ); const savePerf = async (time: number, name: string, error?: string | Error) => { if (error && typeof error != "string") error = error.message; try { - await executePromise("INSERT INTO performance (value, endpoint, timestamp, error) VALUES (?, ?, ?, ?)", [time ?? 0, name, new Date(), error ?? null]); + await executePromise( + "INSERT INTO performance (value, endpoint, timestamp, error) VALUES (?, ?, ?, ?)", + [time ?? 0, name, new Date(), error ?? null], + ); // await executePromise("DELETE FROM performance WHERE DATE(timestamp) < now() - interval ? DAY", [process.env.RETENTION_DAYS]); - } - catch (e) { + } catch (e) { console.error(e); } }; @@ -23,7 +31,11 @@ const doMeasurements = async (channel: Discord.TextChannel) => { timestamp = Date.now(); await channel.send("hello this is a special message kthxbye"); - setTimeout(doMeasurements, parseInt(process.env.MEASURE_INTERVAL as string), channel); + setTimeout( + doMeasurements, + parseInt(process.env.MEASURE_INTERVAL as string), + channel, + ); }; const instance = { @@ -37,8 +49,8 @@ const client = new Fosscord.Client({ intents: [], http: { api: instance.api, - cdn: instance.cdn - } + cdn: instance.cdn, + }, }); client.on("ready", async () => { @@ -52,19 +64,24 @@ client.on("ready", async () => { client.on("messageCreate", async (msg: Discord.Message) => { if (!timestamp) return; - if (msg.author.id != "992745947417141682" - || msg.channel.id != "1019955729054267764" - || msg.content != "hello this is a special message kthxbye") + if ( + msg.author.id != "992745947417141682" || + msg.channel.id != "1019955729054267764" || + msg.content != "hello this is a special message kthxbye" + ) return; await savePerf(Date.now() - timestamp, "messageCreate", undefined); timestamp = undefined; - await fetch(`${instance.api}/channels/1019955729054267764/messages/${msg.id}`, { - method: "DELETE", - headers: { - authorization: instance.token - } - }) + await fetch( + `${instance.api}/channels/1019955729054267764/messages/${msg.id}`, + { + method: "DELETE", + headers: { + authorization: instance.token, + }, + }, + ); }); client.on("error", (error: any) => { @@ -79,4 +96,4 @@ client.on("warn", (msg: any) => { await new Promise((resolve) => dbConn.connect(resolve)); console.log("Connected to db"); await client.login(instance.token); -})(); \ No newline at end of file +})(); diff --git a/src-slowcord/status/src/index.ts b/src-slowcord/status/src/index.ts index 735b8a9b..979469b6 100644 --- a/src-slowcord/status/src/index.ts +++ b/src-slowcord/status/src/index.ts @@ -4,7 +4,13 @@ import mysql from "mysql2"; import fetch from "node-fetch"; const dbConn = mysql.createConnection(process.env.DATABASE as string); -const executePromise = (sql: string, args: any[]) => new Promise((resolve, reject) => dbConn.execute(sql, args, (err, res) => { if (err) reject(err); else resolve(res); })); +const executePromise = (sql: string, args: any[]) => + new Promise((resolve, reject) => + dbConn.execute(sql, args, (err, res) => { + if (err) reject(err); + else resolve(res); + }), + ); const instance = { app: process.env.INSTANCE_WEB_APP as string, @@ -16,73 +22,86 @@ const instance = { const savePerf = async (time: number, name: string, error?: string | Error) => { if (error && typeof error != "string") error = error.message; try { - await executePromise("INSERT INTO performance (value, endpoint, timestamp, error) VALUES (?, ?, ?, ?)", [time ?? 0, name, new Date(), error ?? null]); + await executePromise( + "INSERT INTO performance (value, endpoint, timestamp, error) VALUES (?, ?, ?, ?)", + [time ?? 0, name, new Date(), error ?? null], + ); // await executePromise("DELETE FROM performance WHERE DATE(timestamp) < now() - interval ? DAY", [process.env.RETENTION_DAYS]); - } - catch (e) { + } catch (e) { console.error(e); } }; -const saveSystemUsage = async (load: number, procUptime: number, sysUptime: number, ram: number, sessions: number) => { +const saveSystemUsage = async ( + load: number, + procUptime: number, + sysUptime: number, + ram: number, + sessions: number, +) => { try { - await executePromise("INSERT INTO monitor (time, cpu, procUp, sysUp, ram, sessions) VALUES (?, ?, ?, ?, ?, ?)", [new Date(), load, procUptime, sysUptime, ram, sessions]); - } - catch (e) { + await executePromise( + "INSERT INTO monitor (time, cpu, procUp, sysUp, ram, sessions) VALUES (?, ?, ?, ?, ?, ?)", + [new Date(), load, procUptime, sysUptime, ram, sessions], + ); + } catch (e) { console.error(e); } }; -const makeTimedRequest = (path: string, body?: object): Promise<number> => new Promise((resolve, reject) => { - const opts = { - hostname: new URL(path).hostname, - port: 443, - path: new URL(path).pathname, - method: "GET", - headers: { - "Content-Type": "application/json", - "Authorization": instance.token, - }, - timeout: 1000, - }; - - let start: number, end: number; - const req = https.request(opts, res => { - if (res.statusCode! < 200 || res.statusCode! > 300) { - return reject(`${res.statusCode} ${res.statusMessage}`); - } - - res.on("data", (data) => { +const makeTimedRequest = (path: string, body?: object): Promise<number> => + new Promise((resolve, reject) => { + const opts = { + hostname: new URL(path).hostname, + port: 443, + path: new URL(path).pathname, + method: "GET", + headers: { + "Content-Type": "application/json", + Authorization: instance.token, + }, + timeout: 1000, + }; + + let start: number, end: number; + const req = https.request(opts, (res) => { + if (res.statusCode! < 200 || res.statusCode! > 300) { + return reject(`${res.statusCode} ${res.statusMessage}`); + } + + res.on("data", (data) => {}); + + res.on("end", () => { + end = Date.now(); + resolve(end - start); + }); }); - res.on("end", () => { - end = Date.now(); - resolve(end - start); + req.on("finish", () => { + if (body) req.write(JSON.stringify(body)); + start = Date.now(); }); - }); - req.on("finish", () => { - if (body) req.write(JSON.stringify(body)); - start = Date.now(); - }); + req.on("error", (error) => { + reject(error); + }); - req.on("error", (error) => { - reject(error); + req.end(); }); - req.end(); -}); - const measureApi = async (name: string, path: string, body?: object) => { - let error, time = -1; + let error, + time = -1; try { time = await makeTimedRequest(path, body); - } - catch (e) { + } catch (e) { error = e as Error | string; } - console.log(`${name} took ${time}ms ${(error ? "with error" : "")}`, error ?? ""); + console.log( + `${name} took ${time}ms ${error ? "with error" : ""}`, + error ?? "", + ); await savePerf(time, name, error); }; @@ -100,7 +119,11 @@ const app = async () => { console.log("Connected to db"); // await client.login(instance.token); - console.log(`Monitoring performance for instance at ${new URL(instance.api).hostname}`); + console.log( + `Monitoring performance for instance at ${ + new URL(instance.api).hostname + }`, + ); const doMeasurements = async () => { await measureApi("ping", `${instance.api}/ping`); @@ -112,18 +135,25 @@ const app = async () => { const res = await fetch(`${instance.api}/-/monitorz`, { headers: { Authorization: process.env.INSTANCE_TOKEN as string, - } + }, }); - const json = await res.json() as monitorzSchema; - await saveSystemUsage(json.load[1], json.procUptime, json.sysUptime, json.memPercent, json.sessions); - } - catch (e) { - } - - setTimeout(doMeasurements, parseInt(process.env.MEASURE_INTERVAL as string)); + const json = (await res.json()) as monitorzSchema; + await saveSystemUsage( + json.load[1], + json.procUptime, + json.sysUptime, + json.memPercent, + json.sessions, + ); + } catch (e) {} + + setTimeout( + doMeasurements, + parseInt(process.env.MEASURE_INTERVAL as string), + ); }; doMeasurements(); }; -app(); \ No newline at end of file +app(); diff --git a/src-slowcord/status/tsconfig.json b/src-slowcord/status/tsconfig.json index 6d6ec56d..4d96714c 100644 --- a/src-slowcord/status/tsconfig.json +++ b/src-slowcord/status/tsconfig.json @@ -1,10 +1,6 @@ { - "exclude": [ - "node_modules" - ], - "include": [ - "src/**/*.ts" - ], + "exclude": ["node_modules"], + "include": ["src/**/*.ts"], "compilerOptions": { /* Visit https://aka.ms/tsconfig.json to read more about this file */ /* Projects */ @@ -15,10 +11,12 @@ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ /* Language and Environment */ - "target": "ES6", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ - "lib": ["ES2021"], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + "target": "ES6" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */, + "lib": [ + "ES2021" + ] /* Specify a set of bundled library declaration files that describe the target runtime environment. */, // "jsx": "preserve", /* Specify what JSX code is generated. */ - "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */ + "experimentalDecorators": true /* Enable experimental support for TC39 stage 2 draft decorators. */, // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */ // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ @@ -27,14 +25,16 @@ // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ /* Modules */ - "module": "ES2020", /* Specify what module code is generated. */ + "module": "ES2020" /* Specify what module code is generated. */, // "rootDir": "./", /* Specify the root folder within your source files. */ - "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ + "moduleResolution": "node" /* Specify how TypeScript looks up a file from a given module specifier. */, // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ // "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */ - "types": ["node"], /* Specify type package names to be included without being referenced in a source file. */ + "types": [ + "node" + ] /* Specify type package names to be included without being referenced in a source file. */, // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ // "resolveJsonModule": true, /* Enable importing .json files */ // "noResolve": true, /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */ @@ -46,9 +46,9 @@ // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ // "declarationMap": true, /* Create sourcemaps for d.ts files. */ // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ - "sourceMap": true, /* Create source map files for emitted JavaScript files. */ + "sourceMap": true /* Create source map files for emitted JavaScript files. */, // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */ - "outDir": "./build", /* Specify an output folder for all emitted files. */ + "outDir": "./build" /* Specify an output folder for all emitted files. */, // "removeComments": true, /* Disable emitting comments. */ // "noEmit": true, /* Disable emitting files from a compilation. */ // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ @@ -69,16 +69,16 @@ /* Interop Constraints */ // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ - "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */ + "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */, // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ - "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */, /* Type Checking */ - "strict": true, /* Enable all strict type-checking options. */ + "strict": true /* Enable all strict type-checking options. */, // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */ // "strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */ // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ // "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */ - "strictPropertyInitialization": false, /* Check for class properties that are declared but not set in the constructor. */ + "strictPropertyInitialization": false /* Check for class properties that are declared but not set in the constructor. */, // "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */ // "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */ // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ @@ -96,4 +96,4 @@ // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ "skipLibCheck": true /* Skip type checking all .d.ts files. */ } -} \ No newline at end of file +} |