1 // Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
3 import fs from
'node:fs';
5 import lockfile from
'proper-lockfile';
7 import { Storage
} from
'./Storage';
8 import { FileType
, type Statistics
} from
'../../types';
9 import { FileUtils
} from
'../../utils/FileUtils';
10 import { Utils
} from
'../../utils/Utils';
12 export class JsonFileStorage
extends Storage
{
13 private fd
: number | null = null;
15 constructor(storageUri
: string, logPrefix
: string) {
16 super(storageUri
, logPrefix
);
17 this.dbName
= this.storageUri
.pathname
;
20 public storePerformanceStatistics(performanceStatistics
: Statistics
): void {
21 this.checkPerformanceRecordsFile();
23 .lock(this.dbName
, { stale
: 5000, retries
: 3 })
24 .then(async (release
) => {
26 const fileData
= fs
.readFileSync(this.dbName
, 'utf8');
27 const performanceRecords
: Statistics
[] = fileData
28 ? (JSON
.parse(fileData
) as Statistics
[])
30 performanceRecords
.push(performanceStatistics
);
33 Utils
.JSONStringifyWithMapSupport(performanceRecords
, 2),
37 FileUtils
.handleFileException(
39 FileType
.PerformanceRecords
,
40 error
as NodeJS
.ErrnoException
,
47 /* This is intentional */
53 if (this?.fd
=== undefined || this?.fd
=== null) {
54 this.fd
= fs
.openSync(this.dbName
, 'a+');
57 FileUtils
.handleFileException(
59 FileType
.PerformanceRecords
,
60 error
as NodeJS
.ErrnoException
,
66 public close(): void {
69 fs
.closeSync(this.fd
);
73 FileUtils
.handleFileException(
75 FileType
.PerformanceRecords
,
76 error
as NodeJS
.ErrnoException
,
82 private checkPerformanceRecordsFile(): void {
85 `${this.logPrefix} Performance records '${this.dbName}' file descriptor not found`