@sphereon/ssi-sdk.data-store 0.23.5-unstable.88 → 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. package/LICENSE +201 -201
  2. package/README.md +77 -77
  3. package/dist/index.d.ts +3 -9
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/index.js +2 -15
  6. package/dist/index.js.map +1 -1
  7. package/dist/migrations/generic/index.d.ts +0 -2
  8. package/dist/migrations/generic/index.d.ts.map +1 -1
  9. package/dist/migrations/generic/index.js +1 -4
  10. package/dist/migrations/generic/index.js.map +1 -1
  11. package/dist/migrations/index.d.ts +1 -1
  12. package/dist/migrations/index.d.ts.map +1 -1
  13. package/dist/migrations/index.js +1 -2
  14. package/dist/migrations/index.js.map +1 -1
  15. package/dist/migrations/postgres/1690925872592-CreateContacts.js +1 -1
  16. package/dist/migrations/postgres/1690925872592-CreateContacts.js.map +1 -1
  17. package/dist/migrations/postgres/1708525189001-CreateDigitalCredential.js +22 -22
  18. package/dist/migrations/postgres/1708797018115-CreateMachineStateStore.js +16 -16
  19. package/dist/migrations/sqlite/1708525189002-CreateDigitalCredential.js +21 -21
  20. package/dist/migrations/sqlite/1708796002272-CreateMachineStateStore.js +15 -15
  21. package/dist/types/index.d.ts +0 -2
  22. package/dist/types/index.d.ts.map +1 -1
  23. package/dist/types/index.js +0 -2
  24. package/dist/types/index.js.map +1 -1
  25. package/package.json +4 -5
  26. package/src/__tests__/contact.entities.test.ts +2542 -2542
  27. package/src/__tests__/contact.store.test.ts +2471 -2471
  28. package/src/__tests__/digitalCredential.entities.test.ts +254 -254
  29. package/src/__tests__/digitalCredential.store.test.ts +294 -294
  30. package/src/__tests__/eventLogger.entities.test.ts +73 -73
  31. package/src/__tests__/eventLogger.store.test.ts +136 -136
  32. package/src/__tests__/issuanceBranding.entities.test.ts +844 -844
  33. package/src/__tests__/issuanceBranding.store.test.ts +1884 -1884
  34. package/src/__tests__/machineState.entities.test.ts +51 -51
  35. package/src/__tests__/machineState.store.test.ts +174 -174
  36. package/src/contact/AbstractContactStore.ts +71 -71
  37. package/src/contact/ContactStore.ts +723 -723
  38. package/src/digitalCredential/AbstractDigitalCredentialStore.ts +17 -17
  39. package/src/digitalCredential/DigitalCredentialStore.ts +127 -127
  40. package/src/entities/contact/BaseContactEntity.ts +39 -39
  41. package/src/entities/contact/ConnectionEntity.ts +29 -29
  42. package/src/entities/contact/CorrelationIdentifierEntity.ts +37 -37
  43. package/src/entities/contact/DidAuthConfigEntity.ts +14 -14
  44. package/src/entities/contact/ElectronicAddressEntity.ts +63 -63
  45. package/src/entities/contact/IdentityEntity.ts +97 -97
  46. package/src/entities/contact/IdentityMetadataItemEntity.ts +35 -35
  47. package/src/entities/contact/NaturalPersonEntity.ts +38 -38
  48. package/src/entities/contact/OpenIdConfigEntity.ts +26 -26
  49. package/src/entities/contact/OrganizationEntity.ts +34 -34
  50. package/src/entities/contact/PartyEntity.ts +110 -110
  51. package/src/entities/contact/PartyRelationshipEntity.ts +61 -61
  52. package/src/entities/contact/PartyTypeEntity.ts +62 -62
  53. package/src/entities/contact/PhysicalAddressEntity.ts +87 -87
  54. package/src/entities/digitalCredential/DigitalCredentialEntity.ts +64 -64
  55. package/src/entities/eventLogger/AuditEventEntity.ts +99 -99
  56. package/src/entities/issuanceBranding/CredentialBrandingEntity.ts +78 -78
  57. package/src/entities/issuanceBranding/ImageAttributesEntity.ts +57 -57
  58. package/src/entities/issuanceBranding/IssuerBrandingEntity.ts +72 -72
  59. package/src/entities/machineState/MachineStateInfoEntity.ts +58 -58
  60. package/src/entities/statusList2021/StatusList2021Entity.ts +96 -96
  61. package/src/eventLogger/AbstractEventLoggerStore.ts +7 -7
  62. package/src/eventLogger/EventLoggerStore.ts +62 -62
  63. package/src/index.ts +141 -154
  64. package/src/issuanceBranding/IssuanceBrandingStore.ts +559 -559
  65. package/src/machineState/IAbstractMachineStateStore.ts +65 -65
  66. package/src/machineState/MachineStateStore.ts +149 -149
  67. package/src/migrations/generic/1-CreateContacts.ts +66 -66
  68. package/src/migrations/generic/2-CreateIssuanceBranding.ts +64 -64
  69. package/src/migrations/generic/3-CreateContacts.ts +66 -66
  70. package/src/migrations/generic/4-CreateStatusList.ts +54 -54
  71. package/src/migrations/generic/5-CreateAuditEvents.ts +66 -66
  72. package/src/migrations/generic/6-CreateDigitalCredential.ts +66 -66
  73. package/src/migrations/generic/7-CreateMachineStateStore.ts +66 -66
  74. package/src/migrations/generic/index.ts +33 -36
  75. package/src/migrations/index.ts +9 -10
  76. package/src/migrations/postgres/1659463079428-CreateContacts.ts +63 -63
  77. package/src/migrations/postgres/1685628974232-CreateIssuanceBranding.ts +85 -85
  78. package/src/migrations/postgres/1690925872592-CreateContacts.ts +104 -104
  79. package/src/migrations/postgres/1693866470001-CreateStatusList.ts +24 -24
  80. package/src/migrations/postgres/1701634812183-CreateAuditEvents.ts +33 -33
  81. package/src/migrations/postgres/1708525189001-CreateDigitalCredential.ts +44 -44
  82. package/src/migrations/postgres/1708797018115-CreateMachineStateStore.ts +29 -29
  83. package/src/migrations/sqlite/1659463069549-CreateContacts.ts +110 -110
  84. package/src/migrations/sqlite/1685628973231-CreateIssuanceBranding.ts +119 -119
  85. package/src/migrations/sqlite/1690925872693-CreateContacts.ts +161 -161
  86. package/src/migrations/sqlite/1693866470000-CreateStatusList.ts +24 -24
  87. package/src/migrations/sqlite/1701634819487-CreateAuditEvents.ts +15 -15
  88. package/src/migrations/sqlite/1708525189002-CreateDigitalCredential.ts +34 -34
  89. package/src/migrations/sqlite/1708796002272-CreateMachineStateStore.ts +28 -28
  90. package/src/statusList/StatusListStore.ts +237 -237
  91. package/src/types/contact/IAbstractContactStore.ts +161 -161
  92. package/src/types/contact/contact.ts +237 -237
  93. package/src/types/digitalCredential/IAbstractDigitalCredentialStore.ts +37 -37
  94. package/src/types/digitalCredential/digitalCredential.ts +46 -46
  95. package/src/types/eventLogger/IAbstractEventLoggerStore.ts +12 -12
  96. package/src/types/eventLogger/eventLogger.ts +3 -3
  97. package/src/types/index.ts +10 -12
  98. package/src/types/machineState/IAbstractMachineStateStore.ts +68 -68
  99. package/src/utils/SortingUtils.ts +16 -16
  100. package/src/utils/contact/MappingUtils.ts +385 -385
  101. package/src/utils/digitalCredential/MappingUtils.ts +122 -122
  102. package/dist/entities/presentationDefinitions/PresentationDefinitionItemEntity.d.ts +0 -13
  103. package/dist/entities/presentationDefinitions/PresentationDefinitionItemEntity.d.ts.map +0 -1
  104. package/dist/entities/presentationDefinitions/PresentationDefinitionItemEntity.js +0 -71
  105. package/dist/entities/presentationDefinitions/PresentationDefinitionItemEntity.js.map +0 -1
  106. package/dist/migrations/generic/8-CreatePresentationDefinitions.d.ts +0 -7
  107. package/dist/migrations/generic/8-CreatePresentationDefinitions.d.ts.map +0 -1
  108. package/dist/migrations/generic/8-CreatePresentationDefinitions.js +0 -78
  109. package/dist/migrations/generic/8-CreatePresentationDefinitions.js.map +0 -1
  110. package/dist/migrations/postgres/1716475165345-CreatePresentationDefinitions.d.ts +0 -7
  111. package/dist/migrations/postgres/1716475165345-CreatePresentationDefinitions.d.ts.map +0 -1
  112. package/dist/migrations/postgres/1716475165345-CreatePresentationDefinitions.js +0 -40
  113. package/dist/migrations/postgres/1716475165345-CreatePresentationDefinitions.js.map +0 -1
  114. package/dist/migrations/sqlite/1716475165344-CreatePresentationDefinitions.d.ts +0 -7
  115. package/dist/migrations/sqlite/1716475165344-CreatePresentationDefinitions.d.ts.map +0 -1
  116. package/dist/migrations/sqlite/1716475165344-CreatePresentationDefinitions.js +0 -37
  117. package/dist/migrations/sqlite/1716475165344-CreatePresentationDefinitions.js.map +0 -1
  118. package/dist/pd/AbstractPDStore.d.ts +0 -10
  119. package/dist/pd/AbstractPDStore.d.ts.map +0 -1
  120. package/dist/pd/AbstractPDStore.js +0 -7
  121. package/dist/pd/AbstractPDStore.js.map +0 -1
  122. package/dist/pd/PDStore.d.ts +0 -14
  123. package/dist/pd/PDStore.d.ts.map +0 -1
  124. package/dist/pd/PDStore.js +0 -90
  125. package/dist/pd/PDStore.js.map +0 -1
  126. package/dist/types/pd/IAbstractPDStore.d.ts +0 -14
  127. package/dist/types/pd/IAbstractPDStore.d.ts.map +0 -1
  128. package/dist/types/pd/IAbstractPDStore.js +0 -3
  129. package/dist/types/pd/IAbstractPDStore.js.map +0 -1
  130. package/dist/types/pd/pd.d.ts +0 -15
  131. package/dist/types/pd/pd.d.ts.map +0 -1
  132. package/dist/types/pd/pd.js +0 -3
  133. package/dist/types/pd/pd.js.map +0 -1
  134. package/dist/utils/presentationDefinitions/MappingUtils.d.ts +0 -6
  135. package/dist/utils/presentationDefinitions/MappingUtils.d.ts.map +0 -1
  136. package/dist/utils/presentationDefinitions/MappingUtils.js +0 -50
  137. package/dist/utils/presentationDefinitions/MappingUtils.js.map +0 -1
  138. package/src/entities/presentationDefinitions/PresentationDefinitionItemEntity.ts +0 -41
  139. package/src/migrations/generic/8-CreatePresentationDefinitions.ts +0 -66
  140. package/src/migrations/postgres/1716475165345-CreatePresentationDefinitions.ts +0 -24
  141. package/src/migrations/sqlite/1716475165344-CreatePresentationDefinitions.ts +0 -23
  142. package/src/pd/AbstractPDStore.ts +0 -10
  143. package/src/pd/PDStore.ts +0 -103
  144. package/src/types/pd/IAbstractPDStore.ts +0 -19
  145. package/src/types/pd/pd.ts +0 -16
  146. package/src/utils/presentationDefinitions/MappingUtils.ts +0 -54
