blaze-aura69 commited on
Commit
4291c3d
·
verified ·
1 Parent(s): c98a7ee

Update index.js

Browse files
Files changed (1) hide show
  1. index.js +90 -78
index.js CHANGED
@@ -1,4 +1,5 @@
1
  'use strict';
 
2
  const { Worker: ThreadWorker, isMainThread, parentPort, workerData } = require('worker_threads');
3
  const os = require('os');
4
 
@@ -7,10 +8,11 @@ if (!isMainThread) {
7
  const Database = require('better-sqlite3');
8
  const path = require('path');
9
  const fs = require('fs');
 
10
  const DATA_DIR = workerData.dataDir || "/data";
11
  const dbPath = path.join(DATA_DIR, 'users.db');
12
-
13
  const db = new Database(dbPath);
 
14
  db.pragma('journal_mode = WAL');
15
  db.pragma('synchronous = NORMAL');
16
  db.pragma('cache_size = -2000000');
@@ -50,18 +52,20 @@ if (!isMainThread) {
50
  getUserByUsername: db.prepare('SELECT * FROM users WHERE username = ?'),
51
  insertUser: db.prepare(`
52
  INSERT OR REPLACE INTO users (
53
- id, username, password_hash, name, email, country, location, created_at,
54
- is_login, bio, pic_url, external_links, date_of_birth,
55
- total_times_profile_updated_today, last_profile_updated, is_profile_public, fing_key
 
56
  ) VALUES (
57
- @id, @username, @password_hash, @name, @email, @country, @location, @created_at,
58
- @is_login, @bio, @pic_url, @external_links, @date_of_birth,
59
- @total_times_profile_updated_today, @last_profile_updated, @is_profile_public, @fing_key
 
60
  )
61
  `),
62
  updateLogin: db.prepare('UPDATE users SET is_login = ? WHERE id = ?'),
63
  updateProfile: db.prepare(`
64
- UPDATE users SET
65
  name = COALESCE(NULLIF(@name, ''), name),
66
  email = COALESCE(NULLIF(@email, ''), email),
67
  country = COALESCE(NULLIF(@country, ''), country),
@@ -80,8 +84,10 @@ if (!isMainThread) {
80
 
81
  parentPort.on('message', async (message) => {
82
  const { id, action, data } = message;
 
83
  try {
84
  let result;
 
85
  switch (action) {
86
  case 'getAllUsers':
87
  result = stmts.getAllUsers.all();
@@ -133,6 +139,7 @@ if (!isMainThread) {
133
  default:
134
  throw new Error(`Unknown action: ${action}`);
135
  }
 
136
  parentPort.postMessage({ id, success: true, result });
137
  } catch (error) {
138
  parentPort.postMessage({ id, success: false, error: error.message });
@@ -164,6 +171,7 @@ if (!isMainThread) {
164
  }
165
  }
166
  });
 
167
  transaction();
168
  return { processed: operations.length };
169
  }
@@ -172,11 +180,11 @@ if (!isMainThread) {
172
  } else {
173
  // ============ MAIN THREAD - OPTIMIZED FASTIFY SERVER ============
174
  const fastify = require('fastify')({
175
- logger: { level: 'warn' }, // Reduce logging overhead
176
  bodyLimit: 10485760,
177
- keepAliveTimeout: 61000, // Increased keepalive
178
  connectionTimeout: 61000,
179
- maxRequestsPerSocket: 0, // Disable to prevent premature closing
180
  requestTimeout: 30000,
181
  return503OnClosing: false
182
  });
@@ -218,7 +226,7 @@ if (!isMainThread) {
218
  const BATCH_SIZE = 15000;
219
  const HASH = process.env.HASH || 'v3l0st-d3f4ult-h4sh-k3y-2024!@#$%^&*()';
220
 
221
- // ============ CACHED METRICS (update periodically, not per request) ============
222
  const metrics = {
223
  bucketSize: 0,
224
  totalUsers: 0,
@@ -299,10 +307,10 @@ if (!isMainThread) {
299
  }
300
  }
301
 
302
- // ============ IN-MEMORY STORAGE - OPTIMIZED ============
303
  let usersCache = new Map();
304
- let usernameIndex = new Map(); // Fast username lookup
305
- let emailIndex = new Map(); // Fast email lookup
306
  let batchBuffer = [];
307
  let batchTimer = null;
308
  let processingLock = false;
@@ -342,33 +350,30 @@ if (!isMainThread) {
342
  // ============ OPTIMIZED UTILITY FUNCTIONS ============
343
  function updateMetrics() {
344
  const now = Date.now();
345
- if (now - metrics.lastUpdate < 1000) return; // Update max once per second
346
-
347
  metrics.ramUsage = process.memoryUsage().rss;
348
  metrics.totalUsers = usersCache.size;
349
  metrics.lastUpdate = now;
350
-
351
- // Update bucket size every 10 seconds
352
  if (now - (metrics._lastBucketUpdate || 0) > 10000) {
353
  metrics.bucketSize = getBucketSizeCached();
354
  metrics._lastBucketUpdate = now;
355
  }
356
-
357
- // Update CPU every 5 seconds
358
  if (now - (metrics._lastCpuUpdate || 0) > 5000) {
359
  metrics.cpuUsage = getCurrentCPUPercentage();
360
  metrics._lastCpuUpdate = now;
361
  }
362
  }
363
 
364
- // Cache bucket size
365
  let cachedBucketSize = 0;
366
  let lastBucketCheck = 0;
367
-
368
  function getBucketSizeCached() {
369
  const now = Date.now();
370
- if (now - lastBucketCheck < 5000) return cachedBucketSize; // Cache for 5 seconds
371
-
372
  let totalSize = 0;
373
  try {
374
  const files = fs.readdirSync(PHOTOS_DIR);
@@ -377,12 +382,11 @@ if (!isMainThread) {
377
  totalSize += fs.statSync(path.join(PHOTOS_DIR, file)).size;
378
  } catch (e) {}
379
  }
380
- // Add DB size
381
  try {
382
  totalSize += fs.statSync(path.join(DATA_DIR, 'users.db')).size;
383
  } catch (e) {}
384
  } catch (e) {}
385
-
386
  cachedBucketSize = totalSize;
387
  lastBucketCheck = now;
388
  return totalSize;
@@ -394,21 +398,20 @@ if (!isMainThread) {
394
 
395
  let lastCPUUsage = process.cpuUsage();
396
  let lastCPUCheck = Date.now();
397
-
398
  function getCurrentCPUPercentage() {
399
  const currentCPUUsage = process.cpuUsage(lastCPUUsage);
400
  const currentTime = Date.now();
401
  const elapsedMS = currentTime - lastCPUCheck;
402
  lastCPUUsage = process.cpuUsage();
403
  lastCPUCheck = currentTime;
 
404
  if (elapsedMS === 0) return 0;
405
  return Math.min(100, ((currentCPUUsage.user + currentCPUUsage.system) / 1000) / elapsedMS * 100);
406
  }
407
 
408
  function safeGet(value, defaultValue = "") {
409
- return (value === null || value === undefined || (typeof value === 'number' && isNaN(value)))
410
- ? defaultValue
411
- : value;
412
  }
413
 
414
  function generateId() {
@@ -500,12 +503,13 @@ if (!isMainThread) {
500
  usersCache.clear();
501
  usernameIndex.clear();
502
  emailIndex.clear();
503
-
504
  for (const user of users) {
505
  usersCache.set(user.id, user);
506
  usernameIndex.set(user.username.toLowerCase(), user);
507
  emailIndex.set(user.email.toLowerCase(), user);
508
  }
 
509
  console.log(`Main: Loaded ${users.length} users into memory`);
510
  metrics.totalUsers = users.length;
511
  } catch (e) {
@@ -513,7 +517,6 @@ if (!isMainThread) {
513
  }
514
  }
515
 
516
- // Fast user lookup using indexes
517
  async function getUser(userId) {
518
  return usersCache.get(userId) || null;
519
  }
@@ -536,9 +539,9 @@ if (!isMainThread) {
536
 
537
  function isSpaceFull() {
538
  updateMetrics();
539
- return getTotalUsers() >= MAX_USERS ||
540
- getBucketSize() >= MAX_BUCKET_SIZE ||
541
- globalRateLimiter.getCurrentCount() >= MAX_RPS ||
542
  metrics.cpuUsage >= 98;
543
  }
544
 
@@ -548,19 +551,20 @@ if (!isMainThread) {
548
  batchTimer = setTimeout(async () => {
549
  batchTimer = null;
550
  await flushBatchToRedis();
551
- }, 100); // Reduced from 1000ms to 100ms for faster processing
552
  }
553
 
554
  async function flushBatchToRedis() {
555
  if (batchBuffer.length === 0 || processingLock) return;
556
  processingLock = true;
 
557
  const batch = batchBuffer.splice(0, BATCH_SIZE);
558
  const batchCount = batch.length;
559
-
560
  try {
561
  await processRequestsBatch(batch);
562
  console.log(`Main: Batch of ${batchCount} processed`);
563
-
564
  if (batchBuffer.length > 0) {
565
  processingLock = false;
566
  scheduleBatchProcess();
@@ -576,13 +580,15 @@ if (!isMainThread) {
576
 
577
  async function processRequestsBatch(requests) {
578
  if (!requests || requests.length === 0) return;
579
-
580
  const operations = [];
 
581
  for (const req of requests) {
582
  try {
583
  if (!req || !req.user_id) continue;
584
-
585
  const action = req.action || 'unknown';
 
586
  switch (action) {
587
  case 'signup': {
588
  const user = {
@@ -604,28 +610,32 @@ if (!isMainThread) {
604
  is_profile_public: 'true',
605
  fing_key: (req.data && req.data.fing_key) || generateFingKey()
606
  };
 
607
  operations.push({ action: 'signup', userId: req.user_id, user });
608
- // Update cache immediately
609
  usersCache.set(req.user_id, user);
610
  usernameIndex.set(user.username.toLowerCase(), user);
611
  emailIndex.set(user.email.toLowerCase(), user);
612
  break;
613
  }
 
614
  case 'login': {
615
  operations.push({ action: 'login', userId: req.user_id });
616
  const loginUser = usersCache.get(req.user_id);
617
  if (loginUser) loginUser.is_login = 1;
618
  break;
619
  }
 
620
  case 'logout': {
621
  operations.push({ action: 'logout', userId: req.user_id });
622
  const logoutUser = usersCache.get(req.user_id);
623
  if (logoutUser) logoutUser.is_login = 0;
624
  break;
625
  }
 
626
  case 'update_profile': {
627
  const profileUser = usersCache.get(req.user_id);
628
  const updateData = req.data || {};
 
629
  if (profileUser) {
630
  const fields = ['name', 'email', 'country', 'location', 'bio', 'external_links', 'date_of_birth', 'is_profile_public'];
631
  for (const field of fields) {
@@ -636,6 +646,7 @@ if (!isMainThread) {
636
  profileUser.total_times_profile_updated_today = (profileUser.total_times_profile_updated_today || 0) + 1;
637
  profileUser.last_profile_updated = new Date().toISOString();
638
  }
 
639
  operations.push({
640
  action: 'updateProfile',
641
  userId: req.user_id,
@@ -655,6 +666,7 @@ if (!isMainThread) {
655
  });
656
  break;
657
  }
 
658
  case 'upload_photo': {
659
  if (req.pic_buffer) {
660
  try {
@@ -662,18 +674,22 @@ if (!isMainThread) {
662
  const filename = `${req.user_id}_${Math.floor(Date.now() / 1000)}.webp`;
663
  const filePath = path.join(PHOTOS_DIR, filename);
664
  await fsp.writeFile(filePath, compressed.buffer);
 
665
  const photoUser = usersCache.get(req.user_id);
666
  if (photoUser) photoUser.pic_url = `/photos/${filename}`;
 
667
  operations.push({ action: 'updatePhoto', userId: req.user_id, picUrl: `/photos/${filename}` });
668
  } catch (photoError) {}
669
  }
670
  break;
671
  }
 
672
  case 'forgot_password': {
673
  const newPassword = (req.data && req.data.new_password) || 'default123';
674
  const newHash = hashPassword(newPassword);
675
  const passUser = usersCache.get(req.user_id);
676
  if (passUser) passUser.password_hash = newHash;
 
677
  operations.push({ action: 'updatePassword', userId: req.user_id, passwordHash: newHash });
678
  break;
679
  }
@@ -694,7 +710,7 @@ if (!isMainThread) {
694
  function addRequest(userId, username, action, data, picBuffer = null) {
695
  if (!userId) userId = generateId();
696
  if (!action) action = 'unknown';
697
-
698
  const request = {
699
  user_id: userId,
700
  username: username || 'unknown_user',
@@ -703,7 +719,7 @@ if (!isMainThread) {
703
  pic_buffer: picBuffer ? picBuffer.toString('base64') : null,
704
  timestamp: Date.now()
705
  };
706
-
707
  batchBuffer.push(request);
708
  scheduleBatchProcess();
709
  return userId;
@@ -712,33 +728,36 @@ if (!isMainThread) {
712
  // ============ IMAGE COMPRESSION ============
713
  async function compressToWebp(fileData, maxSizeKb = 20) {
714
  if (!sharp) return { buffer: fileData, isWebp: false, sizeKb: fileData.length / 1024 };
 
715
  try {
716
  let image = sharp(fileData);
717
  const metadata = await image.metadata();
718
  const currentSizeKb = fileData.length / 1024;
719
-
720
  if (metadata.format === 'webp' && currentSizeKb <= maxSizeKb) {
721
  return { buffer: fileData, isWebp: true, sizeKb: currentSizeKb, wasCompressed: false };
722
  }
723
-
724
  let quality = 80;
725
  let outputBuffer;
 
726
  while (quality >= 10) {
727
  outputBuffer = await image
728
  .resize(800, 800, { fit: 'inside', withoutEnlargement: true })
729
  .webp({ quality })
730
  .toBuffer();
 
731
  if (outputBuffer.length / 1024 <= maxSizeKb) break;
732
  quality -= 10;
733
  }
734
-
735
  if (outputBuffer.length / 1024 > maxSizeKb) {
736
  outputBuffer = await image
737
  .resize(400, 400, { fit: 'inside', withoutEnlargement: true })
738
  .webp({ quality: 30 })
739
  .toBuffer();
740
  }
741
-
742
  return {
743
  buffer: outputBuffer,
744
  isWebp: true,
@@ -770,17 +789,14 @@ if (!isMainThread) {
770
  maxAge: 86400000
771
  });
772
 
773
- // OPTIMIZED: Lightweight onRequest hook
774
  fastify.addHook('onRequest', async (request, reply) => {
775
- // Quick rate limit check
776
  if (!globalRateLimiter.isAllowed()) {
777
  reply.status(503);
778
  reply.header('Content-Type', 'application/json');
779
  reply.send({ error: 'rate_limit', message: 'Rate limit reached', retry_after: 1 });
780
  return;
781
  }
782
-
783
- // Quick capacity check (using cached values)
784
  updateMetrics();
785
  if (metrics.totalUsers >= MAX_USERS || metrics.ramUsage >= MAX_RAM_USAGE) {
786
  reply.status(503);
@@ -790,13 +806,13 @@ if (!isMainThread) {
790
  }
791
  });
792
 
793
- // ROUTES - All optimized for speed
794
  fastify.get('/', async (request, reply) => {
795
  updateMetrics();
796
  const spaceFull = isSpaceFull();
797
  const fullSpaces = await getFullSpaces();
798
  const emptySpaces = SPACE_NAMES.filter(s => !fullSpaces.includes(s));
799
-
800
  reply.header('Content-Type', 'application/json');
801
  return {
802
  message: 'Velost Auth API - Optimized',
@@ -845,7 +861,7 @@ if (!isMainThread) {
845
  const spaceFull = isSpaceFull();
846
  const fullSpaces = await getFullSpaces();
847
  const emptySpaces = SPACE_NAMES.filter(s => !fullSpaces.includes(s));
848
-
849
  reply.header('Content-Type', 'application/json');
850
  return {
851
  worker_pid: process.pid,
@@ -895,7 +911,7 @@ if (!isMainThread) {
895
  }
896
 
897
  const { username, password, name, email, fing_key } = request.body || {};
898
-
899
  if (!username || !password || !name || !email) {
900
  reply.status(400);
901
  return { detail: 'Missing required fields' };
@@ -914,7 +930,6 @@ if (!isMainThread) {
914
  return { detail: 'Password too short' };
915
  }
916
 
917
- // Fast lookup using indexes
918
  if (usernameIndex.has(cleanUsername)) {
919
  reply.status(409);
920
  return { detail: 'Username already exists' };
@@ -946,15 +961,19 @@ if (!isMainThread) {
946
  fing_key: fing_key ? fing_key.trim() : generateFingKey()
947
  };
948
 
949
- // Update cache immediately
950
  usersCache.set(userId, newUser);
951
  usernameIndex.set(cleanUsername, newUser);
952
  emailIndex.set(cleanEmail, newUser);
953
  metrics.totalUsers = usersCache.size;
954
 
955
- // Async DB write (non-blocking)
956
- dbRequest('insertUser', { user: newUser }).catch(err => {
957
- console.error('DB insert error:', err.message);
 
 
 
 
 
958
  });
959
 
960
  return {
@@ -971,7 +990,7 @@ if (!isMainThread) {
971
 
972
  fastify.post('/login', async (request, reply) => {
973
  const { username, password } = request.body || {};
974
-
975
  if (!username || !password) {
976
  reply.status(400);
977
  return { detail: 'Missing username or password' };
@@ -990,7 +1009,6 @@ if (!isMainThread) {
990
  return { detail: 'Invalid credentials' };
991
  }
992
 
993
- // Async update (non-blocking)
994
  addRequest(user.id, cleanUsername, 'login', {});
995
 
996
  return {
@@ -1018,7 +1036,7 @@ if (!isMainThread) {
1018
 
1019
  fastify.post('/logout', async (request, reply) => {
1020
  const { id } = request.body || {};
1021
-
1022
  if (!id) {
1023
  reply.status(400);
1024
  return { detail: 'Missing user ID' };
@@ -1041,7 +1059,7 @@ if (!isMainThread) {
1041
 
1042
  fastify.put('/updateprofiledetails', async (request, reply) => {
1043
  const { id, ...data } = request.body || {};
1044
-
1045
  if (!id) {
1046
  reply.status(400);
1047
  return { detail: 'Missing user ID' };
@@ -1090,7 +1108,7 @@ if (!isMainThread) {
1090
 
1091
  const fileBuffer = await data.toBuffer();
1092
  const id = (data.fields && data.fields.id) ? data.fields.id.value : (request.query ? request.query.id : null);
1093
-
1094
  if (!id) {
1095
  reply.status(400);
1096
  return { detail: 'Missing user ID' };
@@ -1121,8 +1139,8 @@ if (!isMainThread) {
1121
 
1122
  fastify.get('/getuser', async (request, reply) => {
1123
  const { id, username } = request.query || {};
1124
-
1125
  let user;
 
1126
  if (username) {
1127
  user = usernameIndex.get(username.toLowerCase());
1128
  } else if (id) {
@@ -1184,7 +1202,7 @@ if (!isMainThread) {
1184
 
1185
  fastify.post('/forgotpassword', async (request, reply) => {
1186
  const { username, email, fing_key, new_password } = request.body || {};
1187
-
1188
  if (!username || !email || !fing_key || !new_password) {
1189
  reply.status(400);
1190
  return { detail: 'Missing required fields' };
@@ -1193,9 +1211,8 @@ if (!isMainThread) {
1193
  const cleanUsername = username.trim().toLowerCase();
1194
  const cleanEmail = email.trim().toLowerCase();
1195
  const cleanFingKey = fing_key.trim();
1196
-
1197
  const user = usernameIndex.get(cleanUsername);
1198
-
1199
  if (!user) {
1200
  reply.status(404);
1201
  return { detail: 'No account found' };
@@ -1237,9 +1254,8 @@ if (!isMainThread) {
1237
  async function start() {
1238
  try {
1239
  console.log(`Main: Starting optimized server (2 cores)`);
1240
-
1241
  await initDBWorker();
1242
-
1243
  if (redis) {
1244
  try {
1245
  await redis.connect();
@@ -1252,24 +1268,21 @@ if (!isMainThread) {
1252
 
1253
  console.log(`Main: Loading users into memory...`);
1254
  await loadUsersToMemory();
1255
-
1256
  await setupFastify();
1257
 
1258
- // Periodic metrics update (every 1 second)
1259
  setInterval(() => {
1260
  updateMetrics();
1261
  }, 1000);
1262
 
1263
- // Periodic batch processing
1264
  setInterval(() => {
1265
  if (batchBuffer.length > 0) {
1266
  flushBatchToRedis();
1267
  }
1268
- }, 100); // Check every 100ms
1269
 
1270
  const port = process.env.PORT || 7860;
1271
  await fastify.listen({ port, host: '0.0.0.0' });
1272
-
1273
  console.log(`Main: 🚀 Server running on port ${port}`);
1274
  console.log(`Main: 📊 Users loaded: ${getTotalUsers()}`);
1275
  console.log(`Main: 💾 Storage: SQLite at /data/users.db (via Worker Thread)`);
@@ -1283,7 +1296,6 @@ if (!isMainThread) {
1283
  }
1284
  }
1285
 
1286
- // Graceful shutdown
1287
  process.on('SIGTERM', async () => {
1288
  console.log(`Main: Shutting down...`);
1289
  await flushBatchToRedis();
 
1
  'use strict';
2
+
3
  const { Worker: ThreadWorker, isMainThread, parentPort, workerData } = require('worker_threads');
4
  const os = require('os');
5
 
 
8
  const Database = require('better-sqlite3');
9
  const path = require('path');
10
  const fs = require('fs');
11
+
12
  const DATA_DIR = workerData.dataDir || "/data";
13
  const dbPath = path.join(DATA_DIR, 'users.db');
 
14
  const db = new Database(dbPath);
15
+
16
  db.pragma('journal_mode = WAL');
17
  db.pragma('synchronous = NORMAL');
18
  db.pragma('cache_size = -2000000');
 
52
  getUserByUsername: db.prepare('SELECT * FROM users WHERE username = ?'),
53
  insertUser: db.prepare(`
54
  INSERT OR REPLACE INTO users (
55
+ id, username, password_hash, name, email, country, location,
56
+ created_at, is_login, bio, pic_url, external_links,
57
+ date_of_birth, total_times_profile_updated_today,
58
+ last_profile_updated, is_profile_public, fing_key
59
  ) VALUES (
60
+ @id, @username, @password_hash, @name, @email, @country, @location,
61
+ @created_at, @is_login, @bio, @pic_url, @external_links,
62
+ @date_of_birth, @total_times_profile_updated_today,
63
+ @last_profile_updated, @is_profile_public, @fing_key
64
  )
65
  `),
66
  updateLogin: db.prepare('UPDATE users SET is_login = ? WHERE id = ?'),
67
  updateProfile: db.prepare(`
68
+ UPDATE users SET
69
  name = COALESCE(NULLIF(@name, ''), name),
70
  email = COALESCE(NULLIF(@email, ''), email),
71
  country = COALESCE(NULLIF(@country, ''), country),
 
84
 
85
  parentPort.on('message', async (message) => {
86
  const { id, action, data } = message;
87
+
88
  try {
89
  let result;
90
+
91
  switch (action) {
92
  case 'getAllUsers':
93
  result = stmts.getAllUsers.all();
 
139
  default:
140
  throw new Error(`Unknown action: ${action}`);
141
  }
142
+
143
  parentPort.postMessage({ id, success: true, result });
144
  } catch (error) {
145
  parentPort.postMessage({ id, success: false, error: error.message });
 
171
  }
172
  }
173
  });
174
+
175
  transaction();
176
  return { processed: operations.length };
177
  }
 
180
  } else {
181
  // ============ MAIN THREAD - OPTIMIZED FASTIFY SERVER ============
182
  const fastify = require('fastify')({
183
+ logger: { level: 'warn' },
184
  bodyLimit: 10485760,
185
+ keepAliveTimeout: 61000,
186
  connectionTimeout: 61000,
187
+ maxRequestsPerSocket: 0,
188
  requestTimeout: 30000,
189
  return503OnClosing: false
190
  });
 
226
  const BATCH_SIZE = 15000;
227
  const HASH = process.env.HASH || 'v3l0st-d3f4ult-h4sh-k3y-2024!@#$%^&*()';
228
 
229
+ // ============ CACHED METRICS ============
230
  const metrics = {
231
  bucketSize: 0,
232
  totalUsers: 0,
 
307
  }
308
  }
