fix: use homebrew async locking primitive to order file writing
[e-mobility-charging-stations-simulator.git] / src / performance / storage / JsonFileStorage.ts
1 // Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
2
3 import fs from 'node:fs';
4
5 import { FileType, type Statistics } from '../../types';
6 import { AsyncLock, AsyncLockType, Constants, FileUtils, Utils } from '../../utils';
7 import { Storage } from '../internal';
8
9 export class JsonFileStorage extends Storage {
10 private fd: number | null = null;
11
12 constructor(storageUri: string, logPrefix: string) {
13 super(storageUri, logPrefix);
14 this.dbName = this.storageUri.pathname;
15 }
16
17 public storePerformanceStatistics(performanceStatistics: Statistics): void {
18 this.checkPerformanceRecordsFile();
19 const asyncLock = AsyncLock.getInstance(AsyncLockType.performance);
20 asyncLock
21 .acquire()
22 .then(() => {
23 const fileData = fs.readFileSync(this.dbName, 'utf8');
24 const performanceRecords: Statistics[] = fileData
25 ? (JSON.parse(fileData) as Statistics[])
26 : [];
27 performanceRecords.push(performanceStatistics);
28 fs.writeFileSync(
29 this.dbName,
30 Utils.JSONStringifyWithMapSupport(performanceRecords, 2),
31 'utf8'
32 );
33 })
34 .catch((error) => {
35 FileUtils.handleFileException(
36 this.dbName,
37 FileType.PerformanceRecords,
38 error as NodeJS.ErrnoException,
39 this.logPrefix
40 );
41 })
42 .finally(() => {
43 asyncLock.release().catch(Constants.EMPTY_FUNCTION);
44 });
45 }
46
47 public open(): void {
48 try {
49 if (Utils.isNullOrUndefined(this?.fd)) {
50 this.fd = fs.openSync(this.dbName, 'a+');
51 }
52 } catch (error) {
53 FileUtils.handleFileException(
54 this.dbName,
55 FileType.PerformanceRecords,
56 error as NodeJS.ErrnoException,
57 this.logPrefix
58 );
59 }
60 }
61
62 public close(): void {
63 try {
64 if (this?.fd) {
65 fs.closeSync(this.fd);
66 this.fd = null;
67 }
68 } catch (error) {
69 FileUtils.handleFileException(
70 this.dbName,
71 FileType.PerformanceRecords,
72 error as NodeJS.ErrnoException,
73 this.logPrefix
74 );
75 }
76 }
77
78 private checkPerformanceRecordsFile(): void {
79 if (!this?.fd) {
80 throw new Error(
81 `${this.logPrefix} Performance records '${this.dbName}' file descriptor not found`
82 );
83 }
84 }
85 }