Selaa lähdekoodia

TS: enabled strict type checking on all sub-projects

Christian Kahlau 3 vuotta sitten
vanhempi
commit
35dae47dc4

+ 1 - 1
daemon/package.json

@@ -18,6 +18,6 @@
     "dotenv": "^16.0.2",
     "express": "^4.18.1",
     "moment": "^2.29.4",
-    "node-utils": "git+https://gogs.hostbbq.com/hostbbq/node-utils.git#1.0.5"
+    "node-utils": "git+https://gogs.hostbbq.com/hostbbq/node-utils.git#1.0.6"
   }
 }

+ 21 - 11
daemon/src/collector.class.ts

@@ -4,10 +4,10 @@ import moment from 'moment';
 import { exec } from 'node-utils/shell';
 import path from 'path';
 
+import { HttpStatusException } from '../../common/lib/http-status.exception';
 import { Logger } from '../../common/util/logger.class';
-import { HttpStatusException } from './lib/http-status.exception';
 
-const DATA_DIR = process.env.DATA_DIR;
+const DATA_DIR = process.env.DATA_DIR || 'data';
 const DATA_BUFFER_FILE = path.resolve(DATA_DIR, 'buffer.csv');
 const DATA_BUFFER_REMAINS = path.resolve(DATA_DIR, 'remains.csv');
 const DATA_REDUCED_FILE = path.resolve(DATA_DIR, 'reduced.csv');
