feat: add performance statistics to UI protocol
[e-mobility-charging-stations-simulator.git] / src / performance / storage / Storage.ts
CommitLineData
a19b897d 1// Copyright Jerome Benoit. 2021-2024. All Rights Reserved.
c27c3eee 2
66a7748d 3import { URL } from 'node:url'
c27c3eee 4
268a74bb
JB
5import {
6 DBName,
7 type EmptyObject,
8 type HandleErrorParams,
9 type Statistics,
66a7748d
JB
10 StorageType
11} from '../../types/index.js'
12import { logger, setDefaultErrorParams } from '../../utils/index.js'
72f041bd
JB
13
14export abstract class Storage {
66a7748d
JB
15 protected readonly storageUri: URL
16 protected readonly logPrefix: string
17 protected dbName!: string
a66bbcfe 18 private static readonly performanceStatistics = new Map<string, Statistics>()
72f041bd 19
66a7748d
JB
20 constructor (storageUri: string, logPrefix: string) {
21 this.storageUri = new URL(storageUri)
22 this.logPrefix = logPrefix
72f041bd
JB
23 }
24
66a7748d 25 protected handleDBError (
e7aeea18
JB
26 type: StorageType,
27 error: Error,
28 table?: string,
66a7748d 29 params: HandleErrorParams<EmptyObject> = { throwError: false, consoleOut: false }
e7aeea18 30 ): void {
66a7748d
JB
31 setDefaultErrorParams(params, { throwError: false, consoleOut: false })
32 const inTableOrCollectionStr = table != null && ` in table or collection '${table}'`
e7aeea18 33 logger.error(
8f3d04b0
JB
34 `${this.logPrefix} ${this.getDBNameFromStorageType(type)} error '${
35 error.message
32de5a57 36 }'${inTableOrCollectionStr}:`,
66a7748d
JB
37 error
38 )
5199f9fd 39 if (params.throwError === true) {
66a7748d 40 throw error
e0a50bcd 41 }
c27c3eee
JB
42 }
43
66a7748d 44 protected getDBNameFromStorageType (type: StorageType): DBName | undefined {
c27c3eee 45 switch (type) {
4ccf551d
JB
46 case StorageType.SQLITE:
47 return DBName.SQLITE
c27c3eee 48 case StorageType.MARIA_DB:
66a7748d 49 return DBName.MARIA_DB
c27c3eee 50 case StorageType.MYSQL:
66a7748d 51 return DBName.MYSQL
4ccf551d
JB
52 case StorageType.MONGO_DB:
53 return DBName.MONGO_DB
c27c3eee 54 }
2a370053
JB
55 }
56
a66bbcfe
JB
57 public getPerformanceStatistics (): IterableIterator<Statistics> {
58 return Storage.performanceStatistics.values()
59 }
60
61 protected setPerformanceStatistics (performanceStatistics: Statistics): void {
62 Storage.performanceStatistics.set(performanceStatistics.id, performanceStatistics)
63 }
64
65 protected clearPerformanceStatistics (): void {
66 Storage.performanceStatistics.clear()
67 }
68
66a7748d
JB
69 public abstract open (): void | Promise<void>
70 public abstract close (): void | Promise<void>
71 public abstract storePerformanceStatistics (
72 performanceStatistics: Statistics
73 ): void | Promise<void>
72f041bd 74}