309
 
310
+ // ============ IN-MEMORY STORAGE ============
311
  let usersCache = new Map();
312
+ let usernameIndex = new Map();
313
+ let emailIndex = new Map();
314
  let batchBuffer = [];
315
  let batchTimer = null;
316
  let processingLock = false;
 
350
  // ============ OPTIMIZED UTILITY FUNCTIONS ============
351
  function updateMetrics() {
352
  const now = Date.now();
353
+ if (now - metrics.lastUpdate < 1000) return;
354
+
355
  metrics.ramUsage = process.memoryUsage().rss;
356
  metrics.totalUsers = usersCache.size;
357
  metrics.lastUpdate = now;
358
+
 
359
  if (now - (metrics._lastBucketUpdate || 0) > 10000) {
360
  metrics.bucketSize = getBucketSizeCached();
361
  metrics._lastBucketUpdate = now;
362
  }
363
+
 
364
  if (now - (metrics._lastCpuUpdate || 0) > 5000) {
365
  metrics.cpuUsage = getCurrentCPUPercentage();
366
  metrics._lastCpuUpdate = now;
367
  }
368
  }
369
 
 
370
  let cachedBucketSize = 0;
371
  let lastBucketCheck = 0;
372
+
373
  function getBucketSizeCached() {
374
  const now = Date.now();
375
+ if (now - lastBucketCheck < 5000) return cachedBucketSize;
376
+
377
  let totalSize = 0;
378
  try {
379
  const files = fs.readdirSync(PHOTOS_DIR);
 
382
  totalSize += fs.statSync(path.join(PHOTOS_DIR, file)).size;
383
  } catch (e) {}
384
  }
 
