-
Notifications
You must be signed in to change notification settings - Fork 0
/
entityStorage.ts
213 lines (177 loc) · 6.1 KB
/
entityStorage.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
/* eslint-disable @typescript-eslint/no-empty-function */
import path from 'node:path'
import { Mutex } from '../utils/index.js'
import { StorageGetOptions } from './baseStorage.js'
import {
EntityIndexStorage,
EntityIndexStorageOptions,
} from './entityIndexStorage.js'
import { LevelStorage, StorageFilterFn, StorageMapFn } from './levelStorage.js'
import {
EntityUpdateCheckFn,
EntityUpdateOp,
PrimaryKeySchema,
} from './types.js'
export type EntityStorageIndexOptions<Entity> = Omit<
EntityIndexStorageOptions<Entity>,
'path' | 'entityStore'
> & {
name: string
}
export type EntityStorageOptions<Entity> = EntityIndexStorageOptions<Entity> & {
name: string
path: string
key: PrimaryKeySchema<Entity>
indexes?: EntityStorageIndexOptions<Entity>[]
filterFn?: StorageFilterFn<Entity>
mapFn?: StorageMapFn<Entity>
updateCheckFn?: EntityUpdateCheckFn<Entity>
deleteCheckFn?: EntityUpdateCheckFn<Entity>
count?: boolean
}
export type EntityStorageInvokeOptions = { atomic?: boolean }
export type EntityStorageCallOptions = EntityStorageInvokeOptions
export type EntityStorageGetStreamOptions<K, V> = StorageGetOptions<K, V> &
EntityStorageInvokeOptions
/**
* Defines the storage handler class for different entities.
*/
export class EntityStorage<Entity> extends EntityIndexStorage<Entity, Entity> {
protected byIndex: Record<string, EntityIndexStorage<Entity, Entity>> = {}
protected atomicOpMutex: Mutex
protected noopMutex = Promise.resolve((): void => {})
static AddressLength = EntityIndexStorage.AddressLength
static TimestampLength = EntityIndexStorage.TimestampLength
static VariableLength = EntityIndexStorage.VariableLength
static EthereumAddressLength = EntityIndexStorage.EthereumAddressLength
constructor(
protected options: EntityStorageOptions<Entity>,
protected StorageClass: typeof LevelStorage = LevelStorage,
) {
const atomicOpMutex = new Mutex()
const basePath = path.join(options.path, options.name)
const storage = new LevelStorage({ ...options, path: basePath })
const opts = { ...options, sublevel: 'main' }
super(opts, atomicOpMutex, storage)
this.options = opts
this.atomicOpMutex = atomicOpMutex
const { indexes } = this.options
if (!indexes) return
for (const index of indexes) {
if (index.name === 'main')
throw new Error('entity index name is reserved')
this.byIndex[index.name] = new EntityIndexStorage(
{
...options,
sublevel: index.name,
key: index.key,
entityStore: this,
},
this.atomicOpMutex,
storage,
)
}
}
useIndex(indexName?: string): EntityIndexStorage<Entity, Entity> {
if (!indexName) return this
const db = this.byIndex[indexName]
if (db) return db
throw new Error(
`Invalid index "${indexName}" on "${this.options.name}" entity store`,
)
}
async save(entities: Entity | Entity[]): Promise<void> {
const release = await this.getAtomicOpMutex(true)
const batch = this.getBatch()
try {
entities = Array.isArray(entities) ? entities : [entities]
const { toRemove, toUpdate } = await this.getEntityGroups(
entities,
EntityUpdateOp.Update,
)
// @note: Order of operations is relevant for not causing inconsistent indexes lookup keys
// and race conditions issues:
// 1. Save Entity by id
// 2. Save Indexes
const count = toUpdate.length - toRemove.length
await super.save(toUpdate, { count, batch })
await Promise.all(
Object.values(this.byIndex).map(async (byIndex) => {
// @note: Improve performance by storing in a prefixed-sublevel
// the reverse lookup keys on each index database
await byIndex.remove(toRemove, { batch })
await byIndex.save(toUpdate, { batch })
}),
)
await batch.write()
} finally {
await batch.close()
release()
}
}
async remove(entities: Entity | Entity[]): Promise<void> {
const release = await this.getAtomicOpMutex(true)
const batch = this.getBatch()
try {
entities = Array.isArray(entities) ? entities : [entities]
const { toRemove } = await this.getEntityGroups(
entities,
EntityUpdateOp.Delete,
)
// @note: Order of operations is relevant for not causing inconsistent indexes lookup keys
// and race conditions issues:
// 1. Remove Indexes
// 2. Remove Entity by id
await Promise.all(
Object.values(this.byIndex).map(async (byIndex) => {
// @note: Improve performance by storing in a prefixed-sublevel
// the reverse lookup keys on each index database
await byIndex.remove(toRemove, { batch })
}),
)
const count = toRemove.length
await super.remove(toRemove, { count, batch })
await batch.write()
} finally {
await batch.close()
release()
}
}
protected async getEntityGroups(
entities: Entity[],
op: EntityUpdateOp,
): Promise<{
toUpdate: Entity[]
toRemove: Entity[]
}> {
const toRemove: Map<string, Entity> = new Map()
const toUpdate: Map<string, Entity> = new Map()
const { updateCheckFn } = this.options
for (const entity of entities) {
const [primaryKey] = this.getKeys(entity)
const oldEntity = toUpdate.get(primaryKey) || (await this.get(primaryKey))
if (op === EntityUpdateOp.Update && updateCheckFn) {
op = await updateCheckFn(oldEntity, entity)
}
switch (op) {
case EntityUpdateOp.Update: {
toUpdate.set(primaryKey, entity)
if (oldEntity) toRemove.set(primaryKey, oldEntity)
break
}
case EntityUpdateOp.Delete: {
if (oldEntity) toRemove.set(primaryKey, oldEntity)
break
}
case EntityUpdateOp.Keep: // noopMutex
}
}
return {
toUpdate: Array.from(toUpdate.values()),
toRemove: Array.from(toRemove.values()),
}
}
protected getAtomicOpMutex(atomic = false): Promise<() => void> {
return atomic ? this.atomicOpMutex.acquire() : this.noopMutex
}
}