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.js'
7 import { BaseError
} from
'../../exception/index.js'
8 import { FileType
, type Statistics
} from
'../../types/index.js'
12 JSONStringifyWithMapSupport
,
14 } from
'../../utils/index.js'
16 export class JsonFileStorage
extends Storage
{
17 private static performanceRecords
: Map
<string, Statistics
>
21 constructor (storageUri
: string, logPrefix
: string) {
22 super(storageUri
, logPrefix
)
23 this.dbName
= this.storageUri
.pathname
26 public storePerformanceStatistics (performanceStatistics
: Statistics
): void {
27 this.checkPerformanceRecordsFile()
28 JsonFileStorage
.performanceRecords
.set(performanceStatistics
.id
, performanceStatistics
)
29 AsyncLock
.runExclusive(AsyncLockType
.performance
, () => {
31 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
33 JSONStringifyWithMapSupport([...JsonFileStorage
.performanceRecords
.values()], 2),
40 FileType
.PerformanceRecords
,
41 error
as NodeJS
.ErrnoException
,
47 public open (): void {
48 JsonFileStorage
.performanceRecords
= new Map
<string, Statistics
>()
50 if (this.fd
== null) {
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()
69 if (this.fd
!= null) {
76 FileType
.PerformanceRecords
,
77 error
as NodeJS
.ErrnoException
,
83 private checkPerformanceRecordsFile (): void {
84 if (this.fd
== null) {
86 `${this.logPrefix} Performance records '${this.dbName}' file descriptor not found`