385
  try {
386
  totalSize += fs.statSync(path.join(DATA_DIR, 'users.db')).size;
387
  } catch (e) {}
388
  } catch (e) {}
389
+
390
  cachedBucketSize = totalSize;
391
  lastBucketCheck = now;
392
  return totalSize;
 
398
 
399
  let lastCPUUsage = process.cpuUsage();
400
  let lastCPUCheck = Date.now();
401
+
402
  function getCurrentCPUPercentage() {
403
  const currentCPUUsage = process.cpuUsage(lastCPUUsage);
404
  const currentTime = Date.now();
405
  const elapsedMS = currentTime - lastCPUCheck;
406
  lastCPUUsage = process.cpuUsage();
407
  lastCPUCheck = currentTime;
408
+
409
  if (elapsedMS === 0) return 0;
410
  return Math.min(100, ((currentCPUUsage.user + currentCPUUsage.system) / 1000) / elapsedMS * 100);
411
  }
412
 
413
  function safeGet(value, defaultValue = "") {
414
+ return (value === null || value === undefined || (typeof value === 'number' && isNaN(value))) ? defaultValue : value;
 
 
415
  }
416
 
417
  function generateId() {
 
503
  usersCache.clear();
504
  usernameIndex.clear();
505
  emailIndex.clear();
506
+
507
  for (const user of users) {
508
  usersCache.set(user.id, user);
509
  usernameIndex.set(user.username.toLowerCase(), user);
510
  emailIndex.set(user.email.toLowerCase(), user);
511
  }
512
+
513
  console.log(`Main: Loaded ${users.length} users into memory`);
514
  metrics.totalUsers = users.length;
515
  } catch (e) {
 
517
  }
