-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmigrate-enhanced-verification.js
More file actions
478 lines (406 loc) Β· 13.3 KB
/
Copy pathmigrate-enhanced-verification.js
File metadata and controls
478 lines (406 loc) Β· 13.3 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
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
/**
* Database Migration Script for Enhanced Background Verification System v2.0.0
*
* This script migrates the database to support the new enhanced verification features:
* - Adds new indexes for optimal query performance
* - Adds processing lock fields to existing transactions
* - Cleans up any stale processing locks
* - Validates data integrity
*/
const mongoose = require('mongoose');
require('dotenv').config();
const MONGODB_URI = process.env.MONGODB_URI;
if (!MONGODB_URI) {
console.error('β MONGODB_URI environment variable is required');
process.exit(1);
}
/**
* Connect to MongoDB
*/
async function connectDB() {
try {
await mongoose.connect(MONGODB_URI);
console.log('β
Connected to MongoDB');
} catch (error) {
console.error('β Failed to connect to MongoDB:', error.message);
process.exit(1);
}
}
/**
* Create enhanced indexes for optimal query performance
*/
async function createIndexes() {
console.log('π Creating enhanced database indexes...');
const db = mongoose.connection.db;
const collection = db.collection('transactions');
try {
// Enhanced indexes for background verification performance
const indexes = [
{
name: 'enhanced_verification_primary',
spec: {
state: 1,
verificationStartedAt: 1,
expiresAt: 1
},
options: {
name: 'enhanced_verification_primary',
background: true
}
},
{
name: 'enhanced_verification_secondary',
spec: {
state: 1,
lastVerificationCheck: 1,
expiresAt: 1
},
options: {
name: 'enhanced_verification_secondary',
background: true
}
},
{
name: 'processing_locks',
spec: {
processingBy: 1,
processingStartedAt: 1
},
options: {
name: 'processing_locks',
sparse: true,
background: true
}
}
];
for (const index of indexes) {
try {
await collection.createIndex(index.spec, index.options);
console.log(`β
Created index: ${index.name}`);
} catch (error) {
if (error.code === 85) { // Index already exists
console.log(`βΉοΈ Index already exists: ${index.name}`);
} else {
console.error(`β Failed to create index ${index.name}:`, error.message);
}
}
}
console.log('β
Index creation completed');
} catch (error) {
console.error('β Failed to create indexes:', error.message);
throw error;
}
}
/**
* Clean up stale processing locks
*/
async function cleanupStaleLocks() {
console.log('π§Ή Cleaning up stale processing locks...');
const db = mongoose.connection.db;
const collection = db.collection('transactions');
try {
// Find transactions with stale processing locks (older than 5 minutes)
const fiveMinutesAgo = new Date(Date.now() - 5 * 60 * 1000);
const staleLocksQuery = {
processingBy: { $exists: true },
processingStartedAt: { $lt: fiveMinutesAgo }
};
const staleCount = await collection.countDocuments(staleLocksQuery);
if (staleCount > 0) {
console.log(`π Found ${staleCount} transactions with stale processing locks`);
const result = await collection.updateMany(
staleLocksQuery,
{
$unset: {
processingBy: 1,
processingStartedAt: 1
}
}
);
console.log(`β
Cleaned up ${result.modifiedCount} stale processing locks`);
} else {
console.log('β
No stale processing locks found');
}
} catch (error) {
console.error('β Failed to cleanup stale locks:', error.message);
throw error;
}
}
/**
* Validate data integrity
*/
async function validateDataIntegrity() {
console.log('π Validating data integrity...');
const db = mongoose.connection.db;
const collection = db.collection('transactions');
try {
// Check for transactions without required fields
const checks = [
{
name: 'Missing verificationStartedAt',
query: {
state: { $in: ['PENDING', 'INITIALIZED'] },
verificationStartedAt: { $exists: false }
}
},
{
name: 'Missing expiresAt',
query: {
expiresAt: { $exists: false }
}
},
{
name: 'Expired but still PENDING',
query: {
state: 'PENDING',
expiresAt: { $lt: new Date() }
}
}
];
for (const check of checks) {
const count = await collection.countDocuments(check.query);
if (count > 0) {
console.log(`β οΈ ${check.name}: ${count} transactions`);
} else {
console.log(`β
${check.name}: OK`);
}
}
// Get overall statistics
const totalTransactions = await collection.countDocuments();
const pendingTransactions = await collection.countDocuments({ state: 'PENDING' });
const completedTransactions = await collection.countDocuments({ state: 'COMPLETED' });
const expiredTransactions = await collection.countDocuments({ state: 'PAYOUT_FAILED' });
console.log('\nπ Database Statistics:');
console.log(` Total Transactions: ${totalTransactions}`);
console.log(` Pending: ${pendingTransactions}`);
console.log(` Completed: ${completedTransactions}`);
console.log(` Expired: ${expiredTransactions}`);
console.log('β
Data integrity validation completed');
} catch (error) {
console.error('β Failed to validate data integrity:', error.message);
throw error;
}
}
/**
* Fix missing timestamps for existing transactions
*/
async function fixMissingTimestamps() {
console.log('π§ Fixing missing timestamps...');
const db = mongoose.connection.db;
const collection = db.collection('transactions');
try {
// Fix missing verificationStartedAt (use createdAt as fallback)
const missingVerificationStarted = await collection.updateMany(
{
verificationStartedAt: { $exists: false },
createdAt: { $exists: true }
},
[
{
$set: {
verificationStartedAt: '$createdAt'
}
}
]
);
if (missingVerificationStarted.modifiedCount > 0) {
console.log(`β
Fixed verificationStartedAt for ${missingVerificationStarted.modifiedCount} transactions`);
}
// Fix missing expiresAt (24 hours from createdAt)
const missingExpiresAt = await collection.updateMany(
{
expiresAt: { $exists: false },
createdAt: { $exists: true }
},
[
{
$set: {
expiresAt: {
$add: ['$createdAt', 24 * 60 * 60 * 1000] // 24 hours in milliseconds
}
}
}
]
);
if (missingExpiresAt.modifiedCount > 0) {
console.log(`β
Fixed expiresAt for ${missingExpiresAt.modifiedCount} transactions`);
}
console.log('β
Timestamp fixes completed');
} catch (error) {
console.error('β Failed to fix missing timestamps:', error.message);
throw error;
}
}
/**
* Test query performance
*/
async function testQueryPerformance() {
console.log('β‘ Testing query performance...');
const db = mongoose.connection.db;
const collection = db.collection('transactions');
try {
// Test the main background verification query
const now = new Date();
const immediatePhaseEndTime = new Date(now.getTime() - 16 * 60 * 1000); // 16 minutes ago
const lastCheckCutoff = new Date(now.getTime() - 5 * 60 * 1000); // 5 minutes ago
const query = {
state: 'PENDING',
expiresAt: { $gt: now },
verificationStartedAt: { $lt: immediatePhaseEndTime },
$or: [
{ lastVerificationCheck: { $lt: lastCheckCutoff } },
{ lastVerificationCheck: { $exists: false } }
]
};
const startTime = Date.now();
const count = await collection.countDocuments(query);
const queryTime = Date.now() - startTime;
console.log(`β
Background verification query: ${count} results in ${queryTime}ms`);
// Test explain plan
const explainResult = await collection.find(query).limit(100).explain('executionStats');
const executionStats = explainResult.executionStats;
console.log(`π Query execution stats:`);
console.log(` Documents examined: ${executionStats.totalDocsExamined}`);
console.log(` Documents returned: ${executionStats.totalDocsReturned}`);
console.log(` Execution time: ${executionStats.executionTimeMillis}ms`);
console.log(` Index used: ${executionStats.executionStages.indexName || 'No index'}`);
if (queryTime > 1000) {
console.log('β οΈ Query is slow (>1s). Consider optimizing indexes.');
} else {
console.log('β
Query performance is good');
}
} catch (error) {
console.error('β Failed to test query performance:', error.message);
throw error;
}
}
/**
* Main migration function
*/
async function runMigration() {
console.log('π Enhanced Background Verification System Migration v2.0.0');
console.log('================================================================\n');
try {
await connectDB();
console.log('π Migration Steps:');
console.log('1. Create enhanced database indexes');
console.log('2. Clean up stale processing locks');
console.log('3. Fix missing timestamps');
console.log('4. Validate data integrity');
console.log('5. Test query performance');
console.log('');
// Step 1: Create indexes
await createIndexes();
console.log('');
// Step 2: Cleanup stale locks
await cleanupStaleLocks();
console.log('');
// Step 3: Fix missing timestamps
await fixMissingTimestamps();
console.log('');
// Step 4: Validate data integrity
await validateDataIntegrity();
console.log('');
// Step 5: Test query performance
await testQueryPerformance();
console.log('');
console.log('π Migration completed successfully!');
console.log('β
Database is ready for Enhanced Background Verification System v2.0.0');
} catch (error) {
console.error('π₯ Migration failed:', error.message);
process.exit(1);
} finally {
await mongoose.disconnect();
console.log('π Disconnected from MongoDB');
}
}
/**
* Rollback function (if needed)
*/
async function rollbackMigration() {
console.log('π Rolling back Enhanced Background Verification System Migration...');
try {
await connectDB();
const db = mongoose.connection.db;
const collection = db.collection('transactions');
// Remove processing lock fields
const result = await collection.updateMany(
{
$or: [
{ processingBy: { $exists: true } },
{ processingStartedAt: { $exists: true } }
]
},
{
$unset: {
processingBy: 1,
processingStartedAt: 1
}
}
);
console.log(`β
Removed processing lock fields from ${result.modifiedCount} transactions`);
// Note: We don't remove the new indexes as they don't hurt and might be useful
console.log('βΉοΈ Enhanced indexes left in place (they don\'t interfere with normal operation)');
console.log('β
Rollback completed');
} catch (error) {
console.error('β Rollback failed:', error.message);
process.exit(1);
} finally {
await mongoose.disconnect();
}
}
// CLI interface
async function main() {
const args = process.argv.slice(2);
const command = args[0];
switch (command) {
case 'migrate':
case 'up':
await runMigration();
break;
case 'rollback':
case 'down':
await rollbackMigration();
break;
case 'validate':
await connectDB();
await validateDataIntegrity();
await mongoose.disconnect();
break;
case 'cleanup':
await connectDB();
await cleanupStaleLocks();
await mongoose.disconnect();
break;
case 'test-performance':
await connectDB();
await testQueryPerformance();
await mongoose.disconnect();
break;
default:
console.log('π§ Enhanced Background Verification System Migration Tool');
console.log('');
console.log('Usage:');
console.log(' node migrate-enhanced-verification.js migrate - Run full migration');
console.log(' node migrate-enhanced-verification.js rollback - Rollback migration');
console.log(' node migrate-enhanced-verification.js validate - Validate data integrity');
console.log(' node migrate-enhanced-verification.js cleanup - Clean stale locks');
console.log(' node migrate-enhanced-verification.js test-performance - Test query performance');
console.log('');
console.log('Examples:');
console.log(' node migrate-enhanced-verification.js migrate');
console.log(' MONGODB_URI=mongodb://localhost:27017/mydb node migrate-enhanced-verification.js migrate');
break;
}
}
// Run CLI if executed directly
if (require.main === module) {
main().catch(console.error);
}
module.exports = {
runMigration,
rollbackMigration,
validateDataIntegrity,
cleanupStaleLocks,
testQueryPerformance
};