-
Notifications
You must be signed in to change notification settings - Fork 0
/
entityIndexStorage.ts
657 lines (548 loc) · 17.7 KB
/
entityIndexStorage.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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
/* eslint-disable @typescript-eslint/no-empty-function */
import path from 'node:path'
import {
StorageBatch,
StorageCommonOptions,
StorageGetOptions,
StoragePutOptions,
} from './baseStorage.js'
import { LevelStorage, LevelStorageOptions } from './levelStorage.js'
import {
KeySchema,
StorageKeyStream,
StorageStream,
StorageEntry,
StorageValueStream,
Stringifable,
} from './types.js'
import { StreamFilter, StreamMap } from '../utils/stream.js'
import { Mutex } from '../utils/index.js'
export type EntityIndexStorageOptions<Entity> = LevelStorageOptions<
string | Entity
> & {
name: string
sublevel?: string
key: KeySchema<Entity>
entityStore?: EntityIndexStorage<Entity, Entity>
count?: boolean
}
export type EntityIndexStorageInvokeOptions = StorageCommonOptions & {
atomic?: boolean
}
export type EntityIndexStorageCallOptions = EntityIndexStorageInvokeOptions
export type EntityIndexStorageSaveOptions<V> = StoragePutOptions<string, V> &
EntityIndexStorageInvokeOptions & {
count?: number
}
export type EntityIndexStorageRemoveOptions<V> =
EntityIndexStorageSaveOptions<V>
export type EntityIndexStorageGetStreamOptions<V> = StorageGetOptions<
string,
V
> &
EntityIndexStorageInvokeOptions
export class EntityIndexStorage<
Entity,
Returned extends Entity | string = string,
> {
static keyValueDelimiter = '|'
// @note: https://docs.solana.com/es/cli/transfer-tokens#receive-tokens
// The public key is a long string of base58 characters. Its length varies from 32 to 44 characters.
static AddressLength = 44
// @note: Timestamps in millis take 13 chars
static TimestampLength = 13
static VariableLength = 0
// @note: Refactor
// @note: 20 bytes (40 hex chars + 2 chars for "0x" prefix) = 42
static EthereumAddressLength = 42
protected self: typeof EntityIndexStorage
protected noopMutex = Promise.resolve((): void => {})
protected count = 0
constructor(
protected options: EntityIndexStorageOptions<Entity>,
protected atomicOpMutex: Mutex = new Mutex(),
protected storage: LevelStorage<string | Entity> = new LevelStorage({
...options,
path: path.join(options.path, options.name),
}),
) {
this.self = this.constructor as typeof EntityIndexStorage
this.init()
}
async init(): Promise<void> {
const release = await this.getAtomicOpMutex(true)
const { count, sublevel } = this.options
try {
if (count) {
const allKeys = this.storage.getAllKeys({ sublevel })
for await (const _ of allKeys) {
this.count++
}
}
} finally {
release()
}
}
async getCount(options?: EntityIndexStorageCallOptions): Promise<number> {
if (!this.options.count) throw new Error('Count option not configured')
const release = await this.getAtomicOpMutex(options?.atomic)
try {
return this.count
} finally {
release()
}
}
getBatch(): StorageBatch<string, string | Entity> {
return this.storage.getBatch()
}
async getAll(
options?: EntityIndexStorageGetStreamOptions<Returned>,
): Promise<StorageStream<string, Returned>> {
return this.getAllFromTo(undefined, undefined, options)
}
async getAllKeys(
options?: EntityIndexStorageGetStreamOptions<Returned>,
): Promise<StorageKeyStream<string>> {
const stream = await this.getAll(options)
return stream.pipe(new StreamMap(this.mapItemToKey.bind(this)))
}
async getAllValues(
options?: EntityIndexStorageGetStreamOptions<Returned>,
): Promise<StorageValueStream<Returned>> {
const stream = await this.getAll(options)
return stream.pipe(new StreamMap(this.mapItemToValue.bind(this)))
}
async getFirstKey(
options?: EntityIndexStorageCallOptions,
): Promise<string | undefined> {
return this.getFirstKeyFromTo(undefined, undefined, options)
}
async getLastKey(
options?: EntityIndexStorageCallOptions,
): Promise<string | undefined> {
return this.getLastKeyFromTo(undefined, undefined, options)
}
async getFirstValue(
options?: EntityIndexStorageCallOptions,
): Promise<Returned | undefined> {
return this.getFirstValueFromTo(undefined, undefined, options)
}
async getLastValue(
options?: EntityIndexStorageCallOptions,
): Promise<Returned | undefined> {
return this.getLastValueFromTo(undefined, undefined, options)
}
async getAllFromTo(
start?: Stringifable[],
end?: Stringifable[],
options: EntityIndexStorageGetStreamOptions<Returned> = { reverse: true },
): Promise<StorageStream<string, Returned>> {
const release = await this.getAtomicOpMutex(options?.atomic)
try {
const from = this.mapKeyChunks(start, false)
const to = this.mapKeyChunks(end, true)
const opts = { ...options, sublevel: this.options.sublevel }
if (options.debug) {
console.log(`
dbDebug:
getAllFromTo: ${this.options.name} [${opts.sublevel}]
from: ${from}
to: ${to}
`)
}
const stream = this.storage.getAllFromTo(from, to, opts)
return this.mapItems(stream, options)
} finally {
release()
}
}
async getAllKeysFromTo(
start?: Stringifable[],
end?: Stringifable[],
options?: EntityIndexStorageGetStreamOptions<Returned>,
): Promise<StorageKeyStream<string>> {
const stream = await this.getAllFromTo(start, end, options)
return stream.pipe(new StreamMap(this.mapItemToKey.bind(this)))
}
async getAllValuesFromTo(
start?: Stringifable[],
end?: Stringifable[],
options?: EntityIndexStorageGetStreamOptions<Returned>,
): Promise<StorageValueStream<Returned>> {
const stream = await this.getAllFromTo(start, end, options)
return stream.pipe(new StreamMap(this.mapItemToValue.bind(this)))
}
async getFirstItemFromTo(
start?: Stringifable[],
end?: Stringifable[],
options?: EntityIndexStorageCallOptions,
): Promise<StorageEntry<string, Returned> | undefined> {
const release = await this.getAtomicOpMutex(options?.atomic)
try {
const from = this.mapKeyChunks(start, false)
const to = this.mapKeyChunks(end, true)
const opts = { ...options, sublevel: this.options.sublevel }
if (options?.debug) {
console.log(`
dbDebug:
getFirstItemFromTo: ${this.options.name} [${opts.sublevel}]
from: ${from}
to: ${to}
`)
}
const item = await this.storage.getFirstItemFromTo(from, to, opts)
if (!item) return
return this.mapItem(options, item)
} finally {
release()
}
}
async getFirstKeyFromTo(
start?: Stringifable[],
end?: Stringifable[],
options?: EntityIndexStorageCallOptions,
): Promise<string | undefined> {
const item = await this.getFirstItemFromTo(start, end, options)
return item?.key
}
async getFirstValueFromTo(
start?: Stringifable[],
end?: Stringifable[],
options?: EntityIndexStorageCallOptions,
): Promise<Returned | undefined> {
const item = await this.getFirstItemFromTo(start, end, options)
return item?.value
}
async getLastItemFromTo(
start?: Stringifable[],
end?: Stringifable[],
options?: EntityIndexStorageCallOptions,
): Promise<StorageEntry<string, Returned> | undefined> {
const release = await this.getAtomicOpMutex(options?.atomic)
try {
const from = this.mapKeyChunks(start, false)
const to = this.mapKeyChunks(end, true)
const opts = { ...options, sublevel: this.options.sublevel }
if (options?.debug) {
console.log(`
dbDebug:
getLastItemFromTo: ${this.options.name} [${opts.sublevel}]
from: ${from}
to: ${to}
`)
}
const item = await this.storage.getLastItemFromTo(from, to, opts)
if (!item) return
return this.mapItem(options, item)
} finally {
release()
}
}
async getLastKeyFromTo(
start?: Stringifable[],
end?: Stringifable[],
options?: EntityIndexStorageCallOptions,
): Promise<string | undefined> {
const item = await this.getLastItemFromTo(start, end, options)
return item?.key
}
async getLastValueFromTo(
start?: Stringifable[],
end?: Stringifable[],
options?: EntityIndexStorageCallOptions,
): Promise<Returned | undefined> {
const item = await this.getLastItemFromTo(start, end, options)
return item?.value
}
async get(
key: string | Stringifable[],
options?: EntityIndexStorageCallOptions,
): Promise<Returned | undefined> {
const release = await this.getAtomicOpMutex(options?.atomic)
try {
const { entityStore } = this.options
if (
entityStore &&
typeof key === 'string' &&
key.indexOf(this.self.keyValueDelimiter) >= 0
) {
const mappedItem = await this.mapItem(options, { key, value: '' })
return mappedItem?.value
}
const innerKey = this.storage.composeKey(
Array.isArray(key) ? (this.mapKeyChunks(key, true) as string[]) : key,
)
const value = await this.storage.get(innerKey, {
sublevel: this.options.sublevel,
})
if (!value) return
const item = await this.mapItem(options, { key: innerKey, value })
return item?.value
} finally {
release()
}
}
async getMany(
keys: string[] | Stringifable[][],
options?: EntityIndexStorageCallOptions,
): Promise<Returned[]> {
const release = await this.getAtomicOpMutex(options?.atomic)
try {
const innerKeys = keys.map((key) =>
this.storage.composeKey(
Array.isArray(key) ? (this.mapKeyChunks(key, true) as string[]) : key,
),
)
const values = await this.storage.getMany(innerKeys, {
sublevel: this.options.sublevel,
})
if (!values || !values.length) return []
const items = await this.mapManyItem(
options,
values.map((v, i) => ({ key: innerKeys[i], value: v })),
)
return items.map((item) => item.value)
} finally {
release()
}
}
async exists(
key: string,
options?: EntityIndexStorageCallOptions,
): Promise<boolean> {
const release = await this.getAtomicOpMutex(options?.atomic)
try {
return this.storage.exists(key, { sublevel: this.options.sublevel })
} finally {
release()
}
}
async save(
entities: Entity | Entity[],
options?: EntityIndexStorageSaveOptions<string | Entity>,
): Promise<void> {
const release = await this.getAtomicOpMutex(options?.atomic)
try {
entities = Array.isArray(entities) ? entities : [entities]
const items = entities.flatMap((entity) => {
return this.getKeys(entity).map(
(key) =>
({ key, value: this.getValue(entity) } as StorageEntry<
string,
Entity
>),
)
})
const keys = items.map(({ key }) => key)
const countDelta = await this.getCountDelta(keys, false, options?.count)
await this.storage.save(items, {
sublevel: this.options.sublevel,
batch: options?.batch,
})
this.count += countDelta
} finally {
release()
}
}
async remove(
entities: Entity | Entity[],
options?: EntityIndexStorageRemoveOptions<string | Entity>,
): Promise<void> {
const release = await this.getAtomicOpMutex(options?.atomic)
try {
entities = Array.isArray(entities) ? entities : [entities]
const items = entities
.flatMap((entity) => this.getKeys(entity))
.filter((key) => key !== undefined) as string[]
const countDelta = await this.getCountDelta(items, true, options?.count)
await this.storage.remove(items, {
sublevel: this.options.sublevel,
batch: options?.batch,
})
this.count -= countDelta
} finally {
release()
}
}
getKeys(entity: Entity): string[] {
return this.getAllSubkeysStartingFrom(entity, 0)
}
protected getAllSubkeysStartingFrom(
entity: Entity,
chunk = 0,
prevSubkeys: string[] = [],
): string[] {
const schema = this.options.key[chunk]
if (!schema) return []
const key = schema.get(entity, prevSubkeys)
const keys = Array.isArray(key) ? key : [key]
return keys
.map((key) => ({ key, keyChunk: this.getKeyChunk(key, chunk) }))
.filter(
(item): item is { key: string; keyChunk: string } =>
item.keyChunk !== undefined,
)
.flatMap(({ key, keyChunk }) => {
const nextKeyChunks = this.getAllSubkeysStartingFrom(
entity,
chunk + 1,
prevSubkeys.concat(key),
)
if (nextKeyChunks.length) {
return nextKeyChunks.map(
(nextKeyChunk) =>
`${keyChunk}${LevelStorage.keyChunkDelimiter}${nextKeyChunk}`,
)
}
const { entityStore } = this.options
if (entityStore) {
const [primaryKey] = entityStore.getKeys(entity)
keyChunk = `${keyChunk}${this.self.keyValueDelimiter}${primaryKey}`
}
return [keyChunk]
})
}
protected getKeyChunk(key: Stringifable, chunk = 0): string | undefined {
if (key === undefined || key === null) return
const schema = this.options.key[chunk]
if (!schema)
throw new Error(
`Key chunk schema not found for ${this.options.sublevel} key (chunk ${chunk})`,
)
const { length, padEnd } = schema
const { minChar, maxChar } = LevelStorage
key = String(key)
key =
key === minChar
? key.padEnd(length, minChar)
: key === maxChar
? key.padEnd(length, maxChar)
: key
key =
length !== this.self.VariableLength && key.length > length
? padEnd
? key.substring(0, length)
: key.substring(key.length - length, key.length)
: key
key =
key.length < length
? key[padEnd ? 'padEnd' : 'padStart'](length, minChar)
: key
return key
}
protected getValue(entity: Entity): Entity | string {
const { entityStore } = this.options
if (entityStore) {
// @note: Do not waste space storing the entity key as value
// as it is already being stored as part of the index key
return ''
}
return entity
}
protected mapKeyChunks(
chunks?: Stringifable[],
isEnd = false,
): string[] | undefined {
if (!chunks) return
return chunks
.map((value, i) => {
if ((value === undefined || value === null) && i < chunks.length - 1) {
const { minChar, maxChar } = LevelStorage
value = isEnd ? maxChar : minChar
}
return this.getKeyChunk(value, i)
})
.filter((chunk): chunk is string => chunk !== undefined && chunk !== null)
}
protected mapItems(
stream: StorageStream<string, Entity | string>,
options: StorageCommonOptions,
): StorageStream<string, Returned> {
return stream
.pipe(new StreamMap(this.mapItem.bind(this, options)))
.pipe(new StreamFilter(this.filterItem.bind(this)))
}
protected async mapItem(
options: EntityIndexStorageInvokeOptions | undefined,
item: StorageEntry<string, string | Entity>,
): Promise<StorageEntry<string, Returned> | undefined> {
const { entityStore } = this.options
if (entityStore) {
const { key } = item
const [, entityKey] = key.split(this.self.keyValueDelimiter)
const value = await entityStore.get(entityKey)
if (options?.debug) {
console.log(`
dbDebug:
mapItem: ${this.options.name} [${options.sublevel}]
indexKey: ${key}
entityKey: ${entityKey}
hasValue: ${!!value}
`)
}
if (value === undefined && options?.atomic) {
console.log(
`🟥 Inconsistent lookup key [${entityKey}] from key (${key}) on index [${this.options.sublevel}]`,
)
return
}
return { key: entityKey, value: value as Returned }
}
return item as StorageEntry<string, Returned>
}
protected async mapManyItem(
options: EntityIndexStorageGetStreamOptions<Returned> | undefined,
items: StorageEntry<string, string | Entity>[],
): Promise<StorageEntry<string, Returned>[]> {
const { entityStore } = this.options
if (entityStore) {
const entityKeys = items
.map((item) => item.key.split(this.self.keyValueDelimiter)?.[1])
.filter((k) => !!k)
const values = await entityStore.getMany(entityKeys)
if ((!values || !values.length) && options?.atomic) {
console.log(
`🟥 Inconsistent lookup keys from key on index [${this.options.sublevel}]`,
)
return []
}
return values.map((v, i) => ({
key: entityKeys[i],
value: v as unknown as Returned,
}))
}
return items as StorageEntry<string, Returned>[]
}
protected async filterItem(
item: StorageEntry<string, Entity> | undefined,
): Promise<boolean> {
return item !== undefined
}
protected mapItemToKey(item: StorageEntry<string, Returned>): string {
return item.key
}
protected mapItemToValue(item: StorageEntry<string, Returned>): Returned {
return item.value
}
protected getAtomicOpMutex(atomic = false): Promise<() => void> {
return atomic ? this.atomicOpMutex.acquire() : this.noopMutex
}
protected async getCountDelta(
items: string[],
isDelete: boolean,
fixedCount?: number,
): Promise<number> {
if (!this.options.count) return 0
if (fixedCount !== undefined) return fixedCount
const storedCount = (
await this.storage.getMany(items, { sublevel: this.options.sublevel })
).length
return isDelete ? storedCount : items.length - storedCount
}
async backup(): Promise<void> {
return this.storage.backup()
}
async restore(): Promise<boolean> {
return this.storage.restore()
}
}