fix: use homebrew async locking primitive to order file writing
[e-mobility-charging-stations-simulator.git] / src / performance / storage / JsonFileStorage.ts
index fcb35a4df0507569d941edbcb1aac223561e6be4..5effae906dc6965d3d60893c801d5e6b465e8d4d 100644 (file)
@@ -2,10 +2,8 @@
 
 import fs from 'node:fs';
 
-import lockfile from 'proper-lockfile';
-
 import { FileType, type Statistics } from '../../types';
-import { Constants, FileUtils, Utils } from '../../utils';
+import { AsyncLock, AsyncLockType, Constants, FileUtils, Utils } from '../../utils';
 import { Storage } from '../internal';
 
 export class JsonFileStorage extends Storage {
@@ -18,31 +16,32 @@ export class JsonFileStorage extends Storage {
 
   public storePerformanceStatistics(performanceStatistics: Statistics): void {
     this.checkPerformanceRecordsFile();
-    lockfile
-      .lock(this.dbName, { stale: 5000, retries: 3 })
-      .then(async (release) => {
-        try {
-          const fileData = fs.readFileSync(this.dbName, 'utf8');
-          const performanceRecords: Statistics[] = fileData
-            ? (JSON.parse(fileData) as Statistics[])
-            : [];
-          performanceRecords.push(performanceStatistics);
-          fs.writeFileSync(
-            this.dbName,
-            Utils.JSONStringifyWithMapSupport(performanceRecords, 2),
-            'utf8'
-          );
-        } catch (error) {
-          FileUtils.handleFileException(
-            this.dbName,
-            FileType.PerformanceRecords,
-            error as NodeJS.ErrnoException,
-            this.logPrefix
-          );
-        }
-        await release();
+    const asyncLock = AsyncLock.getInstance(AsyncLockType.performance);
+    asyncLock
+      .acquire()
+      .then(() => {
+        const fileData = fs.readFileSync(this.dbName, 'utf8');
+        const performanceRecords: Statistics[] = fileData
+          ? (JSON.parse(fileData) as Statistics[])
+          : [];
+        performanceRecords.push(performanceStatistics);
+        fs.writeFileSync(
+          this.dbName,
+          Utils.JSONStringifyWithMapSupport(performanceRecords, 2),
+          'utf8'
+        );
+      })
+      .catch((error) => {
+        FileUtils.handleFileException(
+          this.dbName,
+          FileType.PerformanceRecords,
+          error as NodeJS.ErrnoException,
+          this.logPrefix
+        );
       })
-      .catch(Constants.EMPTY_FUNCTION);
+      .finally(() => {
+        asyncLock.release().catch(Constants.EMPTY_FUNCTION);
+      });
   }
 
   public open(): void {