blaze-aura69 commited on
Commit
724e7de
·
verified ·
1 Parent(s): fcb5166

Update index.js

Browse files
Files changed (1) hide show
  1. index.js +542 -278
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
- date_of_birth, total_times_profile_updated_today,
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
- @date_of_birth, @total_times_profile_updated_today,
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 = ["data3"];
246
  const BASE_SPACE_URL = "https://velost-db1-{space}.hf.space";
247
- const CURRENT_SPACE_NAME = "2";
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
- redis = new Redis({
320
- host: process.env.REDIS_HOST || '127.0.0.1',
321
- port: process.env.REDIS_PORT || 6379,
322
- maxRetriesPerRequest: 3,
323
- enableReadyCheck: false,
324
- lazyConnect: true,
325
- connectTimeout: 5000,
326
- retryStrategy(times) {
327
- if (times > 3) return null;
328
- return Math.min(times * 50, 2000);
329
- }
330
- });
331
- redis.on('error', (err) => {
332
- console.error(`Main: Redis error:`, err.message);
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 || cpuUsage >= 98 || totalUsers >= MAX_USERS ||
533
- bucketSize >= MAX_BUCKET_SIZE || ramUsage >= MAX_RAM_USAGE;
 
 
 
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.resize(800, 800, { fit: 'inside', withoutEnlargement: true })
567
- .webp({ quality }).toBuffer();
 
 
 
568
  if (outputBuffer.length / 1024 <= maxSizeKb) break;
569
  quality -= 10;
570
  }
571
 
572
  if (outputBuffer.length / 1024 > maxSizeKb) {
573
- outputBuffer = await image.resize(400, 400, { fit: 'inside', withoutEnlargement: true })
574
- .webp({ quality: 30 }).toBuffer();
 
 
575
  }
576
 
577
- return { buffer: outputBuffer, isWebp: true, sizeKb: outputBuffer.length / 1024, wasCompressed: true };
 
 
 
 
 
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 || getBucketSize() >= MAX_BUCKET_SIZE ||
649
- globalRateLimiter.getCurrentCount() >= MAX_RPS || getCurrentCPUPercentage() >= 98;
 
 
650
  }
651
 
652
  // ============ BATCH PROCESSING ============
