blaze-aura69 commited on
Commit
2a426cd
Β·
verified Β·
1 Parent(s): d7e2451

Update index.js

Browse files
Files changed (1) hide show
  1. index.js +1038 -346
index.js CHANGED
@@ -4,6 +4,7 @@ const os = require('os');
4
 
5
  // ============ DATABASE WORKER THREAD ============
6
  if (!isMainThread) {
 
7
  const Database = require('better-sqlite3');
8
  const path = require('path');
9
  const fs = require('fs');
@@ -12,12 +13,14 @@ if (!isMainThread) {
12
  const DATA_DIR = workerData.dataDir || "/data";
13
  const dbPath = path.join(DATA_DIR, 'users.db');
14
 
 
15
  const db = new Database(dbPath);
16
  db.pragma('journal_mode = WAL');
17
  db.pragma('synchronous = NORMAL');
18
  db.pragma('cache_size = -2000000');
19
  db.pragma('temp_store = MEMORY');
20
 
 
21
  db.exec(`
22
  CREATE TABLE IF NOT EXISTS users (
23
  id TEXT PRIMARY KEY,
@@ -45,6 +48,7 @@ if (!isMainThread) {
45
  CREATE INDEX IF NOT EXISTS idx_email ON users(email);
46
  `);
47
 
 
48
  const stmts = {
49
  getAllUsers: db.prepare('SELECT * FROM users'),
50
  getUserById: db.prepare('SELECT * FROM users WHERE id = ?'),
@@ -79,112 +83,111 @@ if (!isMainThread) {
79
  updatePassword: db.prepare('UPDATE users SET password_hash = ? WHERE id = ?')
80
  };
81
 
82
- // Message queue with read priority
83
- const messageQueue = [];
84
- let processingMessage = false;
85
-
86
- async function processMessageQueue() {
87
- if (processingMessage) return;
88
- processingMessage = true;
89
 
90
- while (messageQueue.length > 0) {
91
- const readMsg = messageQueue.find(m =>
92
- m.action === 'getUserById' ||
93
- m.action === 'getUserByUsername' ||
94
- m.action === 'getAllUsers' ||
95
- m.action === 'getCount'
96
- );
97
 
98
- const msg = readMsg || messageQueue.shift();
99
- if (readMsg) {
100
- messageQueue.splice(messageQueue.indexOf(readMsg), 1);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  }
102
 
103
- const { id, action, data } = msg;
104
-
105
- try {
106
- let result;
107
-
108
- switch (action) {
109
- case 'getAllUsers':
110
- result = stmts.getAllUsers.all();
111
- break;
112
- case 'getUserById':
113
- result = stmts.getUserById.get(data.userId);
114
- break;
115
- case 'getUserByUsername':
116
- result = stmts.getUserByUsername.get(data.username);
117
  break;
118
- case 'insertUser':
119
- stmts.insertUser.run(data.user);
120
- result = { success: true };
121
  break;
122
- case 'updateLogin':
123
- stmts.updateLogin.run(data.isLogin ? 1 : 0, data.userId);
124
- result = { success: true };
125
  break;
126
  case 'updateProfile':
127
- stmts.updateProfile.run({
128
- id: data.userId,
129
- name: data.name || 'Unknown',
130
- email: data.email || 'no-email@example.com',
131
- country: data.country || '',
132
- location: data.location || '',
133
- bio: data.bio || '',
134
- external_links: data.external_links || '[]',
135
- date_of_birth: data.date_of_birth || '',
136
- is_profile_public: data.is_profile_public || 'true',
137
- total_times_profile_updated_today: data.total_times_profile_updated_today || 0,
138
- last_profile_updated: data.last_profile_updated || ''
139
- });
140
- result = { success: true };
141
- break;
142
- case 'updatePhoto':
143
- stmts.updatePhoto.run(data.picUrl, data.userId);
144
- result = { success: true };
145
  break;
146
  case 'updatePassword':
147
- stmts.updatePassword.run(data.passwordHash, data.userId);
148
- result = { success: true };
149
- break;
150
- case 'batchOperation':
151
- const ops = data.operations;
152
- const transaction = db.transaction(() => {
153
- for (const op of ops) {
154
- switch (op.action) {
155
- case 'signup': stmts.insertUser.run(op.user); break;
156
- case 'login': stmts.updateLogin.run(1, op.userId); break;
157
- case 'logout': stmts.updateLogin.run(0, op.userId); break;
158
- case 'updateProfile': stmts.updateProfile.run(op.data); break;
159
- case 'updatePassword': stmts.updatePassword.run(op.passwordHash, op.userId); break;
160
- case 'updatePhoto': stmts.updatePhoto.run(op.picUrl, op.userId); break;
161
- }
162
- }
163
- });
164
- transaction();
165
- result = { processed: ops.length };
166
  break;
167
- case 'getCount':
168
- result = stmts.getAllUsers.all().length;
169
  break;
170
- default:
171
- throw new Error(`Unknown action: ${action}`);
172
  }
173
-
174
- parentPort.postMessage({ id, success: true, result });
175
- } catch (error) {
176
- parentPort.postMessage({ id, success: false, error: error.message });
177
  }
178
- }
179
 
180
- processingMessage = false;
 
181
  }
182
 
183
- parentPort.on('message', (message) => {
184
- messageQueue.push(message);
185
- processMessageQueue();
186
- });
187
-
188
  console.log(`DB Worker Thread: SQLite initialized at ${dbPath}`);
189
 
190
  } else {
@@ -206,22 +209,42 @@ if (!isMainThread) {
206
  const path = require('path');
207
  const { Readable } = require('stream');
208
 
209
- let sharp;
210
- try { sharp = require('sharp'); } catch (e) { console.log(`Main: Sharp not available`); }
 
 
 
 
 
 
 
 
 
 
211
 
 
212
  const MAX_BUCKET_SIZE = 60 * 1024 * 1024 * 1024;
213
  const MAX_USERS = 15000;
214
  const MAX_USERS_SIZE_LIMIT = 15000;
215
  const MAX_RAM_USAGE = 7 * 1024 * 1024 * 1024;
216
  const MAX_PROFILE_UPDATES_PER_DAY = Infinity;
217
  const MAX_PHOTO_SIZE_KB = 5;
 
218
  const MAX_EXTERNAL_LINKS = 3;
 
 
 
 
 
 
219
  const MAX_RPS = 15000;
220
  const SPACE_NAMES = ["data2"];
 
221
  const CURRENT_SPACE_NAME = "1";
222
  const BATCH_SIZE = 15000;
223
  const HASH = process.env.HASH || 'v3l0st-d3f4ult-h4sh-k3y-2024!@#$%^&*()';
224
 
 
225
  const DATA_DIR = process.env.DATA_DIR || "/data";
226
  const PHOTOS_DIR = path.join(DATA_DIR, "photos");
227
  const STATUS_DIR = process.env.STATUS_DIR || "/status";
@@ -229,29 +252,51 @@ if (!isMainThread) {
229
  const SIZE_FILE = path.join(STATUS_DIR, "size.txt");
230
 
231
  [DATA_DIR, PHOTOS_DIR, STATUS_DIR].forEach(dir => {
232
- try { if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); } catch (e) {}
 
 
 
 
 
 
233
  });
234
 
235
- if (!fs.existsSync(FULL_FILE)) fs.writeFileSync(FULL_FILE, '', 'utf8');
236
- if (!fs.existsSync(SIZE_FILE)) fs.writeFileSync(SIZE_FILE, '', 'utf8');
 
 
 
 
237
 
238
- let dbWorker, dbRequestId = 0;
 
 
239
  const dbPromises = new Map();
240
 
241
  function initDBWorker() {
242
  return new Promise((resolve, reject) => {
243
- dbWorker = new ThreadWorker(__filename, { workerData: { dataDir: DATA_DIR } });
 
 
 
244
  dbWorker.on('message', (message) => {
245
  const { id, success, result, error } = message;
246
  const promise = dbPromises.get(id);
247
  if (promise) {
248
  dbPromises.delete(id);
249
- if (success) promise.resolve(result);
250
- else promise.reject(new Error(error));
 
 
 
251
  }
252
  });
 
253
  dbWorker.on('error', reject);
254
- dbWorker.on('online', () => { console.log(`Main: DB Worker Thread online`); resolve(); });
 
 
 
255
  });
256
  }
257
 
@@ -263,21 +308,62 @@ if (!isMainThread) {
263
  });
264
  }
265
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
266
  let usersCache = new Map();
267
  let batchBuffer = [];
268
- let batchInterval = null;
269
  let processingLock = false;
270
 
 
271
  class GlobalRateLimiter {
272
  constructor(maxRequests = 15000, window = 1) {
273
- this.maxRequests = maxRequests; this.window = window; this.requests = [];
 
 
274
  }
 
275
  isAllowed() {
276
  const now = Date.now() / 1000;
277
  this.requests = this.requests.filter(t => now - t < this.window);
278
  if (this.requests.length >= this.maxRequests) return false;
279
- this.requests.push(now); return true;
 
280
  }
 
281
  getCurrentCount() {
282
  const now = Date.now() / 1000;
283
  this.requests = this.requests.filter(t => now - t < this.window);
@@ -287,23 +373,32 @@ if (!isMainThread) {
287
 
288
  class RateLimiter {
289
  constructor(maxRequests = 15000, window = 1) {
290
- this.maxRequests = maxRequests; this.window = window; this.requests = new Map();
 
 
291
  }
 
292
  isAllowed(clientIp) {
293
  const now = Date.now() / 1000;
294
- if (!this.requests.has(clientIp)) this.requests.set(clientIp, []);
 
 
295
  const clientRequests = this.requests.get(clientIp);
296
  const filtered = clientRequests.filter(t => now - t < this.window);
297
  this.requests.set(clientIp, filtered);
298
  if (filtered.length >= this.maxRequests) return false;
299
- filtered.push(now); return true;
 
300
  }
301
  }
302
 
303
  const globalRateLimiter = new GlobalRateLimiter(15000, 1);
304
  const rateLimiter = new RateLimiter(15000, 1);
305
 
306
- function getMemoryUsage() { return process.memoryUsage().rss; }
 
 
 
307
 
308
  let lastCPUUsage = process.cpuUsage();
309
  let lastCPUCheck = Date.now();
@@ -315,7 +410,8 @@ if (!isMainThread) {
315
  lastCPUUsage = process.cpuUsage();
316
  lastCPUCheck = currentTime;
317
  if (elapsedMS === 0) return 0;
318
- return Math.min(100, ((currentCPUUsage.user + currentCPUUsage.system) / 1000) / elapsedMS * 100);
 
319
  }
320
 
321
  function safeGet(value, defaultValue = "") {
@@ -327,7 +423,8 @@ if (!isMainThread) {
327
  function generateId() {
328
  const buffer = Buffer.alloc(16);
329
  const [seconds, nanoseconds] = process.hrtime();
330
- buffer.writeBigInt64BE(BigInt(Math.floor((seconds * 1e12 + nanoseconds * 1000) / 1000)));
 
331
  crypto.randomFillSync(buffer, 6, 10);
332
  buffer[15] = buffer[15] & 0xF8;
333
  return buffer.toString('base64url').substring(0, 21);
@@ -337,24 +434,37 @@ if (!isMainThread) {
337
  return crypto.createHash('sha256').update(uuidv4()).digest('hex').substring(0, 32);
338
  }
339
 
340
- function generateRandomUsername() { return 'user_' + crypto.randomBytes(4).toString('hex'); }
341
- function generateRandomName() { return 'User_' + crypto.randomBytes(3).toString('hex'); }
 
 
 
 
 
342
 
343
  function formatSize(bytesSize) {
344
  if (bytesSize === 0) return "0 B";
345
  const units = ["B", "KB", "MB", "GB", "TB"];
346
- let size = bytesSize, unitIndex = 0;
347
- while (size >= 1024 && unitIndex < units.length - 1) { size /= 1024; unitIndex++; }
 
 
 
 
348
  return `${size.toFixed(2)} ${units[unitIndex]}`;
349
  }
350
 
351
- function toJsonl(data) { return JSON.stringify(data) + "\n"; }
 
 
352
 
353
  function hashPassword(password) {
354
  return crypto.createHash('sha256').update(HASH + password + HASH).digest('hex');
355
  }
356
 
357
- function verifyPassword(password, hash) { return hashPassword(password) === hash; }
 
 
358
 
359
  function validateExternalLinks(linksStr) {
360
  if (!linksStr) return { valid: true, error: null };
@@ -363,38 +473,70 @@ if (!isMainThread) {
363
  if (!Array.isArray(links)) return { valid: false, error: "External links must be a JSON array" };
364
  if (links.length > MAX_EXTERNAL_LINKS) return { valid: false, error: `Maximum ${MAX_EXTERNAL_LINKS} external links allowed` };
365
  return { valid: true, error: null };
366
- } catch (e) { return { valid: false, error: "Invalid JSON format for external links" }; }
 
 
367
  }
368
 
 
369
  let lastFullStatus = false;
370
 
371
  async function getFullSpaces() {
372
- try { const content = await fsp.readFile(FULL_FILE, 'utf8'); return content.trim() ? content.trim().split('|') : []; } catch (e) { return []; }
 
 
 
 
 
373
  }
 
374
  async function addSpaceToFull(spacename) {
375
  try {
376
- let content = await fsp.readFile(FULL_FILE, 'utf8'); content = content.trim();
 
377
  let spaces = content ? content.split('|') : [];
378
- if (!spaces.includes(spacename)) { spaces.push(spacename); await fsp.writeFile(FULL_FILE, spaces.join('|'), 'utf8'); }
379
- } catch (e) {}
 
 
 
 
 
380
  }
 
381
  async function removeSpaceFromFull(spacename) {
382
  try {
383
- let content = await fsp.readFile(FULL_FILE, 'utf8'); content = content.trim();
 
384
  let spaces = content ? content.split('|') : [];
385
  spaces = spaces.filter(s => s !== spacename);
386
  await fsp.writeFile(FULL_FILE, spaces.join('|'), 'utf8');
387
- } catch (e) {}
 
 
388
  }
 
389
  async function getSizeSpaces() {
390
- try { const content = await fsp.readFile(SIZE_FILE, 'utf8'); return content.trim() ? content.trim().split('|') : []; } catch (e) { return []; }
 
 
 
 
 
391
  }
 
392
  async function addSpaceToSize(spacename) {
393
  try {
394
- let content = await fsp.readFile(SIZE_FILE, 'utf8'); content = content.trim();
 
395
  let spaces = content ? content.split('|') : [];
396
- if (!spaces.includes(spacename)) { spaces.push(spacename); await fsp.writeFile(SIZE_FILE, spaces.join('|'), 'utf8'); }
397
- } catch (e) {}
 
 
 
 
 
398
  }
399
 
400
  async function checkAndUpdateFullStatus() {
@@ -403,40 +545,83 @@ if (!isMainThread) {
403
  const totalUsers = getTotalUsers();
404
  const bucketSize = getBucketSize();
405
  const ramUsage = getMemoryUsage();
406
- const isFull = currentRPS >= MAX_RPS || cpuUsage >= 98 || totalUsers >= MAX_USERS || bucketSize >= MAX_BUCKET_SIZE || ramUsage >= MAX_RAM_USAGE;
 
 
 
 
 
 
407
  if (isFull !== lastFullStatus) {
408
  lastFullStatus = isFull;
409
- if (isFull) await addSpaceToFull(CURRENT_SPACE_NAME);
410
- else await removeSpaceFromFull(CURRENT_SPACE_NAME);
 
 
 
 
 
 
 
411
  }
412
- if (totalUsers >= MAX_USERS_SIZE_LIMIT) await addSpaceToSize(CURRENT_SPACE_NAME);
413
  }
414
 
 
415
  async function compressToWebp(fileData, maxSizeKb = 20) {
416
  if (!sharp) return { buffer: fileData, isWebp: false, sizeKb: fileData.length / 1024 };
 
417
  try {
418
  let image = sharp(fileData);
419
  const metadata = await image.metadata();
420
  const currentSizeKb = fileData.length / 1024;
421
- if (metadata.format === 'webp' && currentSizeKb <= maxSizeKb) return { buffer: fileData, isWebp: true, sizeKb: currentSizeKb, wasCompressed: false };
422
- let quality = 80, outputBuffer;
 
 
 
 
 
 
423
  while (quality >= 10) {
424
- outputBuffer = await image.resize(800, 800, { fit: 'inside', withoutEnlargement: true }).webp({ quality }).toBuffer();
 
 
 
 
425
  if (outputBuffer.length / 1024 <= maxSizeKb) break;
426
  quality -= 10;
427
  }
428
- if (outputBuffer.length / 1024 > maxSizeKb) outputBuffer = await image.resize(400, 400, { fit: 'inside', withoutEnlargement: true }).webp({ quality: 30 }).toBuffer();
429
- return { buffer: outputBuffer, isWebp: true, sizeKb: outputBuffer.length / 1024, wasCompressed: true };
430
- } catch (e) { return { buffer: fileData, isWebp: false, sizeKb: fileData.length / 1024, wasCompressed: false }; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
431
  }
432
 
 
433
  async function loadUsersToMemory() {
434
  try {
435
  const users = await dbRequest('getAllUsers');
436
  usersCache.clear();
437
- for (const user of users) usersCache.set(user.id, user);
 
 
438
  console.log(`Main: Loaded ${users.length} users into memory`);
439
- } catch (e) { console.error(`Main: Error loading users:`, e.message); }
 
 
440
  }
441
 
442
  async function getUser(userId) {
@@ -445,19 +630,27 @@ if (!isMainThread) {
445
  const user = await dbRequest('getUserById', { userId });
446
  if (user) usersCache.set(userId, user);
447
  return user;
448
- } catch (e) { return null; }
 
 
449
  }
450
 
451
  async function getUserByUsername(username) {
452
- for (const user of usersCache.values()) if (user.username === username) return user;
 
 
453
  try {
454
  const user = await dbRequest('getUserByUsername', { username });
455
  if (user) usersCache.set(user.id, user);
456
  return user;
457
- } catch (e) { return null; }
 
 
458
  }
459
 
460
- function getTotalUsers() { return usersCache.size; }
 
 
461
 
462
  function getBucketSize() {
463
  let totalSize = 0;
@@ -478,42 +671,134 @@ if (!isMainThread) {
478
  }
479
 
480
  function isSpaceFull() {
481
- return getTotalUsers() >= MAX_USERS || getBucketSize() >= MAX_BUCKET_SIZE || globalRateLimiter.getCurrentCount() >= MAX_RPS || getCurrentCPUPercentage() >= 98;
 
 
 
482
  }
483
 
484
  // ============ BATCH PROCESSING ============
485
- function scheduleBatchProcess() {
486
- if (batchInterval) return;
487
- batchInterval = setInterval(async () => {
488
- if (batchBuffer.length === 0 || processingLock) return;
489
- processingLock = true;
490
- const batch = batchBuffer.splice(0, Math.min(batchBuffer.length, BATCH_SIZE));
491
- const batchCount = batch.length;
492
- console.log(`Main: Processing batch of ${batchCount} requests`);
493
- const startTime = Date.now();
494
- try {
495
- await processRequestsBatch(batch);
496
- console.log(`Main: Batch of ${batchCount} processed in ${Date.now() - startTime}ms`);
497
- } catch (e) {
498
- console.error(`Main: Batch error:`, e.message);
499
- batchBuffer.unshift(...batch);
500
- } finally {
501
- processingLock = false;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
502
  }
503
- }, 1000);
 
 
504
  }
505
 
 
506
  async function processRequestsBatch(requests) {
507
- if (!requests || requests.length === 0) return;
 
 
 
 
 
508
  const operations = [];
 
509
  for (const req of requests) {
510
  try {
511
- if (!req || !req.user_id) continue;
 
 
 
 
 
 
512
  const action = req.action || 'unknown';
 
513
  switch (action) {
514
  case 'signup':
 
515
  operations.push({
516
- action: 'signup', userId: req.user_id,
 
517
  user: {
518
  id: req.user_id,
519
  username: (req.data && req.data.username) || generateRandomUsername(),
@@ -522,79 +807,124 @@ if (!isMainThread) {
522
  email: (req.data && req.data.email) || `${req.user_id}@default.com`,
523
  country: (req.data && req.data.country) || '',
524
  location: (req.data && req.data.location) || '',
525
- created_at: new Date().toISOString(), is_login: 0, bio: '', pic_url: '',
526
- external_links: '[]', date_of_birth: '',
527
- total_times_profile_updated_today: 0, last_profile_updated: '',
 
 
 
 
 
528
  is_profile_public: 'true',
529
  fing_key: (req.data && req.data.fing_key) || generateFingKey()
530
  }
531
  });
532
  usersCache.set(req.user_id, operations[operations.length - 1].user);
533
  break;
 
534
  case 'login':
535
  operations.push({ action: 'login', userId: req.user_id });
536
  const loginUser = usersCache.get(req.user_id);
537
  if (loginUser) loginUser.is_login = 1;
538
  break;
 
539
  case 'logout':
540
  operations.push({ action: 'logout', userId: req.user_id });
541
  const logoutUser = usersCache.get(req.user_id);
542
  if (logoutUser) logoutUser.is_login = 0;
543
  break;
 
544
  case 'update_profile':
545
  const profileUser = usersCache.get(req.user_id);
546
  const updateData = req.data || {};
 
 
547
  if (profileUser) {
548
- const fields = ['name', 'email', 'country', 'location', 'bio', 'external_links', 'date_of_birth', 'is_profile_public'];
 
549
  for (const field of fields) {
550
  if (updateData[field] !== null && updateData[field] !== undefined && updateData[field] !== '') {
551
- profileUser[field] = typeof updateData[field] === 'string' ? updateData[field].trim() : String(updateData[field]).trim();
 
552
  }
553
  }
554
- profileUser.total_times_profile_updated_today = (profileUser.total_times_profile_updated_today || 0) + 1;
 
555
  profileUser.last_profile_updated = new Date().toISOString();
556
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
557
  operations.push({
558
- action: 'updateProfile', userId: req.user_id,
559
- data: {
560
- userId: req.user_id,
561
- name: updateData.name || (profileUser ? profileUser.name : generateRandomName()),
562
- email: updateData.email || (profileUser ? profileUser.email : `${req.user_id}@default.com`),
563
- country: updateData.country || (profileUser ? profileUser.country : ''),
564
- location: updateData.location || (profileUser ? profileUser.location : ''),
565
- bio: updateData.bio || (profileUser ? profileUser.bio : ''),
566
- external_links: updateData.external_links || (profileUser ? profileUser.external_links : '[]'),
567
- date_of_birth: updateData.date_of_birth || (profileUser ? profileUser.date_of_birth : ''),
568
- is_profile_public: updateData.is_profile_public || (profileUser ? profileUser.is_profile_public : 'true'),
569
- total_times_profile_updated_today: (profileUser ? profileUser.total_times_profile_updated_today : 0) || 0,
570
- last_profile_updated: (profileUser ? profileUser.last_profile_updated : new Date().toISOString())
571
- }
572
  });
573
  break;
 
574
  case 'upload_photo':
575
  if (req.pic_buffer) {
576
  try {
577
- const compressed = await compressToWebp(Buffer.from(req.pic_buffer, 'base64'), MAX_PHOTO_SIZE_KB);
 
 
 
578
  const filename = `${req.user_id}_${Math.floor(Date.now() / 1000)}.webp`;
579
- await fsp.writeFile(path.join(PHOTOS_DIR, filename), compressed.buffer);
 
 
580
  const photoUser = usersCache.get(req.user_id);
581
  if (photoUser) photoUser.pic_url = `/photos/${filename}`;
582
- operations.push({ action: 'updatePhoto', userId: req.user_id, picUrl: `/photos/${filename}` });
583
- } catch (photoError) {}
 
 
 
 
 
 
 
584
  }
585
  break;
 
586
  case 'forgot_password':
587
- const newHash = hashPassword((req.data && req.data.new_password) || 'default123');
 
588
  const passUser = usersCache.get(req.user_id);
589
  if (passUser) passUser.password_hash = newHash;
590
- operations.push({ action: 'updatePassword', userId: req.user_id, passwordHash: newHash });
 
 
 
 
 
591
  break;
 
 
 
592
  }
593
- } catch (reqError) {}
 
 
594
  }
 
595
  if (operations.length > 0) {
596
  try {
597
  await dbRequest('batchOperation', { operations });
 
598
  } catch (dbError) {
599
  console.error(`Main: DB batch operation failed:`, dbError.message);
600
  throw dbError;
@@ -602,10 +932,23 @@ if (!isMainThread) {
602
  }
603
  }
604
 
 
605
  function addRequest(userId, username, action, data, picBuffer = null) {
606
- if (!userId) userId = generateId();
607
- if (!action) action = 'unknown';
 
 
 
 
 
 
 
 
 
 
 
608
  const safeData = data || {};
 
609
  if (action === 'signup') {
610
  safeData.username = safeData.username || generateRandomUsername();
611
  safeData.password = safeData.password || 'default123';
@@ -613,38 +956,83 @@ if (!isMainThread) {
613
  safeData.email = safeData.email || `${userId}@default.com`;
614
  safeData.fing_key = safeData.fing_key || generateFingKey();
615
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
616
  const request = {
617
- id: generateId(), user_id: userId, username: username || 'unknown_user',
618
- action: action, data: safeData,
 
 
 
619
  pic_buffer: picBuffer ? picBuffer.toString('base64') : null,
620
- type: action, timestamp: Date.now()
 
621
  };
 
 
 
622
  batchBuffer.push(request);
 
623
  return request.id;
624
  }
625
 
626
  // ============ FASTIFY SETUP ============
627
  async function setupFastify() {
628
- await fastify.register(cors, { origin: '*', credentials: true, methods: ['*'], allowedHeaders: ['*'] });
629
- await fastify.register(multipart, { limits: { fileSize: 5 * 1024 * 1024 } });
630
- await fastify.register(fastifyStatic, { root: PHOTOS_DIR, prefix: '/photos/', decorateReply: false, maxAge: 86400000 });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
631
 
632
  fastify.addHook('onRequest', async (request, reply) => {
633
  const cpuUsage = getCurrentCPUPercentage();
634
  const totalUsers = getTotalUsers();
635
- if (cpuUsage >= 98 || totalUsers >= MAX_USERS || getBucketSize() >= MAX_BUCKET_SIZE || getMemoryUsage() >= MAX_RAM_USAGE) {
 
 
636
  await addSpaceToFull(CURRENT_SPACE_NAME);
637
  reply.status(503);
638
- return { error: 'space_full', message: 'Server at maximum capacity', retry_after: 1 };
 
639
  }
 
640
  if (!globalRateLimiter.isAllowed()) {
641
  await addSpaceToFull(CURRENT_SPACE_NAME);
642
  reply.status(503);
643
- return { error: 'space_full', message: 'Global rate limit reached', retry_after: 1 };
 
644
  }
 
645
  if (!rateLimiter.isAllowed(request.ip)) {
646
  reply.status(429);
647
- return { error: 'rate_limit_exceeded', message: 'Per-IP rate limit exceeded', retry_after: 1 };
 
648
  }
649
  });
650
 
@@ -652,11 +1040,11 @@ if (!isMainThread) {
652
  fastify.get('/', async (request, reply) => {
653
  const spaceFull = isSpaceFull();
654
  const fullSpaces = await getFullSpaces();
655
- const sizeSpaces = await getSizeSpaces();
656
  const emptySpaces = SPACE_NAMES.filter(s => !fullSpaces.includes(s));
657
  const cpuUsage = getCurrentCPUPercentage();
 
658
 
659
- return {
660
  message: 'Velost Auth API - Worker Threads',
661
  version: '15.0.0-THREADS',
662
  worker_pid: process.pid,
@@ -670,7 +1058,7 @@ if (!isMainThread) {
670
  current_global_rps: globalRateLimiter.getCurrentCount()
671
  },
672
  storage: {
673
- type: 'SQLite',
674
  max_ram_gb: 7,
675
  current_ram_mb: Math.round(getMemoryUsage() / (1024 * 1024) * 100) / 100,
676
  max_bucket_size: '60GB',
@@ -681,7 +1069,7 @@ if (!isMainThread) {
681
  processing: {
682
  buffer_size: batchBuffer.length,
683
  batch_size: BATCH_SIZE,
684
- processing: '1S_WINDOW_BATCH',
685
  cpu_usage_percent: cpuUsage.toFixed(1)
686
  },
687
  space_status: {
@@ -698,18 +1086,22 @@ if (!isMainThread) {
698
  },
699
  timestamp: new Date().toISOString()
700
  };
 
 
 
701
  });
702
 
703
  fastify.get('/status', async (request, reply) => {
704
  const spaceFull = isSpaceFull();
705
  await checkAndUpdateFullStatus();
706
  const fullSpaces = await getFullSpaces();
707
- const sizeSpaces = await getSizeSpaces();
708
  const emptySpaces = SPACE_NAMES.filter(s => !fullSpaces.includes(s));
 
709
  const cpuUsage = getCurrentCPUPercentage();
710
  const totalUsers = getTotalUsers();
711
 
712
- return {
 
713
  worker_pid: process.pid,
714
  architecture: '1 Process + 1 DB Thread',
715
  space: CURRENT_SPACE_NAME,
@@ -738,72 +1130,146 @@ if (!isMainThread) {
738
  empty_spaces: emptySpaces,
739
  size_spaces: sizeSpaces,
740
  timestamp: new Date().toISOString()
741
- };
742
  });
743
 
744
  fastify.get('/health', async (request, reply) => {
745
- return {
 
746
  status: 'healthy',
747
  architecture: '1 Process + 1 DB Thread',
748
  users: getTotalUsers(),
749
  global_rps: globalRateLimiter.getCurrentCount(),
750
  timestamp: new Date().toISOString()
751
- };
752
  });
753
 
754
  fastify.post('/signup', async (request, reply) => {
755
- if (getTotalUsers() >= MAX_USERS) { reply.status(507); return { detail: `Maximum users (${MAX_USERS}) reached.` }; }
756
- const { username, password, name, email, fing_key } = request.body || {};
757
- if (!username || !password || !name || !email) { reply.status(400); return { detail: 'Missing required fields' }; }
758
- const cleanUsername = username.trim().toLowerCase();
759
- const cleanEmail = email.trim().toLowerCase();
760
- if (cleanUsername.length < 3) { reply.status(400); return { detail: 'Username too short' }; }
761
- if (password.length < 6) { reply.status(400); return { detail: 'Password too short' }; }
762
- const existingUser = await getUserByUsername(cleanUsername);
763
- if (existingUser) { reply.status(409); return { detail: 'Username already exists' }; }
764
- for (const user of usersCache.values()) { if (user.email === cleanEmail) { reply.status(409); return { detail: 'Email already registered' }; } }
765
-
766
- const userId = generateId();
767
- const newUser = {
768
- id: userId, username: cleanUsername, password_hash: hashPassword(password),
769
- name: name.trim(), email: cleanEmail,
770
- country: request.body.country || '', location: request.body.location || '',
771
- created_at: new Date().toISOString(), is_login: 0, bio: '', pic_url: '',
772
- external_links: '[]', date_of_birth: request.body.date_of_birth || '',
773
- total_times_profile_updated_today: 0, last_profile_updated: '',
774
- is_profile_public: 'true', fing_key: fing_key ? fing_key.trim() : generateFingKey()
775
- };
776
-
777
- usersCache.set(userId, newUser);
778
-
779
- try {
780
- await dbRequest('insertUser', { user: newUser });
781
- } catch (dbError) {
782
- addRequest(userId, cleanUsername, 'signup', { username: cleanUsername, password, name: name.trim(), email: cleanEmail, fing_key: fing_key ? fing_key.trim() : '' });
783
- }
784
-
785
- return {
786
- success: true,
787
- message: 'Account created successfully',
788
- user_id: userId,
789
- id: userId,
790
- username: cleanUsername,
791
- name: name.trim(),
792
- email: cleanEmail,
793
- timestamp: new Date().toISOString()
794
- };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
795
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
796
 
797
  fastify.post('/login', async (request, reply) => {
798
  const { username, password } = request.body || {};
799
- if (!username || !password) { reply.status(400); return { detail: 'Missing username or password' }; }
 
 
 
 
 
800
  const cleanUsername = username.trim().toLowerCase();
801
  const user = await getUserByUsername(cleanUsername);
802
- if (!user) { reply.status(401); return { detail: 'Invalid credentials' }; }
803
- if (!verifyPassword(password, user.password_hash)) { reply.status(401); return { detail: 'Invalid credentials' }; }
 
 
 
 
 
 
 
 
 
804
  addRequest(user.id, cleanUsername, 'login', {});
805
- return {
 
 
806
  success: true,
 
807
  id: user.id,
808
  username: user.username,
809
  name: user.name,
@@ -821,110 +1287,250 @@ if (!isMainThread) {
821
  total_times_profile_updated_today: parseInt(safeGet(user.total_times_profile_updated_today, 0)),
822
  last_profile_updated: safeGet(user.last_profile_updated),
823
  timestamp: new Date().toISOString()
824
- };
825
  });
826
 
827
  fastify.post('/logout', async (request, reply) => {
828
  const { id } = request.body || {};
829
- if (!id) { reply.status(400); return { detail: 'Missing user ID' }; }
 
 
 
 
 
830
  const user = await getUser(id);
831
- if (!user) { reply.status(404); return { detail: 'User not found' }; }
 
 
 
 
832
  addRequest(id, '', 'logout', {});
833
- return { success: true, message: 'Logged out successfully', timestamp: new Date().toISOString() };
 
 
 
 
 
 
834
  });
835
 
836
  fastify.put('/updateprofiledetails', async (request, reply) => {
837
  const { id, ...data } = request.body || {};
838
- if (!id) { reply.status(400); return { detail: 'Missing user ID' }; }
 
 
 
 
 
839
  const user = await getUser(id);
840
- if (!user) { reply.status(404); return { detail: 'User not found' }; }
 
 
 
 
841
  if (data.external_links !== null && data.external_links !== undefined) {
842
  const { valid, error } = validateExternalLinks(data.external_links);
843
- if (!valid) { reply.status(400); return { detail: error }; }
 
 
 
 
 
 
 
 
 
 
 
 
 
844
  }
 
 
845
  addRequest(id, '', 'update_profile', data);
846
- return { success: true, message: 'Profile update processed', timestamp: new Date().toISOString() };
 
 
 
 
 
 
847
  });
848
 
849
  fastify.post('/uploadphoto', async (request, reply) => {
850
- if (getBucketSize() >= MAX_BUCKET_SIZE) { reply.status(507); return { detail: 'Storage full.' }; }
 
 
 
 
851
  try {
852
  const data = await request.file();
853
- if (!data) { reply.status(400); return { detail: 'No file uploaded' }; }
854
- if (!data.mimetype.startsWith('image/')) { reply.status(400); return { detail: 'File must be an image' }; }
 
 
 
 
 
 
 
 
855
  const fileBuffer = await data.toBuffer();
856
- const id = (data.fields && data.fields.id) ? data.fields.id.value : (request.query ? request.query.id : null);
857
- if (!id) { reply.status(400); return { detail: 'Missing user ID' }; }
 
 
 
 
 
 
858
  const user = await getUser(id);
859
- if (!user) { reply.status(404); return { detail: 'User not found' }; }
860
- addRequest(id, '', 'upload_photo', { original_size_kb: fileBuffer.length / 1024 }, fileBuffer);
861
- return { success: true, message: 'Photo upload queued', format: 'webp', max_size_kb: MAX_PHOTO_SIZE_KB, timestamp: new Date().toISOString() };
862
- } catch (e) { reply.status(500); return { detail: 'Upload failed' }; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
863
  });
864
 
865
  fastify.get('/getuser', async (request, reply) => {
866
- const { id, username } = request.query || {};
867
-
868
- if (username) {
869
- const user = await getUserByUsername(username);
870
- if (!user) { reply.status(404); return { detail: 'User not found' }; }
871
- return {
872
- id: user.id, username: user.username, name: user.name, email: safeGet(user.email),
873
- country: safeGet(user.country), location: safeGet(user.location), created_at: safeGet(user.created_at),
874
- is_login: Boolean(safeGet(user.is_login, false)), bio: safeGet(user.bio), pic_url: safeGet(user.pic_url),
875
- external_links: safeGet(user.external_links, '[]'), date_of_birth: safeGet(user.date_of_birth),
876
- is_profile_public: safeGet(user.is_profile_public, 'true'), fing_key: safeGet(user.fing_key, ''),
877
- total_times_profile_updated_today: parseInt(safeGet(user.total_times_profile_updated_today, 0)),
878
- last_profile_updated: safeGet(user.last_profile_updated)
879
- };
880
- }
881
-
882
- if (id) {
883
- let user = usersCache.get(id);
884
- if (!user) {
885
- for (const item of batchBuffer) {
886
- if (item.user_id === id && item.action === 'signup') {
887
- user = {
888
- id, username: item.data.username || '', name: item.data.name || '',
889
- email: item.data.email || '', country: '', location: '',
890
- created_at: new Date().toISOString(), is_login: 0, bio: '', pic_url: '',
891
- external_links: '[]', date_of_birth: '',
892
- is_profile_public: 'true', fing_key: item.data.fing_key || '',
893
- total_times_profile_updated_today: 0, last_profile_updated: ''
894
- };
895
- break;
896
- }
897
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
898
  }
899
- if (!user) user = await getUser(id);
900
- if (!user) { reply.status(404); return { detail: 'User not found' }; }
901
- return {
902
- id: user.id, username: user.username, name: user.name, email: safeGet(user.email),
903
- country: safeGet(user.country), location: safeGet(user.location), created_at: safeGet(user.created_at),
904
- is_login: Boolean(safeGet(user.is_login, false)), bio: safeGet(user.bio), pic_url: safeGet(user.pic_url),
905
- external_links: safeGet(user.external_links, '[]'), date_of_birth: safeGet(user.date_of_birth),
906
- is_profile_public: safeGet(user.is_profile_public, 'true'), fing_key: safeGet(user.fing_key, ''),
907
- total_times_profile_updated_today: parseInt(safeGet(user.total_times_profile_updated_today, 0)),
908
- last_profile_updated: safeGet(user.last_profile_updated)
909
- };
910
- }
911
-
912
- reply.status(400);
913
- return { detail: 'Missing id or username parameter' };
914
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
915
 
916
  fastify.get('/users/count', async (request, reply) => {
917
- return { count: getTotalUsers() };
 
 
 
918
  });
919
 
920
  fastify.get('/users', async (request, reply) => {
921
- if (usersCache.size === 0) return { users: [], total: 0 };
 
 
 
 
922
  const stream = new Readable({
923
  read() {
924
  this.push(toJsonl({ total: usersCache.size }));
925
  for (const user of usersCache.values()) {
926
  this.push(toJsonl({
927
- id: user.id, username: user.username, name: user.name,
 
 
928
  email: safeGet(user.email),
929
  is_login: Boolean(safeGet(user.is_login, false)),
930
  pic_url: safeGet(user.pic_url)
@@ -933,60 +1539,146 @@ if (!isMainThread) {
933
  this.push(null);
934
  }
935
  });
 
 
936
  return stream;
937
  });
938
 
939
  fastify.get('/spaces', async (request, reply) => {
940
  const fullSpaces = await getFullSpaces();
941
- const sizeSpaces = await getSizeSpaces();
942
  const emptySpaces = SPACE_NAMES.filter(s => !fullSpaces.includes(s));
943
- return {
 
 
 
944
  all_spaces: SPACE_NAMES,
945
  full_spaces: fullSpaces,
946
  empty_spaces: emptySpaces,
947
  size_spaces: sizeSpaces,
948
  current_space: CURRENT_SPACE_NAME
949
- };
950
  });
951
 
952
  fastify.post('/forgotpassword', async (request, reply) => {
953
  const { username, email, fing_key, new_password } = request.body || {};
954
- if (!username || !email || !fing_key || !new_password) { reply.status(400); return { detail: 'Missing required fields' }; }
 
 
 
 
 
955
  const cleanUsername = username.trim().toLowerCase();
 
 
 
956
  const user = await getUserByUsername(cleanUsername);
957
- if (!user) { reply.status(404); return { detail: 'No account found' }; }
958
- if (safeGet(user.email, '').toLowerCase() !== email.trim().toLowerCase()) { reply.status(401); return { detail: 'Email does not match' }; }
959
- if (safeGet(user.fing_key, '') !== fing_key.trim()) { reply.status(401); return { detail: 'Fingerprint key does not match' }; }
960
- if (new_password.length < 6) { reply.status(400); return { detail: 'Password too short' }; }
961
- if (verifyPassword(new_password, user.password_hash)) { reply.status(400); return { detail: 'New password must be different' }; }
962
- addRequest(user.id, cleanUsername, 'forgot_password', { new_password });
963
- return { success: true, message: 'Password reset processed', timestamp: new Date().toISOString() };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
964
  });
965
 
966
  return fastify;
967
  }
968
-
969
  async function start() {
970
  try {
971
  console.log(`Main: Starting with 1 Fastify process + 1 DB Worker Thread (2 cores)`);
 
972
  await initDBWorker();
 
 
 
 
 
 
 
 
 
 
 
 
973
  console.log(`Main: Loading users into memory...`);
974
  await loadUsersToMemory();
 
975
  await checkAndUpdateFullStatus();
976
  await setupFastify();
977
- scheduleBatchProcess();
978
- setInterval(async () => { await checkAndUpdateFullStatus(); }, 5000);
 
 
 
 
 
 
979
  const port = process.env.PORT || 7860;
980
  await fastify.listen({ port, host: '0.0.0.0' });
981
- console.log(`Main: Server running on port ${port}`);
982
- console.log(`Main: Users loaded: ${getTotalUsers()}`);
983
- console.log(`Main: Batch: 1s window, max ${BATCH_SIZE}/batch`);
984
- console.log(`Main: Max Users: ${MAX_USERS}`);
985
- } catch (err) { console.error(`Main: Error during startup:`, err); process.exit(1); }
 
 
 
 
 
 
 
 
986
  }
987
 
988
- process.on('SIGTERM', async () => { await fastify.close(); if (dbWorker) await dbWorker.terminate(); process.exit(0); });
989
- process.on('SIGINT', async () => { await fastify.close(); if (dbWorker) await dbWorker.terminate(); process.exit(0); });
 
 
 
 
 
 
990
 
991
- start().catch(err => { console.error(`Main: Failed to start:`, err); process.exit(1); });
992
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
  // ============ DATABASE WORKER THREAD ============
6
  if (!isMainThread) {
7
+ // This runs in the worker thread for database operations
8
  const Database = require('better-sqlite3');
9
  const path = require('path');
10
  const fs = require('fs');
 
13
  const DATA_DIR = workerData.dataDir || "/data";
14
  const dbPath = path.join(DATA_DIR, 'users.db');
15
 
16
+ // Initialize SQLite with WAL mode
17
  const db = new Database(dbPath);
18
  db.pragma('journal_mode = WAL');
19
  db.pragma('synchronous = NORMAL');
20
  db.pragma('cache_size = -2000000');
21
  db.pragma('temp_store = MEMORY');
22
 
23
+ // Create tables
24
  db.exec(`
25
  CREATE TABLE IF NOT EXISTS users (
26
  id TEXT PRIMARY KEY,
 
48
  CREATE INDEX IF NOT EXISTS idx_email ON users(email);
49
  `);
50
 
51
+ // Prepared statements
52
  const stmts = {
53
  getAllUsers: db.prepare('SELECT * FROM users'),
54
  getUserById: db.prepare('SELECT * FROM users WHERE id = ?'),
 
83
  updatePassword: db.prepare('UPDATE users SET password_hash = ? WHERE id = ?')
84
  };
85
 
86
+ // Handle messages from main thread
87
+ parentPort.on('message', async (message) => {
88
+ const { id, action, data } = message;
 
 
 
 
89
 
90
+ try {
91
+ let result;
 
 
 
 
 
92
 
93
+ switch (action) {
94
+ case 'getAllUsers':
95
+ result = stmts.getAllUsers.all();
96
+ break;
97
+
98
+ case 'getUserById':
99
+ result = stmts.getUserById.get(data.userId);
100
+ break;
101
+
102
+ case 'getUserByUsername':
103
+ result = stmts.getUserByUsername.get(data.username);
104
+ break;
105
+
106
+ case 'insertUser':
107
+ stmts.insertUser.run(data.user);
108
+ result = { success: true };
109
+ break;
110
+
111
+ case 'updateLogin':
112
+ stmts.updateLogin.run(data.isLogin ? 1 : 0, data.userId);
113
+ result = { success: true };
114
+ break;
115
+
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
+ });
130
+ result = { success: true };
131
+ break;
132
+
133
+ case 'updatePhoto':
134
+ stmts.updatePhoto.run(data.picUrl, data.userId);
135
+ result = { success: true };
136
+ break;
137
+
138
+ case 'updatePassword':
139
+ stmts.updatePassword.run(data.passwordHash, data.userId);
140
+ result = { success: true };
141
+ break;
142
+
143
+ case 'batchOperation':
144
+ result = await processBatch(data.operations);
145
+ break;
146
+
147
+ case 'getCount':
148
+ result = stmts.getAllUsers.all().length;
149
+ break;
150
+
151
+ default:
152
+ throw new Error(`Unknown action: ${action}`);
153
  }
154
 
155
+ parentPort.postMessage({ id, success: true, result });
156
+ } catch (error) {
157
+ parentPort.postMessage({ id, success: false, error: error.message });
158
+ }
159
+ });
160
+
161
+ async function processBatch(operations) {
162
+ const transaction = db.transaction(() => {
163
+ for (const op of operations) {
164
+ switch (op.action) {
165
+ case 'signup':
166
+ stmts.insertUser.run(op.user);
 
 
167
  break;
168
+ case 'login':
169
+ stmts.updateLogin.run(1, op.userId);
 
170
  break;
171
+ case 'logout':
172
+ stmts.updateLogin.run(0, op.userId);
 
173
  break;
174
  case 'updateProfile':
175
+ stmts.updateProfile.run(op.data);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
  break;
177
  case 'updatePassword':
178
+ stmts.updatePassword.run(op.passwordHash, op.userId);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
179
  break;
180
+ case 'updatePhoto':
181
+ stmts.updatePhoto.run(op.picUrl, op.userId);
182
  break;
 
 
183
  }
 
 
 
 
184
  }
185
+ });
186
 
187
+ transaction();
188
+ return { processed: operations.length };
189
  }
190
 
 
 
 
 
 
191
  console.log(`DB Worker Thread: SQLite initialized at ${dbPath}`);
192
 
193
  } else {
 
209
  const path = require('path');
210
  const { Readable } = require('stream');
211
 
212
+ // Dynamic imports
213
+ let Redis, sharp;
214
+ try {
215
+ Redis = require('ioredis');
216
+ } catch (e) {
217
+ console.log(`Main: ioredis not available:`, e.message);
218
+ }
219
+ try {
220
+ sharp = require('sharp');
221
+ } catch (e) {
222
+ console.log(`Main: Sharp not available, image compression disabled`);
223
+ }
224
 
225
+ // ============ CONSTANTS ============
226
  const MAX_BUCKET_SIZE = 60 * 1024 * 1024 * 1024;
227
  const MAX_USERS = 15000;
228
  const MAX_USERS_SIZE_LIMIT = 15000;
229
  const MAX_RAM_USAGE = 7 * 1024 * 1024 * 1024;
230
  const MAX_PROFILE_UPDATES_PER_DAY = Infinity;
231
  const MAX_PHOTO_SIZE_KB = 5;
232
+ const MAX_FING_KEY_LENGTH = 64;
233
  const MAX_EXTERNAL_LINKS = 3;
234
+ const MAX_USERNAME_LENGTH = 200;
235
+ const MAX_NAME_LENGTH = 200;
236
+ const MAX_PASSWORD_LENGTH = 200;
237
+ const MAX_BIO_LENGTH = 1000;
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
 
247
+ // ============ DIRECTORIES ============
248
  const DATA_DIR = process.env.DATA_DIR || "/data";
249
  const PHOTOS_DIR = path.join(DATA_DIR, "photos");
250
  const STATUS_DIR = process.env.STATUS_DIR || "/status";
 
252
  const SIZE_FILE = path.join(STATUS_DIR, "size.txt");
253
 
254
  [DATA_DIR, PHOTOS_DIR, STATUS_DIR].forEach(dir => {
255
+ try {
256
+ if (!fs.existsSync(dir)) {
257
+ fs.mkdirSync(dir, { recursive: true });
258
+ }
259
+ } catch (e) {
260
+ console.error(`Main: Error creating directory ${dir}:`, e.message);
261
+ }
262
  });
263
 
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
+ }
270
 
271
+ // ============ DATABASE WORKER THREAD ============
272
+ let dbWorker;
273
+ let dbRequestId = 0;
274
  const dbPromises = new Map();
275
 
276
  function initDBWorker() {
277
  return new Promise((resolve, reject) => {
278
+ dbWorker = new ThreadWorker(__filename, {
279
+ workerData: { dataDir: DATA_DIR }
280
+ });
281
+
282
  dbWorker.on('message', (message) => {
283
  const { id, success, result, error } = message;
284
  const promise = dbPromises.get(id);
285
  if (promise) {
286
  dbPromises.delete(id);
287
+ if (success) {
288
+ promise.resolve(result);
289
+ } else {
290
+ promise.reject(new Error(error));
291
+ }
292
  }
293
  });
294
+
295
  dbWorker.on('error', reject);
296
+ dbWorker.on('online', () => {
297
+ console.log(`Main: DB Worker Thread online`);
298
+ resolve();
299
+ });
300
  });
301
  }
302
 
 
308
  });
309
  }
310
 
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 ============
346
  let usersCache = new Map();
347
  let batchBuffer = [];
348
+ let batchTimer = null;
349
  let processingLock = false;
350
 
351
+ // ============ RATE LIMITERS ============
352
  class GlobalRateLimiter {
353
  constructor(maxRequests = 15000, window = 1) {
354
+ this.maxRequests = maxRequests;
355
+ this.window = window;
356
+ this.requests = [];
357
  }
358
+
359
  isAllowed() {
360
  const now = Date.now() / 1000;
361
  this.requests = this.requests.filter(t => now - t < this.window);
362
  if (this.requests.length >= this.maxRequests) return false;
363
+ this.requests.push(now);
364
+ return true;
365
  }
366
+
367
  getCurrentCount() {
368
  const now = Date.now() / 1000;
369
  this.requests = this.requests.filter(t => now - t < this.window);
 
373
 
374
  class RateLimiter {
375
  constructor(maxRequests = 15000, window = 1) {
376
+ this.maxRequests = maxRequests;
377
+ this.window = window;
378
+ this.requests = new Map();
379
  }
380
+
381
  isAllowed(clientIp) {
382
  const now = Date.now() / 1000;
383
+ if (!this.requests.has(clientIp)) {
384
+ this.requests.set(clientIp, []);
385
+ }
386
  const clientRequests = this.requests.get(clientIp);
387
  const filtered = clientRequests.filter(t => now - t < this.window);
388
  this.requests.set(clientIp, filtered);
389
  if (filtered.length >= this.maxRequests) return false;
390
+ filtered.push(now);
391
+ return true;
392
  }
393
  }
394
 
395
  const globalRateLimiter = new GlobalRateLimiter(15000, 1);
396
  const rateLimiter = new RateLimiter(15000, 1);
397
 
398
+ // ============ UTILITY FUNCTIONS ============
399
+ function getMemoryUsage() {
400
+ return process.memoryUsage().rss;
401
+ }
402
 
403
  let lastCPUUsage = process.cpuUsage();
404
  let lastCPUCheck = Date.now();
 
410
  lastCPUUsage = process.cpuUsage();
411
  lastCPUCheck = currentTime;
412
  if (elapsedMS === 0) return 0;
413
+ const usagePercent = ((currentCPUUsage.user + currentCPUUsage.system) / 1000) / elapsedMS * 100;
414
+ return Math.min(100, usagePercent);
415
  }
416
 
417
  function safeGet(value, defaultValue = "") {
 
423
  function generateId() {
424
  const buffer = Buffer.alloc(16);
425
  const [seconds, nanoseconds] = process.hrtime();
426
+ const picoseconds = (seconds * 1e12) + (nanoseconds * 1000);
427
+ buffer.writeBigInt64BE(BigInt(Math.floor(picoseconds / 1000)));
428
  crypto.randomFillSync(buffer, 6, 10);
429
  buffer[15] = buffer[15] & 0xF8;
430
  return buffer.toString('base64url').substring(0, 21);
 
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"];
448
+ let size = bytesSize;
449
+ let unitIndex = 0;
450
+ while (size >= 1024 && unitIndex < units.length - 1) {
451
+ size /= 1024;
452
+ unitIndex++;
453
+ }
454
  return `${size.toFixed(2)} ${units[unitIndex]}`;
455
  }
456
 
457
+ function toJsonl(data) {
458
+ return JSON.stringify(data) + "\n";
459
+ }
460
 
461
  function hashPassword(password) {
462
  return crypto.createHash('sha256').update(HASH + password + HASH).digest('hex');
463
  }
464
 
465
+ function verifyPassword(password, hash) {
466
+ return hashPassword(password) === hash;
467
+ }
468
 
469
  function validateExternalLinks(linksStr) {
470
  if (!linksStr) return { valid: true, error: null };
 
473
  if (!Array.isArray(links)) return { valid: false, error: "External links must be a JSON array" };
474
  if (links.length > MAX_EXTERNAL_LINKS) return { valid: false, error: `Maximum ${MAX_EXTERNAL_LINKS} external links allowed` };
475
  return { valid: true, error: null };
476
+ } catch (e) {
477
+ return { valid: false, error: "Invalid JSON format for external links" };
478
+ }
479
  }
480
 
481
+ // ============ FULL.TXT MANAGEMENT ============
482
  let lastFullStatus = false;
483
 
484
  async function getFullSpaces() {
485
+ try {
486
+ const content = await fsp.readFile(FULL_FILE, 'utf8');
487
+ return content.trim() ? content.trim().split('|') : [];
488
+ } catch (e) {
489
+ return [];
490
+ }
491
  }
492
+
493
  async function addSpaceToFull(spacename) {
494
  try {
495
+ let content = await fsp.readFile(FULL_FILE, 'utf8');
496
+ content = content.trim();
497
  let spaces = content ? content.split('|') : [];
498
+ if (!spaces.includes(spacename)) {
499
+ spaces.push(spacename);
500
+ await fsp.writeFile(FULL_FILE, spaces.join('|'), 'utf8');
501
+ }
502
+ } catch (e) {
503
+ console.error(`Main: Error updating full.txt:`, e.message);
504
+ }
505
  }
506
+
507
  async function removeSpaceFromFull(spacename) {
508
  try {
509
+ let content = await fsp.readFile(FULL_FILE, 'utf8');
510
+ content = content.trim();
511
  let spaces = content ? content.split('|') : [];
512
  spaces = spaces.filter(s => s !== spacename);
513
  await fsp.writeFile(FULL_FILE, spaces.join('|'), 'utf8');
514
+ } catch (e) {
515
+ console.error(`Main: Error removing space from full:`, e.message);
516
+ }
517
  }
518
+
519
  async function getSizeSpaces() {
520
+ try {
521
+ const content = await fsp.readFile(SIZE_FILE, 'utf8');
522
+ return content.trim() ? content.trim().split('|') : [];
523
+ } catch (e) {
524
+ return [];
525
+ }
526
  }
527
+
528
  async function addSpaceToSize(spacename) {
529
  try {
530
+ let content = await fsp.readFile(SIZE_FILE, 'utf8');
531
+ content = content.trim();
532
  let spaces = content ? content.split('|') : [];
533
+ if (!spaces.includes(spacename)) {
534
+ spaces.push(spacename);
535
+ await fsp.writeFile(SIZE_FILE, spaces.join('|'), 'utf8');
536
+ }
537
+ } catch (e) {
538
+ console.error(`Main: Error updating size.txt:`, e.message);
539
+ }
540
  }
541
 
542
  async function checkAndUpdateFullStatus() {
 
545
  const totalUsers = getTotalUsers();
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;
557
+ if (isFull) {
558
+ await addSpaceToFull(CURRENT_SPACE_NAME);
559
+ } else {
560
+ await removeSpaceFromFull(CURRENT_SPACE_NAME);
561
+ }
562
+ }
563
+
564
+ if (totalUsers >= MAX_USERS_SIZE_LIMIT) {
565
+ await addSpaceToSize(CURRENT_SPACE_NAME);
566
  }
 
567
  }
568
 
569
+ // ============ IMAGE COMPRESSION ============
570
  async function compressToWebp(fileData, maxSizeKb = 20) {
571
  if (!sharp) return { buffer: fileData, isWebp: false, sizeKb: fileData.length / 1024 };
572
+
573
  try {
574
  let image = sharp(fileData);
575
  const metadata = await image.metadata();
576
  const currentSizeKb = fileData.length / 1024;
577
+
578
+ if (metadata.format === 'webp' && currentSizeKb <= maxSizeKb) {
579
+ return { buffer: fileData, isWebp: true, sizeKb: currentSizeKb, wasCompressed: false };
580
+ }
581
+
582
+ let quality = 80;
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
+ }
611
  }
612
 
613
+ // ============ DATA MANAGEMENT (through DB Worker) ============
614
  async function loadUsersToMemory() {
615
  try {
616
  const users = await dbRequest('getAllUsers');
617
  usersCache.clear();
618
+ for (const user of users) {
619
+ usersCache.set(user.id, user);
620
+ }
621
  console.log(`Main: Loaded ${users.length} users into memory`);
622
+ } catch (e) {
623
+ console.error(`Main: Error loading users:`, e.message);
624
+ }
625
  }
626
 
627
  async function getUser(userId) {
 
630
  const user = await dbRequest('getUserById', { userId });
631
  if (user) usersCache.set(userId, user);
632
  return user;
633
+ } catch (e) {
634
+ return null;
635
+ }
636
  }
637
 
638
  async function getUserByUsername(username) {
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);
645
  return user;
646
+ } catch (e) {
647
+ return null;
648
+ }
649
  }
650
 
651
+ function getTotalUsers() {
652
+ return usersCache.size;
653
+ }
654
 
655
  function getBucketSize() {
656
  let totalSize = 0;
 
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;
740
+
741
+ const chunks = [];
742
+ for (let i = 0; i < keys.length; i += BATCH_SIZE) {
743
+ chunks.push(keys.slice(i, i + BATCH_SIZE));
744
+ }
745
+
746
+ for (const chunk of chunks) {
747
+ const pipeline = redis.pipeline();
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));
768
+ await deletePipeline.exec();
769
  }
770
+ } catch (e) {
771
+ console.error(`Main: Redis processing error:`, e.message);
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(),
 
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;
 
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';
 
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;
991
  }
992
 
993
  // ============ FASTIFY SETUP ============
994
  async function setupFastify() {
995
+ await fastify.register(cors, {
996
+ origin: '*',
997
+ credentials: true,
998
+ methods: ['*'],
999
+ allowedHeaders: ['*']
1000
+ });
1001
+
1002
+ await fastify.register(multipart, {
1003
+ limits: { fileSize: 5 * 1024 * 1024 }
1004
+ });
1005
+
1006
+ await fastify.register(fastifyStatic, {
1007
+ root: PHOTOS_DIR,
1008
+ prefix: '/photos/',
1009
+ decorateReply: false,
1010
+ maxAge: 86400000
1011
+ });
1012
 
1013
  fastify.addHook('onRequest', async (request, reply) => {
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
  });
1038
 
 
1040
  fastify.get('/', async (request, reply) => {
1041
  const spaceFull = isSpaceFull();
1042
  const fullSpaces = await getFullSpaces();
 
1043
  const emptySpaces = SPACE_NAMES.filter(s => !fullSpaces.includes(s));
1044
  const cpuUsage = getCurrentCPUPercentage();
1045
+ const sizeSpaces = await getSizeSpaces();
1046
 
1047
+ const responseData = {
1048
  message: 'Velost Auth API - Worker Threads',
1049
  version: '15.0.0-THREADS',
1050
  worker_pid: process.pid,
 
1058
  current_global_rps: globalRateLimiter.getCurrentCount()
1059
  },
1060
  storage: {
1061
+ type: redis ? 'SQLite + Redis Buffer' : 'SQLite',
1062
  max_ram_gb: 7,
1063
  current_ram_mb: Math.round(getMemoryUsage() / (1024 * 1024) * 100) / 100,
1064
  max_bucket_size: '60GB',
 
1069
  processing: {
1070
  buffer_size: batchBuffer.length,
1071
  batch_size: BATCH_SIZE,
1072
+ processing: 'WORKER_THREAD_BATCH',
1073
  cpu_usage_percent: cpuUsage.toFixed(1)
1074
  },
1075
  space_status: {
 
1086
  },
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();
1097
  const fullSpaces = await getFullSpaces();
 
1098
  const emptySpaces = SPACE_NAMES.filter(s => !fullSpaces.includes(s));
1099
+ const sizeSpaces = await getSizeSpaces();
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',
1107
  space: CURRENT_SPACE_NAME,
 
1130
  empty_spaces: emptySpaces,
1131
  size_spaces: sizeSpaces,
1132
  timestamp: new Date().toISOString()
1133
+ });
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',
1141
  users: getTotalUsers(),
1142
  global_rps: globalRateLimiter.getCurrentCount(),
1143
  timestamp: new Date().toISOString()
1144
+ });
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 || {};
1248
+
1249
+ if (!username || !password) {
1250
+ reply.status(400);
1251
+ return { detail: 'Missing username or password' };
1252
+ }
1253
+
1254
  const cleanUsername = username.trim().toLowerCase();
1255
  const user = await getUserByUsername(cleanUsername);
1256
+
1257
+ if (!user) {
1258
+ reply.status(401);
1259
+ return { detail: 'Invalid credentials' };
1260
+ }
1261
+
1262
+ if (!verifyPassword(password, user.password_hash)) {
1263
+ reply.status(401);
1264
+ return { detail: 'Invalid credentials' };
1265
+ }
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,
1273
  id: user.id,
1274
  username: user.username,
1275
  name: user.name,
 
1287
  total_times_profile_updated_today: parseInt(safeGet(user.total_times_profile_updated_today, 0)),
1288
  last_profile_updated: safeGet(user.last_profile_updated),
1289
  timestamp: new Date().toISOString()
1290
+ });
1291
  });
1292
 
1293
  fastify.post('/logout', async (request, reply) => {
1294
  const { id } = request.body || {};
1295
+
1296
+ if (!id) {
1297
+ reply.status(400);
1298
+ return { detail: 'Missing user ID' };
1299
+ }
1300
+
1301
  const user = await getUser(id);
1302
+ if (!user) {
1303
+ reply.status(404);
1304
+ return { detail: 'User not found' };
1305
+ }
1306
+
1307
  addRequest(id, '', 'logout', {});
1308
+
1309
+ reply.header('Content-Type', 'application/json');
1310
+ return toJsonl({
1311
+ success: true,
1312
+ message: 'Logged out successfully',
1313
+ timestamp: new Date().toISOString()
1314
+ });
1315
  });
1316
 
1317
  fastify.put('/updateprofiledetails', async (request, reply) => {
1318
  const { id, ...data } = request.body || {};
1319
+
1320
+ if (!id) {
1321
+ reply.status(400);
1322
+ return { detail: 'Missing user ID' };
1323
+ }
1324
+
1325
  const user = await getUser(id);
1326
+ if (!user) {
1327
+ reply.status(404);
1328
+ return { detail: 'User not found' };
1329
+ }
1330
+
1331
  if (data.external_links !== null && data.external_links !== undefined) {
1332
  const { valid, error } = validateExternalLinks(data.external_links);
1333
+ if (!valid) {
1334
+ reply.status(400);
1335
+ return { detail: error };
1336
+ }
1337
+ }
1338
+
1339
+ const today = new Date().toISOString().split('T')[0];
1340
+ const lastUpdated = safeGet(user.last_profile_updated, '');
1341
+ const lastUpdatedDate = lastUpdated ? lastUpdated.substring(0, 10) : '';
1342
+ const currentUpdatesToday = parseInt(safeGet(user.total_times_profile_updated_today, 0));
1343
+
1344
+ if (lastUpdatedDate === today && currentUpdatesToday >= MAX_PROFILE_UPDATES_PER_DAY) {
1345
+ reply.status(429);
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',
1356
+ timestamp: new Date().toISOString()
1357
+ });
1358
  });
1359
 
1360
  fastify.post('/uploadphoto', async (request, reply) => {
1361
+ if (getBucketSize() >= MAX_BUCKET_SIZE) {
1362
+ reply.status(507);
1363
+ return { detail: 'Storage full. Maximum bucket size of 60GB reached.' };
1364
+ }
1365
+
1366
  try {
1367
  const data = await request.file();
1368
+ if (!data) {
1369
+ reply.status(400);
1370
+ return { detail: 'No file uploaded' };
1371
+ }
1372
+
1373
+ if (!data.mimetype.startsWith('image/')) {
1374
+ reply.status(400);
1375
+ return { detail: 'File must be an image' };
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);
1384
+ return { detail: 'Missing user ID' };
1385
+ }
1386
+
1387
  const user = await getUser(id);
1388
+ if (!user) {
1389
+ reply.status(404);
1390
+ return { detail: 'User not found' };
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',
1403
+ original_size_kb: Math.round(originalSizeKb * 100) / 100,
1404
+ format: 'webp',
1405
+ max_size_kb: MAX_PHOTO_SIZE_KB,
1406
+ timestamp: new Date().toISOString()
1407
+ });
1408
+ } catch (e) {
1409
+ console.error(`Main: Upload error:`, e);
1410
+ reply.status(500);
1411
+ return { detail: 'Upload failed' };
1412
+ }
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
+
1526
  const stream = new Readable({
1527
  read() {
1528
  this.push(toJsonl({ total: usersCache.size }));
1529
  for (const user of usersCache.values()) {
1530
  this.push(toJsonl({
1531
+ id: user.id,
1532
+ username: user.username,
1533
+ name: user.name,
1534
  email: safeGet(user.email),
1535
  is_login: Boolean(safeGet(user.is_login, false)),
1536
  pic_url: safeGet(user.pic_url)
 
1539
  this.push(null);
1540
  }
1541
  });
1542
+
1543
+ reply.header('Content-Type', 'application/json');
1544
  return stream;
1545
  });
1546
 
1547
  fastify.get('/spaces', async (request, reply) => {
1548
  const fullSpaces = await getFullSpaces();
 
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,
1556
  empty_spaces: emptySpaces,
1557
  size_spaces: sizeSpaces,
1558
  current_space: CURRENT_SPACE_NAME
1559
+ });
1560
  });
1561
 
1562
  fastify.post('/forgotpassword', async (request, reply) => {
1563
  const { username, email, fing_key, new_password } = request.body || {};
1564
+
1565
+ if (!username || !email || !fing_key || !new_password) {
1566
+ reply.status(400);
1567
+ return { detail: 'Missing required fields' };
1568
+ }
1569
+
1570
  const cleanUsername = username.trim().toLowerCase();
1571
+ const cleanEmail = email.trim().toLowerCase();
1572
+ const cleanFingKey = fing_key.trim();
1573
+
1574
  const user = await getUserByUsername(cleanUsername);
1575
+ if (!user) {
1576
+ reply.status(404);
1577
+ return { detail: 'No account found' };
1578
+ }
1579
+
1580
+ if (safeGet(user.email, '').toLowerCase() !== cleanEmail) {
1581
+ reply.status(401);
1582
+ return { detail: 'Email does not match' };
1583
+ }
1584
+
1585
+ if (safeGet(user.fing_key, '') !== cleanFingKey) {
1586
+ reply.status(401);
1587
+ return { detail: 'Fingerprint key does not match' };
1588
+ }
1589
+
1590
+ if (new_password.length < 6) {
1591
+ reply.status(400);
1592
+ return { detail: 'Password too short' };
1593
+ }
1594
+
1595
+ if (verifyPassword(new_password, user.password_hash)) {
1596
+ reply.status(400);
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',
1608
+ timestamp: new Date().toISOString()
1609
+ });
1610
  });
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) {
1622
+ try {
1623
+ await redis.connect();
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
+ }
1631
+
1632
  console.log(`Main: Loading users into memory...`);
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
+
1645
  const port = process.env.PORT || 7860;
1646
  await fastify.listen({ port, host: '0.0.0.0' });
1647
+
1648
+ console.log(`Main: πŸš€ Server running on port ${port}`);
1649
+ console.log(`Main: πŸ“Š Users loaded: ${getTotalUsers()}`);
1650
+ console.log(`Main: πŸ’Ύ Storage: SQLite at /data/users.db (via Worker Thread)`);
1651
+ console.log(`Main: πŸ—οΈ Architecture: 1 Fastify Process + 1 DB Worker Thread = 2 Cores`);
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();
1665
+ if (redis) await redis.quit();
1666
+ await fastify.close();
1667
+ if (dbWorker) await dbWorker.terminate();
1668
+ process.exit(0);
1669
+ });
1670
 
1671
+ process.on('SIGINT', async () => {
1672
+ console.log(`Main: Shutting down...`);
1673
+ await flushBatchToRedis();
1674
+ if (redis) await redis.quit();
1675
+ await fastify.close();
1676
+ if (dbWorker) await dbWorker.terminate();
1677
+ process.exit(0);
1678
+ });
1679
+
1680
+ start().catch(err => {
1681
+ console.error(`Main: Failed to start:`, err);
1682
+ process.exit(1);
1683
+ });
1684
+ }