@@ -40,7 +40,7 @@ const CSV_COLS = {
 };
 
 export class Collector {
-  private intervalHdl: NodeJS.Timer;
+  private intervalHdl?: NodeJS.Timer;
 
   constructor() {
     (async () => {
@@ -158,6 +158,9 @@ export class Collector {
       let valueBuffer: Array<BufferedData> = [];
       do {
         const line = lines.shift();
+
+        if (!line) break;
+
         const data = this.parseBufferedData(line);
         Logger.debug('[DEBUG] BufferedData:', JSON.stringify(data));
         valueBuffer.push(data);
@@ -186,6 +189,7 @@ export class Collector {
               if (cur.hdd && Object.keys(cur.hdd).length) {
                 const hdd_sums = res.hdd ?? {};
                 res.hdd = Object.keys(cur.hdd).reduce((res_hdd, mount) => {
+                  if (!cur.hdd) return res_hdd;
                   if (!res_hdd[mount]) {
                     res_hdd[mount] = { sum: 0, peak: 0, max: 0 };
                   }
@@ -265,7 +269,7 @@ export class Collector {
     const lastCol = CSV_COLS.buffer.ram;
 
     // HDD (?)
-    let hdd: BufferedDriveData;
+    let hdd: BufferedDriveData | undefined;
     if (MONITOR_MOUNTS.length && line.length > lastCol + 1) {
       for (let i = 1; i <= MONITOR_MOUNTS.length; i++) {
         if (lastCol + i > line.length - 1) break;
@@ -297,7 +301,7 @@ export class Collector {
     const lastCol = CSV_COLS.reduced.ram.max;
 
     // HDD (?)
-    let hdd: ReducedDriveData;
+    let hdd: ReducedDriveData | undefined;
     if (MONITOR_MOUNTS.length && line.length > lastCol + 1) {
       hdd = {};
       for (let i = 1; lastCol + i + 3 < line.length; i += 4) {
@@ -345,7 +349,7 @@ export class Collector {
       moment(data.time).format(TIMESTAMP_FORMAT),
       data.cpu,
       `${(data.ram.used / this.byteFactors['M']).toFixed(2)}/${(data.ram.max / this.byteFactors['M']).toFixed(2)} MiB`,
-      ...(data.hdd ? Object.keys(data.hdd).map(mount => `${mount} ${data.hdd[mount].used}/${data.hdd[mount].max}`) : [])
+      ...(data.hdd ? Object.keys(data.hdd).map(mount => `${mount} ${data.hdd?.[mount].used}/${data.hdd?.[mount].max}`) : [])
     ].join(';');
   }
 
@@ -359,9 +363,14 @@ export class Collector {
       data.ram.max.toFixed(2),
       ...(data.hdd
         ? Object.keys(data.hdd).reduce((res, mount) => {
-            res.push(mount, data.hdd[mount].avg.toFixed(2), data.hdd[mount].peak.toFixed(2), data.hdd[mount].max.toFixed(2));
+            res.push(
+              mount,
+              data.hdd?.[mount].avg.toFixed(2) || '0',
+              data.hdd?.[mount].peak.toFixed(2) || '0',
+              data.hdd?.[mount].max.toFixed(2) || '0'
+            );
             return res;
-          }, [])
+          }, [] as string[])
         : [])
     ].join(';');
   }
@@ -372,7 +381,7 @@ export class Collector {
 
   private _trx: {
     file?: PathLike;
-    start: () => Promise<number>;
+    start: () => Promise<number | null>;
     read: () => Promise<Array<ReducedData>>;
     rollback: (hdl: number) => Promise<void>;
     commit: (hdl: number) => Promise<void>;
@@ -380,7 +389,8 @@ export class Collector {
     start: async () => {
       if (this.trx.file) {
         Logger.warn(`[WARN] Old transaction file found - rolling back now before starting new transaction ...`);
-        const hdl = Number(/trx_(\d+)\.csv/.exec(this.trx.file as string)[1]);
+        const m = /trx_(\d+)\.csv/.exec(this.trx.file as string);
+        const hdl = Number(m?.[1] ?? '0');
         await this.trx.rollback(hdl);
         Logger.warn(`[WARN] Transaction rollback succeeded.`);
       }
@@ -407,7 +417,7 @@ export class Collector {
         if (filename !== this.trx.file) throw new HttpStatusException(`Transaction #${hdl} not found`, 404);
 
         if (fs.existsSync(this.trx.file)) {
-          let tmpFile: string;
+          let tmpFile: string | undefined;
           if (fs.existsSync(DATA_REDUCED_FILE)) {
             tmpFile = `reduced.tmp_${moment().unix().toFixed(0)}.csv`;
             await fsp.rename(DATA_REDUCED_FILE, tmpFile);

+ 2 - 2
daemon/src/webserver.class.ts

@@ -1,4 +1,4 @@
-import express, { Express } from 'express';
+import express, { Express, NextFunction, Request, Response } from 'express';
 
 import { HttpStatusException } from '../../common/lib/http-status.exception';
 import { Logger } from '../../common/util/logger.class';
@@ -50,7 +50,7 @@ export class Webserver {
       }
     });
 
-    this.app.use((err, req, res, next) => {
+    this.app.use((err: any, req: Request, res: Response, next: NextFunction) => {
       if (err instanceof HttpStatusException) {
         res.status(err.statusCode).send(err.message);
       } else {

+ 3 - 5
daemon/tsconfig.json

@@ -1,15 +1,13 @@
 {
   "compilerOptions": {
+    "strict": true,
     "outDir": "./dist",
     "esModuleInterop": true,
     "moduleResolution": "node",
     "module": "commonjs",
     "target": "ES2016",
     "sourceMap": true,
-    "baseUrl": "./src",
-    "paths": {
-      "*": ["node_modules/*", "src/*", "../common/*"]
-    }
+    "baseUrl": "./src"
   },
-  "include": ["./src/*", "./src/**/*, ../common/*", "../common/**/*"]
+  "include": ["./src/*", "./src/**/*", "../common/*", "../common/**/*"]
 }

+ 12 - 5
server/src/database.class.ts

@@ -7,7 +7,7 @@ import { Database as SQLiteDB, OPEN_CREATE, OPEN_READWRITE, RunResult } from 'sq
 import { Logger } from '../../common/util/logger.class';
 
 export class Database {
-  private db: SQLiteDB;
+  private db?: SQLiteDB;
 
   public async open() {
     try {
@@ -122,8 +122,13 @@ export class Database {
         let entryID = result.lastID;
 
         for (const type of Object.keys(entry).filter(t => !['time', 'hdd'].includes(t))) {
-          for (const key of Object.keys(entry[type])) {
-            await this.run('INSERT INTO ServerDataValue(EntryID, Type, Key, Value) VALUES(?, ?, ?, ?);', [entryID, type, key, entry[type][key]]);
+          for (const key of Object.keys((entry as any)[type])) {
+            await this.run('INSERT INTO ServerDataValue(EntryID, Type, Key, Value) VALUES(?, ?, ?, ?);', [
+              entryID,
+              type,
+              key,
+              (entry as any)[type][key]
+            ]);
           }
         }
 
@@ -134,7 +139,7 @@ export class Database {
                 entryID,
                 `hdd:${mount}`,
                 key,
-                entry.hdd[mount][key]
+                (entry.hdd[mount] as any)[key]
               ]);
             }
           }
@@ -170,7 +175,7 @@ export class Database {
           hdd = { type: 'hdd', subtypes: [] };
           res.push(hdd);
         }
-        hdd.subtypes.push({ type: type.substring(4) });
+        hdd.subtypes?.push({ type: type.substring(4) });
       }
       return res;
     }, []) as Array<ServerDataTypesConfig>;
@@ -213,6 +218,7 @@ export class Database {
 
   public async run(sql: string, params: any): Promise<RunResult> {
     return new Promise<RunResult>((res, rej) => {
+      if (!this.db) return rej(new Error('Database not opened.'));
       this.db.run(sql, params, function (err) {
         if (err) return rej(err);
         res(this);
@@ -222,6 +228,7 @@ export class Database {
 
   public async stmt(sql: string, params: any[]) {
     return new Promise<{ result: RunResult; rows: any[] }>((res, rej) => {
+      if (!this.db) return rej(new Error('Database not opened.'));
       const stmt = this.db.prepare(sql);
       stmt.all(params, function (err, rows) {
         if (err) return rej(err);

+ 2 - 2
server/src/server-connector.class.ts

@@ -35,7 +35,7 @@ export class ServerConnector {
   private async timerTick(server: Server) {
     Logger.debug('[DEBUG] TICK', new Date(), JSON.stringify(server));
 
-    let trxHdl: number;
+    let trxHdl: number | undefined = undefined;
     try {
       // Start Transaction, receiving Data and a Transaction Handle
       let response = await axios.get(`http://${server.fqdn}:8890/`, { responseType: 'json' });
@@ -43,7 +43,7 @@ export class ServerConnector {
 
       if (!trxHdl) return; // No data
 
-      const data: ReducedData[] = response.data.data.map(entry => ({ ...entry, time: new Date(entry.time) }));
+      const data: ReducedData[] = response.data.data.map((entry: any) => ({ ...entry, time: new Date(entry.time) }));
 
       // Process data in DB
       await this.db.insertServerData(server.id, data);

+ 2 - 2
server/src/webserver.class.ts

@@ -1,4 +1,4 @@
-import express, { Express } from 'express';
+import express, { Express, NextFunction, Request, Response } from 'express';
 
 import { HttpStatusException } from '../../common/lib/http-status.exception';
 import { Logger } from '../../common/util/logger.class';
@@ -68,7 +68,7 @@ export class Webserver {
 
     this.app.use('/', express.static(process.env.STATIC_DIR || 'public'));
 
-    this.app.use((err, req, res, next) => {
+    this.app.use((err: any, req: Request, res: Response, next: NextFunction) => {
       if (err instanceof HttpStatusException) {
         res.status(err.statusCode).send(err.message);
       } else {

+ 2 - 1
server/tsconfig.json

@@ -1,5 +1,6 @@
 {
   "compilerOptions": {
+    "strict": true,
     "outDir": "./dist",
     "esModuleInterop": true,
     "moduleResolution": "node",
@@ -11,5 +12,5 @@
       "*": ["node_modules/*", "src/*", "../common/*"]
     }
   },
-  "include": ["./src/*", "./src/**/*, ../common/*", "../common/**/*"]
+  "include": ["./src/*", "./src/**/*", "../common/*", "../common/**/*"]
 }