blaze-aura69 commited on
Commit
fd662fd
·
verified ·
1 Parent(s): 2227417

Update index.js

Browse files
Files changed (1) hide show
  1. index.js +46 -231
index.js CHANGED
@@ -16,11 +16,10 @@ if (!isMainThread) {
16
  const db = new Database(dbPath);
17
 
18
  db.pragma('journal_mode = WAL');
19
- db.pragma('synchronous = NORMAL');
20
  db.pragma('cache_size = -2000000');
21
  db.pragma('temp_store = MEMORY');
22
  db.pragma('mmap_size = 268435456');
23
- db.pragma('busy_timeout = 5000');
24
 
25
  db.exec(`
26
  CREATE TABLE IF NOT EXISTS users (
@@ -44,7 +43,7 @@ if (!isMainThread) {
44
  getUserById: db.prepare('SELECT * FROM users WHERE id = ?'),
45
  getUserByUsername: db.prepare('SELECT * FROM users WHERE username = ?'),
46
  insertUser: db.prepare(`
47
- INSERT OR IGNORE INTO users (
48
  id, username, password_hash, name, created_at, is_login,
49
  bio, pic_url, date_of_birth, is_profile_public
50
  ) VALUES (
@@ -121,7 +120,9 @@ if (!isMainThread) {
121
  for (const op of operations) {
122
  switch (op.action) {
123
  case 'signup':
124
- stmts.insertUser.run(op.user);
 
 
125
  break;
126
  case 'login':
127
  stmts.updateLogin.run(1, op.userId);
@@ -142,10 +143,10 @@ if (!isMainThread) {
142
  return { processed: operations.length };
143
  }
144
 
145
- return; // IMPORTANT: Stop execution here for worker thread
146
  }
147
 
148
- // ============ MAIN THREAD - ONLY RUNS ONCE ============
149
  const fastify = require('fastify')({
150
  logger: false,
151
  bodyLimit: 1048576,
@@ -301,12 +302,6 @@ function dbRequest(action, data = {}) {
301
  });
302
  }
303
 
304
- let usersCache = new Map();
305
- let usernameIndex = new Map();
306
- let batchBuffer = [];
307
- let batchTimer = null;
308
- let processingLock = false;
309
-
310
  class FastRateLimiter {
311
  constructor(maxRequests = 15000, windowMs = 1000) {
312
  this.maxRequests = maxRequests;
@@ -358,45 +353,6 @@ function getBucketSize() {
358
  return totalSize;
359
  }
360
 
361
- async function loadUsersToMemory() {
362
- try {
363
- const users = await dbRequest('getAllUsers');
364
- usersCache.clear();
365
- usernameIndex.clear();
366
- for (const user of users) {
367
- usersCache.set(user.id, user);
368
- usernameIndex.set(user.username.toLowerCase(), user);
369
- }
370
- totalUsers = users.length;
371
- await checkUserCountStatus();
372
- } catch (e) {}
373
- }
374
-
375
- // Fetch user from DB if not in cache
376
- async function getUserFromDB(userId) {
377
- try {
378
- const user = await dbRequest('getUserById', { userId });
379
- if (user) {
380
- usersCache.set(user.id, user);
381
- usernameIndex.set(user.username.toLowerCase(), user);
382
- return user;
383
- }
384
- } catch (e) {}
385
- return null;
386
- }
387
-
388
- async function getUserByUsernameFromDB(username) {
389
- try {
390
- const user = await dbRequest('getUserByUsername', { username });
391
- if (user) {
392
- usersCache.set(user.id, user);
393
- usernameIndex.set(user.username.toLowerCase(), user);
394
- return user;
395
- }
396
- } catch (e) {}
397
- return null;
398
- }
399
-
400
  async function compressToWebp(fileData, maxSizeKb = 20) {
401
  if (!sharp) return fileData;
402
  try {
@@ -428,116 +384,6 @@ async function compressToWebp(fileData, maxSizeKb = 20) {
428
  }
429
  }
430
 
431
- function scheduleBatch() {
432
- if (batchTimer) return;
433
- batchTimer = setTimeout(async () => {
434
- batchTimer = null;
435
- await flushBatch();
436
- }, 100);
437
- }
438
-
439
- async function flushBatch() {
440
- if (batchBuffer.length === 0 || processingLock) return;
441
- processingLock = true;
442
- const batch = batchBuffer.splice(0, BATCH_SIZE);
443
- const operations = [];
444
-
445
- for (const req of batch) {
446
- try {
447
- if (!req || !req.user_id) continue;
448
- switch (req.action) {
449
- case 'signup': {
450
- const user = {
451
- id: req.user_id,
452
- username: (req.data && req.data.username) || 'user_' + Math.random().toString(36).substring(2, 10),
453
- password_hash: hashPassword((req.data && req.data.password) || 'default123'),
454
- name: (req.data && req.data.name) || 'User',
455
- created_at: new Date().toISOString(),
456
- is_login: 0,
457
- bio: '',
458
- pic_url: '',
459
- date_of_birth: '',
460
- is_profile_public: 'true'
461
- };
462
- operations.push({ action: 'signup', userId: req.user_id, user });
463
- if (!usersCache.has(req.user_id)) {
464
- usersCache.set(req.user_id, user);
465
- usernameIndex.set(user.username.toLowerCase(), user);
466
- }
467
- break;
468
- }
469
- case 'login':
470
- operations.push({ action: 'login', userId: req.user_id });
471
- let loginUser = usersCache.get(req.user_id);
472
- if (!loginUser) {
473
- loginUser = await getUserFromDB(req.user_id);
474
- }
475
- if (loginUser) loginUser.is_login = 1;
476
- break;
477
- case 'logout':
478
- operations.push({ action: 'logout', userId: req.user_id });
479
- let logoutUser = usersCache.get(req.user_id);
480
- if (!logoutUser) {
481
- logoutUser = await getUserFromDB(req.user_id);
482
- }
483
- if (logoutUser) logoutUser.is_login = 0;
484
- break;
485
- case 'update_profile': {
486
- let profileUser = usersCache.get(req.user_id);
487
- if (!profileUser) {
488
- profileUser = await getUserFromDB(req.user_id);
489
- }
490
- const updateData = req.data || {};
491
- if (profileUser) {
492
- if (updateData.name) profileUser.name = updateData.name;
493
- if (updateData.bio) profileUser.bio = updateData.bio;
494
- if (updateData.date_of_birth) profileUser.date_of_birth = updateData.date_of_birth;
495
- if (updateData.is_profile_public) profileUser.is_profile_public = updateData.is_profile_public;
496
- }
497
- operations.push({ action: 'updateProfile', userId: req.user_id, data: updateData });
498
- break;
499
- }
500
- case 'upload_photo':
501
- if (req.pic_buffer) {
502
- try {
503
- const compressed = await compressToWebp(Buffer.from(req.pic_buffer, 'base64'), MAX_PHOTO_SIZE_KB);
504
- const filename = `${req.user_id}_${Math.floor(Date.now() / 1000)}.webp`;
505
- await fsp.writeFile(path.join(PHOTOS_DIR, filename), compressed);
506
- let photoUser = usersCache.get(req.user_id);
507
- if (!photoUser) {
508
- photoUser = await getUserFromDB(req.user_id);
509
- }
510
- if (photoUser) photoUser.pic_url = `/photos/${filename}`;
511
- operations.push({ action: 'updatePhoto', userId: req.user_id, picUrl: `/photos/${filename}` });
512
- } catch (e) {}
513
- }
514
- break;
515
- }
516
- } catch (e) {}
517
- }
518
-
519
- if (operations.length > 0) {
520
- try {
521
- await dbRequest('batchOperation', { operations });
522
- } catch (e) {}
523
- }
524
- processingLock = false;
525
- }
526
-
527
- function addRequest(userId, username, action, data, picBuffer = null) {
528
- if (!userId) userId = generateId();
529
- batchBuffer.push({
530
- user_id: userId,
531
- username: username || 'unknown',
532
- action: action || 'unknown',
533
- data: data || {},
534
- pic_buffer: picBuffer ? picBuffer.toString('base64') : null,
535
- timestamp: Date.now()
536
- });
537
- scheduleBatch();
538
- return userId;
539
- }
540
-
541
  async function setupFastify() {
542
  await fastify.register(cors, { origin: '*' });
543
  await fastify.register(multipart, { limits: { fileSize: 5 * 1024 * 1024 } });
@@ -548,18 +394,9 @@ async function setupFastify() {
548
  reply.status(503).send({ error: 'rate_limit' });
549
  return;
550
  }
551
- if (totalUsers >= MAX_USERS) {
552
- reply.status(503).send({ error: 'full' });
553
- return;
554
- }
555
  });
556
 
557
  fastify.post('/signup', async (request, reply) => {
558
- if (totalUsers >= MAX_USERS) {
559
- reply.status(507).send({ detail: 'Server full' });
560
- return;
561
- }
562
-
563
  const { username, password, name } = request.body || {};
564
  if (!username || !password || !name) {
565
  reply.status(400).send({ detail: 'Missing fields' });
@@ -580,15 +417,16 @@ async function setupFastify() {
580
  return;
581
  }
582
 
583
- // Check cache first, then DB
584
- if (usernameIndex.has(cleanUsername)) {
 
585
  reply.status(409).send({ detail: 'Username exists' });
586
  return;
587
  }
588
 
589
- const existingUser = await getUserByUsernameFromDB(cleanUsername);
590
- if (existingUser) {
591
- reply.status(409).send({ detail: 'Username exists' });
592
  return;
593
  }
594
 
@@ -606,12 +444,14 @@ async function setupFastify() {
606
  is_profile_public: 'true'
607
  };
608
 
609
- usersCache.set(userId, newUser);
610
- usernameIndex.set(cleanUsername, newUser);
611
- totalUsers = usersCache.size;
612
- addRequest(userId, cleanUsername, 'signup', { username: cleanUsername, password, name: name.trim() });
613
- await checkUserCountStatus();
614
- reply.send({ success: true, user_id: userId, username: cleanUsername });
 
 
615
  });
616
 
617
  fastify.post('/login', async (request, reply) => {
@@ -621,17 +461,21 @@ async function setupFastify() {
621
  return;
622
  }
623
 
624
- let user = usernameIndex.get(username.trim().toLowerCase());
 
 
625
  if (!user) {
626
- user = await getUserByUsernameFromDB(username.trim().toLowerCase());
 
627
  }
628
 
629
- if (!user || !verifyPassword(password, user.password_hash)) {
630
  reply.status(401).send({ detail: 'Invalid credentials' });
631
  return;
632
  }
633
 
634
- addRequest(user.id, user.username, 'login', {});
 
635
  reply.send({
636
  success: true,
637
  id: user.id,
@@ -652,17 +496,13 @@ async function setupFastify() {
652
  return;
653
  }
654
 
655
- let user = usersCache.get(id);
656
- if (!user) {
657
- user = await getUserFromDB(id);
658
- }
659
-
660
  if (!user) {
661
  reply.status(404).send({ detail: 'Not found' });
662
  return;
663
  }
664
 
665
- addRequest(id, '', 'logout', {});
666
  reply.send({ success: true });
667
  });
668
 
@@ -673,11 +513,7 @@ async function setupFastify() {
673
  return;
674
  }
675
 
676
- let user = usersCache.get(id);
677
- if (!user) {
678
- user = await getUserFromDB(id);
679
- }
680
-
681
  if (!user) {
682
  reply.status(404).send({ detail: 'Not found' });
683
  return;
@@ -692,7 +528,7 @@ async function setupFastify() {
692
  return;
693
  }
694
 
695
- addRequest(id, '', 'update_profile', data);
696
  reply.send({ success: true });
697
  });
698
 
@@ -712,17 +548,17 @@ async function setupFastify() {
712
  const fileBuffer = await data.toBuffer();
713
  const id = (data.fields && data.fields.id) ? data.fields.id.value : null;
714
 
715
- let user = usersCache.get(id);
716
- if (!user) {
717
- user = await getUserFromDB(id);
718
- }
719
-
720
  if (!id || !user) {
721
  reply.status(404).send({ detail: 'Not found' });
722
  return;
723
  }
724
 
725
- addRequest(id, '', 'upload_photo', {}, fileBuffer);
 
 
 
 
726
  reply.send({ success: true });
727
  } catch (e) {
728
  reply.status(500).send({ detail: 'Failed' });
@@ -734,15 +570,9 @@ async function setupFastify() {
734
  let user;
735
 
736
  if (username) {
737
- user = usernameIndex.get(username.toLowerCase());
738
- if (!user) {
739
- user = await getUserByUsernameFromDB(username.toLowerCase());
740
- }
741
  } else if (id) {
742
- user = usersCache.get(id);
743
- if (!user) {
744
- user = await getUserFromDB(id);
745
- }
746
  } else {
747
  reply.status(400).send({ detail: 'Missing params' });
748
  return;
@@ -768,12 +598,11 @@ async function setupFastify() {
768
 
769
  fastify.get('/check', async (request, reply) => {
770
  const count = await dbRequest('getCount');
771
- const isFull = totalUsers >= MAX_USERS;
772
  reply.send({
773
  status: 'ok',
774
  count: count,
775
  maxUsers: MAX_USERS,
776
- isFull: isFull,
777
  spaceName: SPACE_NAME
778
  });
779
  });
@@ -784,32 +613,20 @@ async function setupFastify() {
784
  async function start() {
785
  try {
786
  await initDBWorker();
787
- await loadUsersToMemory();
 
 
 
788
  await setupFastify();
789
 
790
  setInterval(() => {
791
  checkRPSStatus();
792
- if (batchBuffer.length > 0) flushBatch();
793
  }, 100);
794
 
795
  setInterval(async () => {
796
  await checkUserCountStatus();
797
  }, 5000);
798
 
799
- // Reload cache from DB every 30 seconds to stay in sync with other spaces
800
- setInterval(async () => {
801
- try {
802
- const users = await dbRequest('getAllUsers');
803
- for (const user of users) {
804
- if (!usersCache.has(user.id)) {
805
- usersCache.set(user.id, user);
806
- usernameIndex.set(user.username.toLowerCase(), user);
807
- }
808
- }
809
- totalUsers = users.length;
810
- } catch (e) {}
811
- }, 30000);
812
-
813
  const port = process.env.PORT || 7860;
814
  await fastify.listen({ port, host: '0.0.0.0' });
815
  console.log(`Server running on port ${port}`);
@@ -821,7 +638,6 @@ async function start() {
821
 
822
  process.on('SIGTERM', async () => {
823
  await removeSpaceFromFull();
824
- await flushBatch();
825
  await fastify.close();
826
  if (dbWorker) await dbWorker.terminate();
827
  process.exit(0);
@@ -829,7 +645,6 @@ process.on('SIGTERM', async () => {
829
 
830
  process.on('SIGINT', async () => {
831
  await removeSpaceFromFull();
832
- await flushBatch();
833
  await fastify.close();
834
  if (dbWorker) await dbWorker.terminate();
835
  process.exit(0);
 
16
  const db = new Database(dbPath);
17
 
18
  db.pragma('journal_mode = WAL');
19
+ db.pragma('synchronous = OFF');
20
  db.pragma('cache_size = -2000000');
21
  db.pragma('temp_store = MEMORY');
22
  db.pragma('mmap_size = 268435456');
 
23
 
24
  db.exec(`
25
  CREATE TABLE IF NOT EXISTS users (
 
43
  getUserById: db.prepare('SELECT * FROM users WHERE id = ?'),
44
  getUserByUsername: db.prepare('SELECT * FROM users WHERE username = ?'),
45
  insertUser: db.prepare(`
46
+ INSERT INTO users (
47
  id, username, password_hash, name, created_at, is_login,
48
  bio, pic_url, date_of_birth, is_profile_public
49
  ) VALUES (
 
120
  for (const op of operations) {
121
  switch (op.action) {
122
  case 'signup':
123
+ try {
124
+ stmts.insertUser.run(op.user);
125
+ } catch (e) {}
126
  break;
127
  case 'login':
128
  stmts.updateLogin.run(1, op.userId);
 
143
  return { processed: operations.length };
144
  }
145
 
146
+ return;
147
  }
148
 
149
+ // ============ MAIN THREAD ============
150
  const fastify = require('fastify')({
151
  logger: false,
152
  bodyLimit: 1048576,
 
302
  });
303
  }
304
 
 
 
 
 
 
 
305
  class FastRateLimiter {
306
  constructor(maxRequests = 15000, windowMs = 1000) {
307
  this.maxRequests = maxRequests;
 
353
  return totalSize;
354
  }
355
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
356
  async function compressToWebp(fileData, maxSizeKb = 20) {
357
  if (!sharp) return fileData;
358
  try {
 
384
  }
385
  }
386
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
387
  async function setupFastify() {
388
  await fastify.register(cors, { origin: '*' });
389
  await fastify.register(multipart, { limits: { fileSize: 5 * 1024 * 1024 } });
 
394
  reply.status(503).send({ error: 'rate_limit' });
395
  return;
396
  }
 
 
 
 
397
  });
398
 
399
  fastify.post('/signup', async (request, reply) => {
 
 
 
 
 
400
  const { username, password, name } = request.body || {};
401
  if (!username || !password || !name) {
402
  reply.status(400).send({ detail: 'Missing fields' });
 
417
  return;
418
  }
419
 
420
+ // Check if username exists directly in DB
421
+ const existingUser = await dbRequest('getUserByUsername', { username: cleanUsername });
422
+ if (existingUser) {
423
  reply.status(409).send({ detail: 'Username exists' });
424
  return;
425
  }
426
 
427
+ const count = await dbRequest('getCount');
428
+ if (count >= MAX_USERS) {
429
+ reply.status(507).send({ detail: 'Server full' });
430
  return;
431
  }
432
 
 
444
  is_profile_public: 'true'
445
  };
446
 
447
+ try {
448
+ await dbRequest('insertUser', { user: newUser });
449
+ totalUsers = count + 1;
450
+ await checkUserCountStatus();
451
+ reply.send({ success: true, user_id: userId, username: cleanUsername });
452
+ } catch (e) {
453
+ reply.status(500).send({ detail: 'Signup failed' });
454
+ }
455
  });
456
 
457
  fastify.post('/login', async (request, reply) => {
 
461
  return;
462
  }
463
 
464
+ const cleanUsername = username.trim().toLowerCase();
465
+ const user = await dbRequest('getUserByUsername', { username: cleanUsername });
466
+
467
  if (!user) {
468
+ reply.status(401).send({ detail: 'Invalid credentials' });
469
+ return;
470
  }
471
 
472
+ if (!verifyPassword(password, user.password_hash)) {
473
  reply.status(401).send({ detail: 'Invalid credentials' });
474
  return;
475
  }
476
 
477
+ await dbRequest('updateLogin', { userId: user.id, isLogin: true });
478
+
479
  reply.send({
480
  success: true,
481
  id: user.id,
 
496
  return;
497
  }
498
 
499
+ const user = await dbRequest('getUserById', { userId: id });
 
 
 
 
500
  if (!user) {
501
  reply.status(404).send({ detail: 'Not found' });
502
  return;
503
  }
504
 
505
+ await dbRequest('updateLogin', { userId: id, isLogin: false });
506
  reply.send({ success: true });
507
  });
508
 
 
513
  return;
514
  }
515
 
516
+ const user = await dbRequest('getUserById', { userId: id });
 
 
 
 
517
  if (!user) {
518
  reply.status(404).send({ detail: 'Not found' });
519
  return;
 
528
  return;
529
  }
530
 
531
+ await dbRequest('updateProfile', { userId: id, ...data });
532
  reply.send({ success: true });
533
  });
534
 
 
548
  const fileBuffer = await data.toBuffer();
549
  const id = (data.fields && data.fields.id) ? data.fields.id.value : null;
550
 
551
+ const user = await dbRequest('getUserById', { userId: id });
 
 
 
 
552
  if (!id || !user) {
553
  reply.status(404).send({ detail: 'Not found' });
554
  return;
555
  }
556
 
557
+ const compressed = await compressToWebp(fileBuffer, MAX_PHOTO_SIZE_KB);
558
+ const filename = `${id}_${Math.floor(Date.now() / 1000)}.webp`;
559
+ await fsp.writeFile(path.join(PHOTOS_DIR, filename), compressed);
560
+
561
+ await dbRequest('updatePhoto', { userId: id, picUrl: `/photos/${filename}` });
562
  reply.send({ success: true });
563
  } catch (e) {
564
  reply.status(500).send({ detail: 'Failed' });
 
570
  let user;
571
 
572
  if (username) {
573
+ user = await dbRequest('getUserByUsername', { username: username.toLowerCase() });
 
 
 
574
  } else if (id) {
575
+ user = await dbRequest('getUserById', { userId: id });
 
 
 
576
  } else {
577
  reply.status(400).send({ detail: 'Missing params' });
578
  return;
 
598
 
599
  fastify.get('/check', async (request, reply) => {
600
  const count = await dbRequest('getCount');
 
601
  reply.send({
602
  status: 'ok',
603
  count: count,
604
  maxUsers: MAX_USERS,
605
+ isFull: count >= MAX_USERS,
606
  spaceName: SPACE_NAME
607
  });
608
  });
 
613
  async function start() {
614
  try {
615
  await initDBWorker();
616
+
617
+ // Get initial count
618
+ totalUsers = await dbRequest('getCount');
619
+
620
  await setupFastify();
621
 
622
  setInterval(() => {
623
  checkRPSStatus();
 
624
  }, 100);
625
 
626
  setInterval(async () => {
627
  await checkUserCountStatus();
628
  }, 5000);
629
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
630
  const port = process.env.PORT || 7860;
631
  await fastify.listen({ port, host: '0.0.0.0' });
632
  console.log(`Server running on port ${port}`);
 
638
 
639
  process.on('SIGTERM', async () => {
640
  await removeSpaceFromFull();
 
641
  await fastify.close();
642
  if (dbWorker) await dbWorker.terminate();
643
  process.exit(0);
 
645
 
646
  process.on('SIGINT', async () => {
647
  await removeSpaceFromFull();
 
648
  await fastify.close();
649
  if (dbWorker) await dbWorker.terminate();
650
  process.exit(0);