518
  }
519
 
 
520
  async function getUser(userId) {
521
  return usersCache.get(userId) || null;
522
  }
 
539
 
540
  function isSpaceFull() {
541
  updateMetrics();
542
+ return getTotalUsers() >= MAX_USERS ||
543
+ getBucketSize() >= MAX_BUCKET_SIZE ||
544
+ globalRateLimiter.getCurrentCount() >= MAX_RPS ||
545
  metrics.cpuUsage >= 98;
546
  }
547
 
 
551
  batchTimer = setTimeout(async () => {
552
  batchTimer = null;
553
  await flushBatchToRedis();
554
+ }, 100);
555
  }
556
 
557
  async function flushBatchToRedis() {
558
  if (batchBuffer.length === 0 || processingLock) return;
559
  processingLock = true;
560
+
561
  const batch = batchBuffer.splice(0, BATCH_SIZE);
562
  const batchCount = batch.length;
563
+
564
  try {
565
  await processRequestsBatch(batch);
566
  console.log(`Main: Batch of ${batchCount} processed`);
567
+
568
  if (batchBuffer.length > 0) {
569
  processingLock = false;
570
  scheduleBatchProcess();
 
580
 
581
  async function processRequestsBatch(requests) {
582
  if (!requests || requests.length === 0) return;
583
+
584
  const operations = [];
585
+
586
  for (const req of requests) {
587
  try {
588
  if (!req || !req.user_id) continue;
589
+
590
  const action = req.action || 'unknown';
591
+
592
  switch (action) {
593
  case 'signup': {
594
  const user = {
 
610
  is_profile_public: 'true',
611
  fing_key: (req.data && req.data.fing_key) || generateFingKey()
612
  };
613
+
614
  operations.push({ action: 'signup', userId: req.user_id, user });
 
615
  usersCache.set(req.user_id, user);
616
  usernameIndex.set(user.username.toLowerCase(), user);
617
  emailIndex.set(user.email.toLowerCase(), user);
618
  break;
619
  }
620
+
621
  case 'login': {
622
  operations.push({ action: 'login', userId: req.user_id });
623
  const loginUser = usersCache.get(req.user_id);
624
  if (loginUser) loginUser.is_login = 1;
625
  break;
626
  }
627
+
628
  case 'logout': {
629
  operations.push({ action: 'logout', userId: req.user_id });
630
  const logoutUser = usersCache.get(req.user_id);
631
  if (logoutUser) logoutUser.is_login = 0;
632
  break;
633
  }
634
+
635
  case 'update_profile': {
636
  const profileUser = usersCache.get(req.user_id);
637
  const updateData = req.data || {};
638
+
639
  if (profileUser) {
640
  const fields = ['name', 'email', 'country', 'location', 'bio', 'external_links', 'date_of_birth', 'is_profile_public'];
641
  for (const field of fields) {
 
646
  profileUser.total_times_profile_updated_today = (profileUser.total_times_profile_updated_today || 0) + 1;
647
  profileUser.last_profile_updated = new Date().toISOString();
648
  }
649
+
650
  operations.push({
651
  action: 'updateProfile',
652
  userId: req.user_id,
 
666
  });
667
  break;
668
  }
669
+
670
  case 'upload_photo': {
671
  if (req.pic_buffer) {
672
  try {
 
674
  const filename = `${req.user_id}_${Math.floor(Date.now() / 1000)}.webp`;
675
  const filePath = path.join(PHOTOS_DIR, filename);
676
  await fsp.writeFile(filePath, compressed.buffer);
677
+
678
  const photoUser = usersCache.get(req.user_id);
679
  if (photoUser) photoUser.pic_url = `/photos/${filename}`;
680
+
681
  operations.push({ action: 'updatePhoto', userId: req.user_id, picUrl: `/photos/${filename}` });
682
  } catch (photoError) {}
683
  }
684
  break;
685
  }
686
+
687
  case 'forgot_password': {
688
  const newPassword = (req.data && req.data.new_password) || 'default123';
689
  const newHash = hashPassword(newPassword);
690
  const passUser = usersCache.get(req.user_id);
691
  if (passUser) passUser.password_hash = newHash;
692
+
693
  operations.push({ action: 'updatePassword', userId: req.user_id, passwordHash: newHash });
694
  break;
695
  }
 
710
  function addRequest(userId, username, action, data, picBuffer = null) {
711
  if (!userId) userId = generateId();
712
  if (!action) action = 'unknown';
713
+
714
  const request = {
715
  user_id: userId,
716
  username: username || 'unknown_user',
 
719
  pic_buffer: picBuffer ? picBuffer.toString('base64') : null,
720
  timestamp: Date.now()
721
  };
722
+
723
  batchBuffer.push(request);
724
  scheduleBatchProcess();
725
  return userId;
 
728
  // ============ IMAGE COMPRESSION ============
729
  async function compressToWebp(fileData, maxSizeKb = 20) {
730
  if (!sharp) return { buffer: fileData, isWebp: false, sizeKb: fileData.length / 1024 };
731
+
732
  try {
733
  let image = sharp(fileData);
734
  const metadata = await image.metadata();
735
  const currentSizeKb = fileData.length / 1024;
736
+
737
  if (metadata.format === 'webp' && currentSizeKb <= maxSizeKb) {
738
  return { buffer: fileData, isWebp: true, sizeKb: currentSizeKb, wasCompressed: false };
739
  }
740
+
741
  let quality = 80;
742
  let outputBuffer;
743
+
744
  while (quality >= 10) {
745
  outputBuffer = await image
746
  .resize(800, 800, { fit: 'inside', withoutEnlargement: true })
747
  .webp({ quality })
748
  .toBuffer();
749
+
750
  if (outputBuffer.length / 1024 <= maxSizeKb) break;
751
  quality -= 10;
752
  }
753
+
754
  if (outputBuffer.length / 1024 > maxSizeKb) {
755
  outputBuffer = await image
756
  .resize(400, 400, { fit: 'inside', withoutEnlargement: true })
757
  .webp({ quality: 30 })
758
  .toBuffer();
759
  }
760
+
761
  return {
762
  buffer: outputBuffer,
763
  isWebp: true,
 
789
  maxAge: 86400000
790
  });
791
 
 
792
  fastify.addHook('onRequest', async (request, reply) => {
 
793
  if (!globalRateLimiter.isAllowed()) {
794
  reply.status(503);
795
  reply.header('Content-Type', 'application/json');
796
  reply.send({ error: 'rate_limit', message: 'Rate limit reached', retry_after: 1 });
797
  return;
798
  }
799
+
 
800
  updateMetrics();
801
  if (metrics.totalUsers >= MAX_USERS || metrics.ramUsage >= MAX_RAM_USAGE) {
802
  reply.status(503);
 
806
  }
807
  });
808
 
809
+ // ROUTES
810
  fastify.get('/', async (request, reply) => {
811
  updateMetrics();
812
  const spaceFull = isSpaceFull();
813
  const fullSpaces = await getFullSpaces();
814
  const emptySpaces = SPACE_NAMES.filter(s => !fullSpaces.includes(s));
815
+
816
  reply.header('Content-Type', 'application/json');
817
  return {
818
  message: 'Velost Auth API - Optimized',
 
861
  const spaceFull = isSpaceFull();
862
  const fullSpaces = await getFullSpaces();
863
  const emptySpaces = SPACE_NAMES.filter(s => !fullSpaces.includes(s));
864
+
865
  reply.header('Content-Type', 'application/json');
866
  return {
867
  worker_pid: process.pid,
 
911
  }
912
 
913
  const { username, password, name, email, fing_key } = request.body || {};
914
+
915
  if (!username || !password || !name || !email) {
916
  reply.status(400);
917
  return { detail: 'Missing required fields' };
 
930
  return { detail: 'Password too short' };
931
  }
932
 
 
933
  if (usernameIndex.has(cleanUsername)) {
934
  reply.status(409);
935
  return { detail: 'Username already exists' };
 
961
  fing_key: fing_key ? fing_key.trim() : generateFingKey()
962
  };
963
 
 
964
  usersCache.set(userId, newUser);
965
  usernameIndex.set(cleanUsername, newUser);
966
  emailIndex.set(cleanEmail, newUser);
967
  metrics.totalUsers = usersCache.size;
968
 
969
+ addRequest(userId, cleanUsername, 'signup', {
970
+ username: cleanUsername,
971
+ password: password,
972
+ name: name.trim(),
973
+ email: cleanEmail,
974
+ country: request.body.country || '',
975
+ location: request.body.location || '',
976
+ fing_key: fing_key ? fing_key.trim() : generateFingKey()
977
  });
978
 
979
  return {
 
990
 
991
  fastify.post('/login', async (request, reply) => {
992
  const { username, password } = request.body || {};
993
+
994
  if (!username || !password) {
995
  reply.status(400);
996
  return { detail: 'Missing username or password' };
 
1009
  return { detail: 'Invalid credentials' };
1010
  }
1011
 
 
1012
  addRequest(user.id, cleanUsername, 'login', {});
1013
 
1014
  return {
 
1036
 
1037
  fastify.post('/logout', async (request, reply) => {
1038
  const { id } = request.body || {};
1039
+
1040
  if (!id) {
1041
  reply.status(400);
1042
  return { detail: 'Missing user ID' };
 
1059
 
1060
  fastify.put('/updateprofiledetails', async (request, reply) => {
1061
  const { id, ...data } = request.body || {};
1062
+
1063
  if (!id) {
1064
  reply.status(400);
1065
  return { detail: 'Missing user ID' };
 
1108
 
1109
  const fileBuffer = await data.toBuffer();
1110
  const id = (data.fields && data.fields.id) ? data.fields.id.value : (request.query ? request.query.id : null);
1111
+
1112
  if (!id) {
1113
  reply.status(400);
1114
  return { detail: 'Missing user ID' };
 
1139
 
1140
  fastify.get('/getuser', async (request, reply) => {
1141
  const { id, username } = request.query || {};
 
1142
  let user;
1143
+
1144
  if (username) {
1145
  user = usernameIndex.get(username.toLowerCase());
1146
  } else if (id) {
 
1202
 
1203
  fastify.post('/forgotpassword', async (request, reply) => {
1204
  const { username, email, fing_key, new_password } = request.body || {};
1205
+
1206
  if (!username || !email || !fing_key || !new_password) {
1207
  reply.status(400);
1208
  return { detail: 'Missing required fields' };
 
1211
  const cleanUsername = username.trim().toLowerCase();
1212
  const cleanEmail = email.trim().toLowerCase();
1213
  const cleanFingKey = fing_key.trim();
 
1214
  const user = usernameIndex.get(cleanUsername);
1215
+
1216
  if (!user) {
1217
  reply.status(404);
1218
  return { detail: 'No account found' };
 
1254
  async function start() {
1255
  try {
1256
  console.log(`Main: Starting optimized server (2 cores)`);
 
1257
  await initDBWorker();
1258
+
1259
  if (redis) {
1260
  try {
1261
  await redis.connect();
 
1268
 
1269
  console.log(`Main: Loading users into memory...`);
1270
  await loadUsersToMemory();
 
1271
  await setupFastify();
1272
 
 
1273
  setInterval(() => {
1274
  updateMetrics();
1275
  }, 1000);
1276
 
 
1277
  setInterval(() => {
1278
  if (batchBuffer.length > 0) {
1279
  flushBatchToRedis();
1280
  }
1281
+ }, 100);
1282
 
1283
  const port = process.env.PORT || 7860;
1284
  await fastify.listen({ port, host: '0.0.0.0' });
1285
+
1286
  console.log(`Main: 🚀 Server running on port ${port}`);
1287
  console.log(`Main: 📊 Users loaded: ${getTotalUsers()}`);
1288
  console.log(`Main: 💾 Storage: SQLite at /data/users.db (via Worker Thread)`);
 
1296
  }
1297
  }
1298
 
 
1299
  process.on('SIGTERM', async () => {
1300
  console.log(`Main: Shutting down...`);
1301
  await flushBatchToRedis();