653
- function scheduleBatchProcess() {
654
- if (batchTimer) return;
655
- batchTimer = setImmediate(async () => {
656
- batchTimer = null;
657
- await flushBatchToRedis();
658
- });
659
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
660
 
661
- async function flushBatchToRedis() {
662
- if (batchBuffer.length === 0 || processingLock) return;
 
663
 
664
- processingLock = true;
665
- const batch = batchBuffer.splice(0, BATCH_SIZE);
666
 
667
- try {
668
- if (redis) {
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
- if (batchBuffer.length > 0) scheduleBatchProcess();
 
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.filter(([err, data]) => !err && data).map(([err, data]) => JSON.parse(data));
704
- if (requests.length > 0) await processRequestsBatch(requests);
 
 
 
 
 
 
 
 
 
 
 
 
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
- switch (req.action) {
720
- case 'signup':
721
- operations.push({
722
- action: 'signup',
723
- userId: req.user_id,
724
- user: {
725
- id: req.user_id,
726
- username: req.data.username || '',
727
- password_hash: hashPassword(req.data.password || ''),
728
- name: req.data.name || '',
729
- email: req.data.email || '',
730
- country: '',
731
- location: '',
732
- created_at: new Date().toISOString(),
733
- is_login: 0,
734
- bio: '',
735
- pic_url: '',
736
- external_links: '[]',
737
- date_of_birth: '',
738
- total_times_profile_updated_today: 0,
739
- last_profile_updated: '',
740
- is_profile_public: 'true',
741
- fing_key: req.data.fing_key || generateFingKey()
742
- }
743
- });
744
- // Update cache immediately
745
- usersCache.set(req.user_id, operations[operations.length - 1].user);
746
- break;
747
-
748
- case 'login':
749
- operations.push({ action: 'login', userId: req.user_id });
750
- const loginUser = usersCache.get(req.user_id);
751
- if (loginUser) loginUser.is_login = 1;
752
- break;
753
-
754
- case 'logout':
755
- operations.push({ action: 'logout', userId: req.user_id });
756
- const logoutUser = usersCache.get(req.user_id);
757
- if (logoutUser) logoutUser.is_login = 0;
758
- break;
759
-
760
- case 'update_profile':
761
- const profileUser = usersCache.get(req.user_id);
762
- if (profileUser) {
763
- const fields = ['name', 'email', 'country', 'location', 'bio', 'external_links', 'date_of_birth', 'is_profile_public'];
764
- for (const field of fields) {
765
- if (field in req.data && req.data[field] !== null && req.data[field] !== undefined) {
766
- profileUser[field] = typeof req.data[field] === 'string' ? req.data[field].trim() : String(req.data[field]).trim();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
767
  }
 
 
 
768
  }
769
- profileUser.total_times_profile_updated_today = (profileUser.total_times_profile_updated_today || 0) + 1;
770
- profileUser.last_profile_updated = new Date().toISOString();
 
 
 
 
 
 
 
 
 
 
 
 
 
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
- const photoUser = usersCache.get(req.user_id);
800
- if (photoUser) photoUser.pic_url = `/photos/${filename}`;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
801
 
802
- operations.push({ action: 'updatePhoto', userId: req.user_id, picUrl: `/photos/${filename}` });
803
- }
804
- break;
805
-
806
- case 'forgot_password':
807
- const newHash = hashPassword(req.data.new_password || '');
808
- const passUser = usersCache.get(req.user_id);
809
- if (passUser) passUser.password_hash = newHash;
810
-
811
- operations.push({ action: 'updatePassword', userId: req.user_id, passwordHash: newHash });
812
- break;
 
 
 
 
 
 
 
813
  }
814
  }
815
 
816
  if (operations.length > 0) {
817
- await dbRequest('batchOperation', { operations });
 
 
 
 
 
 
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: 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 || getBucketSize() >= MAX_BUCKET_SIZE || getMemoryUsage() >= MAX_RAM_USAGE) {
 
863
  await addSpaceToFull(CURRENT_SPACE_NAME);
864
  reply.status(503);
865
- reply.header('Content-Type', 'text/plain');
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', 'text/plain');
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', 'text/plain');
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', 'text/plain');
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', 'text/plain');
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', 'text/plain');
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
- if (getTotalUsers() >= MAX_USERS) {
996
- reply.status(507);
997
- return { detail: `Maximum users (${MAX_USERS}) reached.` };
998
- }
999
-
1000
- const { username, password, name, email, fing_key } = request.body || {};
1001
-
1002
- if (!username || !password || !name || !email) {
1003
- reply.status(400);
1004
- return { detail: 'Missing required fields' };
1005
- }
1006
-
1007
- const cleanUsername = username.trim().toLowerCase();
1008
- const cleanEmail = email.trim().toLowerCase();
1009
-
1010
- if (cleanUsername.length < 3) {
1011
- reply.status(400);
1012
- return { detail: 'Username too short' };
1013
- }
1014
-
1015
- if (password.length < 6) {
1016
- reply.status(400);
1017
- return { detail: 'Password too short' };
1018
- }
1019
-
1020
- const existingUser = await getUserByUsername(cleanUsername);
1021
- if (existingUser) {
1022
- reply.status(409);
1023
- return { detail: 'Username already exists' };
1024
- }
1025
-
1026
- for (const user of usersCache.values()) {
1027
- if (user.email === cleanEmail) {
1028
- reply.status(409);
1029
- return { detail: 'Email already registered' };
1030
- }
1031
- }
1032
-
1033
- const userId = generateId();
1034
- const requestId = addRequest(userId, cleanUsername, 'signup', {
1035
- username: cleanUsername,
1036
- password: password,
1037
- name: name.trim(),
1038
- email: cleanEmail,
1039
- fing_key: fing_key ? fing_key.trim() : ''
1040
- });
1041
-
1042
- reply.header('Content-Type', 'text/plain');
1043
- return toJsonl({
1044
- success: true,
1045
- message: 'Account created successfully',
1046
- worker_pid: process.pid,
1047
- user_id: userId,
1048
- request_id: requestId,
1049
- timestamp: new Date().toISOString()
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', 'text/plain');
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', 'text/plain');
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', 'text/plain');
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 : (request.query ? request.query.id : null);
 
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
- reply.header('Content-Type', 'text/plain');
 
 
 
 
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
- const { id } = request.query || {};
1219
-
1220
- if (!id) {
1221
- reply.status(400);
1222
- return { detail: 'Missing user ID' };
1223
- }
1224
-
1225
- const user = await getUser(id);
1226
- if (!user) {
1227
- reply.status(404);
1228
- return { detail: 'User not found' };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1229
  }
1230
-
1231
- reply.header('Content-Type', 'text/plain');
1232
- return toJsonl({
1233
- worker_pid: process.pid,
1234
- id: user.id,
1235
- username: user.username,
1236
- name: user.name,
1237
- email: safeGet(user.email),
1238
- country: safeGet(user.country),
1239
- location: safeGet(user.location),
1240
- created_at: safeGet(user.created_at),
1241
- is_login: Boolean(safeGet(user.is_login, false)),
1242
- bio: safeGet(user.bio),
1243
- pic_url: safeGet(user.pic_url),
1244
- external_links: safeGet(user.external_links, '[]'),
1245
- date_of_birth: safeGet(user.date_of_birth),
1246
- is_profile_public: safeGet(user.is_profile_public, 'true'),
1247
- fing_key: safeGet(user.fing_key, ''),
1248
- total_times_profile_updated_today: parseInt(safeGet(user.total_times_profile_updated_today, 0)),
1249
- last_profile_updated: safeGet(user.last_profile_updated)
1250
- });
1251
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
1252
 
1253
  fastify.get('/users/count', async (request, reply) => {
1254
- reply.header('Content-Type', 'text/plain');
1255
- return toJsonl({ count: getTotalUsers() });
 
 
1256
  });
1257
 
1258
  fastify.get('/users', async (request, reply) => {
1259
  if (usersCache.size === 0) {
1260
- reply.header('Content-Type', 'text/plain');
1261
  return toJsonl({ users: [], total: 0 });
1262
  }
1263
 
@@ -1278,7 +1540,7 @@ if (!isMainThread) {
1278
  }
1279
  });
1280
 
1281
- reply.header('Content-Type', 'text/plain');
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', 'text/plain');
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', { new_password });
 
 
1339
 
1340
- reply.header('Content-Type', 'text/plain');
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) await processFromRedis();
 
 
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();