@@ -1,65 +1,65 @@
1
- import {
2
- StoreMachineStateDeleteExpiredArgs,
3
- StoreMachineStateDeleteArgs,
4
- StoreMachineStatesFindActiveArgs,
5
- StoreFindMachineStatesArgs,
6
- StoreMachineStatePersistArgs,
7
- StoreMachineStateInfo,
8
- StoreMachineStateGetArgs,
9
- } from '../types'
10
-
11
- /**
12
- * Represents an abstract class for storing machine states.
13
- * This class provides methods for persisting, retrieving, and deleting machine states.
14
- *
15
- * @interface
16
- */
17
- export abstract class IAbstractMachineStateStore {
18
- /**
19
- * Persists the machine state.
20
- *
21
- * @param {StoreMachineStatePersistArgs} state - The object containing the machine state to persist.
22
- * @return {Promise<StoreMachineStateInfo>} - A Promise that resolves to the information about the persisted machine state.
23
- */
24
- abstract persistMachineState(state: StoreMachineStatePersistArgs): Promise<StoreMachineStateInfo>
25
-
26
- /**
27
- * Finds active machine states based on the given arguments.
28
- *
29
- * @param {StoreMachineStatesFindActiveArgs} args - The arguments for finding active machine states.
30
- * @return {Promise<Array<StoreMachineStateInfo>>} - A promise that resolves with an array of active machine states.
31
- */
32
- abstract findActiveMachineStates(args: StoreMachineStatesFindActiveArgs): Promise<Array<StoreMachineStateInfo>>
33
-
34
- /**
35
- * Retrieves the state of a particular machine.
36
- *
37
- * @param {StoreMachineStateGetArgs} args - The arguments for retrieving the machine state.
38
- * @returns {Promise<StoreMachineStateInfo>} - A promise that resolves to the machine state information.
39
- */
40
- abstract getMachineState(args: StoreMachineStateGetArgs): Promise<StoreMachineStateInfo>
41
-
42
- /**
43
- * Finds the machine states based on the given arguments.
44
- *
45
- * @param {StoreFindMachineStatesArgs} [args] - The arguments to filter the machine states.
46
- * @returns {Promise<Array<StoreMachineStateInfo>>} - A promise that resolves to an array of machine state information.
47
- */
48
- abstract findMachineStates(args?: StoreFindMachineStatesArgs): Promise<Array<StoreMachineStateInfo>>
49
-
50
- /**
51
- * Deletes a machine state.
52
- *
53
- * @param {StoreMachineStateDeleteArgs} args - The arguments for deleting the machine state.
54
- * @return {Promise<boolean>} - A promise that resolves to a boolean indicating if the machine state was successfully deleted or not.
55
- */
56
- abstract deleteMachineState(args: StoreMachineStateDeleteArgs): Promise<boolean>
57
-
58
- /**
59
- * Deletes expired machine states from the database.
60
- *
61
- * @param {StoreMachineStateDeleteExpiredArgs} args - The arguments for deleting expired machine states.
62
- * @return {Promise<number>} - A promise that resolves to the number of deleted machine states.
63
- */
64
- abstract deleteExpiredMachineStates(args: StoreMachineStateDeleteExpiredArgs): Promise<number>
65
- }
1
+ import {
2
+ StoreMachineStateDeleteExpiredArgs,
3
+ StoreMachineStateDeleteArgs,
4
+ StoreMachineStatesFindActiveArgs,
5
+ StoreFindMachineStatesArgs,
6
+ StoreMachineStatePersistArgs,
7
+ StoreMachineStateInfo,
8
+ StoreMachineStateGetArgs,
9
+ } from '../types'
10
+
11
+ /**
12
+ * Represents an abstract class for storing machine states.
13
+ * This class provides methods for persisting, retrieving, and deleting machine states.
14
+ *
15
+ * @interface
16
+ */
17
+ export abstract class IAbstractMachineStateStore {
18
+ /**
19
+ * Persists the machine state.
20
+ *
21
+ * @param {StoreMachineStatePersistArgs} state - The object containing the machine state to persist.
22
+ * @return {Promise<StoreMachineStateInfo>} - A Promise that resolves to the information about the persisted machine state.
23
+ */
24
+ abstract persistMachineState(state: StoreMachineStatePersistArgs): Promise<StoreMachineStateInfo>
25
+
26
+ /**
27
+ * Finds active machine states based on the given arguments.
28
+ *
29
+ * @param {StoreMachineStatesFindActiveArgs} args - The arguments for finding active machine states.
30
+ * @return {Promise<Array<StoreMachineStateInfo>>} - A promise that resolves with an array of active machine states.
31
+ */
32
+ abstract findActiveMachineStates(args: StoreMachineStatesFindActiveArgs): Promise<Array<StoreMachineStateInfo>>
33
+
34
+ /**
35
+ * Retrieves the state of a particular machine.
36
+ *
37
+ * @param {StoreMachineStateGetArgs} args - The arguments for retrieving the machine state.
38
+ * @returns {Promise<StoreMachineStateInfo>} - A promise that resolves to the machine state information.
39
+ */
40
+ abstract getMachineState(args: StoreMachineStateGetArgs): Promise<StoreMachineStateInfo>
41
+
42
+ /**
43
+ * Finds the machine states based on the given arguments.
44
+ *
45
+ * @param {StoreFindMachineStatesArgs} [args] - The arguments to filter the machine states.
46
+ * @returns {Promise<Array<StoreMachineStateInfo>>} - A promise that resolves to an array of machine state information.
47
+ */
48
+ abstract findMachineStates(args?: StoreFindMachineStatesArgs): Promise<Array<StoreMachineStateInfo>>
49
+
50
+ /**
51
+ * Deletes a machine state.
52
+ *
53
+ * @param {StoreMachineStateDeleteArgs} args - The arguments for deleting the machine state.
54
+ * @return {Promise<boolean>} - A promise that resolves to a boolean indicating if the machine state was successfully deleted or not.
55
+ */
56
+ abstract deleteMachineState(args: StoreMachineStateDeleteArgs): Promise<boolean>
57
+
58
+ /**
59
+ * Deletes expired machine states from the database.
60
+ *
61
+ * @param {StoreMachineStateDeleteExpiredArgs} args - The arguments for deleting expired machine states.
62
+ * @return {Promise<number>} - A promise that resolves to the number of deleted machine states.
63
+ */
64
+ abstract deleteExpiredMachineStates(args: StoreMachineStateDeleteExpiredArgs): Promise<number>
65
+ }
@@ -1,149 +1,149 @@
1
- import { OrPromise } from '@sphereon/ssi-types'
2
- import Debug from 'debug'
3
- import { Brackets, DataSource, FindOptionsWhere, IsNull, LessThan, Not } from 'typeorm'
4
-
5
- import { MachineStateInfoEntity } from '../entities/machineState/MachineStateInfoEntity'
6
- import {
7
- StoreFindMachineStatesArgs,
8
- StoreMachineStateDeleteArgs,
9
- StoreMachineStateDeleteExpiredArgs,
10
- StoreMachineStateGetArgs,
11
- StoreMachineStateInfo,
12
- StoreMachineStatePersistArgs,
13
- StoreMachineStatesFindActiveArgs,
14
- } from '../types'
15
- import { IAbstractMachineStateStore } from './IAbstractMachineStateStore'
16
-
17
- const debug = Debug('sphereon:ssi-sdk:machine-state:store')
18
-
19
- /**
20
- * Represents a data store for managing machine states.
21
- */
22
- export class MachineStateStore extends IAbstractMachineStateStore {
23
- private readonly _dbConnection: OrPromise<DataSource>
24
-
25
- constructor(dbConnection: OrPromise<DataSource>) {
26
- super()
27
- this._dbConnection = dbConnection
28
- }
29
-
30
- async persistMachineState(state: StoreMachineStatePersistArgs): Promise<StoreMachineStateInfo> {
31
- const connection: DataSource = await this._dbConnection
32
- const { machineName, instanceId, tenantId } = state
33
- debug(`Executing persistMachineState for machine ${machineName}, instance ${instanceId}, tenantId: ${tenantId}...`)
34
- const entity = MachineStateStore.machineStateInfoEntityFrom(state)
35
- const existing = await connection.getRepository(MachineStateInfoEntity).findOne({
36
- where: {
37
- instanceId: state.instanceId,
38
- },
39
- })
40
- if (existing && existing.updatedCount > state.updatedCount) {
41
- const error = `Updating machine state with an older version is not allowed. Machine ${existing.machineName}, last count: ${
42
- existing.updatedCount
43
- }, new count: ${existing.updatedCount}, last updated: ${existing.updatedAt}, current: ${new Date()}, instance: ${existing.instanceId}`
44
- console.log(error)
45
- return Promise.reject(new Error(error))
46
- }
47
- // No need for a transaction. This is a single entity. We don't want to be surprised by an isolation level hiding the state from others
48
- const result = await connection.getRepository(MachineStateInfoEntity).save(entity, { transaction: false })
49
- debug(`Done persistMachineState machine ${machineName}, instance ${instanceId}, tenantId: ${tenantId}`)
50
- return MachineStateStore.machineInfoFrom(result)
51
- }
52
-
53
- async findActiveMachineStates(args: StoreMachineStatesFindActiveArgs): Promise<Array<StoreMachineStateInfo>> {
54
- const { tenantId, machineName, instanceId } = args
55
- const connection: DataSource = await this._dbConnection
56
- debug(`Executing findActiveMachineStates query with machineName: ${machineName}, tenantId: ${tenantId}`)
57
- const queryBuilder = connection
58
- .getRepository(MachineStateInfoEntity)
59
- .createQueryBuilder('state')
60
- .where('state.completedAt IS NULL')
61
- .andWhere(
62
- new Brackets((qb) => {
63
- qb.where('state.expiresAt IS NULL').orWhere('state.expiresAt > :now', { now: new Date() })
64
- }),
65
- )
66
-
67
- if (instanceId) {
68
- queryBuilder.andWhere('state.instanceId = :instanceId', { instanceId })
69
- }
70
- if (tenantId) {
71
- queryBuilder.andWhere('state.tenantId = :tenantId', { tenantId })
72
- }
73
- if (machineName) {
74
- queryBuilder.andWhere('state.machineName = :machineName', { machineName })
75
- }
76
-
77
- return (
78
- (await queryBuilder
79
- .orderBy('state.updatedAt', 'DESC')
80
- .getMany()
81
- .then((entities) => entities.map(MachineStateStore.machineInfoFrom))) ?? []
82
- )
83
- }
84
-
85
- async findMachineStates(args?: StoreFindMachineStatesArgs): Promise<Array<StoreMachineStateInfo>> {
86
- const connection: DataSource = await this._dbConnection
87
- debug('findMachineStates', args)
88
- const result: Array<MachineStateInfoEntity> = await connection.getRepository(MachineStateInfoEntity).find({
89
- ...(args?.filter && { where: args?.filter }),
90
- transaction: false,
91
- })
92
-
93
- return result.map((event: MachineStateInfoEntity) => MachineStateStore.machineInfoFrom(event))
94
- }
95
-
96
- async getMachineState(args: StoreMachineStateGetArgs): Promise<StoreMachineStateInfo> {
97
- const connection: DataSource = await this._dbConnection
98
- debug('getMachineState', args)
99
- return connection.getRepository(MachineStateInfoEntity).findOneOrFail({ where: { instanceId: args.instanceId } })
100
- }
101
-
102
- async deleteMachineState(args: StoreMachineStateDeleteArgs): Promise<boolean> {
103
- debug(`Executing deleteMachineState query with id: ${args.instanceId}`)
104
- if (!args.instanceId) {
105
- throw new Error('No instanceId parameter is provided.')
106
- }
107
- try {
108
- const connection: DataSource = await this._dbConnection
109
-
110
- const result = await connection.getRepository(MachineStateInfoEntity).delete(args.instanceId)
111
- return result.affected != null && result.affected > 0
112
- } catch (error) {
113
- debug(`Error deleting state: ${error}`)
114
- return false
115
- }
116
- }
117
-
118
- async deleteExpiredMachineStates(args: StoreMachineStateDeleteExpiredArgs): Promise<number> {
119
- const { machineName, tenantId, deleteDoneStates } = args
120
- debug(`Executing deleteExpiredMachineStates query with params: ${JSON.stringify(args)}`)
121
- try {
122
- const connection: DataSource = await this._dbConnection
123
-
124
- const deleteCriteria: FindOptionsWhere<MachineStateInfoEntity> = {
125
- ...(machineName && { machineName }),
126
- ...(tenantId && { tenantId }),
127
- // When deleteOnDone state is set we only look at completedAt, in other cases we compare current time with expiresAt
128
- ...(!deleteDoneStates && { expiresAt: LessThan(new Date()) }),
129
- ...(deleteDoneStates && { completedAt: Not(IsNull()) }),
130
- }
131
- const result = await connection.getRepository(MachineStateInfoEntity).delete(deleteCriteria)
132
- return result.affected ?? 0
133
- } catch (error) {
134
- debug(`Error deleting machine info: ${error}`)
135
- return Promise.reject(new Error(`Error deleting expired machine states for machine type ${machineName}`))
136
- }
137
- }
138
-
139
- protected static machineInfoFrom = (machineStateInfoEntity: MachineStateInfoEntity): StoreMachineStateInfo => {
140
- // We are making sure no entity function get copied
141
- return JSON.parse(JSON.stringify(machineStateInfoEntity))
142
- }
143
-
144
- static machineStateInfoEntityFrom = (machineStateInfo: StoreMachineStateInfo | StoreMachineStatePersistArgs): MachineStateInfoEntity => {
145
- const entity = new MachineStateInfoEntity()
146
- Object.assign(entity, machineStateInfo)
147
- return entity
148
- }
149
- }
1
+ import { OrPromise } from '@sphereon/ssi-types'
2
+ import Debug from 'debug'
3
+ import { Brackets, DataSource, FindOptionsWhere, IsNull, LessThan, Not } from 'typeorm'
4
+
5
+ import { MachineStateInfoEntity } from '../entities/machineState/MachineStateInfoEntity'
6
+ import {
7
+ StoreFindMachineStatesArgs,
8
+ StoreMachineStateDeleteArgs,
9
+ StoreMachineStateDeleteExpiredArgs,
10
+ StoreMachineStateGetArgs,
11
+ StoreMachineStateInfo,
12
+ StoreMachineStatePersistArgs,
13
+ StoreMachineStatesFindActiveArgs,
14
+ } from '../types'
15
+ import { IAbstractMachineStateStore } from './IAbstractMachineStateStore'
16
+
17
+ const debug = Debug('sphereon:ssi-sdk:machine-state:store')
18
+
19
+ /**
20
+ * Represents a data store for managing machine states.
21
+ */
22
+ export class MachineStateStore extends IAbstractMachineStateStore {
23
+ private readonly _dbConnection: OrPromise<DataSource>
24
+
25
+ constructor(dbConnection: OrPromise<DataSource>) {
26
+ super()
27
+ this._dbConnection = dbConnection
28
+ }
29
+
30
+ async persistMachineState(state: StoreMachineStatePersistArgs): Promise<StoreMachineStateInfo> {
31
+ const connection: DataSource = await this._dbConnection
32
+ const { machineName, instanceId, tenantId } = state
33
+ debug(`Executing persistMachineState for machine ${machineName}, instance ${instanceId}, tenantId: ${tenantId}...`)
34
+ const entity = MachineStateStore.machineStateInfoEntityFrom(state)
35
+ const existing = await connection.getRepository(MachineStateInfoEntity).findOne({
36
+ where: {
37
+ instanceId: state.instanceId,
38
+ },
39
+ })
40
+ if (existing && existing.updatedCount > state.updatedCount) {
41
+ const error = `Updating machine state with an older version is not allowed. Machine ${existing.machineName}, last count: ${
42
+ existing.updatedCount
43
+ }, new count: ${existing.updatedCount}, last updated: ${existing.updatedAt}, current: ${new Date()}, instance: ${existing.instanceId}`
44
+ console.log(error)
45
+ return Promise.reject(new Error(error))
46
+ }
47
+ // No need for a transaction. This is a single entity. We don't want to be surprised by an isolation level hiding the state from others
48
+ const result = await connection.getRepository(MachineStateInfoEntity).save(entity, { transaction: false })
49
+ debug(`Done persistMachineState machine ${machineName}, instance ${instanceId}, tenantId: ${tenantId}`)
50
+ return MachineStateStore.machineInfoFrom(result)
51
+ }
52
+
53
+ async findActiveMachineStates(args: StoreMachineStatesFindActiveArgs): Promise<Array<StoreMachineStateInfo>> {
54
+ const { tenantId, machineName, instanceId } = args
55
+ const connection: DataSource = await this._dbConnection
56
+ debug(`Executing findActiveMachineStates query with machineName: ${machineName}, tenantId: ${tenantId}`)
57
+ const queryBuilder = connection
58
+ .getRepository(MachineStateInfoEntity)
59
+ .createQueryBuilder('state')
60
+ .where('state.completedAt IS NULL')
61
+ .andWhere(
62
+ new Brackets((qb) => {
63
+ qb.where('state.expiresAt IS NULL').orWhere('state.expiresAt > :now', { now: new Date() })
64
+ }),
65
+ )
66
+
67
+ if (instanceId) {
68
+ queryBuilder.andWhere('state.instanceId = :instanceId', { instanceId })
69
+ }
70
+ if (tenantId) {
71
+ queryBuilder.andWhere('state.tenantId = :tenantId', { tenantId })
72
+ }
73
+ if (machineName) {
74
+ queryBuilder.andWhere('state.machineName = :machineName', { machineName })
75
+ }
76
+
77
+ return (
78
+ (await queryBuilder
79
+ .orderBy('state.updatedAt', 'DESC')
80
+ .getMany()
81
+ .then((entities) => entities.map(MachineStateStore.machineInfoFrom))) ?? []
82
+ )
83
+ }
84
+
85
+ async findMachineStates(args?: StoreFindMachineStatesArgs): Promise<Array<StoreMachineStateInfo>> {
86
+ const connection: DataSource = await this._dbConnection
87
+ debug('findMachineStates', args)
88
+ const result: Array<MachineStateInfoEntity> = await connection.getRepository(MachineStateInfoEntity).find({
89
+ ...(args?.filter && { where: args?.filter }),
90
+ transaction: false,
91
+ })
92
+
93
+ return result.map((event: MachineStateInfoEntity) => MachineStateStore.machineInfoFrom(event))
94
+ }
95
+
96
+ async getMachineState(args: StoreMachineStateGetArgs): Promise<StoreMachineStateInfo> {
97
+ const connection: DataSource = await this._dbConnection
98
+ debug('getMachineState', args)
99
+ return connection.getRepository(MachineStateInfoEntity).findOneOrFail({ where: { instanceId: args.instanceId } })
100
+ }
101
+
102
+ async deleteMachineState(args: StoreMachineStateDeleteArgs): Promise<boolean> {
103
+ debug(`Executing deleteMachineState query with id: ${args.instanceId}`)
104
+ if (!args.instanceId) {
105
+ throw new Error('No instanceId parameter is provided.')
106
+ }
107
+ try {
108
+ const connection: DataSource = await this._dbConnection
109
+
110
+ const result = await connection.getRepository(MachineStateInfoEntity).delete(args.instanceId)
111
+ return result.affected != null && result.affected > 0
112
+ } catch (error) {
113
+ debug(`Error deleting state: ${error}`)
114
+ return false
115
+ }
116
+ }
117
+
118
+ async deleteExpiredMachineStates(args: StoreMachineStateDeleteExpiredArgs): Promise<number> {
119
+ const { machineName, tenantId, deleteDoneStates } = args
120
+ debug(`Executing deleteExpiredMachineStates query with params: ${JSON.stringify(args)}`)
121
+ try {
122
+ const connection: DataSource = await this._dbConnection
123
+
124
+ const deleteCriteria: FindOptionsWhere<MachineStateInfoEntity> = {
125
+ ...(machineName && { machineName }),
126
+ ...(tenantId && { tenantId }),
127
+ // When deleteOnDone state is set we only look at completedAt, in other cases we compare current time with expiresAt
128
+ ...(!deleteDoneStates && { expiresAt: LessThan(new Date()) }),
129
+ ...(deleteDoneStates && { completedAt: Not(IsNull()) }),
130
+ }
131
+ const result = await connection.getRepository(MachineStateInfoEntity).delete(deleteCriteria)
132
+ return result.affected ?? 0
133
+ } catch (error) {
134
+ debug(`Error deleting machine info: ${error}`)
135
+ return Promise.reject(new Error(`Error deleting expired machine states for machine type ${machineName}`))
136
+ }
137
+ }
138
+
139
+ protected static machineInfoFrom = (machineStateInfoEntity: MachineStateInfoEntity): StoreMachineStateInfo => {
140
+ // We are making sure no entity function get copied
141
+ return JSON.parse(JSON.stringify(machineStateInfoEntity))
142
+ }
143
+
144
+ static machineStateInfoEntityFrom = (machineStateInfo: StoreMachineStateInfo | StoreMachineStatePersistArgs): MachineStateInfoEntity => {
145
+ const entity = new MachineStateInfoEntity()
146
+ Object.assign(entity, machineStateInfo)
147
+ return entity
148
+ }
149
+ }
@@ -1,66 +1,66 @@
1
- import { DatabaseType, MigrationInterface, QueryRunner } from 'typeorm'
2
- import Debug from 'debug'
3
- import { CreateContacts1659463079428 } from '../postgres/1659463079428-CreateContacts'
4
- import { CreateContacts1659463069549 } from '../sqlite/1659463069549-CreateContacts'
5
-
6
- const debug: Debug.Debugger = Debug('sphereon:ssi-sdk:migrations')
7
-
8
- export class CreateContacts1659463079429 implements MigrationInterface {
9
- name = 'CreateContacts1659463079429'
10
-
11
- public async up(queryRunner: QueryRunner): Promise<void> {
12
- debug('migration: creating contacts tables')
13
- const dbType: DatabaseType = queryRunner.connection.driver.options.type
14
-
15
- switch (dbType) {
16
- case 'postgres': {
17
- debug('using postgres migration file')
18
- const mig: CreateContacts1659463079428 = new CreateContacts1659463079428()
19
- await mig.up(queryRunner)
20
- debug('Migration statements executed')
21
- return
22
- }
23
- case 'sqlite':
24
- case 'expo':
25
- case 'react-native': {
26
- debug('using sqlite/react-native migration file')
27
- const mig: CreateContacts1659463069549 = new CreateContacts1659463069549()
28
- await mig.up(queryRunner)
29
- debug('Migration statements executed')
30
- return
31
- }
32
- default:
33
- return Promise.reject(
34
- `Migrations are currently only supported for sqlite, react-native, expo and postgres. Was ${dbType}. Please run your database without migrations and with 'migrationsRun: false' and 'synchronize: true' for now`,
35
- )
36
- }
37
- }
38
-
39
- public async down(queryRunner: QueryRunner): Promise<void> {
40
- debug('migration: reverting contacts tables')
41
- const dbType: DatabaseType = queryRunner.connection.driver.options.type
42
-
43
- switch (dbType) {
44
- case 'postgres': {
45
- debug('using postgres migration file')
46
- const mig: CreateContacts1659463079428 = new CreateContacts1659463079428()
47
- await mig.down(queryRunner)
48
- debug('Migration statements executed')
49
- return
50
- }
51
- case 'sqlite':
52
- case 'expo':
53
- case 'react-native': {
54
- debug('using sqlite/react-native migration file')
55
- const mig: CreateContacts1659463069549 = new CreateContacts1659463069549()
56
- await mig.down(queryRunner)
57
- debug('Migration statements executed')
58
- return
59
- }
60
- default:
61
- return Promise.reject(
62
- `Migrations are currently only supported for sqlite, react-native, expo and postgres. Was ${dbType}. Please run your database without migrations and with 'migrationsRun: false' and 'synchronize: true' for now`,
63
- )
64
- }
65
- }
66
- }
1
+ import { DatabaseType, MigrationInterface, QueryRunner } from 'typeorm'
2
+ import Debug from 'debug'
3
+ import { CreateContacts1659463079428 } from '../postgres/1659463079428-CreateContacts'
4
+ import { CreateContacts1659463069549 } from '../sqlite/1659463069549-CreateContacts'
5
+
6
+ const debug: Debug.Debugger = Debug('sphereon:ssi-sdk:migrations')
7
+
8
+ export class CreateContacts1659463079429 implements MigrationInterface {
9
+ name = 'CreateContacts1659463079429'
10
+
11
+ public async up(queryRunner: QueryRunner): Promise<void> {
12
+ debug('migration: creating contacts tables')
13
+ const dbType: DatabaseType = queryRunner.connection.driver.options.type
14
+
15
+ switch (dbType) {
16
+ case 'postgres': {
17
+ debug('using postgres migration file')
18
+ const mig: CreateContacts1659463079428 = new CreateContacts1659463079428()
19
+ await mig.up(queryRunner)
20
+ debug('Migration statements executed')
21
+ return
22
+ }
23
+ case 'sqlite':
24
+ case 'expo':
25
+ case 'react-native': {
26
+ debug('using sqlite/react-native migration file')
27
+ const mig: CreateContacts1659463069549 = new CreateContacts1659463069549()
28
+ await mig.up(queryRunner)
29
+ debug('Migration statements executed')
30
+ return
31
+ }
32
+ default:
33
+ return Promise.reject(
34
+ `Migrations are currently only supported for sqlite, react-native, expo and postgres. Was ${dbType}. Please run your database without migrations and with 'migrationsRun: false' and 'synchronize: true' for now`,
35
+ )
36
+ }
37
+ }
38
+
39
+ public async down(queryRunner: QueryRunner): Promise<void> {
40
+ debug('migration: reverting contacts tables')
41
+ const dbType: DatabaseType = queryRunner.connection.driver.options.type
42
+
43
+ switch (dbType) {
44
+ case 'postgres': {
45
+ debug('using postgres migration file')
46
+ const mig: CreateContacts1659463079428 = new CreateContacts1659463079428()
47
+ await mig.down(queryRunner)
48
+ debug('Migration statements executed')
49
+ return
50
+ }
51
+ case 'sqlite':
52
+ case 'expo':
53
+ case 'react-native': {
54
+ debug('using sqlite/react-native migration file')
55
+ const mig: CreateContacts1659463069549 = new CreateContacts1659463069549()
56
+ await mig.down(queryRunner)
57
+ debug('Migration statements executed')
58
+ return
59
+ }
60
+ default:
61
+ return Promise.reject(
62
+ `Migrations are currently only supported for sqlite, react-native, expo and postgres. Was ${dbType}. Please run your database without migrations and with 'migrationsRun: false' and 'synchronize: true' for now`,
63
+ )
64
+ }
65
+ }
66
+ }