Spaces:
Sleeping
Sleeping
File size: 12,111 Bytes
da819ac |
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 |
const mongoose = require('mongoose');
const fs = require('fs').promises;
const path = require('path');
// Atlas MongoDB connection string
const MONGODB_URI = 'mongodb+srv://nothingyu:wSg3lbO1PkHiRMq9@sandbox.ecysggv.mongodb.net/test?retryWrites=true&w=majority&appName=sandbox';
// Connect to MongoDB Atlas
const connectDB = async () => {
try {
await mongoose.connect(MONGODB_URI);
console.log('β
Connected to MongoDB Atlas');
} catch (error) {
console.error('β MongoDB connection error:', error);
process.exit(1);
}
};
// Backup and Version Control System
const backupVersionControl = {
// Create comprehensive backup
async createBackup(customBackupName = null) {
try {
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const backupName = customBackupName || `comprehensive-backup-${timestamp}`;
console.log(`πΎ Creating comprehensive backup: ${backupName}`);
const collections = ['subtitles', 'sourcetexts', 'submissions', 'users', 'securitylogs'];
const backupData = {
metadata: {
backupName,
timestamp: new Date(),
collections: collections,
totalRecords: 0,
version: '1.0',
createdBy: 'system'
},
data: {}
};
// Export all collections
for (const collection of collections) {
try {
const data = await mongoose.connection.db.collection(collection).find({}).toArray();
backupData.data[collection] = data;
backupData.metadata.totalRecords += data.length;
console.log(` π¦ Exported ${data.length} records from ${collection}`);
} catch (error) {
console.warn(` β οΈ Could not export ${collection}:`, error.message);
}
}
// Save backup to file system
const backupDir = path.join(__dirname, 'backups');
await fs.mkdir(backupDir, { recursive: true });
const backupPath = path.join(backupDir, `${backupName}.json`);
await fs.writeFile(backupPath, JSON.stringify(backupData, null, 2));
// Create backup record in database
const backupRecord = {
backupName,
timestamp: new Date(),
collections: collections,
totalRecords: backupData.metadata.totalRecords,
filePath: backupPath,
status: 'created',
createdBy: 'system'
};
// Save to backup collection
const backupCollection = mongoose.connection.db.collection('backups');
await backupCollection.insertOne(backupRecord);
console.log(`β
Backup created successfully: ${backupName}`);
console.log(`π Total records: ${backupData.metadata.totalRecords}`);
console.log(`πΎ File saved: ${backupPath}`);
return backupName;
} catch (error) {
console.error('β Error creating backup:', error);
throw error;
}
},
// Restore from backup
async restoreFromBackup(backupName) {
try {
console.log(`π Restoring from backup: ${backupName}`);
// Load backup file
const backupPath = path.join(__dirname, 'backups', `${backupName}.json`);
const backupData = JSON.parse(await fs.readFile(backupPath, 'utf8'));
console.log(`π Backup metadata:`, backupData.metadata);
// Confirm restoration
console.log('β οΈ This will overwrite existing data. Are you sure? (y/N)');
// In a real implementation, you'd get user confirmation here
// Restore each collection
for (const [collection, data] of Object.entries(backupData.data)) {
try {
// Clear existing data
await mongoose.connection.db.collection(collection).deleteMany({});
// Insert backup data
if (data.length > 0) {
await mongoose.connection.db.collection(collection).insertMany(data);
}
console.log(` β
Restored ${data.length} records to ${collection}`);
} catch (error) {
console.error(` β Error restoring ${collection}:`, error.message);
}
}
console.log(`β
Restoration completed: ${backupName}`);
} catch (error) {
console.error('β Error restoring from backup:', error);
throw error;
}
},
// List available backups
async listBackups() {
try {
console.log('π Available backups:');
// List from database
const backupCollection = mongoose.connection.db.collection('backups');
const dbBackups = await backupCollection.find({}).sort({ timestamp: -1 }).toArray();
if (dbBackups.length === 0) {
console.log(' No backups found in database');
} else {
console.log(' Database backups:');
dbBackups.forEach(backup => {
console.log(` π¦ ${backup.backupName} (${backup.totalRecords} records, ${new Date(backup.timestamp).toLocaleString()})`);
});
}
// List from file system
const backupDir = path.join(__dirname, 'backups');
try {
const files = await fs.readdir(backupDir);
const backupFiles = files.filter(file => file.endsWith('.json'));
if (backupFiles.length > 0) {
console.log(' File system backups:');
for (const file of backupFiles) {
const filePath = path.join(backupDir, file);
const stats = await fs.stat(filePath);
console.log(` πΎ ${file} (${(stats.size / 1024).toFixed(2)} KB, ${stats.mtime.toLocaleString()})`);
}
}
} catch (error) {
console.log(' No backup directory found');
}
} catch (error) {
console.error('β Error listing backups:', error);
}
},
// Version control for content changes
async createVersionControl() {
try {
console.log('π Creating version control system...');
const versionControlSchema = new mongoose.Schema({
documentId: { type: String, required: true },
collection: { type: String, required: true },
version: { type: Number, required: true },
changes: mongoose.Schema.Types.Mixed,
timestamp: { type: Date, default: Date.now },
userId: String,
commitMessage: String,
previousVersion: Number,
checksum: String
});
const VersionControl = mongoose.model('VersionControl', versionControlSchema);
// Create indexes for efficient querying
await VersionControl.createIndexes();
console.log('β
Version control system created');
return VersionControl;
} catch (error) {
console.error('β Error creating version control:', error);
}
},
// Track content changes
async trackChange(collection, documentId, changes, userId, commitMessage) {
try {
const VersionControl = mongoose.model('VersionControl');
// Get current version
const latestVersion = await VersionControl.findOne({
documentId,
collection
}).sort({ version: -1 });
const newVersion = (latestVersion?.version || 0) + 1;
// Create version record
await VersionControl.create({
documentId,
collection,
version: newVersion,
changes,
userId,
commitMessage,
previousVersion: latestVersion?.version || null,
timestamp: new Date()
});
console.log(`π Version ${newVersion} created for ${collection}/${documentId}`);
} catch (error) {
console.error('β Error tracking change:', error);
}
},
// Get content history
async getContentHistory(collection, documentId) {
try {
const VersionControl = mongoose.model('VersionControl');
const history = await VersionControl.find({
documentId,
collection
}).sort({ version: -1 });
console.log(`π Version history for ${collection}/${documentId}:`);
history.forEach(version => {
console.log(` v${version.version} (${new Date(version.timestamp).toLocaleString()}) - ${version.commitMessage}`);
});
return history;
} catch (error) {
console.error('β Error getting content history:', error);
}
},
// Automated backup scheduling
async scheduleBackups() {
try {
console.log('β° Setting up automated backup scheduling...');
const scheduleSchema = new mongoose.Schema({
scheduleType: { type: String, enum: ['daily', 'weekly', 'monthly'], required: true },
lastBackup: Date,
nextBackup: Date,
isActive: { type: Boolean, default: true },
createdBy: String
});
const Schedule = mongoose.model('Schedule', scheduleSchema);
// Create default daily backup schedule
await Schedule.create({
scheduleType: 'daily',
lastBackup: null,
nextBackup: new Date(Date.now() + 24 * 60 * 60 * 1000), // Tomorrow
isActive: true,
createdBy: 'system'
});
console.log('β
Automated backup schedule created (daily)');
} catch (error) {
console.error('β Error setting up backup scheduling:', error);
}
},
// Verify backup integrity
async verifyBackupIntegrity(backupName) {
try {
console.log(`π Verifying backup integrity: ${backupName}`);
const backupPath = path.join(__dirname, 'backups', `${backupName}.json`);
const backupData = JSON.parse(await fs.readFile(backupPath, 'utf8'));
let verifiedCount = 0;
let failedCount = 0;
// Verify each collection
for (const [collection, data] of Object.entries(backupData.data)) {
try {
const currentCount = await mongoose.connection.db.collection(collection).countDocuments();
const backupCount = data.length;
if (currentCount === backupCount) {
verifiedCount++;
console.log(` β
${collection}: ${backupCount} records verified`);
} else {
failedCount++;
console.log(` β ${collection}: ${backupCount} in backup, ${currentCount} in database`);
}
} catch (error) {
failedCount++;
console.log(` β ${collection}: verification failed`);
}
}
console.log(`π Integrity verification complete:`);
console.log(` - Verified: ${verifiedCount} collections`);
console.log(` - Failed: ${failedCount} collections`);
return { verifiedCount, failedCount };
} catch (error) {
console.error('β Error verifying backup integrity:', error);
}
}
};
// Main function
const main = async () => {
try {
console.log('π Starting backup and version control system...');
// Create comprehensive backup
const backupName = await backupVersionControl.createBackup();
// Create version control system
await backupVersionControl.createVersionControl();
// Set up automated backups
await backupVersionControl.scheduleBackups();
// List available backups
await backupVersionControl.listBackups();
console.log('\nπ Backup and version control system ready!');
console.log('\nπ Available functions:');
console.log(' - createBackup(): Create new backup');
console.log(' - restoreFromBackup(name): Restore from backup');
console.log(' - listBackups(): List available backups');
console.log(' - trackChange(): Track content changes');
console.log(' - getContentHistory(): Get version history');
console.log(' - verifyBackupIntegrity(): Verify backup integrity');
} catch (error) {
console.error('β Error in backup and version control system:', error);
} finally {
await mongoose.disconnect();
console.log('π Disconnected from MongoDB');
}
};
// Run the system
connectDB().then(() => {
main();
}); |