put notes/dcc43ef1-4f83-4afe-a59d-61a9ae99cb51.json
Browse files
notes/dcc43ef1-4f83-4afe-a59d-61a9ae99cb51.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
| 1 |
{
|
| 2 |
"id": "dcc43ef1-4f83-4afe-a59d-61a9ae99cb51",
|
| 3 |
"title": "Untitled",
|
| 4 |
-
"content": "import express from 'express';\nimport { MongoClient, ObjectId } from 'mongodb';\nimport multer from 'multer';\nimport bcryptjs from 'bcryptjs';\nimport jwt from 'jsonwebtoken';\nimport fs from 'fs';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\nimport dotenv from 'dotenv';\nimport cluster from 'cluster';\nimport os from 'os';\nimport compression from 'compression';\n\n// Load environment variables\ndotenv.config({ path: '.env.server' });\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst uploadsDir = path.join(__dirname, 'uploads');\nconst tempChunksDir = path.join(__dirname, 'uploads_tmp');\n\nif (!fs.existsSync(uploadsDir)) {\n fs.mkdirSync(uploadsDir, { recursive: true });\n}\n\nif (!fs.existsSync(tempChunksDir)) {\n fs.mkdirSync(tempChunksDir, { recursive: true });\n}\n\nconst app = express();\nconst PORT = process.env.PORT || 3001;\nconst MONGODB_URI = process.env.MONGODB_URI || 'mongodb+srv://admin:Tuandzvcl@userupload.1zqgqci.mongodb.net/?appName=UserUpload';\nconst JWT_SECRET = process.env.JWT_SECRET || 'TwanDz';\n\n// Rate limiting per IP to prevent abuse\nconst requestCounts = new Map();\nconst RATE_LIMIT_WINDOW = 60000; // 1 minute\nconst MAX_REQUESTS_PER_WINDOW = 1500; // 1500 req/min supports 8 files × adaptive chunks\n\n// Cleanup request counts every 5 minutes\nsetInterval(() => {\n requestCounts.clear();\n}, 5 * 60 * 1000);\n\n// Rate limiter middleware (skip for upload-chunk to allow fast uploads)\napp.use((req, res, next) => {\n // Skip rate limiting for upload-chunk endpoint to allow high-speed parallel uploads\n if (req.path === '/api/files/upload-chunk') {\n return next();\n }\n\n const ip = req.ip;\n const now = Date.now();\n \n if (!requestCounts.has(ip)) {\n requestCounts.set(ip, []);\n }\n \n const requests = requestCounts.get(ip);\n const recentRequests = requests.filter(t => now - t < RATE_LIMIT_WINDOW);\n \n if (recentRequests.length >= MAX_REQUESTS_PER_WINDOW) {\n return res.status(429).json({ error: 'Too many requests, please try again later' });\n }\n \n recentRequests.push(now);\n requestCounts.set(ip, recentRequests);\n next();\n});\n\nlet db;\nlet mongoClient;\n\n// Track concurrent uploads\nconst uploadSessions = new Map(); // uploadId -> { chunks: Set, totalChunks, status }\n\n// Initialize MongoDB\nasync function initMongoDB() {\n try {\n console.log('🔄 Connecting to MongoDB...');\n console.log('URI:', MONGODB_URI.replace(/:[^:]*@/, ':****@')); // Hide password in logs\n \n mongoClient = new MongoClient(MONGODB_URI, {\n serverSelectionTimeoutMS: 5000,\n connectTimeoutMS: 10000,\n // HIGH-PERFORMANCE POOLING: Optimize connection reuse\n maxPoolSize: 80, // Support 8 concurrent files × 10 chunks + parallelism\n minPoolSize: 20, // Keep connections warm for burst uploads\n maxIdleTimeMS: 45000, // Longer idle time reduces reconnection overhead\n waitQueueTimeoutMS: 5000, // Faster timeout for better request queueing\n });\n \n await mongoClient.connect();\n console.log('✅ MongoDB connected successfully');\n \n db = mongoClient.db('file-caddy');\n\n // Create collections if they don't exist\n const collections = await db.listCollections().toArray();\n const collectionNames = collections.map(c => c.name);\n\n if (!collectionNames.includes('users')) {\n await db.createCollection('users');\n await db.collection('users').createIndex({ email: 1 }, { unique: true });\n await db.collection('users').createIndex({ username: 1 }, { unique: true, sparse: true });\n console.log('📦 Created users collection');\n }\n if (!collectionNames.includes('files')) {\n await db.createCollection('files');\n await db.collection('files').createIndex({ user_id: 1 });\n console.log('📦 Created files collection');\n }\n\n console.log('✅ MongoDB fully initialized');\n } catch (err) {\n console.error('❌ MongoDB connection error:', err.message);\n console.error('Full error:', err);\n process.exit(1);\n }\n}\n\n// Middleware - Memory efficient for large uploads\n// Limit JSON requests but NOT file uploads (handled by multer streaming)\napp.use(express.json({ limit: '10mb' }));\napp.use(express.urlencoded({ extended: false, limit: '10mb' })); // Disable extended mode for perf\n\n// ⚡ Response compression for 2-3x faster downloads\napp.use(compression({ level: 6, threshold: 1024 })); // Compress responses > 1KB\n\n// Skip static file serving in production - use CDN/nginx instead\nif (process.env.NODE_ENV !== 'production') {\n app.use('/uploads', express.static(uploadsDir, { \n maxAge: '31d',\n setHeaders: (res) => {\n res.setHeader('Cache-Control', 'public, max-age=2678400, immutable');\n }\n }));\n}\n\n// Increase timeout for large uploads\napp.use((req, res, next) => {\n req.setTimeout(3600000); // 1 hour timeout\n res.setTimeout(3600000);\n // PERF: Increase socket buffer sizes for fast streaming\n if (req.socket) {\n req.socket.setMaxListeners(0); // Unlimited listeners\n }\n next();\n});\n\n// Multer configuration - Optimized for faster uploads\nconst storage = multer.diskStorage({\n destination: (req, file, cb) => {\n cb(null, uploadsDir);\n },\n filename: (req, file, cb) => {\n const uniqueName = `${Date.now()}-${Math.random().toString(36).substr(2, 9)}-${file.originalname}`;\n cb(null, uniqueName);\n }\n});\n\n// High-performance streaming upload configuration\n// Uses disk streaming (not memory buffering) for maximum throughput\nconst upload = multer({\n storage,\n limits: {\n fileSize: 5 * 1024 * 1024 * 1024, // 5GB limit\n files: 10\n },\n // HIGH-PERFORMANCE: 16MB buffer for 100MB/s throughput\n highWaterMark: 16 * 1024 * 1024\n});\n\nconst chunkStorage = multer.diskStorage({\n destination: (req, file, cb) => {\n cb(null, tempChunksDir);\n },\n filename: (req, file, cb) => {\n // Use temporary unique name - will rename after getting uploadId from body\n const tempName = `temp-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n cb(null, tempName);\n }\n});\n\nconst chunkUpload = multer({\n storage: chunkStorage,\n limits: {\n fileSize: 100 * 1024 * 1024, // 100MB per chunk\n files: 1\n },\n highWaterMark: 96 * 1024 * 1024 // 96MB buffer = 3x faster streaming (up to 300MB/s)\n});\n\nasync function tryFinalizeChunkedUpload({ uploadId, totalChunks, originalName, description, mimetype, userId, fileSize }) {\n // Validate parameters\n if (!uploadId || !totalChunks || !originalName || !userId) {\n throw new Error('Missing required parameters for finalize');\n }\n if (typeof fileSize !== 'number' || fileSize <= 0) {\n throw new Error('Invalid fileSize: must be positive number');\n }\n if (totalChunks < 1 || !Number.isInteger(totalChunks)) {\n throw new Error('Invalid totalChunks: must be positive integer');\n }\n\n const parts = Array.from({ length: totalChunks }, (_, index) =>\n path.join(tempChunksDir, `${uploadId}.part.${index}`)\n );\n\n // Check which chunks exist\n console.log(`📦 Merging ${totalChunks} chunks for ${uploadId}`);\n const existingChunks = [];\n for (let i = 0; i < parts.length; i++) {\n if (fs.existsSync(parts[i])) {\n existingChunks.push(i);\n } else {\n console.warn(`⚠️ Missing chunk ${i}: ${parts[i]}`);\n }\n }\n console.log(`✓ Found ${existingChunks.length}/${totalChunks} chunks`);\n\n // Fast check if first chunk exists (fail-fast)\n try {\n await fs.promises.access(parts[0], fs.constants.R_OK);\n } catch {\n console.error(`❌ Cannot read first chunk: ${parts[0]}`);\n return null;\n }\n\n const safeName = `${Date.now()}-${uploadId}-${path.basename(originalName)}`;\n const finalPath = path.join(uploadsDir, safeName);\n console.log(`💾 Saving merged file to: ${finalPath}`);\n \n const writeStream = fs.createWriteStream(finalPath, { flags: 'w', highWaterMark: 16 * 1024 * 1024 }); // 16MB buffer for faster merge writes\n\n // Ultra-fast parallel chunk merging (up to 3 streams at once)\n await new Promise((resolveAll, rejectAll) => {\n let currentIndex = 0;\n let activeStreams = 0;\n const maxActiveStreams = 4; // Process 4 chunks in parallel (more I/O parallelism = faster)\n const queue = [];\n\n const writeNextChunk = () => {\n if (activeStreams >= maxActiveStreams) return;\n if (queue.length === 0 && currentIndex >= parts.length && activeStreams === 0) {\n writeStream.end();\n return;\n }\n if (queue.length === 0) return;\n\n activeStreams++;\n const partPath = queue.shift();\n const readStream = fs.createReadStream(partPath, { highWaterMark: 16 * 1024 * 1024 }); // 16MB buffer per stream for faster reads\n\n readStream.on('error', (err) => {\n writeStream.destroy();\n rejectAll(err);\n });\n\n readStream.on('end', () => {\n activeStreams--;\n // Delete temp chunk immediately (don't wait)\n fs.unlink(partPath, () => {});\n writeNextChunk();\n });\n\n readStream.pipe(writeStream, { end: false });\n };\n\n // Load chunks into queue - allows parallel I/O prep\n const loadChunks = () => {\n // Fill queue up to 8 items for aggressive I/O preparation\n while (currentIndex < parts.length && queue.length < 8) {\n queue.push(parts[currentIndex]);\n currentIndex++;\n }\n // Try to start processing if possible\n if (queue.length > 0 && activeStreams < maxActiveStreams) {\n writeNextChunk();\n }\n // Schedule more loading if we have more chunks\n if (currentIndex < parts.length) {\n setImmediate(loadChunks);\n }\n };\n\n // Handle write stream drain\n const onDrain = () => {\n // When writeStream drains, try to pipe more chunks\n if (queue.length > 0 && activeStreams < maxActiveStreams) {\n writeNextChunk();\n }\n // If no more chunks and no active streams, close the file\n if (currentIndex >= parts.length && queue.length === 0 && activeStreams === 0) {\n writeStream.end();\n }\n };\n\n writeStream.on('drain', onDrain);\n\n writeStream.on('finish', () => {\n console.log(`✅ File write completed: ${finalPath}`);\n console.log(`📊 Final file size: ${fileSize} bytes`);\n \n // Create file doc after write completes\n const fileDoc = {\n user_id: userId,\n file_name: originalName,\n file_size: fileSize,\n file_type: mimetype || 'application/octet-stream',\n storage_path: safeName,\n description: description || null,\n is_public: false,\n created_at: new Date(),\n updated_at: new Date(),\n };\n\n // Verify file exists before inserting to DB\n fs.stat(finalPath, (err, stats) => {\n if (err) {\n console.error(`❌ File not found after write: ${finalPath}`, err);\n return;\n }\n console.log(`📁 File verified: ${stats.size} bytes`);\n \n // Insert to DB\n db.collection('files').insertOne(fileDoc).catch(err => {\n console.error('DB insert error:', err);\n }).then(() => {\n console.log(`💾 Saved to DB: ${originalName}`);\n });\n });\n\n // Clean up upload session\n uploadSessions.delete(uploadId);\n \n resolveAll({ id: safeName, file_name: originalName, file_size: fileSize });\n });\n\n writeStream.on('error', (err) => {\n console.error(`❌ Write stream error: ${err.message}`);\n console.error(err.stack);\n rejectAll(err);\n });\n\n loadChunks();\n });\n}\n\nasync function cleanupOldTempChunks(ageMs = 2 * 60 * 60 * 1000) {\n try {\n const files = await fs.promises.readdir(tempChunksDir);\n const now = Date.now();\n\n await Promise.all(files.map(async (file) => {\n if (!file.includes('.part.')) {\n return;\n }\n const filePath = path.join(tempChunksDir, file);\n try {\n const stat = await fs.promises.stat(filePath);\n if (now - stat.mtimeMs > ageMs) {\n await fs.promises.unlink(filePath);\n }\n } catch (err) {\n // ignore missing file or permission issues\n }\n }));\n } catch (err) {\n console.error('Error cleaning temp chunk files:', err);\n }\n}\n\n// Run cleanup once at startup, then periodically every hour\ncleanupOldTempChunks().catch(err => console.error('Startup temp cleanup failed:', err));\nconst fileCleanupInterval = setInterval(() => cleanupOldTempChunks(), 60 * 60 * 1000);\n\n// Cleanup expired upload sessions to prevent memory leaks\nfunction cleanupExpiredUploadSessions(maxAgeMs = 3600000) { // 1 hour default\n const now = Date.now();\n let cleaned = 0;\n for (const [uploadId, session] of uploadSessions.entries()) {\n if (now - session.createdAt > maxAgeMs) {\n uploadSessions.delete(uploadId);\n cleaned++;\n }\n }\n if (cleaned > 0) {\n console.log(`🧹 Cleaned ${cleaned} expired upload sessions`);\n }\n}\n\nconst sessionCleanupInterval = setInterval(() => cleanupExpiredUploadSessions(), 60000); // Every minute\n\n// Middleware to verify JWT\nfunction verifyToken(req, res, next) {\n const token = req.headers['authorization']?.split(' ')[1];\n if (!token) {\n return res.status(401).json({ error: 'No token provided' });\n }\n try {\n const decoded = jwt.verify(token, JWT_SECRET);\n if (!decoded.userId || !decoded.email) {\n return res.status(401).json({ error: 'Invalid token: missing userId or email' });\n }\n req.userId = decoded.userId;\n req.email = decoded.email;\n next();\n } catch (err) {\n console.warn('Token validation failed:', err.message.substring(0, 100));\n res.status(401).json({ error: 'Invalid or expired token' });\n }\n}\n\n// Input sanitizer utility\nfunction sanitizeInput(str, maxLength = 1000) {\n if (typeof str !== 'string') return '';\n return str.trim().substring(0, maxLength);\n}\n\n// Auth Routes\n\n// Sign up\napp.post('/auth/signup', async (req, res) => {\n try {\n const email = sanitizeInput(req.body.email, 255);\n const password = sanitizeInput(req.body.password, 256);\n const displayName = sanitizeInput(req.body.displayName, 100);\n const username = sanitizeInput(req.body.username, 20);\n\n // Validate email format\n if (!email || !/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email)) {\n return res.status(400).json({ error: 'Invalid email format' });\n }\n\n if (!password || password.length < 6) {\n return res.status(400).json({ error: 'Password must be at least 6 characters' });\n }\n\n if (username && !/^[a-zA-Z0-9_]{3,20}$/.test(username)) {\n return res.status(400).json({ error: 'Username must be 3-20 characters (letters, numbers, underscore only)' });\n }\n\n const usersCollection = db.collection('users');\n const existing = await usersCollection.findOne({ email });\n\n if (existing) {\n return res.status(400).json({ error: 'Email already exists' });\n }\n\n if (username) {\n const existingUsername = await usersCollection.findOne({ username });\n if (existingUsername) {\n return res.status(400).json({ error: 'Username already taken' });\n }\n }\n\n const hashedPassword = await bcryptjs.hash(password, 10);\n const user = {\n email,\n password: hashedPassword,\n username: username || null,\n displayName: displayName || email.split('@')[0],\n display_name: displayName || email.split('@')[0],\n bio: '',\n avatar_url: '',\n location: '',\n website: '',\n phone: '',\n role: 'user', // Mặc định role là 'user'\n social_media: {\n twitter: '',\n github: '',\n linkedin: '',\n instagram: ''\n },\n created_at: new Date(),\n updated_at: new Date(),\n };\n\n const result = await usersCollection.insertOne(user);\n const userId = result.insertedId.toString();\n\n const token = jwt.sign({ userId, email }, JWT_SECRET, { expiresIn: '7d' });\n\n res.json({\n user: {\n id: userId,\n email,\n displayName: user.displayName,\n username: user.username,\n },\n token,\n });\n } catch (err) {\n console.error('Signup error:', err.message);\n if (err.code === 11000) {\n const field = Object.keys(err.keyPattern || {})[0] || 'field';\n res.status(400).json({ error: `${field} already exists` });\n } else {\n res.status(500).json({ error: 'Signup failed' });\n }\n }\n});\n\n// Sign in\napp.post('/auth/signin', async (req, res) => {\n try {\n const { email, password } = req.body;\n\n if (!email || !password) {\n return res.status(400).json({ error: 'Email and password required' });\n }\n\n const usersCollection = db.collection('users');\n const user = await usersCollection.findOne({ email });\n\n if (!user) {\n return res.status(400).json({ error: 'Invalid credentials' });\n }\n\n const isValid = await bcryptjs.compare(password, user.password);\n\n if (!isValid) {\n return res.status(400).json({ error: 'Invalid credentials' });\n }\n\n const token = jwt.sign({ userId: user._id.toString(), email }, JWT_SECRET, { expiresIn: '7d' });\n\n res.json({\n user: {\n id: user._id.toString(),\n email: user.email,\n displayName: user.displayName,\n username: user.username,\n },\n token,\n });\n } catch (err) {\n console.error('Signin error:', err);\n res.status(500).json({ error: 'Signin failed' });\n }\n});\n\n// Get current user\napp.get('/auth/me', verifyToken, async (req, res) => {\n try {\n const usersCollection = db.collection('users');\n const user = await usersCollection.findOne({ _id: new ObjectId(req.userId) });\n\n if (!user) {\n return res.status(404).json({ error: 'User not found' });\n }\n\n // Check if admin\n res.json({\n id: user._id.toString(),\n email: user.email,\n displayName: user.displayName,\n username: user.username || '',\n display_name: user.display_name || user.displayName,\n bio: user.bio || '',\n avatar_url: user.avatar_url || '',\n location: user.location || '',\n website: user.website || '',\n phone: user.phone || '',\n role: user.role || 'user',\n social_media: user.social_media || { twitter: '', github: '', linkedin: '', instagram: '' },\n created_at: user.created_at,\n isAdmin: user.role === 'admin',\n });\n } catch (err) {\n console.error('Get user error:', err);\n res.status(500).json({ error: 'Failed to fetch user' });\n }\n});\n\n// Change password\napp.post('/auth/change-password', verifyToken, async (req, res) => {\n try {\n const { currentPassword, newPassword } = req.body;\n\n if (!currentPassword || !newPassword) {\n return res.status(400).json({ error: 'Current and new password required' });\n }\n\n if (newPassword.length < 6) {\n return res.status(400).json({ error: 'New password must be at least 6 characters' });\n }\n\n const usersCollection = db.collection('users');\n const user = await usersCollection.findOne({ _id: new ObjectId(req.userId) });\n\n if (!user) {\n return res.status(404).json({ error: 'User not found' });\n }\n\n // Verify current password\n const isValid = await bcryptjs.compare(currentPassword, user.password);\n if (!isValid) {\n return res.status(401).json({ error: 'Current password is incorrect' });\n }\n\n // Hash new password\n const hashedPassword = await bcryptjs.hash(newPassword, 10);\n\n // Update password\n await usersCollection.updateOne(\n { _id: new ObjectId(req.userId) },\n { $set: { password: hashedPassword, updated_at: new Date() } }\n );\n\n res.json({ success: true, message: 'Password changed successfully' });\n } catch (err) {\n console.error('Change password error:', err);\n res.status(500).json({ error: 'Failed to change password' });\n }\n});\n\n// Update profile\napp.post('/auth/update-profile', verifyToken, async (req, res) => {\n try {\n const { display_name, bio, avatar_url, location, website, phone, social_media } = req.body;\n\n const usersCollection = db.collection('users');\n const updates = {};\n \n if (display_name !== undefined) updates.display_name = display_name;\n if (bio !== undefined) updates.bio = bio;\n if (avatar_url !== undefined) updates.avatar_url = avatar_url;\n if (location !== undefined) updates.location = location;\n if (website !== undefined) updates.website = website;\n if (phone !== undefined) updates.phone = phone;\n if (social_media !== undefined) updates.social_media = social_media;\n updates.updated_at = new Date();\n\n await usersCollection.updateOne(\n { _id: new ObjectId(req.userId) },\n { $set: updates }\n );\n\n // Return updated user\n const user = await usersCollection.findOne({ _id: new ObjectId(req.userId) });\n\n res.json({\n id: user._id.toString(),\n email: user.email,\n displayName: user.displayName,\n username: user.username || '',\n display_name: user.display_name || user.displayName,\n bio: user.bio || '',\n avatar_url: user.avatar_url || '',\n location: user.location || '',\n website: user.website || '',\n phone: user.phone || '',\n role: user.role || 'user',\n social_media: user.social_media || { twitter: '', github: '', linkedin: '', instagram: '' },\n created_at: user.created_at,\n isAdmin: user.role === 'admin',\n message: 'Profile updated successfully'\n });\n } catch (err) {\n console.error('Update profile error:', err);\n if (err.code === 11000) {\n res.status(400).json({ error: 'Username already taken' });\n } else {\n res.status(500).json({ error: 'Failed to update profile' });\n }\n }\n});\n\n// File Routes\n\n// Chunked upload support for large files - PARALLEL CHUNK SUPPORT\napp.post('/api/files/upload-chunk', verifyToken, (req, res, next) => {\n chunkUpload.single('chunk')(req, res, (err) => {\n if (err) {\n console.error(`Chunk upload error for user ${req.userId}:`, err.message);\n if (err.code === 'LIMIT_FILE_SIZE') {\n return res.status(413).json({ error: `Chunk too large (max: ${(err.limit / 1024 / 1024).toFixed(0)}MB)` });\n }\n return res.status(400).json({ error: err.message || 'Chunk upload failed' });\n }\n next();\n });\n}, async (req, res) => {\n try {\n const uploadId = sanitizeInput(req.body.uploadId, 100);\n const chunkIndex = Number(req.body.chunkIndex);\n const totalChunks = Number(req.body.totalChunks);\n const originalName = sanitizeInput(req.body.fileName, 255);\n const description = sanitizeInput(req.body.description, 1000);\n const isLastChunk = req.body.isLastChunk === 'true';\n\n // Validate metadata\n if (!uploadId || Number.isNaN(chunkIndex) || Number.isNaN(totalChunks) || !originalName) {\n return res.status(400).json({ error: 'Missing or invalid upload metadata' });\n }\n\n if (chunkIndex < 0 || chunkIndex >= totalChunks) {\n return res.status(400).json({ error: 'Invalid chunk index' });\n }\n\n if (totalChunks < 1 || totalChunks > 10000) {\n return res.status(400).json({ error: 'Invalid total chunks (1-10000 allowed)' });\n }\n\n if (!req.file) {\n return res.status(400).json({ error: 'No chunk file provided' });\n }\n\n // Rename temp file to correct chunk filename NOW that we have uploadId/chunkIndex\n const correctChunkName = `${uploadId}.part.${chunkIndex}`;\n const correctChunkPath = path.join(tempChunksDir, correctChunkName);\n const tempFilePath = req.file.path;\n \n try {\n await fs.promises.rename(tempFilePath, correctChunkPath);\n req.file.path = correctChunkPath;\n req.file.filename = correctChunkName;\n } catch (renameErr) {\n console.error(`❌ Failed to rename chunk file: ${renameErr.message}`);\n return res.status(500).json({ error: 'Failed to save chunk' });\n }\n\n console.log(`📥 Received chunk ${chunkIndex + 1}/${totalChunks} for upload ${uploadId.substring(0, 8)}... (${(req.file.size / 1024 / 1024).toFixed(1)}MB)`);\n console.log(` Saved to: ${req.file.path}`);\n\n // Track upload session\n if (!uploadSessions.has(uploadId)) {\n uploadSessions.set(uploadId, { \n chunks: new Set(), \n totalChunks, \n userId: req.userId,\n fileName: originalName,\n description,\n mimetype: req.file.mimetype,\n fileSize: Number(req.body.fileSize),\n createdAt: Date.now(),\n finalized: false,\n finalizedAt: null\n });\n }\n\n const session = uploadSessions.get(uploadId);\n \n // Security: Verify upload belongs to current user\n if (session.userId !== req.userId) {\n return res.status(403).json({ error: 'Upload does not belong to this user' });\n }\n\n session.chunks.add(chunkIndex);\n const chunksReceived = session.chunks.size;\n const progress = Math.round((chunksReceived / totalChunks) * 100);\n\n console.log(` Progress: ${chunksReceived}/${totalChunks} chunks (${progress}%)`);\n\n res.json({ \n chunkIndex, \n totalChunks, \n chunksReceived,\n progress,\n chunkComplete: false,\n ready: chunksReceived === totalChunks\n }).end();\n\n // Async finalize if all chunks received\n // But verify actual chunk files exist (not just in-memory count) since we have clustering\n if (chunksReceived === totalChunks) {\n console.log(`🚀 Memory counter: All chunks received for ${uploadId.substring(0, 8)}... - Verifying chunk files...`);\n \n // Verify all chunks actually exist on disk (async!)\n setImmediate(async () => {\n const allChunkPaths = Array.from({ length: totalChunks }, (_, i) =>\n path.join(tempChunksDir, `${uploadId}.part.${i}`)\n );\n \n const missingChunks = [];\n for (const chunkPath of allChunkPaths) {\n if (!fs.existsSync(chunkPath)) {\n missingChunks.push(chunkPath);\n }\n }\n \n if (missingChunks.length > 0) {\n console.warn(`⚠️ Memory says all ${totalChunks} chunks ready, but ${missingChunks.length} missing on disk!`);\n console.warn(` Missing: ${missingChunks.slice(0, 3).join(', ')}...`);\n // Don't finalize yet - files might still be arriving from other workers\n return;\n }\n \n console.log(`✅ All ${totalChunks} chunks verified on disk - Starting finalization...`);\n try {\n console.log(`[FINALIZE] Starting for ${uploadId}, chunks=${totalChunks}, name=${session.fileName}`);\n const result = await tryFinalizeChunkedUpload({\n uploadId,\n totalChunks,\n originalName: session.fileName,\n description: session.description,\n mimetype: session.mimetype,\n userId: session.userId,\n fileSize: session.fileSize || Number(req.body.fileSize),\n });\n\n if (result) {\n // Mark upload as finalized\n const sessionCheck = uploadSessions.get(uploadId);\n if (sessionCheck) {\n sessionCheck.finalized = true;\n sessionCheck.finalizedAt = Date.now();\n }\n console.log(`✅ Upload complete: ${session.fileName} (${chunksReceived} chunks, user: ${req.userId})`);\n } else {\n console.error(`[FINALIZE] Failed - result is null`);\n }\n } catch (err) {\n console.error(`❌ Finalize error for ${uploadId}:`, err.message);\n console.error(`[FINALIZE] Stack:`, err.stack);\n uploadSessions.delete(uploadId);\n }\n });\n }\n } catch (err) {\n console.error('Chunk upload error:', err.message);\n res.status(500).json({ error: 'Chunk upload failed: ' + err.message });\n }\n});\n\n// Check upload progress endpoint\napp.get('/api/files/upload-progress/:uploadId', verifyToken, (req, res) => {\n const uploadId = req.params.uploadId;\n const session = uploadSessions.get(uploadId);\n\n if (!session) {\n return res.status(404).json({ error: 'Upload session not found' });\n }\n\n if (session.userId !== req.userId) {\n return res.status(403).json({ error: 'Unauthorized' });\n }\n\n const progress = Math.round((session.chunks.size / session.totalChunks) * 100);\n\n res.json({\n uploadId,\n chunksReceived: session.chunks.size,\n totalChunks: session.totalChunks,\n progress,\n complete: session.chunks.size === session.totalChunks,\n missingChunks: Array.from({ length: session.totalChunks }, (_, i) => i).filter(i => !session.chunks.has(i))\n });\n});\n\n// Upload file - Memory-efficient streaming\napp.post('/api/files/upload', verifyToken, (req, res, next) => {\n upload.single('file')(req, res, (err) => {\n // Handle multer errors\n if (err) {\n console.error('Multer error:', err.message);\n if (err.code === 'LIMIT_FILE_SIZE') {\n return res.status(413).json({ error: `File too large. Max size: ${err.limit} bytes` });\n }\n if (err.code === 'LIMIT_FILE_COUNT') {\n return res.status(413).json({ error: 'Too many files' });\n }\n return res.status(400).json({ error: err.message || 'Upload failed' });\n }\n next();\n });\n}, async (req, res) => {\n try {\n if (!req.file) {\n return res.status(400).json({ error: 'No file provided' });\n }\n\n const { description } = req.body;\n const filesCollection = db.collection('files');\n\n // Get actual file size from disk\n const actualSize = req.file.size;\n\n const fileDoc = {\n user_id: req.userId,\n file_name: req.file.originalname,\n file_size: actualSize,\n file_type: req.file.mimetype,\n storage_path: req.file.filename,\n description: description || null,\n is_public: false,\n created_at: new Date(),\n updated_at: new Date(),\n };\n\n // Fast async insert - doesn't wait for completion\n filesCollection.insertOne(fileDoc).catch(err => console.error('DB insert error:', err));\n\n // Send response immediately - data saves in background\n res.json({\n id: req.file.filename,\n file_name: fileDoc.file_name,\n file_size: fileDoc.file_size,\n }).end();\n } catch (err) {\n console.error('Upload error:', err);\n if (req.file && req.file.path) {\n // Async cleanup - don't block response\n fs.unlink(req.file.path, () => {});\n }\n res.status(500).json({ error: 'Upload failed' });\n }\n});\n\n// Get files\napp.get('/api/files', verifyToken, async (req, res) => {\n try {\n const filesCollection = db.collection('files');\n let query = {};\n\n // Check if admin\n const user = await db.collection('users').findOne({ _id: new ObjectId(req.userId) });\n const isAdmin = user?.role === 'admin';\n\n if (!isAdmin) {\n query.user_id = req.userId;\n }\n\n const files = await filesCollection\n .find(query)\n .sort({ created_at: -1 })\n .toArray();\n\n const formattedFiles = files.map(f => ({\n id: f._id.toString(),\n ...f,\n _id: undefined,\n }));\n\n res.json(formattedFiles);\n } catch (err) {\n console.error('Get files error:', err);\n res.status(500).json({ error: 'Failed to fetch files' });\n }\n});\n\n// Delete file\napp.delete('/api/files/:id', verifyToken, async (req, res) => {\n try {\n const filesCollection = db.collection('files');\n const fileDoc = await filesCollection.findOne({ _id: new ObjectId(req.params.id) });\n\n if (!fileDoc) {\n return res.status(404).json({ error: 'File not found' });\n }\n\n // Check ownership or admin\n const user = await db.collection('users').findOne({ _id: new ObjectId(req.userId) });\n const isAdmin = user?.role === 'admin';\n\n if (fileDoc.user_id !== req.userId && !isAdmin) {\n return res.status(403).json({ error: 'Unauthorized' });\n }\n\n // Delete file from disk\n const filePath = path.join(uploadsDir, fileDoc.storage_path);\n fs.unlink(filePath, (err) => {\n if (err) console.error('Error deleting file:', err);\n });\n\n await filesCollection.deleteOne({ _id: new ObjectId(req.params.id) });\n\n res.json({ success: true });\n } catch (err) {\n console.error('Delete file error:', err);\n res.status(500).json({ error: 'Failed to delete file' });\n }\n});\n\n// Get file by storage path\napp.get('/api/files/download/:filename', (req, res) => {\n try {\n const filename = req.params.filename;\n const filepath = path.join(uploadsDir, filename);\n\n // Security: ensure the file is within uploads directory\n if (!path.resolve(filepath).startsWith(path.resolve(uploadsDir))) {\n return res.status(403).json({ error: 'Access denied' });\n }\n\n if (!fs.existsSync(filepath)) {\n return res.status(404).json({ error: 'File not found' });\n }\n\n res.download(filepath);\n } catch (err) {\n console.error('Download error:', err);\n res.status(500).json({ error: 'Download failed' });\n }\n});\n\n// Admin Routes\n\n// Get all users\napp.get('/api/admin/users', verifyToken, async (req, res) => {\n try {\n // Check if admin\n const user = await db.collection('users').findOne({ _id: new ObjectId(req.userId) });\n if (user?.role !== 'admin') {\n return res.status(403).json({ error: 'Unauthorized' });\n }\n\n const usersCollection = db.collection('users');\n const users = await usersCollection\n .find({}, { projection: { password: 0 } })\n .toArray();\n\n const formattedUsers = users.map(u => ({\n id: u._id.toString(),\n ...u,\n _id: undefined,\n isAdmin: u.role === 'admin',\n }));\n\n res.json(formattedUsers);\n } catch (err) {\n console.error('Get users error:', err);\n res.status(500).json({ error: 'Failed to fetch users' });\n }\n});\n\n// Get admin files\napp.get('/api/admin/files', verifyToken, async (req, res) => {\n try {\n // Check if admin\n const user = await db.collection('users').findOne({ _id: new ObjectId(req.userId) });\n if (user?.role !== 'admin') {\n return res.status(403).json({ error: 'Unauthorized' });\n }\n\n const filesCollection = db.collection('files');\n const files = await filesCollection\n .find({})\n .sort({ created_at: -1 })\n .toArray();\n\n const formattedFiles = files.map(f => ({\n id: f._id.toString(),\n ...f,\n _id: undefined,\n }));\n\n res.json(formattedFiles);\n } catch (err) {\n console.error('Get admin files error:', err);\n res.status(500).json({ error: 'Failed to fetch files' });\n }\n});\n\n// Set user as admin\napp.post('/api/admin/users/:userId/role', verifyToken, async (req, res) => {\n try {\n // Check if admin\n const user = await db.collection('users').findOne({ _id: new ObjectId(req.userId) });\n if (user?.role !== 'admin') {\n return res.status(403).json({ error: 'Unauthorized' });\n }\n\n const { role } = req.body;\n const usersCollection = db.collection('users');\n\n // Validate role\n if (!['user', 'admin', 'moderator'].includes(role)) {\n return res.status(400).json({ error: 'Invalid role' });\n }\n\n // Update user role\n await usersCollection.updateOne(\n { _id: new ObjectId(req.params.userId) },\n { $set: { role, updated_at: new Date() } }\n );\n\n res.json({ success: true, role });\n } catch (err) {\n console.error('Set role error:', err);\n res.status(500).json({ error: 'Failed to update role' });\n }\n});\n\n// Health check\napp.get('/health', (req, res) => {\n res.json({ status: 'ok' });\n});\n\n// Health check with stats\napp.get('/health/stats', (req, res) => {\n const activeSessions = uploadSessions.size;\n let totalChunksInProgress = 0;\n let totalSize = 0;\n \n for (const [, session] of uploadSessions.entries()) {\n totalChunksInProgress += session.chunks.size;\n totalSize += session.fileSize || 0;\n }\n \n res.json({\n status: 'ok',\n uptime: process.uptime(),\n memory: process.memoryUsage(),\n pid: process.pid,\n database: {\n schema: 'Embedded role in users collection (no separate user_roles)',\n roles: ['user', 'admin', 'moderator'],\n },\n uploads: {\n activeSessions,\n chunksInProgress: totalChunksInProgress,\n totalSizeInProgress: Math.round(totalSize / 1024 / 1024) + ' MB',\n concurrency: {\n maxConcurrentFiles: 8,\n chunkConcurrencyStrategy: 'adaptive (8-10 for 1 file, 6 for 2-3, 4 for 4+)',\n maxParallelChunkMerges: 4,\n uploadBuffers: { chunk: '96MB', merge: '16MB', readPerStream: '16MB' }\n }\n }\n });\n});\n\n// ⚡ ULTRA-PERFORMANCE: Clustering + Worker Threads\nconst numCPUs = os.cpus().length;\n// DISABLE clustering for now - file uploads need shared session state across workers\n// TODO: Use Redis for shared uploadSessions if clustering needed\nconst enableClustering = false; // process.env.ENABLE_CLUSTERING !== 'false';\n\nif (enableClustering && cluster.isPrimary) {\n console.log(`🚀 Master process ${process.pid} starting...`);\n console.log(`📊 Spawning ${numCPUs} worker processes...`);\n \n // Spawn workers\n for (let i = 0; i < numCPUs; i++) {\n cluster.fork();\n }\n\n // Handle worker restart\n cluster.on('exit', (worker, code, signal) => {\n if (signal) {\n console.log(`⚠️ Worker ${worker.process.pid} killed by signal: ${signal}`);\n } else if (code !== 0) {\n console.log(`⚠️ Worker ${worker.process.pid} exited with error code: ${code}`);\n console.log('🔄 Spawning replacement...');\n cluster.fork();\n }\n });\n\n // Status logger\n setInterval(() => {\n console.log(`📈 Workers: ${Object.keys(cluster.workers).length} | Memory: ${Math.round(process.memoryUsage().heapUsed / 1024 / 1024)}MB`);\n }, 30000);\n} else {\n // Worker process\n initMongoDB().then(() => {\n const server = app.listen(PORT, () => {\n const workerId = cluster.isPrimary ? 'primary' : cluster.worker?.id;\n console.log(`✅ Worker process ${process.pid} (ID: ${workerId}) running on http://localhost:${PORT}`);\n });\n\n // Socket handling optimization\n const maxConnections = 10000;\n server.maxConnections = maxConnections;\n\n // Keep-alive settings - aggressive for high-throughput uploads\n server.keepAliveTimeout = 120000; // 2 min keep-alive for connection reuse\n server.headersTimeout = 125000;\n\n // Error handling\n server.on('error', (err) => {\n console.error('Server error:', err);\n });\n\n // Graceful shutdown\n process.on('SIGTERM', () => {\n console.log(`🛑 Worker ${process.pid} received SIGTERM, shutting down gracefully...`);\n \n // Cleanup intervals\n clearInterval(fileCleanupInterval);\n clearInterval(sessionCleanupInterval);\n \n server.close(async () => {\n console.log(`✅ Worker ${process.pid} server closed`);\n if (mongoClient) {\n await mongoClient.close();\n }\n process.exit(0);\n });\n\n // Force shutdown after 30 seconds\n setTimeout(() => {\n console.error('❌ Forced shutdown after 30s');\n process.exit(1);\n }, 30000);\n });\n\n // Handle other termination signals\n process.on('SIGINT', () => {\n console.log(`🛑 Worker ${process.pid} received SIGINT`);\n clearInterval(fileCleanupInterval);\n clearInterval(sessionCleanupInterval);\n process.exit(0);\n });\n });\n}\n\n",
|
| 5 |
"language": "javascript",
|
| 6 |
"createdAt": 1776244783913,
|
| 7 |
-
"updatedAt":
|
| 8 |
}
|
|
|
|
| 1 |
{
|
| 2 |
"id": "dcc43ef1-4f83-4afe-a59d-61a9ae99cb51",
|
| 3 |
"title": "Untitled",
|
| 4 |
+
"content": "import express from 'express';\nimport { MongoClient, ObjectId } from 'mongodb';\nimport multer from 'multer';\nimport bcryptjs from 'bcryptjs';\nimport jwt from 'jsonwebtoken';\nimport fs from 'fs';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\nimport dotenv from 'dotenv';\nimport cluster from 'cluster';\nimport os from 'os';\nimport compression from 'compression';\n\n// Load environment variables\ndotenv.config({ path: '.env.server' });\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst uploadsDir = path.join(__dirname, 'uploads');\nconst tempChunksDir = path.join(__dirname, 'uploads_tmp');\n\nif (!fs.existsSync(uploadsDir)) {\n fs.mkdirSync(uploadsDir, { recursive: true });\n}\n\nif (!fs.existsSync(tempChunksDir)) {\n fs.mkdirSync(tempChunksDir, { recursive: true });\n}\n\nconst app = express();\nconst PORT = process.env.PORT || 3001;\nconst MONGODB_URI = process.env.MONGODB_URI || 'mongodb+srv://admin:Tuandzvcl@userupload.1zqgqci.mongodb.net/?appName=UserUpload';\nconst JWT_SECRET = process.env.JWT_SECRET || 'TwanDz';\n\n// Rate limiting per IP to prevent abuse\nconst requestCounts = new Map();\nconst RATE_LIMIT_WINDOW = 60000; // 1 minute\nconst MAX_REQUESTS_PER_WINDOW = 1500; // 1500 req/min supports 8 files × adaptive chunks\n\n// Cleanup request counts every 5 minutes\nsetInterval(() => {\n requestCounts.clear();\n}, 5 * 60 * 1000);\n\n// Rate limiter middleware (skip for upload-chunk to allow fast uploads)\napp.use((req, res, next) => {\n // Skip rate limiting for upload-chunk endpoint to allow high-speed parallel uploads\n if (req.path === '/api/files/upload-chunk') {\n return next();\n }\n\n const ip = req.ip;\n const now = Date.now();\n \n if (!requestCounts.has(ip)) {\n requestCounts.set(ip, []);\n }\n \n const requests = requestCounts.get(ip);\n const recentRequests = requests.filter(t => now - t < RATE_LIMIT_WINDOW);\n \n if (recentRequests.length >= MAX_REQUESTS_PER_WINDOW) {\n return res.status(429).json({ error: 'Too many requests, please try again later' });\n }\n \n recentRequests.push(now);\n requestCounts.set(ip, recentRequests);\n next();\n});\n\nlet db;\nlet mongoClient;\n\n// Track concurrent uploads\nconst uploadSessions = new Map(); // uploadId -> { chunks: Set, totalChunks, status }\n\n// Initialize MongoDB\nasync function initMongoDB() {\n try {\n console.log('🔄 Connecting to MongoDB...');\n console.log('URI:', MONGODB_URI.replace(/:[^:]*@/, ':****@')); // Hide password in logs\n \n mongoClient = new MongoClient(MONGODB_URI, {\n serverSelectionTimeoutMS: 5000,\n connectTimeoutMS: 10000,\n // HIGH-PERFORMANCE POOLING: Optimize connection reuse\n maxPoolSize: 80, // Support 8 concurrent files × 10 chunks + parallelism\n minPoolSize: 20, // Keep connections warm for burst uploads\n maxIdleTimeMS: 45000, // Longer idle time reduces reconnection overhead\n waitQueueTimeoutMS: 5000, // Faster timeout for better request queueing\n });\n \n await mongoClient.connect();\n console.log('✅ MongoDB connected successfully');\n \n db = mongoClient.db('file-caddy');\n\n // Create collections if they don't exist\n const collections = await db.listCollections().toArray();\n const collectionNames = collections.map(c => c.name);\n\n if (!collectionNames.includes('users')) {\n await db.createCollection('users');\n await db.collection('users').createIndex({ email: 1 }, { unique: true });\n await db.collection('users').createIndex({ username: 1 }, { unique: true, sparse: true });\n console.log('📦 Created users collection');\n }\n if (!collectionNames.includes('files')) {\n await db.createCollection('files');\n await db.collection('files').createIndex({ user_id: 1 });\n console.log('📦 Created files collection');\n }\n\n console.log('✅ MongoDB fully initialized');\n } catch (err) {\n console.error('❌ MongoDB connection error:', err.message);\n console.error('Full error:', err);\n process.exit(1);\n }\n}\n\n// Middleware - Memory efficient for large uploads\n// Limit JSON requests but NOT file uploads (handled by multer streaming)\napp.use(express.json({ limit: '10mb' }));\napp.use(express.urlencoded({ extended: false, limit: '10mb' })); // Disable extended mode for perf\n\n// ⚡ Response compression for 2-3x faster downloads\napp.use(compression({ level: 6, threshold: 1024 })); // Compress responses > 1KB\n\n// Skip static file serving in production - use CDN/nginx instead\nif (process.env.NODE_ENV !== 'production') {\n app.use('/uploads', express.static(uploadsDir, { \n maxAge: '31d',\n setHeaders: (res) => {\n res.setHeader('Cache-Control', 'public, max-age=2678400, immutable');\n }\n }));\n}\n\n// Increase timeout for large uploads\napp.use((req, res, next) => {\n req.setTimeout(3600000); // 1 hour timeout\n res.setTimeout(3600000);\n // PERF: Increase socket buffer sizes for fast streaming\n if (req.socket) {\n req.socket.setMaxListeners(0); // Unlimited listeners\n }\n next();\n});\n\n// Multer configuration - Optimized for faster uploads\nconst storage = multer.diskStorage({\n destination: (req, file, cb) => {\n cb(null, uploadsDir);\n },\n filename: (req, file, cb) => {\n const uniqueName = `${Date.now()}-${Math.random().toString(36).substr(2, 9)}-${file.originalname}`;\n cb(null, uniqueName);\n }\n});\n\n// High-performance streaming upload configuration\n// Uses disk streaming (not memory buffering) for maximum throughput\nconst upload = multer({\n storage,\n limits: {\n fileSize: 5 * 1024 * 1024 * 1024, // 5GB limit\n files: 10\n },\n // HIGH-PERFORMANCE: 16MB buffer for 100MB/s throughput\n highWaterMark: 16 * 1024 * 1024\n});\n\nconst chunkStorage = multer.diskStorage({\n destination: (req, file, cb) => {\n cb(null, tempChunksDir);\n },\n filename: (req, file, cb) => {\n // Use temporary unique name - will rename after getting uploadId from body\n const tempName = `temp-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n cb(null, tempName);\n }\n});\n\nconst chunkUpload = multer({\n storage: chunkStorage,\n limits: {\n fileSize: 100 * 1024 * 1024, // 100MB per chunk\n files: 1\n },\n highWaterMark: 96 * 1024 * 1024 // 96MB buffer = 3x faster streaming (up to 300MB/s)\n});\n\nasync function tryFinalizeChunkedUpload({ uploadId, totalChunks, originalName, description, mimetype, userId, fileSize }) {\n // Validate parameters\n if (!uploadId || !totalChunks || !originalName || !userId) {\n throw new Error('Missing required parameters for finalize');\n }\n if (typeof fileSize !== 'number' || fileSize <= 0) {\n throw new Error('Invalid fileSize: must be positive number');\n }\n if (totalChunks < 1 || !Number.isInteger(totalChunks)) {\n throw new Error('Invalid totalChunks: must be positive integer');\n }\n\n const parts = Array.from({ length: totalChunks }, (_, index) =>\n path.join(tempChunksDir, `${uploadId}.part.${index}`)\n );\n\n // Check which chunks exist\n console.log(`📦 Merging ${totalChunks} chunks for ${uploadId}`);\n const existingChunks = [];\n for (let i = 0; i < parts.length; i++) {\n if (fs.existsSync(parts[i])) {\n existingChunks.push(i);\n } else {\n console.warn(`⚠️ Missing chunk ${i}: ${parts[i]}`);\n }\n }\n console.log(`✓ Found ${existingChunks.length}/${totalChunks} chunks`);\n\n // Fast check if first chunk exists (fail-fast)\n try {\n await fs.promises.access(parts[0], fs.constants.R_OK);\n } catch {\n console.error(`❌ Cannot read first chunk: ${parts[0]}`);\n return null;\n }\n\n const safeName = `${Date.now()}-${uploadId}-${path.basename(originalName)}`;\n const finalPath = path.join(uploadsDir, safeName);\n console.log(`💾 Saving merged file to: ${finalPath}`);\n \n const writeStream = fs.createWriteStream(finalPath, { flags: 'w', highWaterMark: 16 * 1024 * 1024 }); // 16MB buffer for faster merge writes\n\n // Ultra-fast parallel chunk merging (up to 3 streams at once)\n await new Promise((resolveAll, rejectAll) => {\n let currentIndex = 0;\n let activeStreams = 0;\n const maxActiveStreams = 4; // Process 4 chunks in parallel (more I/O parallelism = faster)\n const queue = [];\n\n const writeNextChunk = () => {\n if (activeStreams >= maxActiveStreams) return;\n if (queue.length === 0 && currentIndex >= parts.length && activeStreams === 0) {\n writeStream.end();\n return;\n }\n if (queue.length === 0) return;\n\n activeStreams++;\n const partPath = queue.shift();\n const readStream = fs.createReadStream(partPath, { highWaterMark: 16 * 1024 * 1024 }); // 16MB buffer per stream for faster reads\n\n readStream.on('error', (err) => {\n writeStream.destroy();\n rejectAll(err);\n });\n\n readStream.on('end', () => {\n activeStreams--;\n // Delete temp chunk immediately (don't wait)\n fs.unlink(partPath, () => {});\n writeNextChunk();\n });\n\n readStream.pipe(writeStream, { end: false });\n };\n\n // Load chunks into queue - allows parallel I/O prep\n const loadChunks = () => {\n // Fill queue up to 8 items for aggressive I/O preparation\n while (currentIndex < parts.length && queue.length < 8) {\n queue.push(parts[currentIndex]);\n currentIndex++;\n }\n // Try to start processing if possible\n if (queue.length > 0 && activeStreams < maxActiveStreams) {\n writeNextChunk();\n }\n // Schedule more loading if we have more chunks\n if (currentIndex < parts.length) {\n setImmediate(loadChunks);\n }\n };\n\n // Handle write stream drain\n const onDrain = () => {\n // When writeStream drains, try to pipe more chunks\n if (queue.length > 0 && activeStreams < maxActiveStreams) {\n writeNextChunk();\n }\n // If no more chunks and no active streams, close the file\n if (currentIndex >= parts.length && queue.length === 0 && activeStreams === 0) {\n writeStream.end();\n }\n };\n\n writeStream.on('drain', onDrain);\n\n writeStream.on('finish', () => {\n console.log(`✅ File write completed: ${finalPath}`);\n console.log(`📊 Final file size: ${fileSize} bytes`);\n \n // Create file doc after write completes\n const fileDoc = {\n user_id: userId,\n file_name: originalName,\n file_size: fileSize,\n file_type: mimetype || 'application/octet-stream',\n storage_path: safeName,\n description: description || null,\n is_public: false,\n created_at: new Date(),\n updated_at: new Date(),\n };\n\n // Verify file exists before inserting to DB\n fs.stat(finalPath, (err, stats) => {\n if (err) {\n console.error(`❌ File not found after write: ${finalPath}`, err);\n return;\n }\n console.log(`📁 File verified: ${stats.size} bytes`);\n \n // Insert to DB\n db.collection('files').insertOne(fileDoc).catch(err => {\n console.error('DB insert error:', err);\n }).then(() => {\n console.log(`💾 Saved to DB: ${originalName}`);\n });\n });\n\n // Clean up upload session\n uploadSessions.delete(uploadId);\n \n resolveAll({ id: safeName, file_name: originalName, file_size: fileSize });\n });\n\n writeStream.on('error', (err) => {\n console.error(`❌ Write stream error: ${err.message}`);\n console.error(err.stack);\n rejectAll(err);\n });\n\n loadChunks();\n });\n}\n\nasync function cleanupOldTempChunks(ageMs = 2 * 60 * 60 * 1000) {\n try {\n const files = await fs.promises.readdir(tempChunksDir);\n const now = Date.now();\n\n await Promise.all(files.map(async (file) => {\n if (!file.includes('.part.')) {\n return;\n }\n const filePath = path.join(tempChunksDir, file);\n try {\n const stat = await fs.promises.stat(filePath);\n if (now - stat.mtimeMs > ageMs) {\n await fs.promises.unlink(filePath);\n }\n } catch (err) {\n // ignore missing file or permission issues\n }\n }));\n } catch (err) {\n console.error('Error cleaning temp chunk files:', err);\n }\n}\n\n// Run cleanup once at startup, then periodically every hour\ncleanupOldTempChunks().catch(err => console.error('Startup temp cleanup failed:', err));\nconst fileCleanupInterval = setInterval(() => cleanupOldTempChunks(), 60 * 60 * 1000);\n\n// Cleanup expired upload sessions to prevent memory leaks\nfunction cleanupExpiredUploadSessions(maxAgeMs = 3600000) { // 1 hour default\n const now = Date.now();\n let cleaned = 0;\n for (const [uploadId, session] of uploadSessions.entries()) {\n if (now - session.createdAt > maxAgeMs) {\n uploadSessions.delete(uploadId);\n cleaned++;\n }\n }\n if (cleaned > 0) {\n console.log(`🧹 Cleaned ${cleaned} expired upload sessions`);\n }\n}\n\nconst sessionCleanupInterval = setInterval(() => cleanupExpiredUploadSessions(), 60000); // Every minute\n\n// Middleware to verify JWT\nfunction verifyToken(req, res, next) {\n const token = req.headers['authorization']?.split(' ')[1];\n if (!token) {\n return res.status(401).json({ error: 'No token provided' });\n }\n try {\n const decoded = jwt.verify(token, JWT_SECRET);\n if (!decoded.userId || !decoded.email) {\n return res.status(401).json({ error: 'Invalid token: missing userId or email' });\n }\n req.userId = decoded.userId;\n req.email = decoded.email;\n next();\n } catch (err) {\n console.warn('Token validation failed:', err.message.substring(0, 100));\n res.status(401).json({ error: 'Invalid or expired token' });\n }\n}\n\n// Input sanitizer utility\nfunction sanitizeInput(str, maxLength = 1000) {\n if (typeof str !== 'string') return '';\n return str.trim().substring(0, maxLength);\n}\n\n// Auth Routes\n\n// Sign up\napp.post('/auth/signup', async (req, res) => {\n try {\n const email = sanitizeInput(req.body.email, 255);\n const password = sanitizeInput(req.body.password, 256);\n const displayName = sanitizeInput(req.body.displayName, 100);\n const username = sanitizeInput(req.body.username, 20);\n\n // Validate email format\n if (!email || !/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email)) {\n return res.status(400).json({ error: 'Invalid email format' });\n }\n\n if (!password || password.length < 6) {\n return res.status(400).json({ error: 'Password must be at least 6 characters' });\n }\n\n if (username && !/^[a-zA-Z0-9_]{3,20}$/.test(username)) {\n return res.status(400).json({ error: 'Username must be 3-20 characters (letters, numbers, underscore only)' });\n }\n\n const usersCollection = db.collection('users');\n const existing = await usersCollection.findOne({ email });\n\n if (existing) {\n return res.status(400).json({ error: 'Email already exists' });\n }\n\n if (username) {\n const existingUsername = await usersCollection.findOne({ username });\n if (existingUsername) {\n return res.status(400).json({ error: 'Username already taken' });\n }\n }\n\n const hashedPassword = await bcryptjs.hash(password, 10);\n const user = {\n email,\n password: hashedPassword,\n username: username || null,\n displayName: displayName || email.split('@')[0],\n display_name: displayName || email.split('@')[0],\n bio: '',\n avatar_url: '',\n location: '',\n website: '',\n phone: '',\n role: 'user', // Mặc định role là 'user'\n social_media: {\n twitter: '',\n github: '',\n linkedin: '',\n instagram: ''\n },\n created_at: new Date(),\n updated_at: new Date(),\n };\n\n const result = await usersCollection.insertOne(user);\n const userId = result.insertedId.toString();\n\n const token = jwt.sign({ userId, email }, JWT_SECRET, { expiresIn: '7d' });\n\n res.json({\n user: {\n id: userId,\n email,\n displayName: user.displayName,\n username: user.username,\n },\n token,\n });\n } catch (err) {\n console.error('Signup error:', err.message);\n if (err.code === 11000) {\n const field = Object.keys(err.keyPattern || {})[0] || 'field';\n res.status(400).json({ error: `${field} already exists` });\n } else {\n res.status(500).json({ error: 'Signup failed' });\n }\n }\n});\n\n// Sign in\napp.post('/auth/signin', async (req, res) => {\n try {\n const { email, password } = req.body;\n\n if (!email || !password) {\n return res.status(400).json({ error: 'Email and password required' });\n }\n\n const usersCollection = db.collection('users');\n const user = await usersCollection.findOne({ email });\n\n if (!user) {\n return res.status(400).json({ error: 'Invalid credentials' });\n }\n\n const isValid = await bcryptjs.compare(password, user.password);\n\n if (!isValid) {\n return res.status(400).json({ error: 'Invalid credentials' });\n }\n\n const token = jwt.sign({ userId: user._id.toString(), email }, JWT_SECRET, { expiresIn: '7d' });\n\n res.json({\n user: {\n id: user._id.toString(),\n email: user.email,\n displayName: user.displayName,\n username: user.username,\n },\n token,\n });\n } catch (err) {\n console.error('Signin error:', err);\n res.status(500).json({ error: 'Signin failed' });\n }\n});\n\n// Get current user\napp.get('/auth/me', verifyToken, async (req, res) => {\n try {\n const usersCollection = db.collection('users');\n const user = await usersCollection.findOne({ _id: new ObjectId(req.userId) });\n\n if (!user) {\n return res.status(404).json({ error: 'User not found' });\n }\n\n // Check if admin\n res.json({\n id: user._id.toString(),\n email: user.email,\n displayName: user.displayName,\n username: user.username || '',\n display_name: user.display_name || user.displayName,\n bio: user.bio || '',\n avatar_url: user.avatar_url || '',\n location: user.location || '',\n website: user.website || '',\n phone: user.phone || '',\n role: user.role || 'user',\n social_media: user.social_media || { twitter: '', github: '', linkedin: '', instagram: '' },\n created_at: user.created_at,\n isAdmin: user.role === 'admin',\n });\n } catch (err) {\n console.error('Get user error:', err);\n res.status(500).json({ error: 'Failed to fetch user' });\n }\n});\n\n// Change password\napp.post('/auth/change-password', verifyToken, async (req, res) => {\n try {\n const { currentPassword, newPassword } = req.body;\n\n if (!currentPassword || !newPassword) {\n return res.status(400).json({ error: 'Current and new password required' });\n }\n\n if (newPassword.length < 6) {\n return res.status(400).json({ error: 'New password must be at least 6 characters' });\n }\n\n const usersCollection = db.collection('users');\n const user = await usersCollection.findOne({ _id: new ObjectId(req.userId) });\n\n if (!user) {\n return res.status(404).json({ error: 'User not found' });\n }\n\n // Verify current password\n const isValid = await bcryptjs.compare(currentPassword, user.password);\n if (!isValid) {\n return res.status(401).json({ error: 'Current password is incorrect' });\n }\n\n // Hash new password\n const hashedPassword = await bcryptjs.hash(newPassword, 10);\n\n // Update password\n await usersCollection.updateOne(\n { _id: new ObjectId(req.userId) },\n { $set: { password: hashedPassword, updated_at: new Date() } }\n );\n\n res.json({ success: true, message: 'Password changed successfully' });\n } catch (err) {\n console.error('Change password error:', err);\n res.status(500).json({ error: 'Failed to change password' });\n }\n});\n\n// Update profile\napp.post('/auth/update-profile', verifyToken, async (req, res) => {\n try {\n const { display_name, bio, avatar_url, location, website, phone, social_media } = req.body;\n\n const usersCollection = db.collection('users');\n const updates = {};\n \n if (display_name !== undefined) updates.display_name = display_name;\n if (bio !== undefined) updates.bio = bio;\n if (avatar_url !== undefined) updates.avatar_url = avatar_url;\n if (location !== undefined) updates.location = location;\n if (website !== undefined) updates.website = website;\n if (phone !== undefined) updates.phone = phone;\n if (social_media !== undefined) updates.social_media = social_media;\n updates.updated_at = new Date();\n\n await usersCollection.updateOne(\n { _id: new ObjectId(req.userId) },\n { $set: updates }\n );\n\n // Return updated user\n const user = await usersCollection.findOne({ _id: new ObjectId(req.userId) });\n\n res.json({\n id: user._id.toString(),\n email: user.email,\n displayName: user.displayName,\n username: user.username || '',\n display_name: user.display_name || user.displayName,\n bio: user.bio || '',\n avatar_url: user.avatar_url || '',\n location: user.location || '',\n website: user.website || '',\n phone: user.phone || '',\n role: user.role || 'user',\n social_media: user.social_media || { twitter: '', github: '', linkedin: '', instagram: '' },\n created_at: user.created_at,\n isAdmin: user.role === 'admin',\n message: 'Profile updated successfully'\n });\n } catch (err) {\n console.error('Update profile error:', err);\n if (err.code === 11000) {\n res.status(400).json({ error: 'Username already taken' });\n } else {\n res.status(500).json({ error: 'Failed to update profile' });\n }\n }\n});\n\n// File Routes\n\n// Chunked upload support for large files - PARALLEL CHUNK SUPPORT\napp.post('/api/files/upload-chunk', verifyToken, (req, res, next) => {\n chunkUpload.single('chunk')(req, res, (err) => {\n if (err) {\n console.error(`Chunk upload error for user ${req.userId}:`, err.message);\n if (err.code === 'LIMIT_FILE_SIZE') {\n return res.status(413).json({ error: `Chunk too large (max: ${(err.limit / 1024 / 1024).toFixed(0)}MB)` });\n }\n return res.status(400).json({ error: err.message || 'Chunk upload failed' });\n }\n next();\n });\n}, async (req, res) => {\n try {\n const uploadId = sanitizeInput(req.body.uploadId, 100);\n const chunkIndex = Number(req.body.chunkIndex);\n const totalChunks = Number(req.body.totalChunks);\n const originalName = sanitizeInput(req.body.fileName, 255);\n const description = sanitizeInput(req.body.description, 1000);\n const isLastChunk = req.body.isLastChunk === 'true';\n\n // Validate metadata\n if (!uploadId || Number.isNaN(chunkIndex) || Number.isNaN(totalChunks) || !originalName) {\n return res.status(400).json({ error: 'Missing or invalid upload metadata' });\n }\n\n if (chunkIndex < 0 || chunkIndex >= totalChunks) {\n return res.status(400).json({ error: 'Invalid chunk index' });\n }\n\n if (totalChunks < 1 || totalChunks > 10000) {\n return res.status(400).json({ error: 'Invalid total chunks (1-10000 allowed)' });\n }\n\n if (!req.file) {\n return res.status(400).json({ error: 'No chunk file provided' });\n }\n\n // Rename temp file to correct chunk filename NOW that we have uploadId/chunkIndex\n const correctChunkName = `${uploadId}.part.${chunkIndex}`;\n const correctChunkPath = path.join(tempChunksDir, correctChunkName);\n const tempFilePath = req.file.path;\n \n try {\n await fs.promises.rename(tempFilePath, correctChunkPath);\n req.file.path = correctChunkPath;\n req.file.filename = correctChunkName;\n } catch (renameErr) {\n console.error(`❌ Failed to rename chunk file: ${renameErr.message}`);\n return res.status(500).json({ error: 'Failed to save chunk' });\n }\n\n console.log(`📥 Received chunk ${chunkIndex + 1}/${totalChunks} for upload ${uploadId.substring(0, 8)}... (${(req.file.size / 1024 / 1024).toFixed(1)}MB)`);\n console.log(` Saved to: ${req.file.path}`);\n\n // Track upload session\n if (!uploadSessions.has(uploadId)) {\n uploadSessions.set(uploadId, { \n chunks: new Set(), \n totalChunks, \n userId: req.userId,\n fileName: originalName,\n description,\n mimetype: req.file.mimetype,\n fileSize: Number(req.body.fileSize),\n createdAt: Date.now(),\n finalized: false,\n finalizedAt: null\n });\n }\n\n const session = uploadSessions.get(uploadId);\n \n // Security: Verify upload belongs to current user\n if (session.userId !== req.userId) {\n return res.status(403).json({ error: 'Upload does not belong to this user' });\n }\n\n session.chunks.add(chunkIndex);\n const chunksReceived = session.chunks.size;\n const progress = Math.round((chunksReceived / totalChunks) * 100);\n\n console.log(` Progress: ${chunksReceived}/${totalChunks} chunks (${progress}%)`);\n\n res.json({ \n chunkIndex, \n totalChunks, \n chunksReceived,\n progress,\n chunkComplete: false,\n ready: chunksReceived === totalChunks\n }).end();\n\n // Async finalize if all chunks received\n // But verify actual chunk files exist (not just in-memory count) since we have clustering\n if (chunksReceived === totalChunks) {\n console.log(`🚀 Memory counter: All chunks received for ${uploadId.substring(0, 8)}... - Verifying chunk files...`);\n \n // Verify all chunks actually exist on disk (async!)\n setImmediate(async () => {\n const allChunkPaths = Array.from({ length: totalChunks }, (_, i) =>\n path.join(tempChunksDir, `${uploadId}.part.${i}`)\n );\n \n const missingChunks = [];\n for (const chunkPath of allChunkPaths) {\n if (!fs.existsSync(chunkPath)) {\n missingChunks.push(chunkPath);\n }\n }\n \n if (missingChunks.length > 0) {\n console.warn(`⚠️ Memory says all ${totalChunks} chunks ready, but ${missingChunks.length} missing on disk!`);\n console.warn(` Missing: ${missingChunks.slice(0, 3).join(', ')}...`);\n // Don't finalize yet - files might still be arriving from other workers\n return;\n }\n \n console.log(`✅ All ${totalChunks} chunks verified on disk - Starting finalization...`);\n try {\n console.log(`[FINALIZE] Starting for ${uploadId}, chunks=${totalChunks}, name=${session.fileName}`);\n const result = await tryFinalizeChunkedUpload({\n uploadId,\n totalChunks,\n originalName: session.fileName,\n description: session.description,\n mimetype: session.mimetype,\n userId: session.userId,\n fileSize: session.fileSize || Number(req.body.fileSize),\n });\n\n if (result) {\n // Mark upload as finalized\n const sessionCheck = uploadSessions.get(uploadId);\n if (sessionCheck) {\n sessionCheck.finalized = true;\n sessionCheck.finalizedAt = Date.now();\n }\n console.log(`✅ Upload complete: ${session.fileName} (${chunksReceived} chunks, user: ${req.userId})`);\n } else {\n console.error(`[FINALIZE] Failed - result is null`);\n }\n } catch (err) {\n console.error(`❌ Finalize error for ${uploadId}:`, err.message);\n console.error(`[FINALIZE] Stack:`, err.stack);\n uploadSessions.delete(uploadId);\n }\n });\n }\n } catch (err) {\n console.error('Chunk upload error:', err.message);\n res.status(500).json({ error: 'Chunk upload failed: ' + err.message });\n }\n});\n\n// Check upload progress endpoint\napp.get('/api/files/upload-progress/:uploadId', verifyToken, (req, res) => {\n const uploadId = req.params.uploadId;\n const session = uploadSessions.get(uploadId);\n\n if (!session) {\n return res.status(404).json({ error: 'Upload session not found' });\n }\n\n if (session.userId !== req.userId) {\n return res.status(403).json({ error: 'Unauthorized' });\n }\n\n const progress = Math.round((session.chunks.size / session.totalChunks) * 100);\n\n res.json({\n uploadId,\n chunksReceived: session.chunks.size,\n totalChunks: session.totalChunks,\n progress,\n complete: session.chunks.size === session.totalChunks,\n missingChunks: Array.from({ length: session.totalChunks }, (_, i) => i).filter(i => !session.chunks.has(i))\n });\n});\n\n// Upload file - Memory-efficient streaming\napp.post('/api/files/upload', verifyToken, (req, res, next) => {\n upload.single('file')(req, res, (err) => {\n // Handle multer errors\n if (err) {\n console.error('Multer error:', err.message);\n if (err.code === 'LIMIT_FILE_SIZE') {\n return res.status(413).json({ error: `File too large. Max size: ${err.limit} bytes` });\n }\n if (err.code === 'LIMIT_FILE_COUNT') {\n return res.status(413).json({ error: 'Too many files' });\n }\n return res.status(400).json({ error: err.message || 'Upload failed' });\n }\n next();\n });\n}, async (req, res) => {\n try {\n if (!req.file) {\n return res.status(400).json({ error: 'No file provided' });\n }\n\n const { description } = req.body;\n const filesCollection = db.collection('files');\n\n // Get actual file size from disk\n const actualSize = req.file.size;\n\n const fileDoc = {\n user_id: req.userId,\n file_name: req.file.originalname,\n file_size: actualSize,\n file_type: req.file.mimetype,\n storage_path: req.file.filename,\n description: description || null,\n is_public: false,\n created_at: new Date(),\n updated_at: new Date(),\n };\n\n // Fast async insert - doesn't wait for completion\n filesCollection.insertOne(fileDoc).catch(err => console.error('DB insert error:', err));\n\n // Send response immediately - data saves in background\n res.json({\n id: req.file.filename,\n file_name: fileDoc.file_name,\n file_size: fileDoc.file_size,\n }).end();\n } catch (err) {\n console.error('Upload error:', err);\n if (req.file && req.file.path) {\n // Async cleanup - don't block response\n fs.unlink(req.file.path, () => {});\n }\n res.status(500).json({ error: 'Upload failed' });\n }\n});\n\n// Get files\napp.get('/api/files', verifyToken, async (req, res) => {\n try {\n const filesCollection = db.collection('files');\n let query = {};\n\n // Check if admin\n const user = await db.collection('users').findOne({ _id: new ObjectId(req.userId) });\n const isAdmin = user?.role === 'admin';\n\n if (!isAdmin) {\n query.user_id = req.userId;\n }\n\n const files = await filesCollection\n .find(query)\n .sort({ created_at: -1 })\n .toArray();\n\n const formattedFiles = files.map(f => ({\n id: f._id.toString(),\n ...f,\n _id: undefined,\n }));\n\n res.json(formattedFiles);\n } catch (err) {\n console.error('Get files error:', err);\n res.status(500).json({ error: 'Failed to fetch files' });\n }\n});\n\n// Delete file\napp.delete('/api/files/:id', verifyToken, async (req, res) => {\n try {\n const filesCollection = db.collection('files');\n const fileDoc = await filesCollection.findOne({ _id: new ObjectId(req.params.id) });\n\n if (!fileDoc) {\n return res.status(404).json({ error: 'File not found' });\n }\n\n // Check ownership or admin\n const user = await db.collection('users').findOne({ _id: new ObjectId(req.userId) });\n const isAdmin = user?.role === 'admin';\n\n if (fileDoc.user_id !== req.userId && !isAdmin) {\n return res.status(403).json({ error: 'Unauthorized' });\n }\n\n // Delete file from disk\n const filePath = path.join(uploadsDir, fileDoc.storage_path);\n fs.unlink(filePath, (err) => {\n if (err) console.error('Error deleting file:', err);\n });\n\n await filesCollection.deleteOne({ _id: new ObjectId(req.params.id) });\n\n res.json({ success: true });\n } catch (err) {\n console.error('Delete file error:', err);\n res.status(500).json({ error: 'Failed to delete file' });\n }\n});\n\n// Get file by storage path\napp.get('/api/files/download/:filename', (req, res) => {\n try {\n const filename = req.params.filename;\n const filepath = path.join(uploadsDir, filename);\n\n // Security: ensure the file is within uploads directory\n if (!path.resolve(filepath).startsWith(path.resolve(uploadsDir))) {\n return res.status(403).json({ error: 'Access denied' });\n }\n\n if (!fs.existsSync(filepath)) {\n return res.status(404).json({ error: 'File not found' });\n }\n\n res.download(filepath);\n } catch (err) {\n console.error('Download error:', err);\n res.status(500).json({ error: 'Download failed' });\n }\n});\n\n// Admin Routes\n\n// Get all users\napp.get('/api/admin/users', verifyToken, async (req, res) => {\n try {\n // Check if admin\n const user = await db.collection('users').findOne({ _id: new ObjectId(req.userId) });\n if (user?.role !== 'admin') {\n return res.status(403).json({ error: 'Unauthorized' });\n }\n\n const usersCollection = db.collection('users');\n const users = await usersCollection\n .find({}, { projection: { password: 0 } })\n .toArray();\n\n const formattedUsers = users.map(u => ({\n id: u._id.toString(),\n ...u,\n _id: undefined,\n isAdmin: u.role === 'admin',\n }));\n\n res.json(formattedUsers);\n } catch (err) {\n console.error('Get users error:', err);\n res.status(500).json({ error: 'Failed to fetch users' });\n }\n});\n\n// Get admin files\napp.get('/api/admin/files', verifyToken, async (req, res) => {\n try {\n // Check if admin\n const user = await db.collection('users').findOne({ _id: new ObjectId(req.userId) });\n if (user?.role !== 'admin') {\n return res.status(403).json({ error: 'Unauthorized' });\n }\n\n const filesCollection = db.collection('files');\n const files = await filesCollection\n .find({})\n .sort({ created_at: -1 })\n .toArray();\n\n const formattedFiles = files.map(f => ({\n id: f._id.toString(),\n ...f,\n _id: undefined,\n }));\n\n res.json(formattedFiles);\n } catch (err) {\n console.error('Get admin files error:', err);\n res.status(500).json({ error: 'Failed to fetch files' });\n }\n});\n\n// Set user as admin\napp.post('/api/admin/users/:userId/role', verifyToken, async (req, res) => {\n try {\n // Check if admin\n const user = await db.collection('users').findOne({ _id: new ObjectId(req.userId) });\n if (user?.role !== 'admin') {\n return res.status(403).json({ error: 'Unauthorized' });\n }\n\n const { role } = req.body;\n const usersCollection = db.collection('users');\n\n // Validate role\n if (!['user', 'admin', 'moderator'].includes(role)) {\n return res.status(400).json({ error: 'Invalid role' });\n }\n\n // Update user role\n await usersCollection.updateOne(\n { _id: new ObjectId(req.params.userId) },\n { $set: { role, updated_at: new Date() } }\n );\n\n res.json({ success: true, role });\n } catch (err) {\n console.error('Set role error:', err);\n res.status(500).json({ error: 'Failed to update role' });\n }\n});\n\n// Get detailed user info with file stats (admin only)\napp.get('/api/admin/users/:userId/detail', verifyToken, async (req, res) => {\n try {\n // Check if admin\n const admin = await db.collection('users').findOne({ _id: new ObjectId(req.userId) });\n if (admin?.role !== 'admin') {\n return res.status(403).json({ error: 'Unauthorized' });\n }\n\n const targetUser = await db.collection('users').findOne(\n { _id: new ObjectId(req.params.userId) },\n { projection: { password: 0 } }\n );\n\n if (!targetUser) {\n return res.status(404).json({ error: 'User not found' });\n }\n\n // Get user's files\n const userFiles = await db.collection('files')\n .find({ user_id: req.params.userId })\n .sort({ created_at: -1 })\n .toArray();\n\n const totalStorage = userFiles.reduce((sum, f) => sum + (f.file_size || 0), 0);\n const averageSize = userFiles.length > 0 ? totalStorage / userFiles.length : 0;\n\n res.json({\n id: targetUser._id.toString(),\n email: targetUser.email,\n displayName: targetUser.displayName,\n username: targetUser.username,\n role: targetUser.role,\n isAdmin: targetUser.role === 'admin',\n bio: targetUser.bio,\n avatar_url: targetUser.avatar_url,\n location: targetUser.location,\n website: targetUser.website,\n phone: targetUser.phone,\n created_at: targetUser.created_at,\n updated_at: targetUser.updated_at,\n stats: {\n totalFiles: userFiles.length,\n totalStorage,\n averageFileSize: averageSize,\n recentFiles: userFiles.slice(0, 5).map(f => ({\n id: f._id.toString(),\n name: f.file_name,\n size: f.file_size,\n type: f.file_type,\n created_at: f.created_at,\n })),\n },\n });\n } catch (err) {\n console.error('Get user detail error:', err);\n res.status(500).json({ error: 'Failed to fetch user details' });\n }\n});\n\n// Delete user file (admin only)\napp.delete('/api/admin/files/:fileId', verifyToken, async (req, res) => {\n try {\n // Check if admin\n const admin = await db.collection('users').findOne({ _id: new ObjectId(req.userId) });\n if (admin?.role !== 'admin') {\n return res.status(403).json({ error: 'Unauthorized' });\n }\n\n const fileDoc = await db.collection('files').findOne({ _id: new ObjectId(req.params.fileId) });\n\n if (!fileDoc) {\n return res.status(404).json({ error: 'File not found' });\n }\n\n // Delete file from disk\n const filePath = path.join(uploadsDir, fileDoc.storage_path);\n fs.unlink(filePath, (err) => {\n if (err) console.error('Error deleting file:', err);\n });\n\n // Delete from database\n await db.collection('files').deleteOne({ _id: new ObjectId(req.params.fileId) });\n\n res.json({ success: true, message: 'File deleted successfully' });\n } catch (err) {\n console.error('Delete file error:', err);\n res.status(500).json({ error: 'Failed to delete file' });\n }\n});\n\n// Delete all user files (admin only)\napp.post('/api/admin/users/:userId/delete-all-files', verifyToken, async (req, res) => {\n try {\n // Check if admin\n const admin = await db.collection('users').findOne({ _id: new ObjectId(req.userId) });\n if (admin?.role !== 'admin') {\n return res.status(403).json({ error: 'Unauthorized' });\n }\n\n // Get all files for this user\n const userFiles = await db.collection('files')\n .find({ user_id: req.params.userId })\n .toArray();\n\n // Delete files from disk\n let deletedCount = 0;\n for (const file of userFiles) {\n const filePath = path.join(uploadsDir, file.storage_path);\n fs.unlink(filePath, (err) => {\n if (err) console.error('Error deleting file:', err);\n });\n deletedCount++;\n }\n\n // Delete all from database\n const result = await db.collection('files').deleteMany({ user_id: req.params.userId });\n\n res.json({ \n success: true, \n message: `Deleted ${result.deletedCount} files`,\n deletedCount: result.deletedCount \n });\n } catch (err) {\n console.error('Delete all files error:', err);\n res.status(500).json({ error: 'Failed to delete files' });\n }\n});\n\n// Get all user files (admin only)\napp.get('/api/admin/users/:userId/files', verifyToken, async (req, res) => {\n try {\n // Check if admin\n const admin = await db.collection('users').findOne({ _id: new ObjectId(req.userId) });\n if (admin?.role !== 'admin') {\n return res.status(403).json({ error: 'Unauthorized' });\n }\n\n const files = await db.collection('files')\n .find({ user_id: req.params.userId })\n .sort({ created_at: -1 })\n .toArray();\n\n const formattedFiles = files.map(f => ({\n id: f._id.toString(),\n ...f,\n _id: undefined,\n }));\n\n res.json(formattedFiles);\n } catch (err) {\n console.error('Get user files error:', err);\n res.status(500).json({ error: 'Failed to fetch user files' });\n }\n});\n\n// Health check\napp.get('/health', (req, res) => {\n res.json({ status: 'ok' });\n});\n\n// Health check with stats\napp.get('/health/stats', (req, res) => {\n const activeSessions = uploadSessions.size;\n let totalChunksInProgress = 0;\n let totalSize = 0;\n \n for (const [, session] of uploadSessions.entries()) {\n totalChunksInProgress += session.chunks.size;\n totalSize += session.fileSize || 0;\n }\n \n res.json({\n status: 'ok',\n uptime: process.uptime(),\n memory: process.memoryUsage(),\n pid: process.pid,\n database: {\n schema: 'Embedded role in users collection (no separate user_roles)',\n roles: ['user', 'admin', 'moderator'],\n },\n uploads: {\n activeSessions,\n chunksInProgress: totalChunksInProgress,\n totalSizeInProgress: Math.round(totalSize / 1024 / 1024) + ' MB',\n concurrency: {\n maxConcurrentFiles: 8,\n chunkConcurrencyStrategy: 'adaptive (8-10 for 1 file, 6 for 2-3, 4 for 4+)',\n maxParallelChunkMerges: 4,\n uploadBuffers: { chunk: '96MB', merge: '16MB', readPerStream: '16MB' }\n }\n }\n });\n});\n\n// ⚡ ULTRA-PERFORMANCE: Clustering + Worker Threads\nconst numCPUs = os.cpus().length;\n// DISABLE clustering for now - file uploads need shared session state across workers\n// TODO: Use Redis for shared uploadSessions if clustering needed\nconst enableClustering = false; // process.env.ENABLE_CLUSTERING !== 'false';\n\nif (enableClustering && cluster.isPrimary) {\n console.log(`🚀 Master process ${process.pid} starting...`);\n console.log(`📊 Spawning ${numCPUs} worker processes...`);\n \n // Spawn workers\n for (let i = 0; i < numCPUs; i++) {\n cluster.fork();\n }\n\n // Handle worker restart\n cluster.on('exit', (worker, code, signal) => {\n if (signal) {\n console.log(`⚠️ Worker ${worker.process.pid} killed by signal: ${signal}`);\n } else if (code !== 0) {\n console.log(`⚠️ Worker ${worker.process.pid} exited with error code: ${code}`);\n console.log('🔄 Spawning replacement...');\n cluster.fork();\n }\n });\n\n // Status logger\n setInterval(() => {\n console.log(`📈 Workers: ${Object.keys(cluster.workers).length} | Memory: ${Math.round(process.memoryUsage().heapUsed / 1024 / 1024)}MB`);\n }, 30000);\n} else {\n // Worker process\n initMongoDB().then(() => {\n const server = app.listen(PORT, () => {\n const workerId = cluster.isPrimary ? 'primary' : cluster.worker?.id;\n console.log(`✅ Worker process ${process.pid} (ID: ${workerId}) running on http://localhost:${PORT}`);\n });\n\n // Socket handling optimization\n const maxConnections = 10000;\n server.maxConnections = maxConnections;\n\n // Keep-alive settings - aggressive for high-throughput uploads\n server.keepAliveTimeout = 120000; // 2 min keep-alive for connection reuse\n server.headersTimeout = 125000;\n\n // Error handling\n server.on('error', (err) => {\n console.error('Server error:', err);\n });\n\n // Graceful shutdown\n process.on('SIGTERM', () => {\n console.log(`🛑 Worker ${process.pid} received SIGTERM, shutting down gracefully...`);\n \n // Cleanup intervals\n clearInterval(fileCleanupInterval);\n clearInterval(sessionCleanupInterval);\n \n server.close(async () => {\n console.log(`✅ Worker ${process.pid} server closed`);\n if (mongoClient) {\n await mongoClient.close();\n }\n process.exit(0);\n });\n\n // Force shutdown after 30 seconds\n setTimeout(() => {\n console.error('❌ Forced shutdown after 30s');\n process.exit(1);\n }, 30000);\n });\n\n // Handle other termination signals\n process.on('SIGINT', () => {\n console.log(`🛑 Worker ${process.pid} received SIGINT`);\n clearInterval(fileCleanupInterval);\n clearInterval(sessionCleanupInterval);\n process.exit(0);\n });\n });\n}\n\n",
|
| 5 |
"language": "javascript",
|
| 6 |
"createdAt": 1776244783913,
|
| 7 |
+
"updatedAt": 1776518462971
|
| 8 |
}
|