perf: create and clear Map in performance code
[e-mobility-charging-stations-simulator.git] / src / performance / storage / JsonFileStorage.ts
index 2f6e498749f5751f2364cc62716b3cfa8904872f..58680181f7499b858e485ea828e6f969910b78f9 100644 (file)
@@ -9,17 +9,13 @@ import { FileType, type Statistics } from '../../types';
 import {
   AsyncLock,
   AsyncLockType,
-  Constants,
   JSONStringifyWithMapSupport,
   handleFileException,
   isNullOrUndefined,
 } from '../../utils';
 
 export class JsonFileStorage extends Storage {
-  private static readonly performanceRecords: Map<string, Statistics> = new Map<
-    string,
-    Statistics
-  >();
+  private static performanceRecords: Map<string, Statistics>;
 
   private fd?: number;
 
@@ -30,36 +26,32 @@ export class JsonFileStorage extends Storage {
 
   public storePerformanceStatistics(performanceStatistics: Statistics): void {
     this.checkPerformanceRecordsFile();
-    AsyncLock.acquire(AsyncLockType.performance)
-      .then(() => {
-        JsonFileStorage.performanceRecords.set(performanceStatistics.id, performanceStatistics);
-        writeSync(
-          this.fd!,
-          JSONStringifyWithMapSupport([...JsonFileStorage.performanceRecords.values()], 2),
-          0,
-          'utf8',
-        );
-      })
-      .catch((error) => {
-        handleFileException(
-          this.dbName,
-          FileType.PerformanceRecords,
-          error as NodeJS.ErrnoException,
-          this.logPrefix,
-        );
-      })
-      .finally(() => {
-        AsyncLock.release(AsyncLockType.performance).catch(Constants.EMPTY_FUNCTION);
-      });
+    JsonFileStorage.performanceRecords.set(performanceStatistics.id, performanceStatistics);
+    AsyncLock.runExclusive(AsyncLockType.performance, () => {
+      writeSync(
+        this.fd!,
+        JSONStringifyWithMapSupport([...JsonFileStorage.performanceRecords.values()], 2),
+        0,
+        'utf8',
+      );
+    }).catch((error) => {
+      handleFileException(
+        this.dbName,
+        FileType.PerformanceRecords,
+        error as NodeJS.ErrnoException,
+        this.logPrefix,
+      );
+    });
   }
 
   public open(): void {
+    JsonFileStorage.performanceRecords = new Map<string, Statistics>();
     try {
       if (isNullOrUndefined(this?.fd)) {
         if (!existsSync(dirname(this.dbName))) {
           mkdirSync(dirname(this.dbName), { recursive: true });
         }
-        this.fd = openSync(this.dbName, 'w+');
+        this.fd = openSync(this.dbName, 'w');
       }
     } catch (error) {
       handleFileException(
@@ -72,6 +64,7 @@ export class JsonFileStorage extends Storage {
   }
 
   public close(): void {
+    JsonFileStorage.performanceRecords.clear();
     try {
       if (this?.fd) {
         closeSync(this.fd);