forked from simpleledger/SLPDB
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.ts
294 lines (255 loc) · 11.3 KB
/
db.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
import { MongoClient, Db as MongoDb } from 'mongodb';
import { DbConfig } from './config';
import { TNATxn } from './tna';
import { GraphTxnDbo, TokenDBObject } from "./interfaces";
import { GraphMap } from './graphmap';
export class Db {
db!: MongoDb;
mongo!: MongoClient;
dbUrl: string;
dbName: string;
config: DbConfig;
constructor({ dbUrl, dbName, config }: { dbUrl: string, dbName: string, config: DbConfig }) {
this.dbUrl = dbUrl;
this.dbName = dbName;
this.config = config;
}
private async checkClientStatus(): Promise<boolean> {
if (!this.mongo) {
this.mongo = await MongoClient.connect(this.dbUrl, {
useNewUrlParser: true, useUnifiedTopology: true, connectTimeoutMS: 300000
});
this.db = this.mongo.db(this.dbName);
return true;
}
return false;
}
async drop() {
await this.db.dropDatabase();
}
async exit() {
await this.mongo.close();
}
async statusUpdate(status: any) {
await this.checkClientStatus();
await this.db.collection('statuses').deleteMany({ "context": status.context });
return await this.db.collection('statuses').insertOne(status);
}
async statusFetch(context: string) {
await this.checkClientStatus();
return await this.db.collection('statuses').findOne({ "context": context });
}
private async tokenInsertReplace(token: any) {
await this.checkClientStatus();
await this.db.collection('tokens').replaceOne({ "tokenDetails.tokenIdHex": token.tokenDetails.tokenIdHex }, token, { upsert: true });
}
async tokenDelete(tokenIdHex: string) {
await this.checkClientStatus();
return await this.db.collection('tokens').deleteMany({ "tokenDetails.tokenIdHex": tokenIdHex });
}
async tokenFetch(tokenIdHex: string): Promise<TokenDBObject|null> {
await this.checkClientStatus();
return await this.db.collection('tokens').findOne({ "tokenDetails.tokenIdHex": tokenIdHex });
}
async tokenFetchAll(): Promise<TokenDBObject[]|null> {
await this.checkClientStatus();
return await this.db.collection('tokens').find({}).toArray();
}
async tokenReset() {
await this.checkClientStatus();
await this.db.collection('tokens').deleteMany({})
.catch(function(err) {
console.log('[ERROR] token collection reset ERR ', err);
throw err;
});
}
async graphItemsUpsert(graph: GraphMap) {
await this.checkClientStatus();
console.time("ToDBO");
let { itemsToUpdate, tokenDbo, txidsToDelete } = GraphMap.toDbos(graph);
console.timeEnd("ToDBO");
for (const i of itemsToUpdate) {
if (txidsToDelete.includes(i.graphTxn.txid)) {
continue;
}
let res = await this.db.collection("graphs").replaceOne({ "tokenDetails.tokenIdHex": i.tokenDetails.tokenIdHex, "graphTxn.txid": i.graphTxn.txid }, i, { upsert: true });
if (res.modifiedCount) {
console.log(`[DEBUG] graphItemsUpsert - modified: ${i.graphTxn.txid}`);
} else if (res.upsertedCount) {
console.log(`[DEBUG] graphItemsUpsert - inserted: ${i.graphTxn.txid}`);
} else {
throw Error(`Graph record was not updated: ${i.graphTxn.txid} (token: ${i.tokenDetails.tokenIdHex})`);
}
}
await this.tokenInsertReplace(tokenDbo);
for (const txid of txidsToDelete) {
await this.db.collection("graphs").deleteMany({ "graphTxn.txid": txid });
await this.db.collection("confirmed").deleteMany({ "tx.h": txid });
await this.db.collection("unconfirmed").deleteMany({ "tx.h": txid });
}
}
async graphDelete(tokenIdHex: string) {
await this.checkClientStatus();
return await this.db.collection('graphs').deleteMany({ "tokenDetails.tokenIdHex": tokenIdHex })
}
async graphItemDelete(txid: string) {
await this.checkClientStatus();
return await this.db.collection('graphs').deleteMany({ "graphTxn.txid": txid });
}
async graphFetch(tokenIdHex: string, lastPrunedHeight?: number): Promise<GraphTxnDbo[]> {
await this.checkClientStatus();
if (lastPrunedHeight) {
return await this.db.collection('graphs').find({
"tokenDetails.tokenIdHex": tokenIdHex,
"$or": [ { "graphTxn._pruneHeight": { "$gt": lastPrunedHeight } }, { "graphTxn._pruneHeight": null }, { "graphTxn.txid": tokenIdHex }]
}).toArray();
} else {
return await this.db.collection('graphs').find({
"tokenDetails.tokenIdHex": tokenIdHex
}).toArray();
}
}
async graphTxnFetch(txid: string): Promise<GraphTxnDbo|null> {
await this.checkClientStatus();
return await this.db.collection('graphs').findOne({ "graphTxn.txid": txid });
}
async graphReset() {
await this.checkClientStatus();
await this.db.collection('graphs').deleteMany({})
.catch(function(err) {
console.log('[ERROR] graphs collection reset ERR ', err)
throw err;
})
}
async unconfirmedInsert(item: TNATxn) {
await this.checkClientStatus();
console.log(`Added unconfirmed: ${item.tx.h}`);
return await this.db.collection('unconfirmed').insertMany([item]);
}
async unconfirmedReset() {
await this.checkClientStatus();
await this.db.collection('unconfirmed').deleteMany({})
.catch(function(err) {
console.log('[ERROR] mempoolreset ERR ', err);
throw err;
})
}
async unconfirmedTxids(): Promise<string[]> {
await this.checkClientStatus();
let res: TNATxn[] = await this.db.collection('unconfirmed').find({}).toArray();
return res.map(u => u.tx.h);
}
async unconfirmedFetch(txid: string): Promise<TNATxn|null> {
await this.checkClientStatus();
let res = await this.db.collection('unconfirmed').findOne({ "tx.h": txid }) as TNATxn;
return res;
}
async unconfirmedDelete(txids: string[]): Promise<number|undefined> {
await this.checkClientStatus();
if (txids.length === 0) {
return 0;
}
let res = (await this.db.collection('unconfirmed').deleteMany({ "$or": txids.map(txid => { return { "tx.h": txid }})})).deletedCount;
return res;
}
async unconfirmedProcessedSlp(): Promise<string[]> {
await this.checkClientStatus();
return (await this.db.collection('unconfirmed').find().toArray()).filter((i:TNATxn) => i.slp);
}
async confirmedFetch(txid: string): Promise<TNATxn|null> {
await this.checkClientStatus();
return await this.db.collection('confirmed').findOne({ "tx.h": txid }) as TNATxn;
}
async confirmedDelete(txid: string): Promise<any> {
await this.checkClientStatus();
return await this.db.collection('confirmed').deleteMany({ "tx.h": txid });
}
async confirmedFetchForReorg(blockIndex: number): Promise<any> {
await this.checkClientStatus();
return await this.db.collection('confirmed').find({ "blk.i": { "$gte": blockIndex }}).toArray();
}
async confirmedDeleteForReorg(blockIndex: number): Promise<any> {
await this.checkClientStatus();
console.log(`[WARN] Deleting all transactions with block greater than or equal to ${blockIndex}.`)
return await this.db.collection('confirmed').deleteMany({ "blk.i": { "$gte": blockIndex }});
}
async confirmedReset() {
await this.checkClientStatus();
await this.db.collection('confirmed').deleteMany({}).catch(function(err) {
console.log('[ERROR] confirmedReset ERR ', err)
throw err;
})
}
async confirmedReplace(items: TNATxn[], blockIndex: number) {
await this.checkClientStatus();
if (items.filter(i => !i.blk).length > 0) {
throw Error("Attempted to add items without BLK property.");
}
if (blockIndex) {
console.log('[INFO] Updating block', blockIndex, 'with', items.length, 'items');
}
for (let i=0; i < items.length; i++) {
await this.db.collection('confirmed').replaceOne({ "tx.h": items[i].tx.h }, items[i], { upsert: true });
}
}
async confirmedIndex() {
await this.checkClientStatus();
console.log('[INFO] * Indexing MongoDB...')
console.time('TotalIndex')
if (this.config.index) {
let collectionNames = Object.keys(this.config.index)
for(let j=0; j<collectionNames.length; j++) {
let collectionName: string = collectionNames[j]
let keys: string[] = this.config.index[collectionName].keys
let fulltext: string[] = this.config.index[collectionName].fulltext
if (keys) {
console.log('[INFO] Indexing keys...')
for(let i=0; i<keys.length; i++) {
let o: { [key:string]: number } = {}
o[keys[i]] = 1
console.time('Index:' + keys[i])
try {
if (keys[i] === 'tx.h') {
await this.db.collection(collectionName).createIndex(o, { unique: true })
//console.log('* Created unique index for ', keys[i])
} else {
await this.db.collection(collectionName).createIndex(o)
//console.log('* Created index for ', keys[i])
}
} catch (e) {
console.log('[ERROR] blockindex error:', e)
throw e;
}
console.timeEnd('Index:' + keys[i])
}
}
if (fulltext && fulltext.length > 0) {
console.log('[INFO] Creating full text index...')
let o: { [key:string]: string } = {}
fulltext.forEach(function(key) {
o[key] = 'text'
})
console.time('Fulltext search for ' + collectionName) //,o)
try {
await this.db.collection(collectionName).createIndex(o, { name: 'fulltext' })
} catch (e) {
console.log('[ERROR] blockindex error:', e)
throw e;
}
console.timeEnd('Fulltext search for ' + collectionName)
}
}
}
//console.log('* Finished indexing MongoDB...')
console.timeEnd('TotalIndex')
try {
let result = await this.db.collection('confirmed').indexInformation(<any>{ full: true }) // <- No MongoSession passed
console.log('* Confirmed Index = ', result)
result = await this.db.collection('unconfirmed').indexInformation(<any>{ full: true }) // <- No MongoSession passed
console.log('* Unonfirmed Index = ', result)
} catch (e) {
console.log('[INFO] * Error fetching index info ', e)
throw e;
}
}
}