Spaces:
Runtime error
Runtime error
blaze-aura69 commited on
Update index.js
Browse files
index.js
CHANGED
|
@@ -2,178 +2,265 @@
|
|
| 2 |
const { Worker: ThreadWorker, isMainThread, parentPort, workerData } = require('worker_threads');
|
| 3 |
const os = require('os');
|
| 4 |
|
| 5 |
-
// ============
|
| 6 |
if (!isMainThread) {
|
| 7 |
-
|
| 8 |
-
const Database = require('better-sqlite3');
|
| 9 |
const path = require('path');
|
| 10 |
const fs = require('fs');
|
| 11 |
-
const
|
|
|
|
| 12 |
const DATA_DIR = workerData.dataDir || "/data";
|
| 13 |
-
const
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
-
//
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
-
//
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
pic_url TEXT DEFAULT '',
|
| 36 |
-
external_links TEXT DEFAULT '[]',
|
| 37 |
-
date_of_birth TEXT DEFAULT '',
|
| 38 |
-
total_times_profile_updated_today INTEGER DEFAULT 0,
|
| 39 |
-
last_profile_updated TEXT DEFAULT '',
|
| 40 |
-
is_profile_public TEXT DEFAULT 'true',
|
| 41 |
-
fing_key TEXT DEFAULT ''
|
| 42 |
-
)
|
| 43 |
-
`);
|
| 44 |
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
CREATE INDEX IF NOT EXISTS idx_email ON users(email);
|
| 48 |
-
`);
|
| 49 |
|
| 50 |
-
//
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
getUserByUsername: db.prepare('SELECT * FROM users WHERE username = ?'),
|
| 55 |
-
insertUser: db.prepare(`
|
| 56 |
-
INSERT OR REPLACE INTO users (
|
| 57 |
-
id, username, password_hash, name, email, country, location, created_at,
|
| 58 |
-
is_login, bio, pic_url, external_links, date_of_birth,
|
| 59 |
-
total_times_profile_updated_today, last_profile_updated, is_profile_public, fing_key
|
| 60 |
-
) VALUES (
|
| 61 |
-
@id, @username, @password_hash, @name, @email, @country, @location, @created_at,
|
| 62 |
-
@is_login, @bio, @pic_url, @external_links, @date_of_birth,
|
| 63 |
-
@total_times_profile_updated_today, @last_profile_updated, @is_profile_public, @fing_key
|
| 64 |
-
)
|
| 65 |
-
`),
|
| 66 |
-
updateLogin: db.prepare('UPDATE users SET is_login = ? WHERE id = ?'),
|
| 67 |
-
updateProfile: db.prepare(`
|
| 68 |
-
UPDATE users SET
|
| 69 |
-
name = COALESCE(NULLIF(@name, ''), name),
|
| 70 |
-
email = COALESCE(NULLIF(@email, ''), email),
|
| 71 |
-
country = COALESCE(NULLIF(@country, ''), country),
|
| 72 |
-
location = COALESCE(NULLIF(@location, ''), location),
|
| 73 |
-
bio = COALESCE(NULLIF(@bio, ''), bio),
|
| 74 |
-
external_links = COALESCE(NULLIF(@external_links, ''), external_links),
|
| 75 |
-
date_of_birth = COALESCE(NULLIF(@date_of_birth, ''), date_of_birth),
|
| 76 |
-
is_profile_public = COALESCE(NULLIF(@is_profile_public, ''), is_profile_public),
|
| 77 |
-
total_times_profile_updated_today = @total_times_profile_updated_today,
|
| 78 |
-
last_profile_updated = @last_profile_updated
|
| 79 |
-
WHERE id = @id
|
| 80 |
-
`),
|
| 81 |
-
updatePhoto: db.prepare('UPDATE users SET pic_url = ? WHERE id = ?'),
|
| 82 |
-
updatePassword: db.prepare('UPDATE users SET password_hash = ? WHERE id = ?')
|
| 83 |
-
};
|
| 84 |
|
| 85 |
-
// Handle messages
|
| 86 |
parentPort.on('message', async (message) => {
|
| 87 |
const { id, action, data } = message;
|
| 88 |
try {
|
| 89 |
let result;
|
|
|
|
| 90 |
switch (action) {
|
| 91 |
case 'getAllUsers':
|
| 92 |
-
result =
|
| 93 |
break;
|
|
|
|
| 94 |
case 'getUserById':
|
| 95 |
-
result =
|
| 96 |
break;
|
|
|
|
| 97 |
case 'getUserByUsername':
|
| 98 |
-
result =
|
| 99 |
break;
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
result =
|
| 103 |
break;
|
| 104 |
-
|
| 105 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
result = { success: true };
|
| 107 |
break;
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
result = { success: true };
|
| 123 |
break;
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
result =
|
| 127 |
break;
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
result = {
|
|
|
|
|
|
|
|
|
|
| 131 |
break;
|
|
|
|
| 132 |
case 'batchOperation':
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
break;
|
|
|
|
| 138 |
default:
|
| 139 |
throw new Error(`Unknown action: ${action}`);
|
| 140 |
}
|
|
|
|
| 141 |
parentPort.postMessage({ id, success: true, result });
|
| 142 |
} catch (error) {
|
| 143 |
parentPort.postMessage({ id, success: false, error: error.message });
|
| 144 |
}
|
| 145 |
});
|
| 146 |
|
| 147 |
-
|
| 148 |
-
const transaction = db.transaction(() => {
|
| 149 |
-
for (const op of operations) {
|
| 150 |
-
switch (op.action) {
|
| 151 |
-
case 'signup':
|
| 152 |
-
stmts.insertUser.run(op.user);
|
| 153 |
-
break;
|
| 154 |
-
case 'login':
|
| 155 |
-
stmts.updateLogin.run(1, op.userId);
|
| 156 |
-
break;
|
| 157 |
-
case 'logout':
|
| 158 |
-
stmts.updateLogin.run(0, op.userId);
|
| 159 |
-
break;
|
| 160 |
-
case 'updateProfile':
|
| 161 |
-
stmts.updateProfile.run(op.data);
|
| 162 |
-
break;
|
| 163 |
-
case 'updatePassword':
|
| 164 |
-
stmts.updatePassword.run(op.passwordHash, op.userId);
|
| 165 |
-
break;
|
| 166 |
-
case 'updatePhoto':
|
| 167 |
-
stmts.updatePhoto.run(op.picUrl, op.userId);
|
| 168 |
-
break;
|
| 169 |
-
}
|
| 170 |
-
}
|
| 171 |
-
});
|
| 172 |
-
transaction();
|
| 173 |
-
return { processed: operations.length };
|
| 174 |
-
}
|
| 175 |
-
|
| 176 |
-
console.log(`DB Worker Thread: SQLite initialized at ${dbPath}`);
|
| 177 |
|
| 178 |
} else {
|
| 179 |
// ============ MAIN THREAD - FASTIFY SERVER ============
|
|
@@ -195,9 +282,8 @@ if (!isMainThread) {
|
|
| 195 |
const { Readable } = require('stream');
|
| 196 |
|
| 197 |
// Dynamic imports
|
| 198 |
-
let
|
| 199 |
-
try {
|
| 200 |
-
try { sharp = require('sharp'); } catch (e) { console.log(`Main: Sharp not available, image compression disabled`); }
|
| 201 |
|
| 202 |
// ============ CONSTANTS ============
|
| 203 |
const MAX_BUCKET_SIZE = 60 * 1024 * 1024 * 1024;
|
|
@@ -216,7 +302,6 @@ if (!isMainThread) {
|
|
| 216 |
const MAX_EMAIL_LENGTH = 200;
|
| 217 |
const MAX_RPS = 15000;
|
| 218 |
const SPACE_NAMES = ["data2"];
|
| 219 |
-
const BASE_SPACE_URL = "https://velost-db1-{space}.hf.space";
|
| 220 |
const CURRENT_SPACE_NAME = "1";
|
| 221 |
const BATCH_SIZE = 15000;
|
| 222 |
const HASH = process.env.HASH || 'v3l0st-d3f4ult-h4sh-k3y-2024!@#$%^&*()';
|
|
@@ -238,14 +323,10 @@ if (!isMainThread) {
|
|
| 238 |
}
|
| 239 |
});
|
| 240 |
|
| 241 |
-
if (!fs.existsSync(FULL_FILE))
|
| 242 |
-
|
| 243 |
-
}
|
| 244 |
-
if (!fs.existsSync(SIZE_FILE)) {
|
| 245 |
-
fs.writeFileSync(SIZE_FILE, '', 'utf8');
|
| 246 |
-
}
|
| 247 |
|
| 248 |
-
// ============
|
| 249 |
let dbWorker;
|
| 250 |
let dbRequestId = 0;
|
| 251 |
const dbPromises = new Map();
|
|
@@ -271,7 +352,7 @@ if (!isMainThread) {
|
|
| 271 |
|
| 272 |
dbWorker.on('error', reject);
|
| 273 |
dbWorker.on('online', () => {
|
| 274 |
-
console.log(`Main:
|
| 275 |
resolve();
|
| 276 |
});
|
| 277 |
});
|
|
@@ -285,33 +366,6 @@ if (!isMainThread) {
|
|
| 285 |
});
|
| 286 |
}
|
| 287 |
|
| 288 |
-
// ============ REDIS SETUP ============
|
| 289 |
-
let redis = null;
|
| 290 |
-
if (Redis) {
|
| 291 |
-
try {
|
| 292 |
-
redis = new Redis({
|
| 293 |
-
host: process.env.REDIS_HOST || '127.0.0.1',
|
| 294 |
-
port: process.env.REDIS_PORT || 6379,
|
| 295 |
-
maxRetriesPerRequest: 3,
|
| 296 |
-
enableReadyCheck: true,
|
| 297 |
-
lazyConnect: true,
|
| 298 |
-
connectTimeout: 5000,
|
| 299 |
-
retryStrategy(times) {
|
| 300 |
-
if (times > 3) {
|
| 301 |
-
console.log(`Main: Redis retry limit reached, disabling Redis buffering`);
|
| 302 |
-
return null;
|
| 303 |
-
}
|
| 304 |
-
return Math.min(times * 50, 2000);
|
| 305 |
-
}
|
| 306 |
-
});
|
| 307 |
-
redis.on('error', (err) => { console.error(`Main: Redis error:`, err.message); });
|
| 308 |
-
redis.on('close', () => { console.log(`Main: Redis connection closed`); });
|
| 309 |
-
} catch (e) {
|
| 310 |
-
console.log(`Main: Failed to create Redis client:`, e.message);
|
| 311 |
-
redis = null;
|
| 312 |
-
}
|
| 313 |
-
}
|
| 314 |
-
|
| 315 |
// ============ IN-MEMORY STORAGE ============
|
| 316 |
let usersCache = new Map();
|
| 317 |
let batchBuffer = [];
|
|
@@ -557,18 +611,13 @@ if (!isMainThread) {
|
|
| 557 |
.toBuffer();
|
| 558 |
}
|
| 559 |
|
| 560 |
-
return {
|
| 561 |
-
buffer: outputBuffer,
|
| 562 |
-
isWebp: true,
|
| 563 |
-
sizeKb: outputBuffer.length / 1024,
|
| 564 |
-
wasCompressed: true
|
| 565 |
-
};
|
| 566 |
} catch (e) {
|
| 567 |
return { buffer: fileData, isWebp: false, sizeKb: fileData.length / 1024, wasCompressed: false };
|
| 568 |
}
|
| 569 |
}
|
| 570 |
|
| 571 |
-
// ============ DATA MANAGEMENT ============
|
| 572 |
async function loadUsersToMemory() {
|
| 573 |
try {
|
| 574 |
const users = await dbRequest('getAllUsers');
|
|
@@ -586,7 +635,7 @@ if (!isMainThread) {
|
|
| 586 |
if (usersCache.has(userId)) return usersCache.get(userId);
|
| 587 |
try {
|
| 588 |
const user = await dbRequest('getUserById', { userId });
|
| 589 |
-
if (user) usersCache.set(
|
| 590 |
return user;
|
| 591 |
} catch (e) {
|
| 592 |
return null;
|
|
@@ -636,222 +685,127 @@ if (!isMainThread) {
|
|
| 636 |
}
|
| 637 |
|
| 638 |
// ============ BATCH PROCESSING ============
|
| 639 |
-
let lastBatchTime = Date.now();
|
| 640 |
-
|
| 641 |
function scheduleBatchProcess() {
|
| 642 |
if (batchTimer) return;
|
| 643 |
batchTimer = setTimeout(async () => {
|
| 644 |
batchTimer = null;
|
| 645 |
-
await
|
| 646 |
}, 1000);
|
| 647 |
}
|
| 648 |
|
| 649 |
-
async function
|
| 650 |
if (batchBuffer.length === 0 || processingLock) return;
|
| 651 |
processingLock = true;
|
| 652 |
|
| 653 |
const batch = batchBuffer.splice(0, BATCH_SIZE);
|
| 654 |
-
|
| 655 |
-
console.log(`Main: Processing batch of ${batchCount} requests (${batchBuffer.length} remaining)`);
|
| 656 |
|
| 657 |
-
const startTime = Date.now();
|
| 658 |
try {
|
| 659 |
await processRequestsBatch(batch);
|
| 660 |
-
|
| 661 |
-
console.log(`Main: Batch of ${batchCount} processed in ${duration}ms`);
|
| 662 |
-
|
| 663 |
-
if (batchBuffer.length > 0) {
|
| 664 |
-
processingLock = false;
|
| 665 |
-
scheduleBatchProcess();
|
| 666 |
-
return;
|
| 667 |
-
}
|
| 668 |
} catch (e) {
|
| 669 |
-
console.error(`Main: Batch
|
| 670 |
batchBuffer.unshift(...batch);
|
| 671 |
} finally {
|
| 672 |
processingLock = false;
|
| 673 |
-
|
| 674 |
-
}
|
| 675 |
-
|
| 676 |
-
async function processFromRedis() {
|
| 677 |
-
if (!redis || redis.status !== 'ready') return;
|
| 678 |
-
try {
|
| 679 |
-
const keys = await redis.keys('req:*');
|
| 680 |
-
if (keys.length === 0) return;
|
| 681 |
-
|
| 682 |
-
const chunks = [];
|
| 683 |
-
for (let i = 0; i < keys.length; i += BATCH_SIZE) {
|
| 684 |
-
chunks.push(keys.slice(i, i + BATCH_SIZE));
|
| 685 |
-
}
|
| 686 |
-
|
| 687 |
-
for (const chunk of chunks) {
|
| 688 |
-
const pipeline = redis.pipeline();
|
| 689 |
-
chunk.forEach(key => pipeline.get(key));
|
| 690 |
-
const results = await pipeline.exec();
|
| 691 |
-
|
| 692 |
-
const requests = results
|
| 693 |
-
.filter(([err, data]) => !err && data)
|
| 694 |
-
.map(([err, data]) => {
|
| 695 |
-
try { return JSON.parse(data); } catch (parseError) { return null; }
|
| 696 |
-
})
|
| 697 |
-
.filter(req => req !== null);
|
| 698 |
-
|
| 699 |
-
if (requests.length > 0) {
|
| 700 |
-
await processRequestsBatch(requests);
|
| 701 |
-
}
|
| 702 |
-
|
| 703 |
-
const deletePipeline = redis.pipeline();
|
| 704 |
-
chunk.forEach(key => deletePipeline.del(key));
|
| 705 |
-
await deletePipeline.exec();
|
| 706 |
-
}
|
| 707 |
-
} catch (e) {
|
| 708 |
-
console.error(`Main: Redis processing error:`, e.message);
|
| 709 |
}
|
| 710 |
}
|
| 711 |
|
| 712 |
async function processRequestsBatch(requests) {
|
| 713 |
-
if (!requests || requests.length === 0)
|
| 714 |
-
console.log('Main: No requests to process');
|
| 715 |
-
return;
|
| 716 |
-
}
|
| 717 |
|
| 718 |
-
console.log(`Main: Processing ${requests.length} requests in batch`);
|
| 719 |
const operations = [];
|
| 720 |
|
| 721 |
for (const req of requests) {
|
| 722 |
-
|
| 723 |
-
|
| 724 |
-
|
| 725 |
-
|
| 726 |
-
|
| 727 |
-
|
| 728 |
-
|
| 729 |
-
|
| 730 |
-
|
| 731 |
-
|
| 732 |
-
|
| 733 |
-
|
| 734 |
-
|
| 735 |
-
|
| 736 |
-
|
| 737 |
-
|
| 738 |
-
|
| 739 |
-
|
| 740 |
-
|
| 741 |
-
|
| 742 |
-
|
| 743 |
-
|
| 744 |
-
|
| 745 |
-
|
| 746 |
-
|
| 747 |
-
|
| 748 |
-
|
| 749 |
-
total_times_profile_updated_today: 0,
|
| 750 |
-
last_profile_updated: '',
|
| 751 |
-
is_profile_public: 'true',
|
| 752 |
-
fing_key: (req.data && req.data.fing_key) || generateFingKey()
|
| 753 |
-
}
|
| 754 |
-
});
|
| 755 |
-
usersCache.set(req.user_id, operations[operations.length - 1].user);
|
| 756 |
-
break;
|
| 757 |
-
|
| 758 |
-
case 'login':
|
| 759 |
-
operations.push({ action: 'login', userId: req.user_id });
|
| 760 |
-
const loginUser = usersCache.get(req.user_id);
|
| 761 |
-
if (loginUser) loginUser.is_login = 1;
|
| 762 |
-
break;
|
| 763 |
-
|
| 764 |
-
case 'logout':
|
| 765 |
-
operations.push({ action: 'logout', userId: req.user_id });
|
| 766 |
-
const logoutUser = usersCache.get(req.user_id);
|
| 767 |
-
if (logoutUser) logoutUser.is_login = 0;
|
| 768 |
-
break;
|
| 769 |
-
|
| 770 |
-
case 'update_profile':
|
| 771 |
-
const profileUser = usersCache.get(req.user_id);
|
| 772 |
-
const updateData = req.data || {};
|
| 773 |
-
|
| 774 |
-
if (profileUser) {
|
| 775 |
-
const fields = ['name', 'email', 'country', 'location', 'bio', 'external_links', 'date_of_birth', 'is_profile_public'];
|
| 776 |
-
for (const field of fields) {
|
| 777 |
-
if (updateData[field] !== null && updateData[field] !== undefined && updateData[field] !== '') {
|
| 778 |
-
profileUser[field] = typeof updateData[field] === 'string' ? updateData[field].trim() : String(updateData[field]).trim();
|
| 779 |
-
}
|
| 780 |
-
}
|
| 781 |
-
profileUser.total_times_profile_updated_today = (profileUser.total_times_profile_updated_today || 0) + 1;
|
| 782 |
-
profileUser.last_profile_updated = new Date().toISOString();
|
| 783 |
}
|
| 784 |
-
|
| 785 |
-
|
| 786 |
-
|
| 787 |
-
|
| 788 |
-
|
| 789 |
-
|
| 790 |
-
|
| 791 |
-
|
| 792 |
-
|
| 793 |
-
|
| 794 |
-
|
| 795 |
-
|
| 796 |
-
|
| 797 |
-
|
| 798 |
-
|
| 799 |
-
|
| 800 |
-
|
| 801 |
-
|
| 802 |
-
|
| 803 |
-
|
| 804 |
-
|
| 805 |
-
|
| 806 |
-
|
| 807 |
-
|
| 808 |
-
|
| 809 |
-
|
| 810 |
-
|
| 811 |
-
operations.push({ action: 'updatePhoto', userId: req.user_id, picUrl: `/photos/${filename}` });
|
| 812 |
-
} catch (photoError) {
|
| 813 |
-
console.error(`Main: Photo processing error:`, photoError.message);
|
| 814 |
-
}
|
| 815 |
}
|
| 816 |
-
|
| 817 |
-
|
| 818 |
-
|
| 819 |
-
|
| 820 |
-
|
| 821 |
-
|
| 822 |
-
|
| 823 |
-
|
| 824 |
-
|
| 825 |
-
|
| 826 |
-
|
| 827 |
-
|
| 828 |
-
|
| 829 |
-
|
| 830 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 831 |
}
|
| 832 |
}
|
| 833 |
|
| 834 |
if (operations.length > 0) {
|
| 835 |
-
|
| 836 |
-
await dbRequest('batchOperation', { operations });
|
| 837 |
-
console.log(`Main: Successfully processed ${operations.length} operations`);
|
| 838 |
-
} catch (dbError) {
|
| 839 |
-
console.error(`Main: DB batch operation failed:`, dbError.message);
|
| 840 |
-
throw dbError;
|
| 841 |
-
}
|
| 842 |
}
|
| 843 |
}
|
| 844 |
|
| 845 |
function addRequest(userId, username, action, data, picBuffer = null) {
|
| 846 |
-
if (!userId)
|
| 847 |
-
|
| 848 |
-
userId = generateId();
|
| 849 |
-
}
|
| 850 |
-
|
| 851 |
-
if (!action) {
|
| 852 |
-
console.error('Main: Cannot add request - missing action, using unknown');
|
| 853 |
-
action = 'unknown';
|
| 854 |
-
}
|
| 855 |
|
| 856 |
const safeData = data || {};
|
| 857 |
|
|
@@ -863,21 +817,6 @@ if (!isMainThread) {
|
|
| 863 |
safeData.fing_key = safeData.fing_key || generateFingKey();
|
| 864 |
}
|
| 865 |
|
| 866 |
-
if (action === 'update_profile') {
|
| 867 |
-
safeData.name = safeData.name || null;
|
| 868 |
-
safeData.email = safeData.email || null;
|
| 869 |
-
safeData.country = safeData.country || null;
|
| 870 |
-
safeData.location = safeData.location || null;
|
| 871 |
-
safeData.bio = safeData.bio || null;
|
| 872 |
-
safeData.external_links = safeData.external_links || null;
|
| 873 |
-
safeData.date_of_birth = safeData.date_of_birth || null;
|
| 874 |
-
safeData.is_profile_public = safeData.is_profile_public || null;
|
| 875 |
-
}
|
| 876 |
-
|
| 877 |
-
if (action === 'forgot_password') {
|
| 878 |
-
safeData.new_password = safeData.new_password || 'default123';
|
| 879 |
-
}
|
| 880 |
-
|
| 881 |
const request = {
|
| 882 |
id: generateId(),
|
| 883 |
user_id: userId,
|
|
@@ -885,11 +824,9 @@ if (!isMainThread) {
|
|
| 885 |
action: action,
|
| 886 |
data: safeData,
|
| 887 |
pic_buffer: picBuffer ? picBuffer.toString('base64') : null,
|
| 888 |
-
type: action,
|
| 889 |
timestamp: Date.now()
|
| 890 |
};
|
| 891 |
|
| 892 |
-
console.log(`Main: Added request - action: ${action}, userId: ${userId}`);
|
| 893 |
batchBuffer.push(request);
|
| 894 |
scheduleBatchProcess();
|
| 895 |
return request.id;
|
|
@@ -915,7 +852,6 @@ if (!isMainThread) {
|
|
| 915 |
maxAge: 86400000
|
| 916 |
});
|
| 917 |
|
| 918 |
-
// ============ FIXED: onRequest hook returns proper JSON ============
|
| 919 |
fastify.addHook('onRequest', async (request, reply) => {
|
| 920 |
const cpuUsage = getCurrentCPUPercentage();
|
| 921 |
const totalUsers = getTotalUsers();
|
|
@@ -944,7 +880,7 @@ if (!isMainThread) {
|
|
| 944 |
}
|
| 945 |
});
|
| 946 |
|
| 947 |
-
// ============ ALL ROUTES RETURN JSON
|
| 948 |
|
| 949 |
fastify.get('/', async (request, reply) => {
|
| 950 |
const spaceFull = isSpaceFull();
|
|
@@ -955,20 +891,13 @@ if (!isMainThread) {
|
|
| 955 |
|
| 956 |
reply.header('Content-Type', 'application/json');
|
| 957 |
return {
|
| 958 |
-
message: 'Velost Auth API -
|
| 959 |
-
version: '
|
| 960 |
worker_pid: process.pid,
|
| 961 |
-
architecture: '1 Process + 1
|
| 962 |
space_name: CURRENT_SPACE_NAME,
|
| 963 |
-
hash_type: 'SHA256',
|
| 964 |
-
database: 'SQLite (better-sqlite3) via Worker Thread',
|
| 965 |
-
rate_limits: {
|
| 966 |
-
global_rps: `${MAX_RPS} requests/second`,
|
| 967 |
-
per_ip_rps: `${MAX_RPS} requests/second`,
|
| 968 |
-
current_global_rps: globalRateLimiter.getCurrentCount()
|
| 969 |
-
},
|
| 970 |
storage: {
|
| 971 |
-
type:
|
| 972 |
max_ram_gb: 7,
|
| 973 |
current_ram_mb: Math.round(getMemoryUsage() / (1024 * 1024) * 100) / 100,
|
| 974 |
max_bucket_size: '60GB',
|
|
@@ -976,12 +905,6 @@ if (!isMainThread) {
|
|
| 976 |
max_users: MAX_USERS,
|
| 977 |
current_users: getTotalUsers()
|
| 978 |
},
|
| 979 |
-
processing: {
|
| 980 |
-
buffer_size: batchBuffer.length,
|
| 981 |
-
batch_size: BATCH_SIZE,
|
| 982 |
-
processing: 'WORKER_THREAD_BATCH',
|
| 983 |
-
cpu_usage_percent: cpuUsage.toFixed(1)
|
| 984 |
-
},
|
| 985 |
space_status: {
|
| 986 |
is_full: spaceFull,
|
| 987 |
full_spaces: fullSpaces,
|
|
@@ -989,53 +912,22 @@ if (!isMainThread) {
|
|
| 989 |
size_spaces: sizeSpaces,
|
| 990 |
all_spaces: SPACE_NAMES
|
| 991 |
},
|
| 992 |
-
image_processing: {
|
| 993 |
-
format: 'webp',
|
| 994 |
-
max_size_kb: MAX_PHOTO_SIZE_KB,
|
| 995 |
-
auto_compress: true
|
| 996 |
-
},
|
| 997 |
timestamp: new Date().toISOString()
|
| 998 |
};
|
| 999 |
});
|
| 1000 |
|
| 1001 |
fastify.get('/status', async (request, reply) => {
|
| 1002 |
-
const spaceFull = isSpaceFull();
|
| 1003 |
await checkAndUpdateFullStatus();
|
| 1004 |
const fullSpaces = await getFullSpaces();
|
| 1005 |
const emptySpaces = SPACE_NAMES.filter(s => !fullSpaces.includes(s));
|
| 1006 |
-
const sizeSpaces = await getSizeSpaces();
|
| 1007 |
-
const cpuUsage = getCurrentCPUPercentage();
|
| 1008 |
-
const totalUsers = getTotalUsers();
|
| 1009 |
|
| 1010 |
reply.header('Content-Type', 'application/json');
|
| 1011 |
return {
|
| 1012 |
-
worker_pid: process.pid,
|
| 1013 |
-
architecture: '1 Process + 1 DB Thread',
|
| 1014 |
space: CURRENT_SPACE_NAME,
|
| 1015 |
-
is_full:
|
| 1016 |
-
|
| 1017 |
-
global_rps_current: globalRateLimiter.getCurrentCount(),
|
| 1018 |
-
global_rps_max: MAX_RPS
|
| 1019 |
-
},
|
| 1020 |
-
storage: {
|
| 1021 |
-
type: 'SQLite via Worker Thread',
|
| 1022 |
-
location: '/data/users.db',
|
| 1023 |
-
current_bucket_size: formatSize(getBucketSize())
|
| 1024 |
-
},
|
| 1025 |
-
ram: {
|
| 1026 |
-
current_mb: Math.round(getMemoryUsage() / (1024 * 1024) * 100) / 100,
|
| 1027 |
-
users_in_memory: totalUsers
|
| 1028 |
-
},
|
| 1029 |
-
cpu: {
|
| 1030 |
-
usage_percent: cpuUsage.toFixed(1)
|
| 1031 |
-
},
|
| 1032 |
-
users: {
|
| 1033 |
-
current: totalUsers,
|
| 1034 |
-
max: MAX_USERS
|
| 1035 |
-
},
|
| 1036 |
full_spaces: fullSpaces,
|
| 1037 |
empty_spaces: emptySpaces,
|
| 1038 |
-
size_spaces: sizeSpaces,
|
| 1039 |
timestamp: new Date().toISOString()
|
| 1040 |
};
|
| 1041 |
});
|
|
@@ -1044,14 +936,12 @@ if (!isMainThread) {
|
|
| 1044 |
reply.header('Content-Type', 'application/json');
|
| 1045 |
return {
|
| 1046 |
status: 'healthy',
|
| 1047 |
-
|
| 1048 |
users: getTotalUsers(),
|
| 1049 |
-
global_rps: globalRateLimiter.getCurrentCount(),
|
| 1050 |
timestamp: new Date().toISOString()
|
| 1051 |
};
|
| 1052 |
});
|
| 1053 |
|
| 1054 |
-
// ============ FIXED: /signup returns JSON object (not JSON.stringify) ============
|
| 1055 |
fastify.post('/signup', async (request, reply) => {
|
| 1056 |
if (getTotalUsers() >= MAX_USERS) {
|
| 1057 |
reply.status(507);
|
|
@@ -1119,12 +1009,14 @@ if (!isMainThread) {
|
|
| 1119 |
fing_key: fing_key ? fing_key.trim() : generateFingKey()
|
| 1120 |
};
|
| 1121 |
|
|
|
|
| 1122 |
usersCache.set(userId, newUser);
|
| 1123 |
|
|
|
|
| 1124 |
try {
|
| 1125 |
await dbRequest('insertUser', { user: newUser });
|
| 1126 |
} catch (dbError) {
|
| 1127 |
-
console.error('
|
| 1128 |
addRequest(userId, cleanUsername, 'signup', {
|
| 1129 |
username: cleanUsername,
|
| 1130 |
password: password,
|
|
@@ -1134,7 +1026,6 @@ if (!isMainThread) {
|
|
| 1134 |
});
|
| 1135 |
}
|
| 1136 |
|
| 1137 |
-
// FIXED: Return plain object - Fastify handles JSON serialization
|
| 1138 |
reply.header('Content-Type', 'application/json');
|
| 1139 |
return {
|
| 1140 |
success: true,
|
|
@@ -1177,7 +1068,6 @@ if (!isMainThread) {
|
|
| 1177 |
reply.header('Content-Type', 'application/json');
|
| 1178 |
return {
|
| 1179 |
success: true,
|
| 1180 |
-
worker_pid: process.pid,
|
| 1181 |
id: user.id,
|
| 1182 |
username: user.username,
|
| 1183 |
name: user.name,
|
|
@@ -1192,8 +1082,6 @@ if (!isMainThread) {
|
|
| 1192 |
date_of_birth: safeGet(user.date_of_birth),
|
| 1193 |
is_profile_public: safeGet(user.is_profile_public, 'true'),
|
| 1194 |
fing_key: safeGet(user.fing_key, ''),
|
| 1195 |
-
total_times_profile_updated_today: parseInt(safeGet(user.total_times_profile_updated_today, 0)),
|
| 1196 |
-
last_profile_updated: safeGet(user.last_profile_updated),
|
| 1197 |
timestamp: new Date().toISOString()
|
| 1198 |
};
|
| 1199 |
});
|
|
@@ -1217,11 +1105,7 @@ if (!isMainThread) {
|
|
| 1217 |
addRequest(id, '', 'logout', {});
|
| 1218 |
|
| 1219 |
reply.header('Content-Type', 'application/json');
|
| 1220 |
-
return {
|
| 1221 |
-
success: true,
|
| 1222 |
-
message: 'Logged out successfully',
|
| 1223 |
-
timestamp: new Date().toISOString()
|
| 1224 |
-
};
|
| 1225 |
});
|
| 1226 |
|
| 1227 |
fastify.put('/updateprofiledetails', async (request, reply) => {
|
|
@@ -1249,25 +1133,10 @@ if (!isMainThread) {
|
|
| 1249 |
}
|
| 1250 |
}
|
| 1251 |
|
| 1252 |
-
const today = new Date().toISOString().split('T')[0];
|
| 1253 |
-
const lastUpdated = safeGet(user.last_profile_updated, '');
|
| 1254 |
-
const lastUpdatedDate = lastUpdated ? lastUpdated.substring(0, 10) : '';
|
| 1255 |
-
const currentUpdatesToday = parseInt(safeGet(user.total_times_profile_updated_today, 0));
|
| 1256 |
-
|
| 1257 |
-
if (lastUpdatedDate === today && currentUpdatesToday >= MAX_PROFILE_UPDATES_PER_DAY) {
|
| 1258 |
-
reply.status(429);
|
| 1259 |
-
reply.header('Content-Type', 'application/json');
|
| 1260 |
-
return { detail: `Profile update limit reached. Max ${MAX_PROFILE_UPDATES_PER_DAY} updates per day.` };
|
| 1261 |
-
}
|
| 1262 |
-
|
| 1263 |
addRequest(id, '', 'update_profile', data);
|
| 1264 |
|
| 1265 |
reply.header('Content-Type', 'application/json');
|
| 1266 |
-
return {
|
| 1267 |
-
success: true,
|
| 1268 |
-
message: 'Profile update processed',
|
| 1269 |
-
timestamp: new Date().toISOString()
|
| 1270 |
-
};
|
| 1271 |
});
|
| 1272 |
|
| 1273 |
fastify.post('/uploadphoto', async (request, reply) => {
|
|
@@ -1320,14 +1189,12 @@ if (!isMainThread) {
|
|
| 1320 |
timestamp: new Date().toISOString()
|
| 1321 |
};
|
| 1322 |
} catch (e) {
|
| 1323 |
-
console.error(`Main: Upload error:`, e);
|
| 1324 |
reply.status(500);
|
| 1325 |
reply.header('Content-Type', 'application/json');
|
| 1326 |
return { detail: 'Upload failed' };
|
| 1327 |
}
|
| 1328 |
});
|
| 1329 |
|
| 1330 |
-
// ============ FIXED: /getuser returns consistent JSON ============
|
| 1331 |
fastify.get('/getuser', async (request, reply) => {
|
| 1332 |
const { id, username } = request.query || {};
|
| 1333 |
|
|
@@ -1341,7 +1208,6 @@ if (!isMainThread) {
|
|
| 1341 |
|
| 1342 |
reply.header('Content-Type', 'application/json');
|
| 1343 |
return {
|
| 1344 |
-
worker_pid: process.pid,
|
| 1345 |
id: user.id,
|
| 1346 |
username: user.username,
|
| 1347 |
name: user.name,
|
|
@@ -1355,45 +1221,12 @@ if (!isMainThread) {
|
|
| 1355 |
external_links: safeGet(user.external_links, '[]'),
|
| 1356 |
date_of_birth: safeGet(user.date_of_birth),
|
| 1357 |
is_profile_public: safeGet(user.is_profile_public, 'true'),
|
| 1358 |
-
fing_key: safeGet(user.fing_key, '')
|
| 1359 |
-
total_times_profile_updated_today: parseInt(safeGet(user.total_times_profile_updated_today, 0)),
|
| 1360 |
-
last_profile_updated: safeGet(user.last_profile_updated)
|
| 1361 |
};
|
| 1362 |
}
|
| 1363 |
|
| 1364 |
if (id) {
|
| 1365 |
-
|
| 1366 |
-
|
| 1367 |
-
if (!user) {
|
| 1368 |
-
for (const item of batchBuffer) {
|
| 1369 |
-
if (item.user_id === id && item.action === 'signup') {
|
| 1370 |
-
user = {
|
| 1371 |
-
id: id,
|
| 1372 |
-
username: item.data.username || '',
|
| 1373 |
-
name: item.data.name || '',
|
| 1374 |
-
email: item.data.email || '',
|
| 1375 |
-
country: '',
|
| 1376 |
-
location: '',
|
| 1377 |
-
created_at: new Date().toISOString(),
|
| 1378 |
-
is_login: 0,
|
| 1379 |
-
bio: '',
|
| 1380 |
-
pic_url: '',
|
| 1381 |
-
external_links: '[]',
|
| 1382 |
-
date_of_birth: '',
|
| 1383 |
-
is_profile_public: 'true',
|
| 1384 |
-
fing_key: item.data.fing_key || '',
|
| 1385 |
-
total_times_profile_updated_today: 0,
|
| 1386 |
-
last_profile_updated: ''
|
| 1387 |
-
};
|
| 1388 |
-
break;
|
| 1389 |
-
}
|
| 1390 |
-
}
|
| 1391 |
-
}
|
| 1392 |
-
|
| 1393 |
-
if (!user) {
|
| 1394 |
-
user = await getUser(id);
|
| 1395 |
-
}
|
| 1396 |
-
|
| 1397 |
if (!user) {
|
| 1398 |
reply.status(404);
|
| 1399 |
reply.header('Content-Type', 'application/json');
|
|
@@ -1402,7 +1235,6 @@ if (!isMainThread) {
|
|
| 1402 |
|
| 1403 |
reply.header('Content-Type', 'application/json');
|
| 1404 |
return {
|
| 1405 |
-
worker_pid: process.pid,
|
| 1406 |
id: user.id,
|
| 1407 |
username: user.username,
|
| 1408 |
name: user.name,
|
|
@@ -1416,9 +1248,7 @@ if (!isMainThread) {
|
|
| 1416 |
external_links: safeGet(user.external_links, '[]'),
|
| 1417 |
date_of_birth: safeGet(user.date_of_birth),
|
| 1418 |
is_profile_public: safeGet(user.is_profile_public, 'true'),
|
| 1419 |
-
fing_key: safeGet(user.fing_key, '')
|
| 1420 |
-
total_times_profile_updated_today: parseInt(safeGet(user.total_times_profile_updated_today, 0)),
|
| 1421 |
-
last_profile_updated: safeGet(user.last_profile_updated)
|
| 1422 |
};
|
| 1423 |
}
|
| 1424 |
|
|
@@ -1433,11 +1263,6 @@ if (!isMainThread) {
|
|
| 1433 |
});
|
| 1434 |
|
| 1435 |
fastify.get('/users', async (request, reply) => {
|
| 1436 |
-
if (usersCache.size === 0) {
|
| 1437 |
-
reply.header('Content-Type', 'application/json');
|
| 1438 |
-
return { users: [], total: 0 };
|
| 1439 |
-
}
|
| 1440 |
-
|
| 1441 |
const usersList = [];
|
| 1442 |
for (const user of usersCache.values()) {
|
| 1443 |
usersList.push({
|
|
@@ -1451,10 +1276,7 @@ if (!isMainThread) {
|
|
| 1451 |
}
|
| 1452 |
|
| 1453 |
reply.header('Content-Type', 'application/json');
|
| 1454 |
-
return {
|
| 1455 |
-
users: usersList,
|
| 1456 |
-
total: usersList.length
|
| 1457 |
-
};
|
| 1458 |
});
|
| 1459 |
|
| 1460 |
fastify.get('/spaces', async (request, reply) => {
|
|
@@ -1482,23 +1304,21 @@ if (!isMainThread) {
|
|
| 1482 |
}
|
| 1483 |
|
| 1484 |
const cleanUsername = username.trim().toLowerCase();
|
| 1485 |
-
const cleanEmail = email.trim().toLowerCase();
|
| 1486 |
-
const cleanFingKey = fing_key.trim();
|
| 1487 |
-
|
| 1488 |
const user = await getUserByUsername(cleanUsername);
|
|
|
|
| 1489 |
if (!user) {
|
| 1490 |
reply.status(404);
|
| 1491 |
reply.header('Content-Type', 'application/json');
|
| 1492 |
return { detail: 'No account found' };
|
| 1493 |
}
|
| 1494 |
|
| 1495 |
-
if (safeGet(user.email, '').toLowerCase() !==
|
| 1496 |
reply.status(401);
|
| 1497 |
reply.header('Content-Type', 'application/json');
|
| 1498 |
return { detail: 'Email does not match' };
|
| 1499 |
}
|
| 1500 |
|
| 1501 |
-
if (safeGet(user.fing_key, '') !==
|
| 1502 |
reply.status(401);
|
| 1503 |
reply.header('Content-Type', 'application/json');
|
| 1504 |
return { detail: 'Fingerprint key does not match' };
|
|
@@ -1519,11 +1339,7 @@ if (!isMainThread) {
|
|
| 1519 |
addRequest(user.id, cleanUsername, 'forgot_password', { new_password });
|
| 1520 |
|
| 1521 |
reply.header('Content-Type', 'application/json');
|
| 1522 |
-
return {
|
| 1523 |
-
success: true,
|
| 1524 |
-
message: 'Password reset processed',
|
| 1525 |
-
timestamp: new Date().toISOString()
|
| 1526 |
-
};
|
| 1527 |
});
|
| 1528 |
|
| 1529 |
return fastify;
|
|
@@ -1532,29 +1348,15 @@ if (!isMainThread) {
|
|
| 1532 |
// ============ STARTUP ============
|
| 1533 |
async function start() {
|
| 1534 |
try {
|
| 1535 |
-
console.log(`Main: Starting with
|
| 1536 |
await initDBWorker();
|
| 1537 |
|
| 1538 |
-
if (redis) {
|
| 1539 |
-
try {
|
| 1540 |
-
await redis.connect();
|
| 1541 |
-
console.log(`Main: Redis connected`);
|
| 1542 |
-
} catch (e) {
|
| 1543 |
-
console.warn(`Main: Redis connection failed:`, e.message);
|
| 1544 |
-
console.log(`Main: Continuing without Redis`);
|
| 1545 |
-
redis = null;
|
| 1546 |
-
}
|
| 1547 |
-
}
|
| 1548 |
-
|
| 1549 |
console.log(`Main: Loading users into memory...`);
|
| 1550 |
await loadUsersToMemory();
|
| 1551 |
await checkAndUpdateFullStatus();
|
| 1552 |
await setupFastify();
|
| 1553 |
|
| 1554 |
setInterval(async () => {
|
| 1555 |
-
if (redis && redis.status === 'ready') {
|
| 1556 |
-
await processFromRedis();
|
| 1557 |
-
}
|
| 1558 |
await checkAndUpdateFullStatus();
|
| 1559 |
}, 50);
|
| 1560 |
|
|
@@ -1563,9 +1365,8 @@ if (!isMainThread) {
|
|
| 1563 |
|
| 1564 |
console.log(`Main: π Server running on port ${port}`);
|
| 1565 |
console.log(`Main: π Users loaded: ${getTotalUsers()}`);
|
| 1566 |
-
console.log(`Main: πΎ Storage:
|
| 1567 |
-
console.log(`Main:
|
| 1568 |
-
console.log(`Main: β‘ Processing: ${BATCH_SIZE} requests/batch`);
|
| 1569 |
console.log(`Main: π Max RPS: ${MAX_RPS} req/sec`);
|
| 1570 |
console.log(`Main: π₯ Max Users: ${MAX_USERS}`);
|
| 1571 |
} catch (err) {
|
|
@@ -1576,8 +1377,7 @@ if (!isMainThread) {
|
|
| 1576 |
|
| 1577 |
process.on('SIGTERM', async () => {
|
| 1578 |
console.log(`Main: Shutting down...`);
|
| 1579 |
-
await
|
| 1580 |
-
if (redis) await redis.quit();
|
| 1581 |
await fastify.close();
|
| 1582 |
if (dbWorker) await dbWorker.terminate();
|
| 1583 |
process.exit(0);
|
|
@@ -1585,8 +1385,7 @@ if (!isMainThread) {
|
|
| 1585 |
|
| 1586 |
process.on('SIGINT', async () => {
|
| 1587 |
console.log(`Main: Shutting down...`);
|
| 1588 |
-
await
|
| 1589 |
-
if (redis) await redis.quit();
|
| 1590 |
await fastify.close();
|
| 1591 |
if (dbWorker) await dbWorker.terminate();
|
| 1592 |
process.exit(0);
|
|
|
|
| 2 |
const { Worker: ThreadWorker, isMainThread, parentPort, workerData } = require('worker_threads');
|
| 3 |
const os = require('os');
|
| 4 |
|
| 5 |
+
// ============ PARQUET WORKER THREAD (ULTRA FAST) ============
|
| 6 |
if (!isMainThread) {
|
| 7 |
+
const parquet = require('parquetjs');
|
|
|
|
| 8 |
const path = require('path');
|
| 9 |
const fs = require('fs');
|
| 10 |
+
const crypto = require('crypto');
|
| 11 |
+
|
| 12 |
const DATA_DIR = workerData.dataDir || "/data";
|
| 13 |
+
const USERS_FILE = path.join(DATA_DIR, 'users.parquet');
|
| 14 |
+
|
| 15 |
+
// In-memory storage for instant access
|
| 16 |
+
let usersMap = new Map();
|
| 17 |
+
let usernameIndex = new Map();
|
| 18 |
+
let emailIndex = new Map();
|
| 19 |
+
let userArray = [];
|
| 20 |
+
|
| 21 |
+
// Parquet schema
|
| 22 |
+
const userSchema = new parquet.ParquetSchema({
|
| 23 |
+
id: { type: 'UTF8' },
|
| 24 |
+
username: { type: 'UTF8' },
|
| 25 |
+
password_hash: { type: 'UTF8' },
|
| 26 |
+
name: { type: 'UTF8' },
|
| 27 |
+
email: { type: 'UTF8' },
|
| 28 |
+
country: { type: 'UTF8', optional: true },
|
| 29 |
+
location: { type: 'UTF8', optional: true },
|
| 30 |
+
created_at: { type: 'UTF8' },
|
| 31 |
+
is_login: { type: 'INT32', optional: true },
|
| 32 |
+
bio: { type: 'UTF8', optional: true },
|
| 33 |
+
pic_url: { type: 'UTF8', optional: true },
|
| 34 |
+
external_links: { type: 'UTF8', optional: true },
|
| 35 |
+
date_of_birth: { type: 'UTF8', optional: true },
|
| 36 |
+
total_times_profile_updated_today: { type: 'INT32', optional: true },
|
| 37 |
+
last_profile_updated: { type: 'UTF8', optional: true },
|
| 38 |
+
is_profile_public: { type: 'UTF8', optional: true },
|
| 39 |
+
fing_key: { type: 'UTF8', optional: true }
|
| 40 |
+
});
|
| 41 |
|
| 42 |
+
// Load all users into memory (EXTREMELY FAST)
|
| 43 |
+
async function loadUsers() {
|
| 44 |
+
try {
|
| 45 |
+
if (fs.existsSync(USERS_FILE)) {
|
| 46 |
+
const reader = await parquet.ParquetReader.openFile(USERS_FILE);
|
| 47 |
+
const cursor = reader.getCursor();
|
| 48 |
+
let record = null;
|
| 49 |
+
userArray = [];
|
| 50 |
+
|
| 51 |
+
while ((record = await cursor.next())) {
|
| 52 |
+
userArray.push(record);
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
await reader.close();
|
| 56 |
+
|
| 57 |
+
usersMap.clear();
|
| 58 |
+
usernameIndex.clear();
|
| 59 |
+
emailIndex.clear();
|
| 60 |
+
|
| 61 |
+
for (const user of userArray) {
|
| 62 |
+
usersMap.set(user.id, user);
|
| 63 |
+
usernameIndex.set(user.username.toLowerCase(), user);
|
| 64 |
+
emailIndex.set(user.email.toLowerCase(), user);
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
console.log(`Parquet Worker: Loaded ${userArray.length} users in memory`);
|
| 68 |
+
} else {
|
| 69 |
+
const writer = await parquet.ParquetWriter.openFile(userSchema, USERS_FILE);
|
| 70 |
+
await writer.close();
|
| 71 |
+
console.log('Parquet Worker: Created new users.parquet');
|
| 72 |
+
}
|
| 73 |
+
} catch (error) {
|
| 74 |
+
console.error('Parquet Worker: Error loading users:', error.message);
|
| 75 |
+
}
|
| 76 |
+
}
|
| 77 |
|
| 78 |
+
// Write all users to Parquet (batch write - very fast)
|
| 79 |
+
async function saveAllUsers() {
|
| 80 |
+
try {
|
| 81 |
+
const writer = await parquet.ParquetWriter.openFile(userSchema, USERS_FILE);
|
| 82 |
+
for (const user of userArray) {
|
| 83 |
+
await writer.appendRow(user);
|
| 84 |
+
}
|
| 85 |
+
await writer.close();
|
| 86 |
+
console.log(`Parquet Worker: Saved ${userArray.length} users to disk`);
|
| 87 |
+
} catch (error) {
|
| 88 |
+
console.error('Parquet Worker: Error saving users:', error.message);
|
| 89 |
+
}
|
| 90 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
|
| 92 |
+
// Initialize
|
| 93 |
+
loadUsers();
|
|
|
|
|
|
|
| 94 |
|
| 95 |
+
// Auto-save every 30 seconds (safety measure)
|
| 96 |
+
setInterval(() => {
|
| 97 |
+
saveAllUsers();
|
| 98 |
+
}, 30000);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
|
| 100 |
+
// Handle messages - ALL READS FROM MEMORY (INSTANT)
|
| 101 |
parentPort.on('message', async (message) => {
|
| 102 |
const { id, action, data } = message;
|
| 103 |
try {
|
| 104 |
let result;
|
| 105 |
+
|
| 106 |
switch (action) {
|
| 107 |
case 'getAllUsers':
|
| 108 |
+
result = userArray;
|
| 109 |
break;
|
| 110 |
+
|
| 111 |
case 'getUserById':
|
| 112 |
+
result = usersMap.get(data.userId) || null;
|
| 113 |
break;
|
| 114 |
+
|
| 115 |
case 'getUserByUsername':
|
| 116 |
+
result = usernameIndex.get(data.username.toLowerCase()) || null;
|
| 117 |
break;
|
| 118 |
+
|
| 119 |
+
case 'getUserByEmail':
|
| 120 |
+
result = emailIndex.get(data.email.toLowerCase()) || null;
|
| 121 |
break;
|
| 122 |
+
|
| 123 |
+
case 'insertUser':
|
| 124 |
+
const newUser = {
|
| 125 |
+
id: data.user.id || '',
|
| 126 |
+
username: data.user.username || '',
|
| 127 |
+
password_hash: data.user.password_hash || '',
|
| 128 |
+
name: data.user.name || '',
|
| 129 |
+
email: data.user.email || '',
|
| 130 |
+
country: data.user.country || '',
|
| 131 |
+
location: data.user.location || '',
|
| 132 |
+
created_at: data.user.created_at || new Date().toISOString(),
|
| 133 |
+
is_login: data.user.is_login || 0,
|
| 134 |
+
bio: data.user.bio || '',
|
| 135 |
+
pic_url: data.user.pic_url || '',
|
| 136 |
+
external_links: data.user.external_links || '[]',
|
| 137 |
+
date_of_birth: data.user.date_of_birth || '',
|
| 138 |
+
total_times_profile_updated_today: data.user.total_times_profile_updated_today || 0,
|
| 139 |
+
last_profile_updated: data.user.last_profile_updated || '',
|
| 140 |
+
is_profile_public: data.user.is_profile_public || 'true',
|
| 141 |
+
fing_key: data.user.fing_key || ''
|
| 142 |
+
};
|
| 143 |
+
|
| 144 |
+
userArray.push(newUser);
|
| 145 |
+
usersMap.set(newUser.id, newUser);
|
| 146 |
+
usernameIndex.set(newUser.username.toLowerCase(), newUser);
|
| 147 |
+
emailIndex.set(newUser.email.toLowerCase(), newUser);
|
| 148 |
+
|
| 149 |
+
// Async save to disk (non-blocking)
|
| 150 |
+
setImmediate(() => saveAllUsers());
|
| 151 |
+
|
| 152 |
result = { success: true };
|
| 153 |
break;
|
| 154 |
+
|
| 155 |
+
case 'updateUser':
|
| 156 |
+
const updatedUser = data.user;
|
| 157 |
+
const index = userArray.findIndex(u => u.id === updatedUser.id);
|
| 158 |
+
|
| 159 |
+
if (index !== -1) {
|
| 160 |
+
const oldUser = userArray[index];
|
| 161 |
+
usernameIndex.delete(oldUser.username.toLowerCase());
|
| 162 |
+
emailIndex.delete(oldUser.email.toLowerCase());
|
| 163 |
+
|
| 164 |
+
userArray[index] = updatedUser;
|
| 165 |
+
usersMap.set(updatedUser.id, updatedUser);
|
| 166 |
+
usernameIndex.set(updatedUser.username.toLowerCase(), updatedUser);
|
| 167 |
+
emailIndex.set(updatedUser.email.toLowerCase(), updatedUser);
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
+
// Async save to disk
|
| 171 |
+
setImmediate(() => saveAllUsers());
|
| 172 |
+
|
| 173 |
result = { success: true };
|
| 174 |
break;
|
| 175 |
+
|
| 176 |
+
case 'getCount':
|
| 177 |
+
result = userArray.length;
|
| 178 |
break;
|
| 179 |
+
|
| 180 |
+
case 'userExists':
|
| 181 |
+
result = {
|
| 182 |
+
username: usernameIndex.has(data.username.toLowerCase()),
|
| 183 |
+
email: emailIndex.has(data.email.toLowerCase())
|
| 184 |
+
};
|
| 185 |
break;
|
| 186 |
+
|
| 187 |
case 'batchOperation':
|
| 188 |
+
for (const op of data.operations) {
|
| 189 |
+
switch (op.action) {
|
| 190 |
+
case 'signup':
|
| 191 |
+
case 'insertUser':
|
| 192 |
+
const user = op.user;
|
| 193 |
+
userArray.push(user);
|
| 194 |
+
usersMap.set(user.id, user);
|
| 195 |
+
usernameIndex.set(user.username.toLowerCase(), user);
|
| 196 |
+
emailIndex.set(user.email.toLowerCase(), user);
|
| 197 |
+
break;
|
| 198 |
+
|
| 199 |
+
case 'updateProfile':
|
| 200 |
+
const profIndex = userArray.findIndex(u => u.id === op.userId);
|
| 201 |
+
if (profIndex !== -1) {
|
| 202 |
+
const oldU = userArray[profIndex];
|
| 203 |
+
usernameIndex.delete(oldU.username.toLowerCase());
|
| 204 |
+
emailIndex.delete(oldU.email.toLowerCase());
|
| 205 |
+
|
| 206 |
+
Object.assign(userArray[profIndex], op.data);
|
| 207 |
+
usersMap.set(op.userId, userArray[profIndex]);
|
| 208 |
+
usernameIndex.set(userArray[profIndex].username.toLowerCase(), userArray[profIndex]);
|
| 209 |
+
emailIndex.set(userArray[profIndex].email.toLowerCase(), userArray[profIndex]);
|
| 210 |
+
}
|
| 211 |
+
break;
|
| 212 |
+
|
| 213 |
+
case 'updatePhoto':
|
| 214 |
+
const photoIndex = userArray.findIndex(u => u.id === op.userId);
|
| 215 |
+
if (photoIndex !== -1) {
|
| 216 |
+
userArray[photoIndex].pic_url = op.picUrl;
|
| 217 |
+
usersMap.set(op.userId, userArray[photoIndex]);
|
| 218 |
+
}
|
| 219 |
+
break;
|
| 220 |
+
|
| 221 |
+
case 'updatePassword':
|
| 222 |
+
const passIndex = userArray.findIndex(u => u.id === op.userId);
|
| 223 |
+
if (passIndex !== -1) {
|
| 224 |
+
userArray[passIndex].password_hash = op.passwordHash;
|
| 225 |
+
usersMap.set(op.userId, userArray[passIndex]);
|
| 226 |
+
}
|
| 227 |
+
break;
|
| 228 |
+
|
| 229 |
+
case 'login':
|
| 230 |
+
const loginIndex = userArray.findIndex(u => u.id === op.userId);
|
| 231 |
+
if (loginIndex !== -1) {
|
| 232 |
+
userArray[loginIndex].is_login = 1;
|
| 233 |
+
usersMap.set(op.userId, userArray[loginIndex]);
|
| 234 |
+
}
|
| 235 |
+
break;
|
| 236 |
+
|
| 237 |
+
case 'logout':
|
| 238 |
+
const logoutIndex = userArray.findIndex(u => u.id === op.userId);
|
| 239 |
+
if (logoutIndex !== -1) {
|
| 240 |
+
userArray[logoutIndex].is_login = 0;
|
| 241 |
+
usersMap.set(op.userId, userArray[logoutIndex]);
|
| 242 |
+
}
|
| 243 |
+
break;
|
| 244 |
+
}
|
| 245 |
+
}
|
| 246 |
+
|
| 247 |
+
// Async save after batch
|
| 248 |
+
setImmediate(() => saveAllUsers());
|
| 249 |
+
|
| 250 |
+
result = { processed: data.operations.length };
|
| 251 |
break;
|
| 252 |
+
|
| 253 |
default:
|
| 254 |
throw new Error(`Unknown action: ${action}`);
|
| 255 |
}
|
| 256 |
+
|
| 257 |
parentPort.postMessage({ id, success: true, result });
|
| 258 |
} catch (error) {
|
| 259 |
parentPort.postMessage({ id, success: false, error: error.message });
|
| 260 |
}
|
| 261 |
});
|
| 262 |
|
| 263 |
+
console.log(`Parquet Worker Thread: Ready with ${userArray.length} users`);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 264 |
|
| 265 |
} else {
|
| 266 |
// ============ MAIN THREAD - FASTIFY SERVER ============
|
|
|
|
| 282 |
const { Readable } = require('stream');
|
| 283 |
|
| 284 |
// Dynamic imports
|
| 285 |
+
let sharp;
|
| 286 |
+
try { sharp = require('sharp'); } catch (e) { console.log(`Main: Sharp not available`); }
|
|
|
|
| 287 |
|
| 288 |
// ============ CONSTANTS ============
|
| 289 |
const MAX_BUCKET_SIZE = 60 * 1024 * 1024 * 1024;
|
|
|
|
| 302 |
const MAX_EMAIL_LENGTH = 200;
|
| 303 |
const MAX_RPS = 15000;
|
| 304 |
const SPACE_NAMES = ["data2"];
|
|
|
|
| 305 |
const CURRENT_SPACE_NAME = "1";
|
| 306 |
const BATCH_SIZE = 15000;
|
| 307 |
const HASH = process.env.HASH || 'v3l0st-d3f4ult-h4sh-k3y-2024!@#$%^&*()';
|
|
|
|
| 323 |
}
|
| 324 |
});
|
| 325 |
|
| 326 |
+
if (!fs.existsSync(FULL_FILE)) fs.writeFileSync(FULL_FILE, '', 'utf8');
|
| 327 |
+
if (!fs.existsSync(SIZE_FILE)) fs.writeFileSync(SIZE_FILE, '', 'utf8');
|
|
|
|
|
|
|
|
|
|
|
|
|
| 328 |
|
| 329 |
+
// ============ PARQUET WORKER THREAD ============
|
| 330 |
let dbWorker;
|
| 331 |
let dbRequestId = 0;
|
| 332 |
const dbPromises = new Map();
|
|
|
|
| 352 |
|
| 353 |
dbWorker.on('error', reject);
|
| 354 |
dbWorker.on('online', () => {
|
| 355 |
+
console.log(`Main: Parquet Worker Thread online`);
|
| 356 |
resolve();
|
| 357 |
});
|
| 358 |
});
|
|
|
|
| 366 |
});
|
| 367 |
}
|
| 368 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 369 |
// ============ IN-MEMORY STORAGE ============
|
| 370 |
let usersCache = new Map();
|
| 371 |
let batchBuffer = [];
|
|
|
|
| 611 |
.toBuffer();
|
| 612 |
}
|
| 613 |
|
| 614 |
+
return { buffer: outputBuffer, isWebp: true, sizeKb: outputBuffer.length / 1024, wasCompressed: true };
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 615 |
} catch (e) {
|
| 616 |
return { buffer: fileData, isWebp: false, sizeKb: fileData.length / 1024, wasCompressed: false };
|
| 617 |
}
|
| 618 |
}
|
| 619 |
|
| 620 |
+
// ============ DATA MANAGEMENT (ALL FROM MEMORY) ============
|
| 621 |
async function loadUsersToMemory() {
|
| 622 |
try {
|
| 623 |
const users = await dbRequest('getAllUsers');
|
|
|
|
| 635 |
if (usersCache.has(userId)) return usersCache.get(userId);
|
| 636 |
try {
|
| 637 |
const user = await dbRequest('getUserById', { userId });
|
| 638 |
+
if (user) usersCache.set(user.id, user);
|
| 639 |
return user;
|
| 640 |
} catch (e) {
|
| 641 |
return null;
|
|
|
|
| 685 |
}
|
| 686 |
|
| 687 |
// ============ BATCH PROCESSING ============
|
|
|
|
|
|
|
| 688 |
function scheduleBatchProcess() {
|
| 689 |
if (batchTimer) return;
|
| 690 |
batchTimer = setTimeout(async () => {
|
| 691 |
batchTimer = null;
|
| 692 |
+
await flushBatch();
|
| 693 |
}, 1000);
|
| 694 |
}
|
| 695 |
|
| 696 |
+
async function flushBatch() {
|
| 697 |
if (batchBuffer.length === 0 || processingLock) return;
|
| 698 |
processingLock = true;
|
| 699 |
|
| 700 |
const batch = batchBuffer.splice(0, BATCH_SIZE);
|
| 701 |
+
console.log(`Main: Processing batch of ${batch.length} requests`);
|
|
|
|
| 702 |
|
|
|
|
| 703 |
try {
|
| 704 |
await processRequestsBatch(batch);
|
| 705 |
+
console.log(`Main: Batch processed successfully`);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 706 |
} catch (e) {
|
| 707 |
+
console.error(`Main: Batch error:`, e.message);
|
| 708 |
batchBuffer.unshift(...batch);
|
| 709 |
} finally {
|
| 710 |
processingLock = false;
|
| 711 |
+
if (batchBuffer.length > 0) scheduleBatchProcess();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 712 |
}
|
| 713 |
}
|
| 714 |
|
| 715 |
async function processRequestsBatch(requests) {
|
| 716 |
+
if (!requests || requests.length === 0) return;
|
|
|
|
|
|
|
|
|
|
| 717 |
|
|
|
|
| 718 |
const operations = [];
|
| 719 |
|
| 720 |
for (const req of requests) {
|
| 721 |
+
if (!req || !req.user_id) continue;
|
| 722 |
+
|
| 723 |
+
const action = req.action || 'unknown';
|
| 724 |
+
|
| 725 |
+
switch (action) {
|
| 726 |
+
case 'signup':
|
| 727 |
+
operations.push({
|
| 728 |
+
action: 'signup',
|
| 729 |
+
userId: req.user_id,
|
| 730 |
+
user: {
|
| 731 |
+
id: req.user_id,
|
| 732 |
+
username: (req.data && req.data.username) || generateRandomUsername(),
|
| 733 |
+
password_hash: hashPassword((req.data && req.data.password) || 'default123'),
|
| 734 |
+
name: (req.data && req.data.name) || generateRandomName(),
|
| 735 |
+
email: (req.data && req.data.email) || `${req.user_id}@default.com`,
|
| 736 |
+
country: (req.data && req.data.country) || '',
|
| 737 |
+
location: (req.data && req.data.location) || '',
|
| 738 |
+
created_at: new Date().toISOString(),
|
| 739 |
+
is_login: 0,
|
| 740 |
+
bio: '',
|
| 741 |
+
pic_url: '',
|
| 742 |
+
external_links: '[]',
|
| 743 |
+
date_of_birth: '',
|
| 744 |
+
total_times_profile_updated_today: 0,
|
| 745 |
+
last_profile_updated: '',
|
| 746 |
+
is_profile_public: 'true',
|
| 747 |
+
fing_key: (req.data && req.data.fing_key) || generateFingKey()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 748 |
}
|
| 749 |
+
});
|
| 750 |
+
break;
|
| 751 |
+
|
| 752 |
+
case 'login':
|
| 753 |
+
operations.push({ action: 'login', userId: req.user_id });
|
| 754 |
+
break;
|
| 755 |
+
|
| 756 |
+
case 'logout':
|
| 757 |
+
operations.push({ action: 'logout', userId: req.user_id });
|
| 758 |
+
break;
|
| 759 |
+
|
| 760 |
+
case 'update_profile':
|
| 761 |
+
const profileData = req.data || {};
|
| 762 |
+
operations.push({
|
| 763 |
+
action: 'updateProfile',
|
| 764 |
+
userId: req.user_id,
|
| 765 |
+
data: {
|
| 766 |
+
name: profileData.name || 'Unknown',
|
| 767 |
+
email: profileData.email || `${req.user_id}@default.com`,
|
| 768 |
+
country: profileData.country || '',
|
| 769 |
+
location: profileData.location || '',
|
| 770 |
+
bio: profileData.bio || '',
|
| 771 |
+
external_links: profileData.external_links || '[]',
|
| 772 |
+
date_of_birth: profileData.date_of_birth || '',
|
| 773 |
+
is_profile_public: profileData.is_profile_public || 'true',
|
| 774 |
+
total_times_profile_updated_today: (profileData.total_times_profile_updated_today || 0) + 1,
|
| 775 |
+
last_profile_updated: new Date().toISOString()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 776 |
}
|
| 777 |
+
});
|
| 778 |
+
break;
|
| 779 |
+
|
| 780 |
+
case 'upload_photo':
|
| 781 |
+
if (req.pic_buffer) {
|
| 782 |
+
try {
|
| 783 |
+
const compressed = await compressToWebp(Buffer.from(req.pic_buffer, 'base64'), MAX_PHOTO_SIZE_KB);
|
| 784 |
+
const filename = `${req.user_id}_${Math.floor(Date.now() / 1000)}.webp`;
|
| 785 |
+
const filePath = path.join(PHOTOS_DIR, filename);
|
| 786 |
+
await fsp.writeFile(filePath, compressed.buffer);
|
| 787 |
+
operations.push({ action: 'updatePhoto', userId: req.user_id, picUrl: `/photos/${filename}` });
|
| 788 |
+
} catch (photoError) {
|
| 789 |
+
console.error(`Main: Photo error:`, photoError.message);
|
| 790 |
+
}
|
| 791 |
+
}
|
| 792 |
+
break;
|
| 793 |
+
|
| 794 |
+
case 'forgot_password':
|
| 795 |
+
const newPassword = (req.data && req.data.new_password) || 'default123';
|
| 796 |
+
operations.push({ action: 'updatePassword', userId: req.user_id, passwordHash: hashPassword(newPassword) });
|
| 797 |
+
break;
|
| 798 |
}
|
| 799 |
}
|
| 800 |
|
| 801 |
if (operations.length > 0) {
|
| 802 |
+
await dbRequest('batchOperation', { operations });
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 803 |
}
|
| 804 |
}
|
| 805 |
|
| 806 |
function addRequest(userId, username, action, data, picBuffer = null) {
|
| 807 |
+
if (!userId) userId = generateId();
|
| 808 |
+
if (!action) action = 'unknown';
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 809 |
|
| 810 |
const safeData = data || {};
|
| 811 |
|
|
|
|
| 817 |
safeData.fing_key = safeData.fing_key || generateFingKey();
|
| 818 |
}
|
| 819 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 820 |
const request = {
|
| 821 |
id: generateId(),
|
| 822 |
user_id: userId,
|
|
|
|
| 824 |
action: action,
|
| 825 |
data: safeData,
|
| 826 |
pic_buffer: picBuffer ? picBuffer.toString('base64') : null,
|
|
|
|
| 827 |
timestamp: Date.now()
|
| 828 |
};
|
| 829 |
|
|
|
|
| 830 |
batchBuffer.push(request);
|
| 831 |
scheduleBatchProcess();
|
| 832 |
return request.id;
|
|
|
|
| 852 |
maxAge: 86400000
|
| 853 |
});
|
| 854 |
|
|
|
|
| 855 |
fastify.addHook('onRequest', async (request, reply) => {
|
| 856 |
const cpuUsage = getCurrentCPUPercentage();
|
| 857 |
const totalUsers = getTotalUsers();
|
|
|
|
| 880 |
}
|
| 881 |
});
|
| 882 |
|
| 883 |
+
// ============ ALL ROUTES RETURN JSON ============
|
| 884 |
|
| 885 |
fastify.get('/', async (request, reply) => {
|
| 886 |
const spaceFull = isSpaceFull();
|
|
|
|
| 891 |
|
| 892 |
reply.header('Content-Type', 'application/json');
|
| 893 |
return {
|
| 894 |
+
message: 'Velost Auth API - Parquet Storage',
|
| 895 |
+
version: '16.0.0-PARQUET',
|
| 896 |
worker_pid: process.pid,
|
| 897 |
+
architecture: '1 Process + 1 Parquet Thread = 2 Cores',
|
| 898 |
space_name: CURRENT_SPACE_NAME,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 899 |
storage: {
|
| 900 |
+
type: 'Parquet (Columnar)',
|
| 901 |
max_ram_gb: 7,
|
| 902 |
current_ram_mb: Math.round(getMemoryUsage() / (1024 * 1024) * 100) / 100,
|
| 903 |
max_bucket_size: '60GB',
|
|
|
|
| 905 |
max_users: MAX_USERS,
|
| 906 |
current_users: getTotalUsers()
|
| 907 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 908 |
space_status: {
|
| 909 |
is_full: spaceFull,
|
| 910 |
full_spaces: fullSpaces,
|
|
|
|
| 912 |
size_spaces: sizeSpaces,
|
| 913 |
all_spaces: SPACE_NAMES
|
| 914 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 915 |
timestamp: new Date().toISOString()
|
| 916 |
};
|
| 917 |
});
|
| 918 |
|
| 919 |
fastify.get('/status', async (request, reply) => {
|
|
|
|
| 920 |
await checkAndUpdateFullStatus();
|
| 921 |
const fullSpaces = await getFullSpaces();
|
| 922 |
const emptySpaces = SPACE_NAMES.filter(s => !fullSpaces.includes(s));
|
|
|
|
|
|
|
|
|
|
| 923 |
|
| 924 |
reply.header('Content-Type', 'application/json');
|
| 925 |
return {
|
|
|
|
|
|
|
| 926 |
space: CURRENT_SPACE_NAME,
|
| 927 |
+
is_full: isSpaceFull(),
|
| 928 |
+
users: { current: getTotalUsers(), max: MAX_USERS },
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 929 |
full_spaces: fullSpaces,
|
| 930 |
empty_spaces: emptySpaces,
|
|
|
|
| 931 |
timestamp: new Date().toISOString()
|
| 932 |
};
|
| 933 |
});
|
|
|
|
| 936 |
reply.header('Content-Type', 'application/json');
|
| 937 |
return {
|
| 938 |
status: 'healthy',
|
| 939 |
+
storage: 'parquet',
|
| 940 |
users: getTotalUsers(),
|
|
|
|
| 941 |
timestamp: new Date().toISOString()
|
| 942 |
};
|
| 943 |
});
|
| 944 |
|
|
|
|
| 945 |
fastify.post('/signup', async (request, reply) => {
|
| 946 |
if (getTotalUsers() >= MAX_USERS) {
|
| 947 |
reply.status(507);
|
|
|
|
| 1009 |
fing_key: fing_key ? fing_key.trim() : generateFingKey()
|
| 1010 |
};
|
| 1011 |
|
| 1012 |
+
// Save to memory
|
| 1013 |
usersCache.set(userId, newUser);
|
| 1014 |
|
| 1015 |
+
// Save to Parquet (async, non-blocking)
|
| 1016 |
try {
|
| 1017 |
await dbRequest('insertUser', { user: newUser });
|
| 1018 |
} catch (dbError) {
|
| 1019 |
+
console.error('Parquet insert failed, using batch:', dbError.message);
|
| 1020 |
addRequest(userId, cleanUsername, 'signup', {
|
| 1021 |
username: cleanUsername,
|
| 1022 |
password: password,
|
|
|
|
| 1026 |
});
|
| 1027 |
}
|
| 1028 |
|
|
|
|
| 1029 |
reply.header('Content-Type', 'application/json');
|
| 1030 |
return {
|
| 1031 |
success: true,
|
|
|
|
| 1068 |
reply.header('Content-Type', 'application/json');
|
| 1069 |
return {
|
| 1070 |
success: true,
|
|
|
|
| 1071 |
id: user.id,
|
| 1072 |
username: user.username,
|
| 1073 |
name: user.name,
|
|
|
|
| 1082 |
date_of_birth: safeGet(user.date_of_birth),
|
| 1083 |
is_profile_public: safeGet(user.is_profile_public, 'true'),
|
| 1084 |
fing_key: safeGet(user.fing_key, ''),
|
|
|
|
|
|
|
| 1085 |
timestamp: new Date().toISOString()
|
| 1086 |
};
|
| 1087 |
});
|
|
|
|
| 1105 |
addRequest(id, '', 'logout', {});
|
| 1106 |
|
| 1107 |
reply.header('Content-Type', 'application/json');
|
| 1108 |
+
return { success: true, message: 'Logged out successfully', timestamp: new Date().toISOString() };
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1109 |
});
|
| 1110 |
|
| 1111 |
fastify.put('/updateprofiledetails', async (request, reply) => {
|
|
|
|
| 1133 |
}
|
| 1134 |
}
|
| 1135 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1136 |
addRequest(id, '', 'update_profile', data);
|
| 1137 |
|
| 1138 |
reply.header('Content-Type', 'application/json');
|
| 1139 |
+
return { success: true, message: 'Profile update processed', timestamp: new Date().toISOString() };
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1140 |
});
|
| 1141 |
|
| 1142 |
fastify.post('/uploadphoto', async (request, reply) => {
|
|
|
|
| 1189 |
timestamp: new Date().toISOString()
|
| 1190 |
};
|
| 1191 |
} catch (e) {
|
|
|
|
| 1192 |
reply.status(500);
|
| 1193 |
reply.header('Content-Type', 'application/json');
|
| 1194 |
return { detail: 'Upload failed' };
|
| 1195 |
}
|
| 1196 |
});
|
| 1197 |
|
|
|
|
| 1198 |
fastify.get('/getuser', async (request, reply) => {
|
| 1199 |
const { id, username } = request.query || {};
|
| 1200 |
|
|
|
|
| 1208 |
|
| 1209 |
reply.header('Content-Type', 'application/json');
|
| 1210 |
return {
|
|
|
|
| 1211 |
id: user.id,
|
| 1212 |
username: user.username,
|
| 1213 |
name: user.name,
|
|
|
|
| 1221 |
external_links: safeGet(user.external_links, '[]'),
|
| 1222 |
date_of_birth: safeGet(user.date_of_birth),
|
| 1223 |
is_profile_public: safeGet(user.is_profile_public, 'true'),
|
| 1224 |
+
fing_key: safeGet(user.fing_key, '')
|
|
|
|
|
|
|
| 1225 |
};
|
| 1226 |
}
|
| 1227 |
|
| 1228 |
if (id) {
|
| 1229 |
+
const user = await getUser(id);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1230 |
if (!user) {
|
| 1231 |
reply.status(404);
|
| 1232 |
reply.header('Content-Type', 'application/json');
|
|
|
|
| 1235 |
|
| 1236 |
reply.header('Content-Type', 'application/json');
|
| 1237 |
return {
|
|
|
|
| 1238 |
id: user.id,
|
| 1239 |
username: user.username,
|
| 1240 |
name: user.name,
|
|
|
|
| 1248 |
external_links: safeGet(user.external_links, '[]'),
|
| 1249 |
date_of_birth: safeGet(user.date_of_birth),
|
| 1250 |
is_profile_public: safeGet(user.is_profile_public, 'true'),
|
| 1251 |
+
fing_key: safeGet(user.fing_key, '')
|
|
|
|
|
|
|
| 1252 |
};
|
| 1253 |
}
|
| 1254 |
|
|
|
|
| 1263 |
});
|
| 1264 |
|
| 1265 |
fastify.get('/users', async (request, reply) => {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1266 |
const usersList = [];
|
| 1267 |
for (const user of usersCache.values()) {
|
| 1268 |
usersList.push({
|
|
|
|
| 1276 |
}
|
| 1277 |
|
| 1278 |
reply.header('Content-Type', 'application/json');
|
| 1279 |
+
return { users: usersList, total: usersList.length };
|
|
|
|
|
|
|
|
|
|
| 1280 |
});
|
| 1281 |
|
| 1282 |
fastify.get('/spaces', async (request, reply) => {
|
|
|
|
| 1304 |
}
|
| 1305 |
|
| 1306 |
const cleanUsername = username.trim().toLowerCase();
|
|
|
|
|
|
|
|
|
|
| 1307 |
const user = await getUserByUsername(cleanUsername);
|
| 1308 |
+
|
| 1309 |
if (!user) {
|
| 1310 |
reply.status(404);
|
| 1311 |
reply.header('Content-Type', 'application/json');
|
| 1312 |
return { detail: 'No account found' };
|
| 1313 |
}
|
| 1314 |
|
| 1315 |
+
if (safeGet(user.email, '').toLowerCase() !== email.trim().toLowerCase()) {
|
| 1316 |
reply.status(401);
|
| 1317 |
reply.header('Content-Type', 'application/json');
|
| 1318 |
return { detail: 'Email does not match' };
|
| 1319 |
}
|
| 1320 |
|
| 1321 |
+
if (safeGet(user.fing_key, '') !== fing_key.trim()) {
|
| 1322 |
reply.status(401);
|
| 1323 |
reply.header('Content-Type', 'application/json');
|
| 1324 |
return { detail: 'Fingerprint key does not match' };
|
|
|
|
| 1339 |
addRequest(user.id, cleanUsername, 'forgot_password', { new_password });
|
| 1340 |
|
| 1341 |
reply.header('Content-Type', 'application/json');
|
| 1342 |
+
return { success: true, message: 'Password reset processed', timestamp: new Date().toISOString() };
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1343 |
});
|
| 1344 |
|
| 1345 |
return fastify;
|
|
|
|
| 1348 |
// ============ STARTUP ============
|
| 1349 |
async function start() {
|
| 1350 |
try {
|
| 1351 |
+
console.log(`Main: Starting with Parquet storage`);
|
| 1352 |
await initDBWorker();
|
| 1353 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1354 |
console.log(`Main: Loading users into memory...`);
|
| 1355 |
await loadUsersToMemory();
|
| 1356 |
await checkAndUpdateFullStatus();
|
| 1357 |
await setupFastify();
|
| 1358 |
|
| 1359 |
setInterval(async () => {
|
|
|
|
|
|
|
|
|
|
| 1360 |
await checkAndUpdateFullStatus();
|
| 1361 |
}, 50);
|
| 1362 |
|
|
|
|
| 1365 |
|
| 1366 |
console.log(`Main: π Server running on port ${port}`);
|
| 1367 |
console.log(`Main: π Users loaded: ${getTotalUsers()}`);
|
| 1368 |
+
console.log(`Main: πΎ Storage: Parquet at /data/users.parquet`);
|
| 1369 |
+
console.log(`Main: β‘ Performance: In-memory reads, Parquet persistence`);
|
|
|
|
| 1370 |
console.log(`Main: π Max RPS: ${MAX_RPS} req/sec`);
|
| 1371 |
console.log(`Main: π₯ Max Users: ${MAX_USERS}`);
|
| 1372 |
} catch (err) {
|
|
|
|
| 1377 |
|
| 1378 |
process.on('SIGTERM', async () => {
|
| 1379 |
console.log(`Main: Shutting down...`);
|
| 1380 |
+
await flushBatch();
|
|
|
|
| 1381 |
await fastify.close();
|
| 1382 |
if (dbWorker) await dbWorker.terminate();
|
| 1383 |
process.exit(0);
|
|
|
|
| 1385 |
|
| 1386 |
process.on('SIGINT', async () => {
|
| 1387 |
console.log(`Main: Shutting down...`);
|
| 1388 |
+
await flushBatch();
|
|
|
|
| 1389 |
await fastify.close();
|
| 1390 |
if (dbWorker) await dbWorker.terminate();
|
| 1391 |
process.exit(0);
|