generated from TBD54566975/tbd-project-template
-
Notifications
You must be signed in to change notification settings - Fork 100
Expand file tree
/
Copy pathlevel-wrapper.ts
More file actions
272 lines (211 loc) · 8.61 KB
/
level-wrapper.ts
File metadata and controls
272 lines (211 loc) · 8.61 KB
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
import type { AbstractBatchOperation, AbstractDatabaseOptions, AbstractIteratorOptions, AbstractLevel } from 'abstract-level';
import { executeUnlessAborted } from '../utils/abort.js';
import { Level } from 'level';
export type CreateLevelDatabaseOptions<V> = AbstractDatabaseOptions<string, V>;
export type LevelDatabase<V> = AbstractLevel<string | Buffer | Uint8Array, string, V>;
export async function createLevelDatabase<V>(location: string, options?: CreateLevelDatabaseOptions<V>): Promise<LevelDatabase<V>> {
// Only import `'level'` when it's actually necessary (i.e. only when the default `createLevelDatabase` is used).
// Overriding `createLevelDatabase` will prevent this from happening.
return new Level(location, { ...options, keyEncoding: 'utf8' });
}
export interface LevelWrapperOptions {
signal?: AbortSignal;
}
export type LevelWrapperBatchOperation<V> = AbstractBatchOperation<LevelDatabase<V>, string, V>;
export type LevelWrapperIteratorOptions<V> = AbstractIteratorOptions<string, V>;
// `Level` works in Node.js 12+ and Electron 5+ on Linux, Mac OS, Windows and FreeBSD, including any
// future Node.js and Electron release thanks to Node-API, including ARM platforms like Raspberry Pi
// and Android, as well as in Chrome, Firefox, Edge, Safari, iOS Safari and Chrome for Android.
export class LevelWrapper<V> {
config: LevelWrapperConfig<V>;
db: LevelDatabase<V>;
/**
* @param config.location - must be a directory path (relative or absolute) where `Level`` will
* store its files, or in browsers, the name of the {@link https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase `IDBDatabase`}
* to be opened.
*/
constructor(config: LevelWrapperConfig<V>, db?: LevelDatabase<V>) {
this.config = {
createLevelDatabase,
...config
};
this.db = db!;
}
async open(): Promise<void> {
await this.createLevelDatabase();
// `db.open()` is automatically called by the database constructor. We may need to call it explicitly
// in order to explicitly catch an error that would otherwise not surface until another method
// like `db.get()` is called. Once `db.open()` has then been called, any read & write
// operations will again be queued internally until opening has finished.
switch (this.db.status) {
// If db is open, we are done.
case 'open':
return;
// If db is still opening, wait until the 'open' event is emitted
case 'opening':
return new Promise((resolve) => {
this.db.once('open', resolve);
});
// If db is closing, wait until it is closed then await `db.open()`
case 'closing':
return new Promise((resolve, reject) => {
const onClosed = (): void => {
// Make sure that errors from `db.open()` propogate up
this.db.open().then(resolve).catch(reject);;
};
this.db.once('closed', onClosed);
});
// If db is closed, `db.open`
case 'closed':
return this.db.open();
}
}
async close(): Promise<void> {
if (!this.db) {
return;
}
switch (this.db.status) {
// If db is open, we `db.close`.
case 'open':
return this.db.close();
// If db is still opening, wait until it is open then await `db.close()`
case 'opening':
return new Promise((resolve, reject) => {
const onOpen = (): void => {
// Make sure that errors from `db.open()` propogate up
this.db.close().then(resolve).catch(reject);;
};
this.db.once('open', onOpen);
});
// If db is closing, wait until the 'closed' event is emitted
case 'closing':
return new Promise((resolve) => {
this.db.once('closed', resolve);
});
// If db is closed, we are done
case 'closed':
return;
}
}
async partition(name: string): Promise<LevelWrapper<V>> {
await this.createLevelDatabase();
return new LevelWrapper(this.config, this.db.sublevel(name, {
keyEncoding : 'utf8',
valueEncoding : this.config.valueEncoding
}));
}
async get(key: string, options?: LevelWrapperOptions): Promise<V|undefined>{
options?.signal?.throwIfAborted();
await executeUnlessAborted(this.createLevelDatabase(), options?.signal);
try {
const value = await executeUnlessAborted(this.db.get(String(key)), options?.signal);
return value;
} catch (error) {
const e = error as { code: string };
// `Level`` throws an error if the key is not present. Return `undefined` in this case.
if (e.code === 'LEVEL_NOT_FOUND') {
return undefined;
} else {
throw error;
}
}
}
async has(key: string, options?: LevelWrapperOptions): Promise<boolean> {
return !! await this.get(key, options);
}
async * keys(options?: LevelWrapperOptions): AsyncGenerator<string> {
options?.signal?.throwIfAborted();
await executeUnlessAborted(this.createLevelDatabase(), options?.signal);
for await (const key of this.db.keys()) {
options?.signal?.throwIfAborted();
yield key;
}
}
async * iterator(iteratorOptions?: LevelWrapperIteratorOptions<V>, options?: LevelWrapperOptions): AsyncGenerator<[string, V]> {
options?.signal?.throwIfAborted();
await executeUnlessAborted(this.createLevelDatabase(), options?.signal);
for await (const entry of this.db.iterator(iteratorOptions!)) {
options?.signal?.throwIfAborted();
yield entry;
}
}
async put(key: string, value: V, options?: LevelWrapperOptions): Promise<void> {
options?.signal?.throwIfAborted();
await executeUnlessAborted(this.createLevelDatabase(), options?.signal);
return executeUnlessAborted(this.db.put(String(key), value), options?.signal);
}
async delete(key: string, options?: LevelWrapperOptions): Promise<void> {
options?.signal?.throwIfAborted();
await executeUnlessAborted(this.createLevelDatabase(), options?.signal);
return executeUnlessAborted(this.db.del(String(key)), options?.signal);
}
async isEmpty(options?: LevelWrapperOptions): Promise<boolean> {
for await (const _key of this.keys(options)) {
return false;
}
return true;
}
async clear(): Promise<void> {
await this.createLevelDatabase();
await this.db.clear();
await this.compactUnderlyingStorage();
}
async batch(operations: Array<LevelWrapperBatchOperation<V>>, options?: LevelWrapperOptions): Promise<void> {
options?.signal?.throwIfAborted();
await executeUnlessAborted(this.createLevelDatabase(), options?.signal);
return executeUnlessAborted(this.db.batch(operations), options?.signal);
}
/**
* Wraps the given LevelWrapperBatchOperation as an operation for the specified partition.
*/
createPartitionOperation(partitionName: string, operation: LevelWrapperBatchOperation<V>): LevelWrapperBatchOperation<V> {
return { ...operation, sublevel: this.db.sublevel(partitionName, {
keyEncoding : 'utf8',
valueEncoding : this.config.valueEncoding
}) };
}
private async compactUnderlyingStorage(options?: LevelWrapperOptions): Promise<void> {
options?.signal?.throwIfAborted();
await executeUnlessAborted(this.createLevelDatabase(), options?.signal);
const range = this.sublevelRange;
if (!range) {
return;
}
// additional methods are only available on the root API instance
const root = this.root;
if (root.db.supports.additionalMethods.compactRange) {
return executeUnlessAborted((root.db as any).compactRange?.(...range), options?.signal);
}
}
/**
* Gets the min and max key value of this partition.
*/
private get sublevelRange(): [ string, string ] | undefined {
const prefix = (this.db as any).prefix as string;
if (!prefix) {
return undefined;
}
// derive an exclusive `maxKey` by changing the last prefix character to the immediate succeeding character in unicode
// (which matches how `abstract-level` creates a `boundary`)
const maxKey = prefix.slice(0, -1) + String.fromCharCode(prefix.charCodeAt(prefix.length - 1) + 1);
const minKey = prefix;
return [minKey, maxKey];
}
private get root(): LevelWrapper<V> {
let db = this.db;
for (const parent = (db as any).db; parent && parent !== db; ) {
db = parent;
}
return new LevelWrapper(this.config, db);
}
private async createLevelDatabase(): Promise<void> {
this.db ??= await this.config.createLevelDatabase!<V>(this.config.location, {
keyEncoding : 'utf8',
valueEncoding : this.config.valueEncoding
});
}
}
export type LevelWrapperConfig<V> = CreateLevelDatabaseOptions<V> & {
location: string,
createLevelDatabase?: typeof createLevelDatabase,
};