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';
13 JSONStringifyWithMapSupport
,
18 export class JsonFileStorage
extends Storage
{
19 private static readonly performanceRecords
: Map
<string, Statistics
> = new Map
<
26 constructor(storageUri
: string, logPrefix
: string) {
27 super(storageUri
, logPrefix
);
28 this.dbName
= this.storageUri
.pathname
;
31 public storePerformanceStatistics(performanceStatistics
: Statistics
): void {
32 this.checkPerformanceRecordsFile();
33 AsyncLock
.acquire(AsyncLockType
.performance
)
35 JsonFileStorage
.performanceRecords
.set(performanceStatistics
.id
, performanceStatistics
);
38 JSONStringifyWithMapSupport([...JsonFileStorage
.performanceRecords
.values()], 2),
46 FileType
.PerformanceRecords
,
47 error
as NodeJS
.ErrnoException
,
52 AsyncLock
.release(AsyncLockType
.performance
).catch(Constants
.EMPTY_FUNCTION
);
58 if (isNullOrUndefined(this?.fd
)) {
59 if (!existsSync(dirname(this.dbName
))) {
60 mkdirSync(dirname(this.dbName
), { recursive
: true });
62 this.fd
= openSync(this.dbName
, 'w+');
67 FileType
.PerformanceRecords
,
68 error
as NodeJS
.ErrnoException
,
74 public close(): void {
83 FileType
.PerformanceRecords
,
84 error
as NodeJS
.ErrnoException
,
90 private checkPerformanceRecordsFile(): void {
93 `${this.logPrefix} Performance records '${this.dbName}' file descriptor not found`,