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 readonly performanceRecords
: Map
<string, Statistics
> = new Map
<
25 constructor(storageUri
: string, logPrefix
: string) {
26 super(storageUri
, logPrefix
);
27 this.dbName
= this.storageUri
.pathname
;
30 public storePerformanceStatistics(performanceStatistics
: Statistics
): void {
31 this.checkPerformanceRecordsFile();
32 JsonFileStorage
.performanceRecords
.set(performanceStatistics
.id
, performanceStatistics
);
33 AsyncLock
.runExclusive(AsyncLockType
.performance
, () => {
36 JSONStringifyWithMapSupport([...JsonFileStorage
.performanceRecords
.values()], 2),
43 FileType
.PerformanceRecords
,
44 error
as NodeJS
.ErrnoException
,
52 if (isNullOrUndefined(this?.fd
)) {
53 if (!existsSync(dirname(this.dbName
))) {
54 mkdirSync(dirname(this.dbName
), { recursive
: true });
56 this.fd
= openSync(this.dbName
, 'w');
61 FileType
.PerformanceRecords
,
62 error
as NodeJS
.ErrnoException
,
68 public close(): void {
77 FileType
.PerformanceRecords
,
78 error
as NodeJS
.ErrnoException
,
84 private checkPerformanceRecordsFile(): void {
87 `${this.logPrefix} Performance records '${this.dbName}' file descriptor not found`,