Spaces:
Runtime error
Runtime error
blaze-aura69 commited on
Update index.js
Browse files
index.js
CHANGED
|
@@ -1,4 +1,3 @@
|
|
| 1 |
-
|
| 2 |
'use strict';
|
| 3 |
const { Worker: ThreadWorker, isMainThread, parentPort, workerData } = require('worker_threads');
|
| 4 |
const os = require('os');
|
|
@@ -57,14 +56,12 @@ if (!isMainThread) {
|
|
| 57 |
insertUser: db.prepare(`
|
| 58 |
INSERT OR REPLACE INTO users (
|
| 59 |
id, username, password_hash, name, email, country, location,
|
| 60 |
-
created_at, is_login, bio, pic_url, external_links,
|
| 61 |
-
|
| 62 |
-
last_profile_updated, is_profile_public, fing_key
|
| 63 |
) VALUES (
|
| 64 |
@id, @username, @password_hash, @name, @email, @country, @location,
|
| 65 |
-
@created_at, @is_login, @bio, @pic_url, @external_links,
|
| 66 |
-
@
|
| 67 |
-
@last_profile_updated, @is_profile_public, @fing_key
|
| 68 |
)
|
| 69 |
`),
|
| 70 |
updateLogin: db.prepare('UPDATE users SET is_login = ? WHERE id = ?'),
|
|
@@ -119,14 +116,14 @@ if (!isMainThread) {
|
|
| 119 |
case 'updateProfile':
|
| 120 |
stmts.updateProfile.run({
|
| 121 |
id: data.userId,
|
| 122 |
-
name: data.name || '',
|
| 123 |
-
email: data.email || '',
|
| 124 |
country: data.country || '',
|
| 125 |
location: data.location || '',
|
| 126 |
bio: data.bio || '',
|
| 127 |
-
external_links: data.external_links || '',
|
| 128 |
date_of_birth: data.date_of_birth || '',
|
| 129 |
-
is_profile_public: data.is_profile_public || '',
|
| 130 |
total_times_profile_updated_today: data.total_times_profile_updated_today || 0,
|
| 131 |
last_profile_updated: data.last_profile_updated || ''
|
| 132 |
});
|
|
@@ -219,7 +216,6 @@ if (!isMainThread) {
|
|
| 219 |
} catch (e) {
|
| 220 |
console.log(`Main: ioredis not available:`, e.message);
|
| 221 |
}
|
| 222 |
-
|
| 223 |
try {
|
| 224 |
sharp = require('sharp');
|
| 225 |
} catch (e) {
|
|
@@ -242,9 +238,9 @@ if (!isMainThread) {
|
|
| 242 |
const MAX_LOCATION_LENGTH = 500;
|
| 243 |
const MAX_EMAIL_LENGTH = 200;
|
| 244 |
const MAX_RPS = 15000;
|
| 245 |
-
const SPACE_NAMES = ["
|
| 246 |
const BASE_SPACE_URL = "https://velost-db1-{space}.hf.space";
|
| 247 |
-
const CURRENT_SPACE_NAME = "
|
| 248 |
const BATCH_SIZE = 15000;
|
| 249 |
const HASH = process.env.HASH || 'v3l0st-d3f4ult-h4sh-k3y-2024!@#$%^&*()';
|
| 250 |
|
|
@@ -268,7 +264,6 @@ if (!isMainThread) {
|
|
| 268 |
if (!fs.existsSync(FULL_FILE)) {
|
| 269 |
fs.writeFileSync(FULL_FILE, '', 'utf8');
|
| 270 |
}
|
| 271 |
-
|
| 272 |
if (!fs.existsSync(SIZE_FILE)) {
|
| 273 |
fs.writeFileSync(SIZE_FILE, '', 'utf8');
|
| 274 |
}
|
|
@@ -316,21 +311,35 @@ if (!isMainThread) {
|
|
| 316 |
// ============ REDIS SETUP ============
|
| 317 |
let redis = null;
|
| 318 |
if (Redis) {
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 334 |
}
|
| 335 |
|
| 336 |
// ============ IN-MEMORY STORAGE ============
|
|
@@ -425,6 +434,14 @@ if (!isMainThread) {
|
|
| 425 |
return crypto.createHash('sha256').update(uuidv4()).digest('hex').substring(0, 32);
|
| 426 |
}
|
| 427 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 428 |
function formatSize(bytesSize) {
|
| 429 |
if (bytesSize === 0) return "0 B";
|
| 430 |
const units = ["B", "KB", "MB", "GB", "TB"];
|
|
@@ -529,8 +546,11 @@ if (!isMainThread) {
|
|
| 529 |
const bucketSize = getBucketSize();
|
| 530 |
const ramUsage = getMemoryUsage();
|
| 531 |
|
| 532 |
-
const isFull = currentRPS >= MAX_RPS ||
|
| 533 |
-
|
|
|
|
|
|
|
|
|
|
| 534 |
|
| 535 |
if (isFull !== lastFullStatus) {
|
| 536 |
lastFullStatus = isFull;
|
|
@@ -563,18 +583,28 @@ if (!isMainThread) {
|
|
| 563 |
let outputBuffer;
|
| 564 |
|
| 565 |
while (quality >= 10) {
|
| 566 |
-
outputBuffer = await image
|
| 567 |
-
.
|
|
|
|
|
|
|
|
|
|
| 568 |
if (outputBuffer.length / 1024 <= maxSizeKb) break;
|
| 569 |
quality -= 10;
|
| 570 |
}
|
| 571 |
|
| 572 |
if (outputBuffer.length / 1024 > maxSizeKb) {
|
| 573 |
-
outputBuffer = await image
|
| 574 |
-
.
|
|
|
|
|
|
|
| 575 |
}
|
| 576 |
|
| 577 |
-
return {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 578 |
} catch (e) {
|
| 579 |
return { buffer: fileData, isWebp: false, sizeKb: fileData.length / 1024, wasCompressed: false };
|
| 580 |
}
|
|
@@ -596,7 +626,6 @@ if (!isMainThread) {
|
|
| 596 |
|
| 597 |
async function getUser(userId) {
|
| 598 |
if (usersCache.has(userId)) return usersCache.get(userId);
|
| 599 |
-
|
| 600 |
try {
|
| 601 |
const user = await dbRequest('getUserById', { userId });
|
| 602 |
if (user) usersCache.set(userId, user);
|
|
@@ -610,7 +639,6 @@ if (!isMainThread) {
|
|
| 610 |
for (const user of usersCache.values()) {
|
| 611 |
if (user.username === username) return user;
|
| 612 |
}
|
| 613 |
-
|
| 614 |
try {
|
| 615 |
const user = await dbRequest('getUserByUsername', { username });
|
| 616 |
if (user) usersCache.set(user.id, user);
|
|
@@ -626,7 +654,6 @@ if (!isMainThread) {
|
|
| 626 |
|
| 627 |
function getBucketSize() {
|
| 628 |
let totalSize = 0;
|
| 629 |
-
|
| 630 |
function walkDir(dir) {
|
| 631 |
if (!fs.existsSync(dir)) return;
|
| 632 |
try {
|
|
@@ -639,53 +666,74 @@ if (!isMainThread) {
|
|
| 639 |
}
|
| 640 |
} catch (e) {}
|
| 641 |
}
|
| 642 |
-
|
| 643 |
walkDir(DATA_DIR);
|
| 644 |
return totalSize;
|
| 645 |
}
|
| 646 |
|
| 647 |
function isSpaceFull() {
|
| 648 |
-
return getTotalUsers() >= MAX_USERS ||
|
| 649 |
-
|
|
|
|
|
|
|
| 650 |
}
|
| 651 |
|
| 652 |
// ============ BATCH PROCESSING ============
|
| 653 |
-
|
| 654 |
-
|
| 655 |
-
|
| 656 |
-
|
| 657 |
-
|
| 658 |
-
|
| 659 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 660 |
|
| 661 |
-
|
| 662 |
-
|
|
|
|
| 663 |
|
| 664 |
-
|
| 665 |
-
|
| 666 |
|
| 667 |
-
|
| 668 |
-
|
| 669 |
-
const pipeline = redis.pipeline();
|
| 670 |
-
for (const item of batch) {
|
| 671 |
-
pipeline.setex(`req:${item.type}:${item.id}`, 300, JSON.stringify(item));
|
| 672 |
-
}
|
| 673 |
-
await pipeline.exec();
|
| 674 |
-
await processFromRedis();
|
| 675 |
-
} else {
|
| 676 |
-
await processRequestsBatch(batch);
|
| 677 |
-
}
|
| 678 |
-
} catch (e) {
|
| 679 |
-
console.error(`Main: Batch flush error:`, e.message);
|
| 680 |
-
batchBuffer.unshift(...batch);
|
| 681 |
-
} finally {
|
| 682 |
processingLock = false;
|
| 683 |
-
|
|
|
|
| 684 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 685 |
}
|
| 686 |
|
| 687 |
async function processFromRedis() {
|
| 688 |
-
if (!redis) return;
|
|
|
|
| 689 |
try {
|
| 690 |
const keys = await redis.keys('req:*');
|
| 691 |
if (keys.length === 0) return;
|
|
@@ -700,8 +748,20 @@ if (!isMainThread) {
|
|
| 700 |
chunk.forEach(key => pipeline.get(key));
|
| 701 |
const results = await pipeline.exec();
|
| 702 |
|
| 703 |
-
const requests = results
|
| 704 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 705 |
|
| 706 |
const deletePipeline = redis.pipeline();
|
| 707 |
chunk.forEach(key => deletePipeline.del(key));
|
|
@@ -712,124 +772,219 @@ if (!isMainThread) {
|
|
| 712 |
}
|
| 713 |
}
|
| 714 |
|
|
|
|
| 715 |
async function processRequestsBatch(requests) {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 716 |
const operations = [];
|
| 717 |
|
| 718 |
for (const req of requests) {
|
| 719 |
-
|
| 720 |
-
|
| 721 |
-
|
| 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 |
-
|
| 750 |
-
|
| 751 |
-
|
| 752 |
-
|
| 753 |
-
|
| 754 |
-
|
| 755 |
-
|
| 756 |
-
|
| 757 |
-
|
| 758 |
-
|
| 759 |
-
|
| 760 |
-
|
| 761 |
-
|
| 762 |
-
|
| 763 |
-
|
| 764 |
-
|
| 765 |
-
|
| 766 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 767 |
}
|
|
|
|
|
|
|
|
|
|
| 768 |
}
|
| 769 |
-
|
| 770 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 771 |
|
| 772 |
operations.push({
|
| 773 |
action: 'updateProfile',
|
| 774 |
userId: req.user_id,
|
| 775 |
-
data:
|
| 776 |
-
userId: req.user_id,
|
| 777 |
-
name: req.data.name || '',
|
| 778 |
-
email: req.data.email || '',
|
| 779 |
-
country: req.data.country || '',
|
| 780 |
-
location: req.data.location || '',
|
| 781 |
-
bio: req.data.bio || '',
|
| 782 |
-
external_links: req.data.external_links || '',
|
| 783 |
-
date_of_birth: req.data.date_of_birth || '',
|
| 784 |
-
is_profile_public: req.data.is_profile_public || '',
|
| 785 |
-
total_times_profile_updated_today: profileUser.total_times_profile_updated_today,
|
| 786 |
-
last_profile_updated: profileUser.last_profile_updated
|
| 787 |
-
}
|
| 788 |
});
|
| 789 |
-
|
| 790 |
-
break;
|
| 791 |
-
|
| 792 |
-
case 'upload_photo':
|
| 793 |
-
if (req.pic_buffer) {
|
| 794 |
-
const compressed = await compressToWebp(Buffer.from(req.pic_buffer, 'base64'), MAX_PHOTO_SIZE_KB);
|
| 795 |
-
const filename = `${req.user_id}_${Math.floor(Date.now() / 1000)}.webp`;
|
| 796 |
-
const filePath = path.join(PHOTOS_DIR, filename);
|
| 797 |
-
await fsp.writeFile(filePath, compressed.buffer);
|
| 798 |
|
| 799 |
-
|
| 800 |
-
if (
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 801 |
|
| 802 |
-
|
| 803 |
-
|
| 804 |
-
|
| 805 |
-
|
| 806 |
-
|
| 807 |
-
|
| 808 |
-
|
| 809 |
-
|
| 810 |
-
|
| 811 |
-
|
| 812 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 813 |
}
|
| 814 |
}
|
| 815 |
|
| 816 |
if (operations.length > 0) {
|
| 817 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 818 |
}
|
| 819 |
}
|
| 820 |
|
|
|
|
| 821 |
function addRequest(userId, username, action, data, picBuffer = null) {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 822 |
const request = {
|
| 823 |
id: generateId(),
|
| 824 |
user_id: userId,
|
| 825 |
-
username: username,
|
| 826 |
action: action,
|
| 827 |
-
data:
|
| 828 |
pic_buffer: picBuffer ? picBuffer.toString('base64') : null,
|
| 829 |
type: action,
|
| 830 |
timestamp: Date.now()
|
| 831 |
};
|
| 832 |
|
|
|
|
|
|
|
| 833 |
batchBuffer.push(request);
|
| 834 |
scheduleBatchProcess();
|
| 835 |
return request.id;
|
|
@@ -859,23 +1014,24 @@ if (!isMainThread) {
|
|
| 859 |
const cpuUsage = getCurrentCPUPercentage();
|
| 860 |
const totalUsers = getTotalUsers();
|
| 861 |
|
| 862 |
-
if (cpuUsage >= 98 || totalUsers >= MAX_USERS ||
|
|
|
|
| 863 |
await addSpaceToFull(CURRENT_SPACE_NAME);
|
| 864 |
reply.status(503);
|
| 865 |
-
reply.header('Content-Type', '
|
| 866 |
return toJsonl({ error: 'space_full', message: 'Server at maximum capacity', retry_after: 1 });
|
| 867 |
}
|
| 868 |
|
| 869 |
if (!globalRateLimiter.isAllowed()) {
|
| 870 |
await addSpaceToFull(CURRENT_SPACE_NAME);
|
| 871 |
reply.status(503);
|
| 872 |
-
reply.header('Content-Type', '
|
| 873 |
return toJsonl({ error: 'space_full', message: 'Global rate limit reached', retry_after: 1 });
|
| 874 |
}
|
| 875 |
|
| 876 |
if (!rateLimiter.isAllowed(request.ip)) {
|
| 877 |
reply.status(429);
|
| 878 |
-
reply.header('Content-Type', '
|
| 879 |
return toJsonl({ error: 'rate_limit_exceeded', message: 'Per-IP rate limit exceeded', retry_after: 1 });
|
| 880 |
}
|
| 881 |
});
|
|
@@ -931,13 +1087,10 @@ if (!isMainThread) {
|
|
| 931 |
timestamp: new Date().toISOString()
|
| 932 |
};
|
| 933 |
|
| 934 |
-
reply.header('Content-Type', '
|
| 935 |
return toJsonl(responseData);
|
| 936 |
});
|
| 937 |
|
| 938 |
-
// All other routes remain the same as your original code...
|
| 939 |
-
// [Include all routes from your original code here: /status, /health, /signup, /login, /logout, etc.]
|
| 940 |
-
|
| 941 |
fastify.get('/status', async (request, reply) => {
|
| 942 |
const spaceFull = isSpaceFull();
|
| 943 |
await checkAndUpdateFullStatus();
|
|
@@ -947,7 +1100,7 @@ if (!isMainThread) {
|
|
| 947 |
const cpuUsage = getCurrentCPUPercentage();
|
| 948 |
const totalUsers = getTotalUsers();
|
| 949 |
|
| 950 |
-
reply.header('Content-Type', '
|
| 951 |
return toJsonl({
|
| 952 |
worker_pid: process.pid,
|
| 953 |
architecture: '1 Process + 1 DB Thread',
|
|
@@ -981,7 +1134,7 @@ if (!isMainThread) {
|
|
| 981 |
});
|
| 982 |
|
| 983 |
fastify.get('/health', async (request, reply) => {
|
| 984 |
-
reply.header('Content-Type', '
|
| 985 |
return toJsonl({
|
| 986 |
status: 'healthy',
|
| 987 |
architecture: '1 Process + 1 DB Thread',
|
|
@@ -992,63 +1145,103 @@ if (!isMainThread) {
|
|
| 992 |
});
|
| 993 |
|
| 994 |
fastify.post('/signup', async (request, reply) => {
|
| 995 |
-
|
| 996 |
-
|
| 997 |
-
|
| 998 |
-
|
| 999 |
-
|
| 1000 |
-
|
| 1001 |
-
|
| 1002 |
-
|
| 1003 |
-
|
| 1004 |
-
|
| 1005 |
-
|
| 1006 |
-
|
| 1007 |
-
|
| 1008 |
-
|
| 1009 |
-
|
| 1010 |
-
|
| 1011 |
-
|
| 1012 |
-
|
| 1013 |
-
|
| 1014 |
-
|
| 1015 |
-
|
| 1016 |
-
|
| 1017 |
-
|
| 1018 |
-
|
| 1019 |
-
|
| 1020 |
-
|
| 1021 |
-
|
| 1022 |
-
|
| 1023 |
-
|
| 1024 |
-
|
| 1025 |
-
|
| 1026 |
-
|
| 1027 |
-
|
| 1028 |
-
|
| 1029 |
-
|
| 1030 |
-
|
| 1031 |
-
|
| 1032 |
-
|
| 1033 |
-
|
| 1034 |
-
|
| 1035 |
-
|
| 1036 |
-
|
| 1037 |
-
|
| 1038 |
-
|
| 1039 |
-
|
| 1040 |
-
|
| 1041 |
-
|
| 1042 |
-
|
| 1043 |
-
|
| 1044 |
-
|
| 1045 |
-
|
| 1046 |
-
|
| 1047 |
-
|
| 1048 |
-
|
| 1049 |
-
|
| 1050 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1051 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1052 |
|
| 1053 |
fastify.post('/login', async (request, reply) => {
|
| 1054 |
const { username, password } = request.body || {};
|
|
@@ -1073,7 +1266,7 @@ if (!isMainThread) {
|
|
| 1073 |
|
| 1074 |
addRequest(user.id, cleanUsername, 'login', {});
|
| 1075 |
|
| 1076 |
-
reply.header('Content-Type', '
|
| 1077 |
return toJsonl({
|
| 1078 |
success: true,
|
| 1079 |
worker_pid: process.pid,
|
|
@@ -1113,7 +1306,7 @@ if (!isMainThread) {
|
|
| 1113 |
|
| 1114 |
addRequest(id, '', 'logout', {});
|
| 1115 |
|
| 1116 |
-
reply.header('Content-Type', '
|
| 1117 |
return toJsonl({
|
| 1118 |
success: true,
|
| 1119 |
message: 'Logged out successfully',
|
|
@@ -1153,9 +1346,10 @@ if (!isMainThread) {
|
|
| 1153 |
return { detail: `Profile update limit reached. Max ${MAX_PROFILE_UPDATES_PER_DAY} updates per day.` };
|
| 1154 |
}
|
| 1155 |
|
|
|
|
| 1156 |
addRequest(id, '', 'update_profile', data);
|
| 1157 |
|
| 1158 |
-
reply.header('Content-Type', '
|
| 1159 |
return toJsonl({
|
| 1160 |
success: true,
|
| 1161 |
message: 'Profile update processed',
|
|
@@ -1182,7 +1376,8 @@ if (!isMainThread) {
|
|
| 1182 |
}
|
| 1183 |
|
| 1184 |
const fileBuffer = await data.toBuffer();
|
| 1185 |
-
const id = (data.fields && data.fields.id) ? data.fields.id.value :
|
|
|
|
| 1186 |
|
| 1187 |
if (!id) {
|
| 1188 |
reply.status(400);
|
|
@@ -1196,9 +1391,12 @@ if (!isMainThread) {
|
|
| 1196 |
}
|
| 1197 |
|
| 1198 |
const originalSizeKb = fileBuffer.length / 1024;
|
| 1199 |
-
addRequest(id, '', 'upload_photo', { original_size_kb: originalSizeKb }, fileBuffer);
|
| 1200 |
|
| 1201 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1202 |
return toJsonl({
|
| 1203 |
success: true,
|
| 1204 |
message: 'Photo upload queued',
|
|
@@ -1215,49 +1413,113 @@ if (!isMainThread) {
|
|
| 1215 |
});
|
| 1216 |
|
| 1217 |
fastify.get('/getuser', async (request, reply) => {
|
| 1218 |
-
|
| 1219 |
-
|
| 1220 |
-
|
| 1221 |
-
|
| 1222 |
-
|
| 1223 |
-
|
| 1224 |
-
|
| 1225 |
-
|
| 1226 |
-
|
| 1227 |
-
|
| 1228 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1229 |
}
|
| 1230 |
-
|
| 1231 |
-
|
| 1232 |
-
|
| 1233 |
-
|
| 1234 |
-
|
| 1235 |
-
|
| 1236 |
-
|
| 1237 |
-
|
| 1238 |
-
|
| 1239 |
-
|
| 1240 |
-
|
| 1241 |
-
|
| 1242 |
-
|
| 1243 |
-
|
| 1244 |
-
|
| 1245 |
-
|
| 1246 |
-
|
| 1247 |
-
|
| 1248 |
-
|
| 1249 |
-
|
| 1250 |
-
|
| 1251 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1252 |
|
| 1253 |
fastify.get('/users/count', async (request, reply) => {
|
| 1254 |
-
reply.header('Content-Type', '
|
| 1255 |
-
return toJsonl({
|
|
|
|
|
|
|
| 1256 |
});
|
| 1257 |
|
| 1258 |
fastify.get('/users', async (request, reply) => {
|
| 1259 |
if (usersCache.size === 0) {
|
| 1260 |
-
reply.header('Content-Type', '
|
| 1261 |
return toJsonl({ users: [], total: 0 });
|
| 1262 |
}
|
| 1263 |
|
|
@@ -1278,7 +1540,7 @@ if (!isMainThread) {
|
|
| 1278 |
}
|
| 1279 |
});
|
| 1280 |
|
| 1281 |
-
reply.header('Content-Type', '
|
| 1282 |
return stream;
|
| 1283 |
});
|
| 1284 |
|
|
@@ -1287,7 +1549,7 @@ if (!isMainThread) {
|
|
| 1287 |
const emptySpaces = SPACE_NAMES.filter(s => !fullSpaces.includes(s));
|
| 1288 |
const sizeSpaces = await getSizeSpaces();
|
| 1289 |
|
| 1290 |
-
reply.header('Content-Type', '
|
| 1291 |
return toJsonl({
|
| 1292 |
all_spaces: SPACE_NAMES,
|
| 1293 |
full_spaces: fullSpaces,
|
|
@@ -1335,9 +1597,11 @@ if (!isMainThread) {
|
|
| 1335 |
return { detail: 'New password must be different' };
|
| 1336 |
}
|
| 1337 |
|
| 1338 |
-
addRequest(user.id, cleanUsername, 'forgot_password', {
|
|
|
|
|
|
|
| 1339 |
|
| 1340 |
-
reply.header('Content-Type', '
|
| 1341 |
return toJsonl({
|
| 1342 |
success: true,
|
| 1343 |
message: 'Password reset processed',
|
|
@@ -1347,13 +1611,11 @@ if (!isMainThread) {
|
|
| 1347 |
|
| 1348 |
return fastify;
|
| 1349 |
}
|
| 1350 |
-
|
| 1351 |
// ============ STARTUP ============
|
| 1352 |
async function start() {
|
| 1353 |
try {
|
| 1354 |
console.log(`Main: Starting with 1 Fastify process + 1 DB Worker Thread (2 cores)`);
|
| 1355 |
|
| 1356 |
-
// Initialize DB Worker Thread
|
| 1357 |
await initDBWorker();
|
| 1358 |
|
| 1359 |
if (redis) {
|
|
@@ -1362,6 +1624,7 @@ if (!isMainThread) {
|
|
| 1362 |
console.log(`Main: Redis connected`);
|
| 1363 |
} catch (e) {
|
| 1364 |
console.warn(`Main: Redis connection failed:`, e.message);
|
|
|
|
| 1365 |
redis = null;
|
| 1366 |
}
|
| 1367 |
}
|
|
@@ -1370,11 +1633,12 @@ if (!isMainThread) {
|
|
| 1370 |
await loadUsersToMemory();
|
| 1371 |
|
| 1372 |
await checkAndUpdateFullStatus();
|
| 1373 |
-
|
| 1374 |
await setupFastify();
|
| 1375 |
|
| 1376 |
setInterval(async () => {
|
| 1377 |
-
if (redis
|
|
|
|
|
|
|
| 1378 |
await checkAndUpdateFullStatus();
|
| 1379 |
}, 50);
|
| 1380 |
|
|
@@ -1388,13 +1652,13 @@ if (!isMainThread) {
|
|
| 1388 |
console.log(`Main: ⚡ Processing: ${BATCH_SIZE} requests/batch`);
|
| 1389 |
console.log(`Main: 📈 Max RPS: ${MAX_RPS} req/sec`);
|
| 1390 |
console.log(`Main: 👥 Max Users: ${MAX_USERS}`);
|
|
|
|
| 1391 |
} catch (err) {
|
| 1392 |
console.error(`Main: Error during startup:`, err);
|
| 1393 |
process.exit(1);
|
| 1394 |
}
|
| 1395 |
}
|
| 1396 |
|
| 1397 |
-
// Handle shutdown
|
| 1398 |
process.on('SIGTERM', async () => {
|
| 1399 |
console.log(`Main: Shutting down...`);
|
| 1400 |
await flushBatchToRedis();
|
|
|
|
|
|
|
| 1 |
'use strict';
|
| 2 |
const { Worker: ThreadWorker, isMainThread, parentPort, workerData } = require('worker_threads');
|
| 3 |
const os = require('os');
|
|
|
|
| 56 |
insertUser: db.prepare(`
|
| 57 |
INSERT OR REPLACE INTO users (
|
| 58 |
id, username, password_hash, name, email, country, location,
|
| 59 |
+
created_at, is_login, bio, pic_url, external_links, date_of_birth,
|
| 60 |
+
total_times_profile_updated_today, last_profile_updated, is_profile_public, fing_key
|
|
|
|
| 61 |
) VALUES (
|
| 62 |
@id, @username, @password_hash, @name, @email, @country, @location,
|
| 63 |
+
@created_at, @is_login, @bio, @pic_url, @external_links, @date_of_birth,
|
| 64 |
+
@total_times_profile_updated_today, @last_profile_updated, @is_profile_public, @fing_key
|
|
|
|
| 65 |
)
|
| 66 |
`),
|
| 67 |
updateLogin: db.prepare('UPDATE users SET is_login = ? WHERE id = ?'),
|
|
|
|
| 116 |
case 'updateProfile':
|
| 117 |
stmts.updateProfile.run({
|
| 118 |
id: data.userId,
|
| 119 |
+
name: data.name || 'Unknown',
|
| 120 |
+
email: data.email || 'no-email@example.com',
|
| 121 |
country: data.country || '',
|
| 122 |
location: data.location || '',
|
| 123 |
bio: data.bio || '',
|
| 124 |
+
external_links: data.external_links || '[]',
|
| 125 |
date_of_birth: data.date_of_birth || '',
|
| 126 |
+
is_profile_public: data.is_profile_public || 'true',
|
| 127 |
total_times_profile_updated_today: data.total_times_profile_updated_today || 0,
|
| 128 |
last_profile_updated: data.last_profile_updated || ''
|
| 129 |
});
|
|
|
|
| 216 |
} catch (e) {
|
| 217 |
console.log(`Main: ioredis not available:`, e.message);
|
| 218 |
}
|
|
|
|
| 219 |
try {
|
| 220 |
sharp = require('sharp');
|
| 221 |
} catch (e) {
|
|
|
|
| 238 |
const MAX_LOCATION_LENGTH = 500;
|
| 239 |
const MAX_EMAIL_LENGTH = 200;
|
| 240 |
const MAX_RPS = 15000;
|
| 241 |
+
const SPACE_NAMES = ["data2"];
|
| 242 |
const BASE_SPACE_URL = "https://velost-db1-{space}.hf.space";
|
| 243 |
+
const CURRENT_SPACE_NAME = "1";
|
| 244 |
const BATCH_SIZE = 15000;
|
| 245 |
const HASH = process.env.HASH || 'v3l0st-d3f4ult-h4sh-k3y-2024!@#$%^&*()';
|
| 246 |
|
|
|
|
| 264 |
if (!fs.existsSync(FULL_FILE)) {
|
| 265 |
fs.writeFileSync(FULL_FILE, '', 'utf8');
|
| 266 |
}
|
|
|
|
| 267 |
if (!fs.existsSync(SIZE_FILE)) {
|
| 268 |
fs.writeFileSync(SIZE_FILE, '', 'utf8');
|
| 269 |
}
|
|
|
|
| 311 |
// ============ REDIS SETUP ============
|
| 312 |
let redis = null;
|
| 313 |
if (Redis) {
|
| 314 |
+
try {
|
| 315 |
+
redis = new Redis({
|
| 316 |
+
host: process.env.REDIS_HOST || '127.0.0.1',
|
| 317 |
+
port: process.env.REDIS_PORT || 6379,
|
| 318 |
+
maxRetriesPerRequest: 3,
|
| 319 |
+
enableReadyCheck: true,
|
| 320 |
+
lazyConnect: true,
|
| 321 |
+
connectTimeout: 5000,
|
| 322 |
+
retryStrategy(times) {
|
| 323 |
+
if (times > 3) {
|
| 324 |
+
console.log(`Main: Redis retry limit reached, disabling Redis buffering`);
|
| 325 |
+
return null;
|
| 326 |
+
}
|
| 327 |
+
return Math.min(times * 50, 2000);
|
| 328 |
+
}
|
| 329 |
+
});
|
| 330 |
+
|
| 331 |
+
redis.on('error', (err) => {
|
| 332 |
+
console.error(`Main: Redis error:`, err.message);
|
| 333 |
+
});
|
| 334 |
+
|
| 335 |
+
redis.on('close', () => {
|
| 336 |
+
console.log(`Main: Redis connection closed`);
|
| 337 |
+
});
|
| 338 |
+
|
| 339 |
+
} catch (e) {
|
| 340 |
+
console.log(`Main: Failed to create Redis client:`, e.message);
|
| 341 |
+
redis = null;
|
| 342 |
+
}
|
| 343 |
}
|
| 344 |
|
| 345 |
// ============ IN-MEMORY STORAGE ============
|
|
|
|
| 434 |
return crypto.createHash('sha256').update(uuidv4()).digest('hex').substring(0, 32);
|
| 435 |
}
|
| 436 |
|
| 437 |
+
function generateRandomUsername() {
|
| 438 |
+
return 'user_' + crypto.randomBytes(4).toString('hex');
|
| 439 |
+
}
|
| 440 |
+
|
| 441 |
+
function generateRandomName() {
|
| 442 |
+
return 'User_' + crypto.randomBytes(3).toString('hex');
|
| 443 |
+
}
|
| 444 |
+
|
| 445 |
function formatSize(bytesSize) {
|
| 446 |
if (bytesSize === 0) return "0 B";
|
| 447 |
const units = ["B", "KB", "MB", "GB", "TB"];
|
|
|
|
| 546 |
const bucketSize = getBucketSize();
|
| 547 |
const ramUsage = getMemoryUsage();
|
| 548 |
|
| 549 |
+
const isFull = currentRPS >= MAX_RPS ||
|
| 550 |
+
cpuUsage >= 98 ||
|
| 551 |
+
totalUsers >= MAX_USERS ||
|
| 552 |
+
bucketSize >= MAX_BUCKET_SIZE ||
|
| 553 |
+
ramUsage >= MAX_RAM_USAGE;
|
| 554 |
|
| 555 |
if (isFull !== lastFullStatus) {
|
| 556 |
lastFullStatus = isFull;
|
|
|
|
| 583 |
let outputBuffer;
|
| 584 |
|
| 585 |
while (quality >= 10) {
|
| 586 |
+
outputBuffer = await image
|
| 587 |
+
.resize(800, 800, { fit: 'inside', withoutEnlargement: true })
|
| 588 |
+
.webp({ quality })
|
| 589 |
+
.toBuffer();
|
| 590 |
+
|
| 591 |
if (outputBuffer.length / 1024 <= maxSizeKb) break;
|
| 592 |
quality -= 10;
|
| 593 |
}
|
| 594 |
|
| 595 |
if (outputBuffer.length / 1024 > maxSizeKb) {
|
| 596 |
+
outputBuffer = await image
|
| 597 |
+
.resize(400, 400, { fit: 'inside', withoutEnlargement: true })
|
| 598 |
+
.webp({ quality: 30 })
|
| 599 |
+
.toBuffer();
|
| 600 |
}
|
| 601 |
|
| 602 |
+
return {
|
| 603 |
+
buffer: outputBuffer,
|
| 604 |
+
isWebp: true,
|
| 605 |
+
sizeKb: outputBuffer.length / 1024,
|
| 606 |
+
wasCompressed: true
|
| 607 |
+
};
|
| 608 |
} catch (e) {
|
| 609 |
return { buffer: fileData, isWebp: false, sizeKb: fileData.length / 1024, wasCompressed: false };
|
| 610 |
}
|
|
|
|
| 626 |
|
| 627 |
async function getUser(userId) {
|
| 628 |
if (usersCache.has(userId)) return usersCache.get(userId);
|
|
|
|
| 629 |
try {
|
| 630 |
const user = await dbRequest('getUserById', { userId });
|
| 631 |
if (user) usersCache.set(userId, user);
|
|
|
|
| 639 |
for (const user of usersCache.values()) {
|
| 640 |
if (user.username === username) return user;
|
| 641 |
}
|
|
|
|
| 642 |
try {
|
| 643 |
const user = await dbRequest('getUserByUsername', { username });
|
| 644 |
if (user) usersCache.set(user.id, user);
|
|
|
|
| 654 |
|
| 655 |
function getBucketSize() {
|
| 656 |
let totalSize = 0;
|
|
|
|
| 657 |
function walkDir(dir) {
|
| 658 |
if (!fs.existsSync(dir)) return;
|
| 659 |
try {
|
|
|
|
| 666 |
}
|
| 667 |
} catch (e) {}
|
| 668 |
}
|
|
|
|
| 669 |
walkDir(DATA_DIR);
|
| 670 |
return totalSize;
|
| 671 |
}
|
| 672 |
|
| 673 |
function isSpaceFull() {
|
| 674 |
+
return getTotalUsers() >= MAX_USERS ||
|
| 675 |
+
getBucketSize() >= MAX_BUCKET_SIZE ||
|
| 676 |
+
globalRateLimiter.getCurrentCount() >= MAX_RPS ||
|
| 677 |
+
getCurrentCPUPercentage() >= 98;
|
| 678 |
}
|
| 679 |
|
| 680 |
// ============ BATCH PROCESSING ============
|
| 681 |
+
// ============ BATCH PROCESSING - PROCESS EVERY 1 SECOND ============
|
| 682 |
+
let lastBatchTime = Date.now();
|
| 683 |
+
|
| 684 |
+
function scheduleBatchProcess() {
|
| 685 |
+
if (batchTimer) return;
|
| 686 |
+
|
| 687 |
+
// Process every 1 second
|
| 688 |
+
batchTimer = setTimeout(async () => {
|
| 689 |
+
batchTimer = null;
|
| 690 |
+
await flushBatchToRedis();
|
| 691 |
+
}, 1000); // 1 second
|
| 692 |
+
}
|
| 693 |
+
|
| 694 |
+
async function flushBatchToRedis() {
|
| 695 |
+
if (batchBuffer.length === 0 || processingLock) return;
|
| 696 |
+
processingLock = true;
|
| 697 |
+
|
| 698 |
+
// Take up to BATCH_SIZE (15000) items
|
| 699 |
+
const batch = batchBuffer.splice(0, BATCH_SIZE);
|
| 700 |
+
const batchCount = batch.length;
|
| 701 |
+
|
| 702 |
+
console.log(`Main: Processing batch of ${batchCount} requests (${batchBuffer.length} remaining)`);
|
| 703 |
+
|
| 704 |
+
const startTime = Date.now();
|
| 705 |
|
| 706 |
+
try {
|
| 707 |
+
// Process directly without Redis
|
| 708 |
+
await processRequestsBatch(batch);
|
| 709 |
|
| 710 |
+
const duration = Date.now() - startTime;
|
| 711 |
+
console.log(`Main: Batch of ${batchCount} processed in ${duration}ms`);
|
| 712 |
|
| 713 |
+
// If more items in buffer, process immediately
|
| 714 |
+
if (batchBuffer.length > 0) {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 715 |
processingLock = false;
|
| 716 |
+
scheduleBatchProcess();
|
| 717 |
+
return;
|
| 718 |
}
|
| 719 |
+
|
| 720 |
+
} catch (e) {
|
| 721 |
+
console.error(`Main: Batch processing error:`, e.message);
|
| 722 |
+
// Put failed items back
|
| 723 |
+
batchBuffer.unshift(...batch);
|
| 724 |
+
} finally {
|
| 725 |
+
processingLock = false;
|
| 726 |
+
}
|
| 727 |
+
}
|
| 728 |
+
|
| 729 |
+
async function processRequestsBatchDirectly(batch) {
|
| 730 |
+
console.log(`Main: Processing ${batch.length} requests directly`);
|
| 731 |
+
await processRequestsBatch(batch);
|
| 732 |
}
|
| 733 |
|
| 734 |
async function processFromRedis() {
|
| 735 |
+
if (!redis || redis.status !== 'ready') return;
|
| 736 |
+
|
| 737 |
try {
|
| 738 |
const keys = await redis.keys('req:*');
|
| 739 |
if (keys.length === 0) return;
|
|
|
|
| 748 |
chunk.forEach(key => pipeline.get(key));
|
| 749 |
const results = await pipeline.exec();
|
| 750 |
|
| 751 |
+
const requests = results
|
| 752 |
+
.filter(([err, data]) => !err && data)
|
| 753 |
+
.map(([err, data]) => {
|
| 754 |
+
try {
|
| 755 |
+
return JSON.parse(data);
|
| 756 |
+
} catch (parseError) {
|
| 757 |
+
return null;
|
| 758 |
+
}
|
| 759 |
+
})
|
| 760 |
+
.filter(req => req !== null);
|
| 761 |
+
|
| 762 |
+
if (requests.length > 0) {
|
| 763 |
+
await processRequestsBatch(requests);
|
| 764 |
+
}
|
| 765 |
|
| 766 |
const deletePipeline = redis.pipeline();
|
| 767 |
chunk.forEach(key => deletePipeline.del(key));
|
|
|
|
| 772 |
}
|
| 773 |
}
|
| 774 |
|
| 775 |
+
// FIXED: processRequestsBatch - ID always present, empty fields get defaults
|
| 776 |
async function processRequestsBatch(requests) {
|
| 777 |
+
if (!requests || requests.length === 0) {
|
| 778 |
+
console.log('Main: No requests to process');
|
| 779 |
+
return;
|
| 780 |
+
}
|
| 781 |
+
|
| 782 |
+
console.log(`Main: Processing ${requests.length} requests in batch`);
|
| 783 |
const operations = [];
|
| 784 |
|
| 785 |
for (const req of requests) {
|
| 786 |
+
try {
|
| 787 |
+
// MUST have user_id - skip if missing
|
| 788 |
+
if (!req || !req.user_id) {
|
| 789 |
+
console.error('Main: Skipping request - missing user_id');
|
| 790 |
+
continue;
|
| 791 |
+
}
|
| 792 |
+
|
| 793 |
+
// Default action if missing
|
| 794 |
+
const action = req.action || 'unknown';
|
| 795 |
+
|
| 796 |
+
switch (action) {
|
| 797 |
+
case 'signup':
|
| 798 |
+
// Ensure all required fields with defaults
|
| 799 |
+
operations.push({
|
| 800 |
+
action: 'signup',
|
| 801 |
+
userId: req.user_id,
|
| 802 |
+
user: {
|
| 803 |
+
id: req.user_id,
|
| 804 |
+
username: (req.data && req.data.username) || generateRandomUsername(),
|
| 805 |
+
password_hash: hashPassword((req.data && req.data.password) || 'default123'),
|
| 806 |
+
name: (req.data && req.data.name) || generateRandomName(),
|
| 807 |
+
email: (req.data && req.data.email) || `${req.user_id}@default.com`,
|
| 808 |
+
country: (req.data && req.data.country) || '',
|
| 809 |
+
location: (req.data && req.data.location) || '',
|
| 810 |
+
created_at: new Date().toISOString(),
|
| 811 |
+
is_login: 0,
|
| 812 |
+
bio: '',
|
| 813 |
+
pic_url: '',
|
| 814 |
+
external_links: '[]',
|
| 815 |
+
date_of_birth: '',
|
| 816 |
+
total_times_profile_updated_today: 0,
|
| 817 |
+
last_profile_updated: '',
|
| 818 |
+
is_profile_public: 'true',
|
| 819 |
+
fing_key: (req.data && req.data.fing_key) || generateFingKey()
|
| 820 |
+
}
|
| 821 |
+
});
|
| 822 |
+
usersCache.set(req.user_id, operations[operations.length - 1].user);
|
| 823 |
+
break;
|
| 824 |
+
|
| 825 |
+
case 'login':
|
| 826 |
+
operations.push({ action: 'login', userId: req.user_id });
|
| 827 |
+
const loginUser = usersCache.get(req.user_id);
|
| 828 |
+
if (loginUser) loginUser.is_login = 1;
|
| 829 |
+
break;
|
| 830 |
+
|
| 831 |
+
case 'logout':
|
| 832 |
+
operations.push({ action: 'logout', userId: req.user_id });
|
| 833 |
+
const logoutUser = usersCache.get(req.user_id);
|
| 834 |
+
if (logoutUser) logoutUser.is_login = 0;
|
| 835 |
+
break;
|
| 836 |
+
|
| 837 |
+
case 'update_profile':
|
| 838 |
+
const profileUser = usersCache.get(req.user_id);
|
| 839 |
+
const updateData = req.data || {};
|
| 840 |
+
|
| 841 |
+
// Update cache if user exists
|
| 842 |
+
if (profileUser) {
|
| 843 |
+
const fields = ['name', 'email', 'country', 'location', 'bio',
|
| 844 |
+
'external_links', 'date_of_birth', 'is_profile_public'];
|
| 845 |
+
for (const field of fields) {
|
| 846 |
+
if (updateData[field] !== null && updateData[field] !== undefined && updateData[field] !== '') {
|
| 847 |
+
profileUser[field] = typeof updateData[field] === 'string' ?
|
| 848 |
+
updateData[field].trim() : String(updateData[field]).trim();
|
| 849 |
+
}
|
| 850 |
}
|
| 851 |
+
profileUser.total_times_profile_updated_today =
|
| 852 |
+
(profileUser.total_times_profile_updated_today || 0) + 1;
|
| 853 |
+
profileUser.last_profile_updated = new Date().toISOString();
|
| 854 |
}
|
| 855 |
+
|
| 856 |
+
// Build operation with ALL fields having defaults - ID always present
|
| 857 |
+
const profileOpData = {
|
| 858 |
+
userId: req.user_id,
|
| 859 |
+
name: updateData.name || (profileUser ? profileUser.name : generateRandomName()),
|
| 860 |
+
email: updateData.email || (profileUser ? profileUser.email : `${req.user_id}@default.com`),
|
| 861 |
+
country: updateData.country || (profileUser ? profileUser.country : ''),
|
| 862 |
+
location: updateData.location || (profileUser ? profileUser.location : ''),
|
| 863 |
+
bio: updateData.bio || (profileUser ? profileUser.bio : ''),
|
| 864 |
+
external_links: updateData.external_links || (profileUser ? profileUser.external_links : '[]'),
|
| 865 |
+
date_of_birth: updateData.date_of_birth || (profileUser ? profileUser.date_of_birth : ''),
|
| 866 |
+
is_profile_public: updateData.is_profile_public || (profileUser ? profileUser.is_profile_public : 'true'),
|
| 867 |
+
total_times_profile_updated_today: (profileUser ? profileUser.total_times_profile_updated_today : 0) || 0,
|
| 868 |
+
last_profile_updated: (profileUser ? profileUser.last_profile_updated : new Date().toISOString())
|
| 869 |
+
};
|
| 870 |
|
| 871 |
operations.push({
|
| 872 |
action: 'updateProfile',
|
| 873 |
userId: req.user_id,
|
| 874 |
+
data: profileOpData
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 875 |
});
|
| 876 |
+
break;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 877 |
|
| 878 |
+
case 'upload_photo':
|
| 879 |
+
if (req.pic_buffer) {
|
| 880 |
+
try {
|
| 881 |
+
const compressed = await compressToWebp(
|
| 882 |
+
Buffer.from(req.pic_buffer, 'base64'),
|
| 883 |
+
MAX_PHOTO_SIZE_KB
|
| 884 |
+
);
|
| 885 |
+
const filename = `${req.user_id}_${Math.floor(Date.now() / 1000)}.webp`;
|
| 886 |
+
const filePath = path.join(PHOTOS_DIR, filename);
|
| 887 |
+
await fsp.writeFile(filePath, compressed.buffer);
|
| 888 |
+
|
| 889 |
+
const photoUser = usersCache.get(req.user_id);
|
| 890 |
+
if (photoUser) photoUser.pic_url = `/photos/${filename}`;
|
| 891 |
+
|
| 892 |
+
operations.push({
|
| 893 |
+
action: 'updatePhoto',
|
| 894 |
+
userId: req.user_id,
|
| 895 |
+
picUrl: `/photos/${filename}`
|
| 896 |
+
});
|
| 897 |
+
} catch (photoError) {
|
| 898 |
+
console.error(`Main: Photo processing error:`, photoError.message);
|
| 899 |
+
}
|
| 900 |
+
}
|
| 901 |
+
break;
|
| 902 |
|
| 903 |
+
case 'forgot_password':
|
| 904 |
+
const newPassword = (req.data && req.data.new_password) || 'default123';
|
| 905 |
+
const newHash = hashPassword(newPassword);
|
| 906 |
+
const passUser = usersCache.get(req.user_id);
|
| 907 |
+
if (passUser) passUser.password_hash = newHash;
|
| 908 |
+
|
| 909 |
+
operations.push({
|
| 910 |
+
action: 'updatePassword',
|
| 911 |
+
userId: req.user_id,
|
| 912 |
+
passwordHash: newHash
|
| 913 |
+
});
|
| 914 |
+
break;
|
| 915 |
+
|
| 916 |
+
default:
|
| 917 |
+
console.error('Main: Unknown action:', action);
|
| 918 |
+
}
|
| 919 |
+
} catch (reqError) {
|
| 920 |
+
console.error(`Main: Error processing request:`, reqError.message);
|
| 921 |
}
|
| 922 |
}
|
| 923 |
|
| 924 |
if (operations.length > 0) {
|
| 925 |
+
try {
|
| 926 |
+
await dbRequest('batchOperation', { operations });
|
| 927 |
+
console.log(`Main: Successfully processed ${operations.length} operations`);
|
| 928 |
+
} catch (dbError) {
|
| 929 |
+
console.error(`Main: DB batch operation failed:`, dbError.message);
|
| 930 |
+
throw dbError;
|
| 931 |
+
}
|
| 932 |
}
|
| 933 |
}
|
| 934 |
|
| 935 |
+
// FIXED: addRequest - ID always present, empty fields get random defaults
|
| 936 |
function addRequest(userId, username, action, data, picBuffer = null) {
|
| 937 |
+
// MUST have userId
|
| 938 |
+
if (!userId) {
|
| 939 |
+
console.error('Main: Cannot add request - missing userId, generating random');
|
| 940 |
+
userId = generateId();
|
| 941 |
+
}
|
| 942 |
+
|
| 943 |
+
// Default action if missing
|
| 944 |
+
if (!action) {
|
| 945 |
+
console.error('Main: Cannot add request - missing action, using unknown');
|
| 946 |
+
action = 'unknown';
|
| 947 |
+
}
|
| 948 |
+
|
| 949 |
+
// Ensure data has all required fields with defaults
|
| 950 |
+
const safeData = data || {};
|
| 951 |
+
|
| 952 |
+
if (action === 'signup') {
|
| 953 |
+
safeData.username = safeData.username || generateRandomUsername();
|
| 954 |
+
safeData.password = safeData.password || 'default123';
|
| 955 |
+
safeData.name = safeData.name || generateRandomName();
|
| 956 |
+
safeData.email = safeData.email || `${userId}@default.com`;
|
| 957 |
+
safeData.fing_key = safeData.fing_key || generateFingKey();
|
| 958 |
+
}
|
| 959 |
+
|
| 960 |
+
if (action === 'update_profile') {
|
| 961 |
+
safeData.name = safeData.name || null;
|
| 962 |
+
safeData.email = safeData.email || null;
|
| 963 |
+
safeData.country = safeData.country || null;
|
| 964 |
+
safeData.location = safeData.location || null;
|
| 965 |
+
safeData.bio = safeData.bio || null;
|
| 966 |
+
safeData.external_links = safeData.external_links || null;
|
| 967 |
+
safeData.date_of_birth = safeData.date_of_birth || null;
|
| 968 |
+
safeData.is_profile_public = safeData.is_profile_public || null;
|
| 969 |
+
}
|
| 970 |
+
|
| 971 |
+
if (action === 'forgot_password') {
|
| 972 |
+
safeData.new_password = safeData.new_password || 'default123';
|
| 973 |
+
}
|
| 974 |
+
|
| 975 |
const request = {
|
| 976 |
id: generateId(),
|
| 977 |
user_id: userId,
|
| 978 |
+
username: username || 'unknown_user',
|
| 979 |
action: action,
|
| 980 |
+
data: safeData,
|
| 981 |
pic_buffer: picBuffer ? picBuffer.toString('base64') : null,
|
| 982 |
type: action,
|
| 983 |
timestamp: Date.now()
|
| 984 |
};
|
| 985 |
|
| 986 |
+
console.log(`Main: Added request - action: ${action}, userId: ${userId}`);
|
| 987 |
+
|
| 988 |
batchBuffer.push(request);
|
| 989 |
scheduleBatchProcess();
|
| 990 |
return request.id;
|
|
|
|
| 1014 |
const cpuUsage = getCurrentCPUPercentage();
|
| 1015 |
const totalUsers = getTotalUsers();
|
| 1016 |
|
| 1017 |
+
if (cpuUsage >= 98 || totalUsers >= MAX_USERS ||
|
| 1018 |
+
getBucketSize() >= MAX_BUCKET_SIZE || getMemoryUsage() >= MAX_RAM_USAGE) {
|
| 1019 |
await addSpaceToFull(CURRENT_SPACE_NAME);
|
| 1020 |
reply.status(503);
|
| 1021 |
+
reply.header('Content-Type', 'application/json');
|
| 1022 |
return toJsonl({ error: 'space_full', message: 'Server at maximum capacity', retry_after: 1 });
|
| 1023 |
}
|
| 1024 |
|
| 1025 |
if (!globalRateLimiter.isAllowed()) {
|
| 1026 |
await addSpaceToFull(CURRENT_SPACE_NAME);
|
| 1027 |
reply.status(503);
|
| 1028 |
+
reply.header('Content-Type', 'application/json');
|
| 1029 |
return toJsonl({ error: 'space_full', message: 'Global rate limit reached', retry_after: 1 });
|
| 1030 |
}
|
| 1031 |
|
| 1032 |
if (!rateLimiter.isAllowed(request.ip)) {
|
| 1033 |
reply.status(429);
|
| 1034 |
+
reply.header('Content-Type', 'application/json');
|
| 1035 |
return toJsonl({ error: 'rate_limit_exceeded', message: 'Per-IP rate limit exceeded', retry_after: 1 });
|
| 1036 |
}
|
| 1037 |
});
|
|
|
|
| 1087 |
timestamp: new Date().toISOString()
|
| 1088 |
};
|
| 1089 |
|
| 1090 |
+
reply.header('Content-Type', 'application/json');
|
| 1091 |
return toJsonl(responseData);
|
| 1092 |
});
|
| 1093 |
|
|
|
|
|
|
|
|
|
|
| 1094 |
fastify.get('/status', async (request, reply) => {
|
| 1095 |
const spaceFull = isSpaceFull();
|
| 1096 |
await checkAndUpdateFullStatus();
|
|
|
|
| 1100 |
const cpuUsage = getCurrentCPUPercentage();
|
| 1101 |
const totalUsers = getTotalUsers();
|
| 1102 |
|
| 1103 |
+
reply.header('Content-Type', 'application/json');
|
| 1104 |
return toJsonl({
|
| 1105 |
worker_pid: process.pid,
|
| 1106 |
architecture: '1 Process + 1 DB Thread',
|
|
|
|
| 1134 |
});
|
| 1135 |
|
| 1136 |
fastify.get('/health', async (request, reply) => {
|
| 1137 |
+
reply.header('Content-Type', 'application/json');
|
| 1138 |
return toJsonl({
|
| 1139 |
status: 'healthy',
|
| 1140 |
architecture: '1 Process + 1 DB Thread',
|
|
|
|
| 1145 |
});
|
| 1146 |
|
| 1147 |
fastify.post('/signup', async (request, reply) => {
|
| 1148 |
+
if (getTotalUsers() >= MAX_USERS) {
|
| 1149 |
+
reply.status(507);
|
| 1150 |
+
reply.header('Content-Type', 'application/json');
|
| 1151 |
+
return JSON.stringify({ detail: `Maximum users (${MAX_USERS}) reached.` });
|
| 1152 |
+
}
|
| 1153 |
+
|
| 1154 |
+
const { username, password, name, email, fing_key } = request.body || {};
|
| 1155 |
+
|
| 1156 |
+
if (!username || !password || !name || !email) {
|
| 1157 |
+
reply.status(400);
|
| 1158 |
+
reply.header('Content-Type', 'application/json');
|
| 1159 |
+
return JSON.stringify({ detail: 'Missing required fields' });
|
| 1160 |
+
}
|
| 1161 |
+
|
| 1162 |
+
const cleanUsername = username.trim().toLowerCase();
|
| 1163 |
+
const cleanEmail = email.trim().toLowerCase();
|
| 1164 |
+
|
| 1165 |
+
if (cleanUsername.length < 3) {
|
| 1166 |
+
reply.status(400);
|
| 1167 |
+
reply.header('Content-Type', 'application/json');
|
| 1168 |
+
return JSON.stringify({ detail: 'Username too short' });
|
| 1169 |
+
}
|
| 1170 |
+
|
| 1171 |
+
if (password.length < 6) {
|
| 1172 |
+
reply.status(400);
|
| 1173 |
+
reply.header('Content-Type', 'application/json');
|
| 1174 |
+
return JSON.stringify({ detail: 'Password too short' });
|
| 1175 |
+
}
|
| 1176 |
+
|
| 1177 |
+
const existingUser = await getUserByUsername(cleanUsername);
|
| 1178 |
+
if (existingUser) {
|
| 1179 |
+
reply.status(409);
|
| 1180 |
+
reply.header('Content-Type', 'application/json');
|
| 1181 |
+
return JSON.stringify({ detail: 'Username already exists' });
|
| 1182 |
+
}
|
| 1183 |
+
|
| 1184 |
+
for (const user of usersCache.values()) {
|
| 1185 |
+
if (user.email === cleanEmail) {
|
| 1186 |
+
reply.status(409);
|
| 1187 |
+
reply.header('Content-Type', 'application/json');
|
| 1188 |
+
return JSON.stringify({ detail: 'Email already registered' });
|
| 1189 |
+
}
|
| 1190 |
+
}
|
| 1191 |
+
|
| 1192 |
+
const userId = generateId();
|
| 1193 |
+
|
| 1194 |
+
// ✅ WRITE DIRECTLY TO DATABASE - NO BATCH WAITING
|
| 1195 |
+
const newUser = {
|
| 1196 |
+
id: userId,
|
| 1197 |
+
username: cleanUsername,
|
| 1198 |
+
password_hash: hashPassword(password),
|
| 1199 |
+
name: name.trim(),
|
| 1200 |
+
email: cleanEmail,
|
| 1201 |
+
country: request.body.country || '',
|
| 1202 |
+
location: request.body.location || '',
|
| 1203 |
+
created_at: new Date().toISOString(),
|
| 1204 |
+
is_login: 0,
|
| 1205 |
+
bio: '',
|
| 1206 |
+
pic_url: '',
|
| 1207 |
+
external_links: '[]',
|
| 1208 |
+
date_of_birth: request.body.date_of_birth || '',
|
| 1209 |
+
total_times_profile_updated_today: 0,
|
| 1210 |
+
last_profile_updated: '',
|
| 1211 |
+
is_profile_public: 'true',
|
| 1212 |
+
fing_key: fing_key ? fing_key.trim() : generateFingKey()
|
| 1213 |
+
};
|
| 1214 |
+
|
| 1215 |
+
// Save to cache immediately
|
| 1216 |
+
usersCache.set(userId, newUser);
|
| 1217 |
+
|
| 1218 |
+
// Write to database directly (bypass batch)
|
| 1219 |
+
try {
|
| 1220 |
+
await dbRequest('insertUser', { user: newUser });
|
| 1221 |
+
} catch (dbError) {
|
| 1222 |
+
console.error('Direct insert failed, adding to batch:', dbError.message);
|
| 1223 |
+
addRequest(userId, cleanUsername, 'signup', {
|
| 1224 |
+
username: cleanUsername,
|
| 1225 |
+
password: password,
|
| 1226 |
+
name: name.trim(),
|
| 1227 |
+
email: cleanEmail,
|
| 1228 |
+
fing_key: fing_key ? fing_key.trim() : ''
|
| 1229 |
});
|
| 1230 |
+
}
|
| 1231 |
+
|
| 1232 |
+
// Return response immediately
|
| 1233 |
+
reply.header('Content-Type', 'application/json');
|
| 1234 |
+
return JSON.stringify({
|
| 1235 |
+
success: true,
|
| 1236 |
+
message: 'Account created successfully',
|
| 1237 |
+
user_id: userId,
|
| 1238 |
+
id: userId,
|
| 1239 |
+
username: cleanUsername,
|
| 1240 |
+
name: name.trim(),
|
| 1241 |
+
email: cleanEmail,
|
| 1242 |
+
timestamp: new Date().toISOString()
|
| 1243 |
+
});
|
| 1244 |
+
});
|
| 1245 |
|
| 1246 |
fastify.post('/login', async (request, reply) => {
|
| 1247 |
const { username, password } = request.body || {};
|
|
|
|
| 1266 |
|
| 1267 |
addRequest(user.id, cleanUsername, 'login', {});
|
| 1268 |
|
| 1269 |
+
reply.header('Content-Type', 'application/json');
|
| 1270 |
return toJsonl({
|
| 1271 |
success: true,
|
| 1272 |
worker_pid: process.pid,
|
|
|
|
| 1306 |
|
| 1307 |
addRequest(id, '', 'logout', {});
|
| 1308 |
|
| 1309 |
+
reply.header('Content-Type', 'application/json');
|
| 1310 |
return toJsonl({
|
| 1311 |
success: true,
|
| 1312 |
message: 'Logged out successfully',
|
|
|
|
| 1346 |
return { detail: `Profile update limit reached. Max ${MAX_PROFILE_UPDATES_PER_DAY} updates per day.` };
|
| 1347 |
}
|
| 1348 |
|
| 1349 |
+
// ID is always present, other fields can be empty
|
| 1350 |
addRequest(id, '', 'update_profile', data);
|
| 1351 |
|
| 1352 |
+
reply.header('Content-Type', 'application/json');
|
| 1353 |
return toJsonl({
|
| 1354 |
success: true,
|
| 1355 |
message: 'Profile update processed',
|
|
|
|
| 1376 |
}
|
| 1377 |
|
| 1378 |
const fileBuffer = await data.toBuffer();
|
| 1379 |
+
const id = (data.fields && data.fields.id) ? data.fields.id.value :
|
| 1380 |
+
(request.query ? request.query.id : null);
|
| 1381 |
|
| 1382 |
if (!id) {
|
| 1383 |
reply.status(400);
|
|
|
|
| 1391 |
}
|
| 1392 |
|
| 1393 |
const originalSizeKb = fileBuffer.length / 1024;
|
|
|
|
| 1394 |
|
| 1395 |
+
addRequest(id, '', 'upload_photo', {
|
| 1396 |
+
original_size_kb: originalSizeKb
|
| 1397 |
+
}, fileBuffer);
|
| 1398 |
+
|
| 1399 |
+
reply.header('Content-Type', 'application/json');
|
| 1400 |
return toJsonl({
|
| 1401 |
success: true,
|
| 1402 |
message: 'Photo upload queued',
|
|
|
|
| 1413 |
});
|
| 1414 |
|
| 1415 |
fastify.get('/getuser', async (request, reply) => {
|
| 1416 |
+
const { id, username } = request.query || {};
|
| 1417 |
+
|
| 1418 |
+
// If username provided, look up by username
|
| 1419 |
+
if (username) {
|
| 1420 |
+
const user = await getUserByUsername(username);
|
| 1421 |
+
|
| 1422 |
+
if (!user) {
|
| 1423 |
+
reply.status(404);
|
| 1424 |
+
return { detail: 'User not found' };
|
| 1425 |
+
}
|
| 1426 |
+
|
| 1427 |
+
return {
|
| 1428 |
+
worker_pid: process.pid,
|
| 1429 |
+
id: user.id,
|
| 1430 |
+
username: user.username,
|
| 1431 |
+
name: user.name,
|
| 1432 |
+
email: safeGet(user.email),
|
| 1433 |
+
country: safeGet(user.country),
|
| 1434 |
+
location: safeGet(user.location),
|
| 1435 |
+
created_at: safeGet(user.created_at),
|
| 1436 |
+
is_login: Boolean(safeGet(user.is_login, false)),
|
| 1437 |
+
bio: safeGet(user.bio),
|
| 1438 |
+
pic_url: safeGet(user.pic_url),
|
| 1439 |
+
external_links: safeGet(user.external_links, '[]'),
|
| 1440 |
+
date_of_birth: safeGet(user.date_of_birth),
|
| 1441 |
+
is_profile_public: safeGet(user.is_profile_public, 'true'),
|
| 1442 |
+
fing_key: safeGet(user.fing_key, ''),
|
| 1443 |
+
total_times_profile_updated_today: parseInt(safeGet(user.total_times_profile_updated_today, 0)),
|
| 1444 |
+
last_profile_updated: safeGet(user.last_profile_updated)
|
| 1445 |
+
};
|
| 1446 |
+
}
|
| 1447 |
+
|
| 1448 |
+
// If id provided, look up by id
|
| 1449 |
+
if (id) {
|
| 1450 |
+
let user = usersCache.get(id);
|
| 1451 |
+
|
| 1452 |
+
if (!user) {
|
| 1453 |
+
// Check batch buffer
|
| 1454 |
+
for (const item of batchBuffer) {
|
| 1455 |
+
if (item.user_id === id && item.action === 'signup') {
|
| 1456 |
+
user = {
|
| 1457 |
+
id: id,
|
| 1458 |
+
username: item.data.username || '',
|
| 1459 |
+
name: item.data.name || '',
|
| 1460 |
+
email: item.data.email || '',
|
| 1461 |
+
country: '',
|
| 1462 |
+
location: '',
|
| 1463 |
+
created_at: new Date().toISOString(),
|
| 1464 |
+
is_login: 0,
|
| 1465 |
+
bio: '',
|
| 1466 |
+
pic_url: '',
|
| 1467 |
+
external_links: '[]',
|
| 1468 |
+
date_of_birth: '',
|
| 1469 |
+
is_profile_public: 'true',
|
| 1470 |
+
fing_key: item.data.fing_key || '',
|
| 1471 |
+
total_times_profile_updated_today: 0,
|
| 1472 |
+
last_profile_updated: ''
|
| 1473 |
+
};
|
| 1474 |
+
break;
|
| 1475 |
+
}
|
| 1476 |
}
|
| 1477 |
+
}
|
| 1478 |
+
|
| 1479 |
+
if (!user) {
|
| 1480 |
+
user = await getUser(id);
|
| 1481 |
+
}
|
| 1482 |
+
|
| 1483 |
+
if (!user) {
|
| 1484 |
+
reply.status(404);
|
| 1485 |
+
return { detail: 'User not found' };
|
| 1486 |
+
}
|
| 1487 |
+
|
| 1488 |
+
return {
|
| 1489 |
+
worker_pid: process.pid,
|
| 1490 |
+
id: user.id,
|
| 1491 |
+
username: user.username,
|
| 1492 |
+
name: user.name,
|
| 1493 |
+
email: safeGet(user.email),
|
| 1494 |
+
country: safeGet(user.country),
|
| 1495 |
+
location: safeGet(user.location),
|
| 1496 |
+
created_at: safeGet(user.created_at),
|
| 1497 |
+
is_login: Boolean(safeGet(user.is_login, false)),
|
| 1498 |
+
bio: safeGet(user.bio),
|
| 1499 |
+
pic_url: safeGet(user.pic_url),
|
| 1500 |
+
external_links: safeGet(user.external_links, '[]'),
|
| 1501 |
+
date_of_birth: safeGet(user.date_of_birth),
|
| 1502 |
+
is_profile_public: safeGet(user.is_profile_public, 'true'),
|
| 1503 |
+
fing_key: safeGet(user.fing_key, ''),
|
| 1504 |
+
total_times_profile_updated_today: parseInt(safeGet(user.total_times_profile_updated_today, 0)),
|
| 1505 |
+
last_profile_updated: safeGet(user.last_profile_updated)
|
| 1506 |
+
};
|
| 1507 |
+
}
|
| 1508 |
+
|
| 1509 |
+
reply.status(400);
|
| 1510 |
+
return { detail: 'Missing id or username parameter' };
|
| 1511 |
+
});
|
| 1512 |
|
| 1513 |
fastify.get('/users/count', async (request, reply) => {
|
| 1514 |
+
reply.header('Content-Type', 'application/json');
|
| 1515 |
+
return toJsonl({
|
| 1516 |
+
count: getTotalUsers()
|
| 1517 |
+
});
|
| 1518 |
});
|
| 1519 |
|
| 1520 |
fastify.get('/users', async (request, reply) => {
|
| 1521 |
if (usersCache.size === 0) {
|
| 1522 |
+
reply.header('Content-Type', 'application/json');
|
| 1523 |
return toJsonl({ users: [], total: 0 });
|
| 1524 |
}
|
| 1525 |
|
|
|
|
| 1540 |
}
|
| 1541 |
});
|
| 1542 |
|
| 1543 |
+
reply.header('Content-Type', 'application/json');
|
| 1544 |
return stream;
|
| 1545 |
});
|
| 1546 |
|
|
|
|
| 1549 |
const emptySpaces = SPACE_NAMES.filter(s => !fullSpaces.includes(s));
|
| 1550 |
const sizeSpaces = await getSizeSpaces();
|
| 1551 |
|
| 1552 |
+
reply.header('Content-Type', 'application/json');
|
| 1553 |
return toJsonl({
|
| 1554 |
all_spaces: SPACE_NAMES,
|
| 1555 |
full_spaces: fullSpaces,
|
|
|
|
| 1597 |
return { detail: 'New password must be different' };
|
| 1598 |
}
|
| 1599 |
|
| 1600 |
+
addRequest(user.id, cleanUsername, 'forgot_password', {
|
| 1601 |
+
new_password
|
| 1602 |
+
});
|
| 1603 |
|
| 1604 |
+
reply.header('Content-Type', 'application/json');
|
| 1605 |
return toJsonl({
|
| 1606 |
success: true,
|
| 1607 |
message: 'Password reset processed',
|
|
|
|
| 1611 |
|
| 1612 |
return fastify;
|
| 1613 |
}
|
|
|
|
| 1614 |
// ============ STARTUP ============
|
| 1615 |
async function start() {
|
| 1616 |
try {
|
| 1617 |
console.log(`Main: Starting with 1 Fastify process + 1 DB Worker Thread (2 cores)`);
|
| 1618 |
|
|
|
|
| 1619 |
await initDBWorker();
|
| 1620 |
|
| 1621 |
if (redis) {
|
|
|
|
| 1624 |
console.log(`Main: Redis connected`);
|
| 1625 |
} catch (e) {
|
| 1626 |
console.warn(`Main: Redis connection failed:`, e.message);
|
| 1627 |
+
console.log(`Main: Continuing without Redis`);
|
| 1628 |
redis = null;
|
| 1629 |
}
|
| 1630 |
}
|
|
|
|
| 1633 |
await loadUsersToMemory();
|
| 1634 |
|
| 1635 |
await checkAndUpdateFullStatus();
|
|
|
|
| 1636 |
await setupFastify();
|
| 1637 |
|
| 1638 |
setInterval(async () => {
|
| 1639 |
+
if (redis && redis.status === 'ready') {
|
| 1640 |
+
await processFromRedis();
|
| 1641 |
+
}
|
| 1642 |
await checkAndUpdateFullStatus();
|
| 1643 |
}, 50);
|
| 1644 |
|
|
|
|
| 1652 |
console.log(`Main: ⚡ Processing: ${BATCH_SIZE} requests/batch`);
|
| 1653 |
console.log(`Main: 📈 Max RPS: ${MAX_RPS} req/sec`);
|
| 1654 |
console.log(`Main: 👥 Max Users: ${MAX_USERS}`);
|
| 1655 |
+
|
| 1656 |
} catch (err) {
|
| 1657 |
console.error(`Main: Error during startup:`, err);
|
| 1658 |
process.exit(1);
|
| 1659 |
}
|
| 1660 |
}
|
| 1661 |
|
|
|
|
| 1662 |
process.on('SIGTERM', async () => {
|
| 1663 |
console.log(`Main: Shutting down...`);
|
| 1664 |
await flushBatchToRedis();
|