1 // Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
3 import { closeSync
, existsSync
, mkdirSync
, openSync
, writeSync
} from
'node:fs';
4 import { dirname
} from
'node:path';
6 import { Storage
} from
'./Storage';
7 import { BaseError
} from
'../../exception';
8 import { FileType
, type Statistics
} from
'../../types';
12 JSONStringifyWithMapSupport
,
17 export class JsonFileStorage
extends Storage
{
18 private static performanceRecords
: Map
<string, Statistics
>;
22 constructor(storageUri
: string, logPrefix
: string) {
23 super(storageUri
, logPrefix
);
24 this.dbName
= this.storageUri
.pathname
;
27 public storePerformanceStatistics(performanceStatistics
: Statistics
): void {
28 this.checkPerformanceRecordsFile();
29 JsonFileStorage
.performanceRecords
.set(performanceStatistics
.id
, performanceStatistics
);
30 AsyncLock
.runExclusive(AsyncLockType
.performance
, () => {
33 JSONStringifyWithMapSupport([...JsonFileStorage
.performanceRecords
.values()], 2),
40 FileType
.PerformanceRecords
,
41 error
as NodeJS
.ErrnoException
,
48 JsonFileStorage
.performanceRecords
= new Map
<string, Statistics
>();
50 if (isNullOrUndefined(this?.fd
)) {
51 if (!existsSync(dirname(this.dbName
))) {
52 mkdirSync(dirname(this.dbName
), { recursive
: true });
54 this.fd
= openSync(this.dbName
, 'w');
59 FileType
.PerformanceRecords
,
60 error
as NodeJS
.ErrnoException
,
66 public close(): void {
67 JsonFileStorage
.performanceRecords
.clear();
76 FileType
.PerformanceRecords
,
77 error
as NodeJS
.ErrnoException
,
83 private checkPerformanceRecordsFile(): void {
86 `${this.logPrefix} Performance records '${this.dbName}' file descriptor not found`,