blaze-aura69 commited on
Commit
d7fc8d9
ยท
verified ยท
1 Parent(s): 9709a2d

Update index.js

Browse files
Files changed (1) hide show
  1. index.js +291 -139
index.js CHANGED
@@ -8,19 +8,19 @@ const NUM_WORKERS = 2; // Use both cores
8
  if (cluster.isMaster) {
9
  console.log(`Master process ${process.pid} is running`);
10
  console.log(`Forking ${NUM_WORKERS} workers for 2 vCPU cores`);
11
-
12
  // Fork workers
13
  for (let i = 0; i < NUM_WORKERS; i++) {
14
  cluster.fork();
15
  }
16
-
17
  // Handle worker exit
18
  cluster.on('exit', (worker, code, signal) => {
19
  console.log(`Worker ${worker.process.pid} died (code: ${code}, signal: ${signal})`);
20
  console.log('Restarting worker...');
21
  cluster.fork();
22
  });
23
-
24
  // Handle master shutdown
25
  process.on('SIGTERM', () => {
26
  console.log('Master SIGTERM received. Shutting down workers...');
@@ -29,7 +29,7 @@ if (cluster.isMaster) {
29
  }
30
  process.exit(0);
31
  });
32
-
33
  process.on('SIGINT', () => {
34
  console.log('Master SIGINT received. Shutting down workers...');
35
  for (const id in cluster.workers) {
@@ -37,15 +37,16 @@ if (cluster.isMaster) {
37
  }
38
  process.exit(0);
39
  });
40
-
41
  } else {
42
  // ============ WORKER PROCESS ============
43
- const fastify = require('fastify')({
44
  logger: { level: 'info' },
45
  bodyLimit: 10485760,
46
  keepAliveTimeout: 5000,
47
- connectionTimeout: 5000
48
  });
 
49
  const cors = require('@fastify/cors');
50
  const multipart = require('@fastify/multipart');
51
  const fastifyStatic = require('@fastify/static');
@@ -84,10 +85,11 @@ if (cluster.isMaster) {
84
  } catch (e) {
85
  console.log(`Worker ${process.pid}: Sharp not available, image compression disabled`);
86
  }
87
-
88
  // ============ CONSTANTS ============
89
  const MAX_BUCKET_SIZE = 60 * 1024 * 1024 * 1024; // 60GB
90
- const MAX_USERS = 30000; // 40k users
 
91
  const MAX_RAM_USAGE = 7 * 1024 * 1024 * 1024; // 7GB
92
  const MAX_PROFILE_UPDATES_PER_DAY = 3;
93
  const MAX_PHOTO_SIZE_KB = 20;
@@ -99,19 +101,21 @@ if (cluster.isMaster) {
99
  const MAX_BIO_LENGTH = 1000;
100
  const MAX_LOCATION_LENGTH = 500;
101
  const MAX_EMAIL_LENGTH = 200;
102
- const SPACE_NAMES = ["data1", "data2", "data3", "data4", "data5"];
 
103
  const BASE_SPACE_URL = "https://velost-db1-{space}.hf.space";
104
- const CURRENT_SPACE_NAME = "1";
105
  const BATCH_FLUSH_INTERVAL = 9; // ms - ultra fast flush
106
  const BATCH_SIZE = 15000; // Process all 20k at once
107
  const HASH = process.env.HASH || 'v3l0st-d3f4ult-h4sh-k3y-2024!@#$%^&*()';
108
-
109
  // ============ DIRECTORIES ============
110
  const DATA_DIR = process.env.DATA_DIR || "/data";
111
  const PHOTOS_DIR = path.join(DATA_DIR, "photos");
112
  const STATUS_DIR = process.env.STATUS_DIR || "/status";
113
  const FULL_FILE = path.join(STATUS_DIR, "full.txt");
114
-
 
115
  // Initialize directories
116
  [DATA_DIR, PHOTOS_DIR, STATUS_DIR].forEach(dir => {
117
  try {
@@ -123,7 +127,7 @@ if (cluster.isMaster) {
123
  console.error(`Worker ${process.pid}: Error creating directory ${dir}:`, e.message);
124
  }
125
  });
126
-
127
  // Initialize full.txt if it doesn't exist
128
  if (!fs.existsSync(FULL_FILE)) {
129
  try {
@@ -133,14 +137,24 @@ if (cluster.isMaster) {
133
  console.error(`Worker ${process.pid}: Error creating full.txt:`, e.message);
134
  }
135
  }
136
-
 
 
 
 
 
 
 
 
 
 
137
  // ============ ROCKSDB SETUP ============
138
- const dbPath = path.join(DATA_DIR, 'rocksdb');
139
  let db;
140
-
141
  async function initDB() {
142
  try {
143
- db = level(dbPath, {
144
  createIfMissing: true,
145
  cacheSize: 4 * 1024 * 1024 * 1024, // 4GB cache for RocksDB
146
  writeBufferSize: 512 * 1024 * 1024, // 512MB write buffer for bulk writes
@@ -153,10 +167,9 @@ if (cluster.isMaster) {
153
  throw e;
154
  }
155
  }
156
-
157
  // ============ REDIS SETUP (Optional) ============
158
  let redis = null;
159
-
160
  if (Redis) {
161
  redis = new Redis({
162
  host: process.env.REDIS_HOST || '127.0.0.1',
@@ -170,18 +183,17 @@ if (cluster.isMaster) {
170
  return Math.min(times * 50, 2000);
171
  }
172
  });
173
-
174
  redis.on('error', (err) => {
175
  console.error(`Worker ${process.pid}: Redis error:`, err.message);
176
  });
177
  }
178
-
179
  // ============ IN-MEMORY STORAGE ============
180
  let usersCache = new Map(); // All users in memory
181
  let batchBuffer = []; // Request buffer
182
  let batchTimer = null;
183
  let processingLock = false;
184
-
185
  // ============ RATE LIMITERS ============
186
  class GlobalRateLimiter {
187
  constructor(maxRequests = 15000, window = 1) {
@@ -189,7 +201,7 @@ if (cluster.isMaster) {
189
  this.window = window;
190
  this.requests = [];
191
  }
192
-
193
  isAllowed() {
194
  const now = Date.now() / 1000;
195
  this.requests = this.requests.filter(t => now - t < this.window);
@@ -199,21 +211,21 @@ if (cluster.isMaster) {
199
  this.requests.push(now);
200
  return true;
201
  }
202
-
203
  getCurrentCount() {
204
  const now = Date.now() / 1000;
205
  this.requests = this.requests.filter(t => now - t < this.window);
206
  return this.requests.length;
207
  }
208
  }
209
-
210
  class RateLimiter {
211
  constructor(maxRequests = 15000, window = 1) {
212
  this.maxRequests = maxRequests;
213
  this.window = window;
214
  this.requests = new Map();
215
  }
216
-
217
  isAllowed(clientIp) {
218
  const now = Date.now() / 1000;
219
  if (!this.requests.has(clientIp)) {
@@ -229,29 +241,50 @@ if (cluster.isMaster) {
229
  return true;
230
  }
231
  }
232
-
233
  const globalRateLimiter = new GlobalRateLimiter(15000, 1);
234
  const rateLimiter = new RateLimiter(15000, 1);
235
-
236
  // ============ UTILITY FUNCTIONS ============
237
  function getMemoryUsage() {
238
  return process.memoryUsage().rss;
239
  }
240
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
241
  function safeGet(value, defaultValue = "") {
242
  if (value === null || value === undefined) return defaultValue;
243
  if (typeof value === 'number' && isNaN(value)) return defaultValue;
244
  return value;
245
  }
246
-
247
  function generateId() {
248
  return crypto.randomUUID();
249
  }
250
-
251
  function generateFingKey() {
252
  return crypto.createHash('sha256').update(uuidv4()).digest('hex').substring(0, 32);
253
  }
254
-
255
  function formatSize(bytesSize) {
256
  if (bytesSize === 0) return "0 B";
257
  const units = ["B", "KB", "MB", "GB", "TB"];
@@ -263,23 +296,23 @@ if (cluster.isMaster) {
263
  }
264
  return `${size.toFixed(2)} ${units[unitIndex]}`;
265
  }
266
-
267
  function toJsonl(data) {
268
  return JSON.stringify(data) + "\n";
269
  }
270
-
271
  // Fast SHA256 hash for passwords using HASH env
272
  function hashPassword(password) {
273
  return crypto.createHash('sha256')
274
  .update(HASH + password + HASH)
275
  .digest('hex');
276
  }
277
-
278
  function verifyPassword(password, hash) {
279
  const newHash = hashPassword(password);
280
  return newHash === hash;
281
  }
282
-
283
  function validateExternalLinks(linksStr) {
284
  if (!linksStr) return { valid: true, error: null };
285
  try {
@@ -295,10 +328,10 @@ if (cluster.isMaster) {
295
  return { valid: false, error: "Invalid JSON format for external links" };
296
  }
297
  }
298
-
299
  // ============ FULL.TXT MANAGEMENT ============
300
  let lastFullStatus = false; // Track last known status to prevent unnecessary writes
301
-
302
  async function getFullSpaces() {
303
  try {
304
  const content = await fsp.readFile(FULL_FILE, 'utf8');
@@ -307,7 +340,7 @@ if (cluster.isMaster) {
307
  return [];
308
  }
309
  }
310
-
311
  async function addSpaceToFull(spacename) {
312
  try {
313
  let content = await fsp.readFile(FULL_FILE, 'utf8');
@@ -322,7 +355,7 @@ if (cluster.isMaster) {
322
  console.error(`Worker ${process.pid}: Error updating full.txt:`, e.message);
323
  }
324
  }
325
-
326
  async function removeSpaceFromFull(spacename) {
327
  try {
328
  let content = await fsp.readFile(FULL_FILE, 'utf8');
@@ -334,71 +367,137 @@ if (cluster.isMaster) {
334
  console.error(`Worker ${process.pid}: Error removing space from full:`, e.message);
335
  }
336
  }
337
-
338
- // Only updates full.txt when status actually changes
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
339
  async function checkAndUpdateFullStatus() {
340
  const currentRPS = globalRateLimiter.getCurrentCount();
341
- const isFull = currentRPS >= 15000;
 
 
 
 
 
 
 
 
 
 
 
 
 
342
 
343
- // Only update file if status changed
344
  if (isFull !== lastFullStatus) {
345
  lastFullStatus = isFull;
346
  if (isFull) {
347
  await addSpaceToFull(CURRENT_SPACE_NAME);
 
 
 
 
348
  } else {
349
  await removeSpaceFromFull(CURRENT_SPACE_NAME);
 
350
  }
351
  }
352
 
353
- return { isFull, currentRPS };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
354
  }
355
-
356
  // ============ IMAGE COMPRESSION ============
357
  async function compressToWebp(fileData, maxSizeKb = 20) {
358
  if (!sharp) {
359
  return { buffer: fileData, isWebp: false, sizeKb: fileData.length / 1024 };
360
  }
361
-
362
  try {
363
  let image = sharp(fileData);
364
  const metadata = await image.metadata();
365
  const currentSizeKb = fileData.length / 1024;
366
-
367
  if (metadata.format === 'webp' && currentSizeKb <= maxSizeKb) {
368
  return { buffer: fileData, isWebp: true, sizeKb: currentSizeKb, wasCompressed: false };
369
  }
370
-
371
  let quality = 80;
372
  let outputBuffer;
373
-
374
  while (quality >= 10) {
375
  outputBuffer = await image
376
  .resize(800, 800, { fit: 'inside', withoutEnlargement: true })
377
  .webp({ quality })
378
  .toBuffer();
379
-
380
  if (outputBuffer.length / 1024 <= maxSizeKb) break;
381
  quality -= 10;
382
  }
383
-
384
  if (outputBuffer.length / 1024 > maxSizeKb) {
385
  outputBuffer = await image
386
  .resize(400, 400, { fit: 'inside', withoutEnlargement: true })
387
  .webp({ quality: 30 })
388
  .toBuffer();
389
  }
390
-
391
- return {
392
- buffer: outputBuffer,
393
- isWebp: true,
394
  sizeKb: outputBuffer.length / 1024,
395
  wasCompressed: true
396
  };
397
  } catch (e) {
398
- return { buffer: fileData, isWebp: false, sizeKb: fileData.length / 1024, wasCompressed: false };
 
 
 
 
 
399
  }
400
  }
401
-
402
  // ============ DATA MANAGEMENT ============
403
  async function loadUsersToMemory() {
404
  try {
@@ -423,7 +522,7 @@ if (cluster.isMaster) {
423
  console.error(`Worker ${process.pid}: Error loading users to memory:`, e.message);
424
  }
425
  }
426
-
427
  async function saveUser(userId, userData) {
428
  try {
429
  await db.put(`user:${userId}`, JSON.stringify(userData));
@@ -432,12 +531,12 @@ if (cluster.isMaster) {
432
  console.error(`Worker ${process.pid}: Error saving user:`, e.message);
433
  }
434
  }
435
-
436
  async function getUser(userId) {
437
  if (usersCache.has(userId)) {
438
  return usersCache.get(userId);
439
  }
440
-
441
  try {
442
  const data = await db.get(`user:${userId}`);
443
  const user = JSON.parse(data);
@@ -447,16 +546,20 @@ if (cluster.isMaster) {
447
  return null;
448
  }
449
  }
450
-
451
  async function getUserByUsername(username) {
452
  // Fast memory search
453
  for (const user of usersCache.values()) {
454
  if (user.username === username) return user;
455
  }
456
-
457
  // DB fallback
458
  try {
459
- const stream = db.createReadStream({ gte: 'user:', lte: 'user:\xff' });
 
 
 
 
460
  for await (const { value } of stream) {
461
  const user = JSON.parse(value);
462
  if (user.username === username) {
@@ -467,14 +570,14 @@ if (cluster.isMaster) {
467
  } catch (e) {
468
  // Ignore
469
  }
470
-
471
  return null;
472
  }
473
-
474
  function getTotalUsers() {
475
  return usersCache.size;
476
  }
477
-
478
  function getBucketSize() {
479
  let totalSize = 0;
480
 
@@ -499,25 +602,28 @@ if (cluster.isMaster) {
499
  walkDir(DATA_DIR);
500
  return totalSize;
501
  }
502
-
503
  function isSpaceFull() {
504
  const totalUsers = getTotalUsers();
505
  const bucketSize = getBucketSize();
506
- const globalRpsFull = globalRateLimiter.getCurrentCount() >= 20000;
 
507
 
508
- return totalUsers >= MAX_USERS || bucketSize >= MAX_BUCKET_SIZE || globalRpsFull;
 
 
 
509
  }
510
-
511
  // ============ ULTRA FAST BATCH PROCESSING ============
512
  function scheduleBatchProcess() {
513
  if (batchTimer) return;
514
-
515
  batchTimer = setImmediate(async () => {
516
  batchTimer = null;
517
  await flushBatchToRedis();
518
  });
519
  }
520
-
521
  async function flushBatchToRedis() {
522
  if (batchBuffer.length === 0 || processingLock) return;
523
 
@@ -553,7 +659,7 @@ if (cluster.isMaster) {
553
  }
554
  }
555
  }
556
-
557
  async function processFromRedis() {
558
  if (!redis) return;
559
 
@@ -590,7 +696,7 @@ if (cluster.isMaster) {
590
  console.error(`Worker ${process.pid}: Redis processing error:`, e.message);
591
  }
592
  }
593
-
594
  async function processRequestsBatch(requests) {
595
  const startTime = Date.now();
596
 
@@ -622,8 +728,13 @@ if (cluster.isMaster) {
622
 
623
  const elapsed = Date.now() - startTime;
624
  console.log(`Worker ${process.pid}: Processed ${requests.length} requests in ${elapsed}ms (${Math.round(requests.length / (elapsed / 1000))} req/sec)`);
 
 
 
 
 
625
  }
626
-
627
  async function processSignupBatch(requests) {
628
  if (requests.length === 0) return;
629
 
@@ -667,12 +778,11 @@ if (cluster.isMaster) {
667
  usersCache.set(id, user);
668
  }
669
  }
670
-
671
  async function processLoginBatch(requests) {
672
  if (requests.length === 0) return;
673
 
674
  const batch = db.batch();
675
-
676
  for (const req of requests) {
677
  const user = usersCache.get(req.user_id);
678
  if (user) {
@@ -680,15 +790,13 @@ if (cluster.isMaster) {
680
  batch.put(`user:${req.user_id}`, JSON.stringify(user));
681
  }
682
  }
683
-
684
  await batch.write();
685
  }
686
-
687
  async function processLogoutBatch(requests) {
688
  if (requests.length === 0) return;
689
 
690
  const batch = db.batch();
691
-
692
  for (const req of requests) {
693
  const user = usersCache.get(req.user_id);
694
  if (user) {
@@ -696,15 +804,13 @@ if (cluster.isMaster) {
696
  batch.put(`user:${req.user_id}`, JSON.stringify(user));
697
  }
698
  }
699
-
700
  await batch.write();
701
  }
702
-
703
  async function processUpdateProfileBatch(requests) {
704
  if (requests.length === 0) return;
705
 
706
  const batch = db.batch();
707
-
708
  for (const req of requests) {
709
  const user = usersCache.get(req.user_id);
710
  if (user) {
@@ -733,15 +839,13 @@ if (cluster.isMaster) {
733
  batch.put(`user:${req.user_id}`, JSON.stringify(user));
734
  }
735
  }
736
-
737
  await batch.write();
738
  }
739
-
740
  async function processUploadPhotoBatch(requests) {
741
  if (requests.length === 0) return;
742
 
743
  const batch = db.batch();
744
-
745
  for (const req of requests) {
746
  const user = usersCache.get(req.user_id);
747
  if (user && req.pic_buffer) {
@@ -766,15 +870,13 @@ if (cluster.isMaster) {
766
  batch.put(`user:${req.user_id}`, JSON.stringify(user));
767
  }
768
  }
769
-
770
  await batch.write();
771
  }
772
-
773
  async function processForgotPasswordBatch(requests) {
774
  if (requests.length === 0) return;
775
 
776
  const batch = db.batch();
777
-
778
  for (const req of requests) {
779
  const user = usersCache.get(req.user_id);
780
  if (user) {
@@ -782,10 +884,9 @@ if (cluster.isMaster) {
782
  batch.put(`user:${req.user_id}`, JSON.stringify(user));
783
  }
784
  }
785
-
786
  await batch.write();
787
  }
788
-
789
  // Add request to buffer
790
  function addRequest(userId, username, action, data, picBuffer = null) {
791
  const request = {
@@ -806,18 +907,20 @@ if (cluster.isMaster) {
806
 
807
  return request.id;
808
  }
809
-
810
  // ============ FASTIFY SETUP ============
811
  async function setupFastify() {
812
- await fastify.register(cors, {
813
- origin: '*',
814
- credentials: true,
815
- methods: ['*'],
816
- allowedHeaders: ['*']
817
  });
818
 
819
  await fastify.register(multipart, {
820
- limits: { fileSize: 5 * 1024 * 1024 }
 
 
821
  });
822
 
823
  await fastify.register(fastifyStatic, {
@@ -826,14 +929,34 @@ if (cluster.isMaster) {
826
  decorateReply: false,
827
  maxAge: 86400000
828
  });
829
-
830
  // Rate limiting middleware
831
  fastify.addHook('onRequest', async (request, reply) => {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
832
  if (!globalRateLimiter.isAllowed()) {
833
  await addSpaceToFull(CURRENT_SPACE_NAME);
834
  const responseData = {
835
  error: 'space_full',
836
- message: 'Server at maximum capacity. Global rate limit (20,000 req/sec) reached.',
837
  current_global_rps: globalRateLimiter.getCurrentCount(),
838
  retry_after: 1
839
  };
@@ -846,7 +969,7 @@ if (cluster.isMaster) {
846
  if (!rateLimiter.isAllowed(clientIp)) {
847
  const responseData = {
848
  error: 'rate_limit_exceeded',
849
- message: 'Per-IP rate limit exceeded. Max 20000 requests per second.',
850
  retry_after: 1
851
  };
852
  reply.status(429);
@@ -854,12 +977,14 @@ if (cluster.isMaster) {
854
  return toJsonl(responseData);
855
  }
856
  });
857
-
858
  // ============ ROUTES ============
859
  fastify.get('/', async (request, reply) => {
860
  const spaceFull = isSpaceFull();
861
  const fullSpaces = await getFullSpaces();
862
  const emptySpaces = SPACE_NAMES.filter(s => !fullSpaces.includes(s));
 
 
863
 
864
  const responseData = {
865
  message: 'Velost Auth API - Ultra Fast',
@@ -868,8 +993,8 @@ if (cluster.isMaster) {
868
  space_name: CURRENT_SPACE_NAME,
869
  hash_type: 'SHA256',
870
  rate_limits: {
871
- global_rps: '20,000 requests/second',
872
- per_ip_rps: '20,000 requests/second',
873
  current_global_rps: globalRateLimiter.getCurrentCount()
874
  },
875
  storage: {
@@ -885,12 +1010,14 @@ if (cluster.isMaster) {
885
  buffer_size: batchBuffer.length,
886
  batch_size: BATCH_SIZE,
887
  processing: 'ULTRA_FAST_BATCH',
888
- worker_pid: process.pid
 
889
  },
890
  space_status: {
891
  is_full: spaceFull,
892
  full_spaces: fullSpaces,
893
  empty_spaces: emptySpaces,
 
894
  all_spaces: SPACE_NAMES
895
  },
896
  image_processing: {
@@ -904,12 +1031,15 @@ if (cluster.isMaster) {
904
  reply.header('Content-Type', 'text/plain');
905
  return toJsonl(responseData);
906
  });
907
-
908
  fastify.get('/status', async (request, reply) => {
909
  const spaceFull = isSpaceFull();
910
  await checkAndUpdateFullStatus();
911
  const fullSpaces = await getFullSpaces();
912
  const emptySpaces = SPACE_NAMES.filter(s => !fullSpaces.includes(s));
 
 
 
913
 
914
  const responseData = {
915
  worker_pid: process.pid,
@@ -917,8 +1047,8 @@ if (cluster.isMaster) {
917
  is_full: spaceFull,
918
  rate_limits: {
919
  global_rps_current: globalRateLimiter.getCurrentCount(),
920
- global_rps_max: 20000,
921
- per_ip_rps_max: 20000
922
  },
923
  storage: {
924
  type: redis ? 'RocksDB + Redis' : 'RocksDB',
@@ -930,26 +1060,34 @@ if (cluster.isMaster) {
930
  ram: {
931
  max_gb: 7,
932
  current_mb: Math.round(getMemoryUsage() / (1024 * 1024) * 100) / 100,
933
- users_in_memory: getTotalUsers(),
934
  buffer_size: batchBuffer.length
935
  },
 
 
 
 
936
  users: {
937
- current: getTotalUsers(),
938
  max: MAX_USERS,
939
- remaining: MAX_USERS - getTotalUsers(),
940
- percent_full: MAX_USERS > 0 ? `${((getTotalUsers() / MAX_USERS) * 100).toFixed(2)}%` : '0%'
 
941
  },
942
  full_spaces: fullSpaces,
943
  empty_spaces: emptySpaces,
 
944
  full_file_content: await fsp.readFile(FULL_FILE, 'utf8').catch(() => ''),
 
945
  timestamp: new Date().toISOString()
946
  };
947
 
948
  reply.header('Content-Type', 'text/plain');
949
  return toJsonl(responseData);
950
  });
951
-
952
  fastify.get('/health', async (request, reply) => {
 
953
  const responseData = {
954
  worker_pid: process.pid,
955
  status: 'healthy',
@@ -959,13 +1097,14 @@ if (cluster.isMaster) {
959
  max_ram_gb: 7,
960
  bucket_size: formatSize(getBucketSize()),
961
  buffer_size: batchBuffer.length,
 
962
  timestamp: new Date().toISOString()
963
  };
964
 
965
  reply.header('Content-Type', 'text/plain');
966
  return toJsonl(responseData);
967
  });
968
-
969
  fastify.post('/signup', async (request, reply) => {
970
  if (getTotalUsers() >= MAX_USERS) {
971
  reply.status(507);
@@ -1028,7 +1167,7 @@ if (cluster.isMaster) {
1028
  reply.header('Content-Type', 'text/plain');
1029
  return toJsonl(responseData);
1030
  });
1031
-
1032
  fastify.post('/login', async (request, reply) => {
1033
  const { username, password } = request.body || {};
1034
 
@@ -1078,7 +1217,7 @@ if (cluster.isMaster) {
1078
  reply.header('Content-Type', 'text/plain');
1079
  return toJsonl(responseData);
1080
  });
1081
-
1082
  fastify.post('/logout', async (request, reply) => {
1083
  const { id } = request.body || {};
1084
 
@@ -1105,7 +1244,7 @@ if (cluster.isMaster) {
1105
  reply.header('Content-Type', 'text/plain');
1106
  return toJsonl(responseData);
1107
  });
1108
-
1109
  fastify.put('/updateprofiledetails', async (request, reply) => {
1110
  const { id, ...data } = request.body || {};
1111
 
@@ -1150,7 +1289,7 @@ if (cluster.isMaster) {
1150
  reply.header('Content-Type', 'text/plain');
1151
  return toJsonl(responseData);
1152
  });
1153
-
1154
  fastify.post('/uploadphoto', async (request, reply) => {
1155
  if (getBucketSize() >= MAX_BUCKET_SIZE) {
1156
  reply.status(507);
@@ -1184,6 +1323,7 @@ if (cluster.isMaster) {
1184
  }
1185
 
1186
  const originalSizeKb = fileBuffer.length / 1024;
 
1187
  addRequest(id, '', 'upload_photo', { original_size_kb: originalSizeKb }, fileBuffer);
1188
 
1189
  const responseData = {
@@ -1204,7 +1344,7 @@ if (cluster.isMaster) {
1204
  return { detail: 'Upload failed' };
1205
  }
1206
  });
1207
-
1208
  fastify.get('/getuser', async (request, reply) => {
1209
  const { id } = request.query || {};
1210
 
@@ -1242,12 +1382,15 @@ if (cluster.isMaster) {
1242
  reply.header('Content-Type', 'text/plain');
1243
  return toJsonl(responseData);
1244
  });
1245
-
1246
  fastify.get('/users/count', async (request, reply) => {
1247
  reply.header('Content-Type', 'text/plain');
1248
- return toJsonl({ worker_pid: process.pid, count: getTotalUsers() });
 
 
 
1249
  });
1250
-
1251
  fastify.get('/users', async (request, reply) => {
1252
  if (usersCache.size === 0) {
1253
  reply.header('Content-Type', 'text/plain');
@@ -1256,7 +1399,11 @@ if (cluster.isMaster) {
1256
 
1257
  const stream = new Readable({
1258
  read() {
1259
- this.push(toJsonl({ worker_pid: process.pid, total: usersCache.size }));
 
 
 
 
1260
  for (const user of usersCache.values()) {
1261
  this.push(toJsonl({
1262
  id: user.id,
@@ -1275,6 +1422,7 @@ if (cluster.isMaster) {
1275
  last_profile_updated: safeGet(user.last_profile_updated)
1276
  }));
1277
  }
 
1278
  this.push(null);
1279
  }
1280
  });
@@ -1282,10 +1430,11 @@ if (cluster.isMaster) {
1282
  reply.header('Content-Type', 'text/plain');
1283
  return stream;
1284
  });
1285
-
1286
  fastify.get('/spaces', async (request, reply) => {
1287
  const fullSpaces = await getFullSpaces();
1288
  const emptySpaces = SPACE_NAMES.filter(s => !fullSpaces.includes(s));
 
1289
 
1290
  reply.header('Content-Type', 'text/plain');
1291
  return toJsonl({
@@ -1293,11 +1442,12 @@ if (cluster.isMaster) {
1293
  all_spaces: SPACE_NAMES,
1294
  full_spaces: fullSpaces,
1295
  empty_spaces: emptySpaces,
 
1296
  current_space: CURRENT_SPACE_NAME,
1297
  timestamp: new Date().toISOString()
1298
  });
1299
  });
1300
-
1301
  fastify.get('/buffer-status', async (request, reply) => {
1302
  let redisSize = 0;
1303
  if (redis) {
@@ -1308,6 +1458,8 @@ if (cluster.isMaster) {
1308
  }
1309
  }
1310
 
 
 
1311
  reply.header('Content-Type', 'text/plain');
1312
  return toJsonl({
1313
  worker_pid: process.pid,
@@ -1316,10 +1468,11 @@ if (cluster.isMaster) {
1316
  batch_size: BATCH_SIZE,
1317
  processing: batchBuffer.length > 0 ? 'active' : 'idle',
1318
  ram_usage_mb: Math.round(getMemoryUsage() / (1024 * 1024) * 100) / 100,
 
1319
  timestamp: new Date().toISOString()
1320
  });
1321
  });
1322
-
1323
  fastify.post('/forgotpassword', async (request, reply) => {
1324
  const { username, email, fing_key, new_password } = request.body || {};
1325
 
@@ -1379,10 +1532,10 @@ if (cluster.isMaster) {
1379
  reply.header('Content-Type', 'text/plain');
1380
  return toJsonl(responseData);
1381
  });
1382
-
1383
  return fastify;
1384
  }
1385
-
1386
  // ============ STARTUP ============
1387
  async function start() {
1388
  try {
@@ -1405,7 +1558,7 @@ if (cluster.isMaster) {
1405
  console.log(`Worker ${process.pid}: Loading users into memory...`);
1406
  await loadUsersToMemory();
1407
 
1408
- console.log(`Worker ${process.pid}: Setting up full.txt...`);
1409
  await checkAndUpdateFullStatus();
1410
 
1411
  console.log(`Worker ${process.pid}: Setting up Fastify...`);
@@ -1420,7 +1573,6 @@ if (cluster.isMaster) {
1420
  }, 50); // Check every 50ms
1421
 
1422
  const port = process.env.PORT || 7860;
1423
-
1424
  // CRITICAL: Bind to 0.0.0.0 for Hugging Face Spaces
1425
  await fastify.listen({ port, host: '0.0.0.0' });
1426
 
@@ -1431,15 +1583,15 @@ if (cluster.isMaster) {
1431
  console.log(`Worker ${process.pid}: ๐Ÿ” Hash: SHA256 (HASH env: ${HASH.substring(0, 8)}...)`);
1432
  console.log(`Worker ${process.pid}: ๐Ÿ–ผ๏ธ Image format: WebP, max ${MAX_PHOTO_SIZE_KB}KB`);
1433
  console.log(`Worker ${process.pid}: ๐Ÿ“ Space: ${CURRENT_SPACE_NAME}`);
1434
-
 
1435
  } catch (err) {
1436
  console.error(`Worker ${process.pid}: Error during startup:`, err);
1437
- // Don't exit immediately, log the error
1438
  console.error(`Worker ${process.pid}: Stack trace:`, err.stack);
1439
  process.exit(1);
1440
  }
1441
  }
1442
-
1443
  // Handle worker shutdown
1444
  process.on('SIGTERM', async () => {
1445
  console.log(`Worker ${process.pid}: SIGTERM received. Shutting down...`);
@@ -1450,7 +1602,7 @@ if (cluster.isMaster) {
1450
  if (db) await db.close();
1451
  process.exit(0);
1452
  });
1453
-
1454
  process.on('SIGINT', async () => {
1455
  console.log(`Worker ${process.pid}: SIGINT received. Shutting down...`);
1456
  await flushBatchToRedis();
@@ -1460,19 +1612,19 @@ if (cluster.isMaster) {
1460
  if (db) await db.close();
1461
  process.exit(0);
1462
  });
1463
-
1464
  // Handle uncaught exceptions
1465
  process.on('uncaughtException', (err) => {
1466
  console.error(`Worker ${process.pid}: Uncaught exception:`, err);
1467
  console.error(`Worker ${process.pid}: Stack trace:`, err.stack);
1468
  // Don't exit, try to continue
1469
  });
1470
-
1471
  process.on('unhandledRejection', (reason, promise) => {
1472
  console.error(`Worker ${process.pid}: Unhandled rejection at:`, promise, 'reason:', reason);
1473
  // Don't exit, try to continue
1474
  });
1475
-
1476
  // Start worker
1477
  start().catch(err => {
1478
  console.error(`Worker ${process.pid}: Failed to start:`, err);
 
8
  if (cluster.isMaster) {
9
  console.log(`Master process ${process.pid} is running`);
10
  console.log(`Forking ${NUM_WORKERS} workers for 2 vCPU cores`);
11
+
12
  // Fork workers
13
  for (let i = 0; i < NUM_WORKERS; i++) {
14
  cluster.fork();
15
  }
16
+
17
  // Handle worker exit
18
  cluster.on('exit', (worker, code, signal) => {
19
  console.log(`Worker ${worker.process.pid} died (code: ${code}, signal: ${signal})`);
20
  console.log('Restarting worker...');
21
  cluster.fork();
22
  });
23
+
24
  // Handle master shutdown
25
  process.on('SIGTERM', () => {
26
  console.log('Master SIGTERM received. Shutting down workers...');
 
29
  }
30
  process.exit(0);
31
  });
32
+
33
  process.on('SIGINT', () => {
34
  console.log('Master SIGINT received. Shutting down workers...');
35
  for (const id in cluster.workers) {
 
37
  }
38
  process.exit(0);
39
  });
40
+
41
  } else {
42
  // ============ WORKER PROCESS ============
43
+ const fastify = require('fastify')({
44
  logger: { level: 'info' },
45
  bodyLimit: 10485760,
46
  keepAliveTimeout: 5000,
47
+ connectionTimeout: 5000
48
  });
49
+
50
  const cors = require('@fastify/cors');
51
  const multipart = require('@fastify/multipart');
52
  const fastifyStatic = require('@fastify/static');
 
85
  } catch (e) {
86
  console.log(`Worker ${process.pid}: Sharp not available, image compression disabled`);
87
  }
88
+
89
  // ============ CONSTANTS ============
90
  const MAX_BUCKET_SIZE = 60 * 1024 * 1024 * 1024; // 60GB
91
+ const MAX_USERS = 30000; // 30k users
92
+ const MAX_USERS_SIZE_LIMIT = 30000; // Add to size.txt at 30k users
93
  const MAX_RAM_USAGE = 7 * 1024 * 1024 * 1024; // 7GB
94
  const MAX_PROFILE_UPDATES_PER_DAY = 3;
95
  const MAX_PHOTO_SIZE_KB = 20;
 
101
  const MAX_BIO_LENGTH = 1000;
102
  const MAX_LOCATION_LENGTH = 500;
103
  const MAX_EMAIL_LENGTH = 200;
104
+ const MAX_RPS = 15000; // Maximum RPS limit
105
+ const SPACE_NAMES = ["data1", "data2"];
106
  const BASE_SPACE_URL = "https://velost-db1-{space}.hf.space";
107
+ const CURRENT_SPACE_NAME = "3";
108
  const BATCH_FLUSH_INTERVAL = 9; // ms - ultra fast flush
109
  const BATCH_SIZE = 15000; // Process all 20k at once
110
  const HASH = process.env.HASH || 'v3l0st-d3f4ult-h4sh-k3y-2024!@#$%^&*()';
111
+
112
  // ============ DIRECTORIES ============
113
  const DATA_DIR = process.env.DATA_DIR || "/data";
114
  const PHOTOS_DIR = path.join(DATA_DIR, "photos");
115
  const STATUS_DIR = process.env.STATUS_DIR || "/status";
116
  const FULL_FILE = path.join(STATUS_DIR, "full.txt");
117
+ const SIZE_FILE = path.join(STATUS_DIR, "size.txt");
118
+
119
  // Initialize directories
120
  [DATA_DIR, PHOTOS_DIR, STATUS_DIR].forEach(dir => {
121
  try {
 
127
  console.error(`Worker ${process.pid}: Error creating directory ${dir}:`, e.message);
128
  }
129
  });
130
+
131
  // Initialize full.txt if it doesn't exist
132
  if (!fs.existsSync(FULL_FILE)) {
133
  try {
 
137
  console.error(`Worker ${process.pid}: Error creating full.txt:`, e.message);
138
  }
139
  }
140
+
141
+ // Initialize size.txt if it doesn't exist
142
+ if (!fs.existsSync(SIZE_FILE)) {
143
+ try {
144
+ fs.writeFileSync(SIZE_FILE, '', 'utf8');
145
+ console.log(`Worker ${process.pid}: Created size.txt`);
146
+ } catch (e) {
147
+ console.error(`Worker ${process.pid}: Error creating size.txt:`, e.message);
148
+ }
149
+ }
150
+
151
  // ============ ROCKSDB SETUP ============
152
+ const dbPath = path.join(DATA_DIR, `rocksdb-${process.pid}`);
153
  let db;
154
+
155
  async function initDB() {
156
  try {
157
+ db = level(dbPath, {
158
  createIfMissing: true,
159
  cacheSize: 4 * 1024 * 1024 * 1024, // 4GB cache for RocksDB
160
  writeBufferSize: 512 * 1024 * 1024, // 512MB write buffer for bulk writes
 
167
  throw e;
168
  }
169
  }
170
+
171
  // ============ REDIS SETUP (Optional) ============
172
  let redis = null;
 
173
  if (Redis) {
174
  redis = new Redis({
175
  host: process.env.REDIS_HOST || '127.0.0.1',
 
183
  return Math.min(times * 50, 2000);
184
  }
185
  });
 
186
  redis.on('error', (err) => {
187
  console.error(`Worker ${process.pid}: Redis error:`, err.message);
188
  });
189
  }
190
+
191
  // ============ IN-MEMORY STORAGE ============
192
  let usersCache = new Map(); // All users in memory
193
  let batchBuffer = []; // Request buffer
194
  let batchTimer = null;
195
  let processingLock = false;
196
+
197
  // ============ RATE LIMITERS ============
198
  class GlobalRateLimiter {
199
  constructor(maxRequests = 15000, window = 1) {
 
201
  this.window = window;
202
  this.requests = [];
203
  }
204
+
205
  isAllowed() {
206
  const now = Date.now() / 1000;
207
  this.requests = this.requests.filter(t => now - t < this.window);
 
211
  this.requests.push(now);
212
  return true;
213
  }
214
+
215
  getCurrentCount() {
216
  const now = Date.now() / 1000;
217
  this.requests = this.requests.filter(t => now - t < this.window);
218
  return this.requests.length;
219
  }
220
  }
221
+
222
  class RateLimiter {
223
  constructor(maxRequests = 15000, window = 1) {
224
  this.maxRequests = maxRequests;
225
  this.window = window;
226
  this.requests = new Map();
227
  }
228
+
229
  isAllowed(clientIp) {
230
  const now = Date.now() / 1000;
231
  if (!this.requests.has(clientIp)) {
 
241
  return true;
242
  }
243
  }
244
+
245
  const globalRateLimiter = new GlobalRateLimiter(15000, 1);
246
  const rateLimiter = new RateLimiter(15000, 1);
247
+
248
  // ============ UTILITY FUNCTIONS ============
249
  function getMemoryUsage() {
250
  return process.memoryUsage().rss;
251
  }
252
+
253
+ // CPU usage tracking
254
+ let lastCPUUsage = process.cpuUsage();
255
+ let lastCPUCheck = Date.now();
256
+
257
+ function getCurrentCPUPercentage() {
258
+ const currentCPUUsage = process.cpuUsage(lastCPUUsage);
259
+ const currentTime = Date.now();
260
+ const elapsedMS = currentTime - lastCPUCheck;
261
+
262
+ // Reset for next check
263
+ lastCPUUsage = process.cpuUsage();
264
+ lastCPUCheck = currentTime;
265
+
266
+ if (elapsedMS === 0) return 0;
267
+
268
+ // Calculate CPU usage percentage
269
+ const usagePercent = ((currentCPUUsage.user + currentCPUUsage.system) / 1000) / elapsedMS * 100;
270
+
271
+ return Math.min(100, usagePercent);
272
+ }
273
+
274
  function safeGet(value, defaultValue = "") {
275
  if (value === null || value === undefined) return defaultValue;
276
  if (typeof value === 'number' && isNaN(value)) return defaultValue;
277
  return value;
278
  }
279
+
280
  function generateId() {
281
  return crypto.randomUUID();
282
  }
283
+
284
  function generateFingKey() {
285
  return crypto.createHash('sha256').update(uuidv4()).digest('hex').substring(0, 32);
286
  }
287
+
288
  function formatSize(bytesSize) {
289
  if (bytesSize === 0) return "0 B";
290
  const units = ["B", "KB", "MB", "GB", "TB"];
 
296
  }
297
  return `${size.toFixed(2)} ${units[unitIndex]}`;
298
  }
299
+
300
  function toJsonl(data) {
301
  return JSON.stringify(data) + "\n";
302
  }
303
+
304
  // Fast SHA256 hash for passwords using HASH env
305
  function hashPassword(password) {
306
  return crypto.createHash('sha256')
307
  .update(HASH + password + HASH)
308
  .digest('hex');
309
  }
310
+
311
  function verifyPassword(password, hash) {
312
  const newHash = hashPassword(password);
313
  return newHash === hash;
314
  }
315
+
316
  function validateExternalLinks(linksStr) {
317
  if (!linksStr) return { valid: true, error: null };
318
  try {
 
328
  return { valid: false, error: "Invalid JSON format for external links" };
329
  }
330
  }
331
+
332
  // ============ FULL.TXT MANAGEMENT ============
333
  let lastFullStatus = false; // Track last known status to prevent unnecessary writes
334
+
335
  async function getFullSpaces() {
336
  try {
337
  const content = await fsp.readFile(FULL_FILE, 'utf8');
 
340
  return [];
341
  }
342
  }
343
+
344
  async function addSpaceToFull(spacename) {
345
  try {
346
  let content = await fsp.readFile(FULL_FILE, 'utf8');
 
355
  console.error(`Worker ${process.pid}: Error updating full.txt:`, e.message);
356
  }
357
  }
358
+
359
  async function removeSpaceFromFull(spacename) {
360
  try {
361
  let content = await fsp.readFile(FULL_FILE, 'utf8');
 
367
  console.error(`Worker ${process.pid}: Error removing space from full:`, e.message);
368
  }
369
  }
370
+
371
+ // ============ SIZE.TXT MANAGEMENT ============
372
+ async function getSizeSpaces() {
373
+ try {
374
+ const content = await fsp.readFile(SIZE_FILE, 'utf8');
375
+ return content.trim() ? content.trim().split('|') : [];
376
+ } catch (e) {
377
+ return [];
378
+ }
379
+ }
380
+
381
+ async function addSpaceToSize(spacename) {
382
+ try {
383
+ let content = await fsp.readFile(SIZE_FILE, 'utf8');
384
+ content = content.trim();
385
+ let spaces = content ? content.split('|') : [];
386
+ if (!spaces.includes(spacename)) {
387
+ spaces.push(spacename);
388
+ await fsp.writeFile(SIZE_FILE, spaces.join('|'), 'utf8');
389
+ console.log(`Worker ${process.pid}: Added ${spacename} to size.txt (30k users reached)`);
390
+ }
391
+ } catch (e) {
392
+ console.error(`Worker ${process.pid}: Error updating size.txt:`, e.message);
393
+ }
394
+ }
395
+
396
+ // Only updates full.txt and size.txt when status actually changes
397
  async function checkAndUpdateFullStatus() {
398
  const currentRPS = globalRateLimiter.getCurrentCount();
399
+ const cpuUsage = getCurrentCPUPercentage();
400
+ const totalUsers = getTotalUsers();
401
+ const bucketSize = getBucketSize();
402
+ const ramUsage = getMemoryUsage();
403
+
404
+ // Check multiple conditions for "full" status
405
+ const isRPSFull = currentRPS >= MAX_RPS;
406
+ const isCPUOverloaded = cpuUsage >= 98;
407
+ const isUsersFull = totalUsers >= MAX_USERS;
408
+ const isStorageFull = bucketSize >= MAX_BUCKET_SIZE;
409
+ const isRAMFull = ramUsage >= MAX_RAM_USAGE;
410
+
411
+ // Space is full if ANY condition is met
412
+ const isFull = isRPSFull || isCPUOverloaded || isUsersFull || isStorageFull || isRAMFull;
413
 
414
+ // Only update full.txt if status changed
415
  if (isFull !== lastFullStatus) {
416
  lastFullStatus = isFull;
417
  if (isFull) {
418
  await addSpaceToFull(CURRENT_SPACE_NAME);
419
+ console.log(`Worker ${process.pid}: Space marked as FULL - ` +
420
+ `RPS: ${currentRPS}/${MAX_RPS}, CPU: ${cpuUsage.toFixed(1)}%, ` +
421
+ `Users: ${totalUsers}/${MAX_USERS}, Storage: ${formatSize(bucketSize)}/${formatSize(MAX_BUCKET_SIZE)}, ` +
422
+ `RAM: ${formatSize(ramUsage)}/${formatSize(MAX_RAM_USAGE)}`);
423
  } else {
424
  await removeSpaceFromFull(CURRENT_SPACE_NAME);
425
+ console.log(`Worker ${process.pid}: Space removed from full.txt`);
426
  }
427
  }
428
 
429
+ // Add to size.txt when users reach 30k (never remove, only add)
430
+ if (totalUsers >= MAX_USERS_SIZE_LIMIT) {
431
+ await addSpaceToSize(CURRENT_SPACE_NAME);
432
+ }
433
+
434
+ return {
435
+ isFull,
436
+ currentRPS,
437
+ cpuUsage,
438
+ totalUsers,
439
+ details: {
440
+ rps: { current: currentRPS, max: MAX_RPS, isFull: isRPSFull },
441
+ cpu: { current: cpuUsage, max: 98, isOverloaded: isCPUOverloaded },
442
+ users: { current: totalUsers, max: MAX_USERS, isFull: isUsersFull },
443
+ storage: { current: formatSize(bucketSize), max: formatSize(MAX_BUCKET_SIZE), isFull: isStorageFull },
444
+ ram: { current: formatSize(ramUsage), max: formatSize(MAX_RAM_USAGE), isFull: isRAMFull },
445
+ sizeLimit: { current: totalUsers, limit: MAX_USERS_SIZE_LIMIT, reached: totalUsers >= MAX_USERS_SIZE_LIMIT }
446
+ }
447
+ };
448
  }
449
+
450
  // ============ IMAGE COMPRESSION ============
451
  async function compressToWebp(fileData, maxSizeKb = 20) {
452
  if (!sharp) {
453
  return { buffer: fileData, isWebp: false, sizeKb: fileData.length / 1024 };
454
  }
455
+
456
  try {
457
  let image = sharp(fileData);
458
  const metadata = await image.metadata();
459
  const currentSizeKb = fileData.length / 1024;
460
+
461
  if (metadata.format === 'webp' && currentSizeKb <= maxSizeKb) {
462
  return { buffer: fileData, isWebp: true, sizeKb: currentSizeKb, wasCompressed: false };
463
  }
464
+
465
  let quality = 80;
466
  let outputBuffer;
467
+
468
  while (quality >= 10) {
469
  outputBuffer = await image
470
  .resize(800, 800, { fit: 'inside', withoutEnlargement: true })
471
  .webp({ quality })
472
  .toBuffer();
473
+
474
  if (outputBuffer.length / 1024 <= maxSizeKb) break;
475
  quality -= 10;
476
  }
477
+
478
  if (outputBuffer.length / 1024 > maxSizeKb) {
479
  outputBuffer = await image
480
  .resize(400, 400, { fit: 'inside', withoutEnlargement: true })
481
  .webp({ quality: 30 })
482
  .toBuffer();
483
  }
484
+
485
+ return {
486
+ buffer: outputBuffer,
487
+ isWebp: true,
488
  sizeKb: outputBuffer.length / 1024,
489
  wasCompressed: true
490
  };
491
  } catch (e) {
492
+ return {
493
+ buffer: fileData,
494
+ isWebp: false,
495
+ sizeKb: fileData.length / 1024,
496
+ wasCompressed: false
497
+ };
498
  }
499
  }
500
+
501
  // ============ DATA MANAGEMENT ============
502
  async function loadUsersToMemory() {
503
  try {
 
522
  console.error(`Worker ${process.pid}: Error loading users to memory:`, e.message);
523
  }
524
  }
525
+
526
  async function saveUser(userId, userData) {
527
  try {
528
  await db.put(`user:${userId}`, JSON.stringify(userData));
 
531
  console.error(`Worker ${process.pid}: Error saving user:`, e.message);
532
  }
533
  }
534
+
535
  async function getUser(userId) {
536
  if (usersCache.has(userId)) {
537
  return usersCache.get(userId);
538
  }
539
+
540
  try {
541
  const data = await db.get(`user:${userId}`);
542
  const user = JSON.parse(data);
 
546
  return null;
547
  }
548
  }
549
+
550
  async function getUserByUsername(username) {
551
  // Fast memory search
552
  for (const user of usersCache.values()) {
553
  if (user.username === username) return user;
554
  }
555
+
556
  // DB fallback
557
  try {
558
+ const stream = db.createReadStream({
559
+ gte: 'user:',
560
+ lte: 'user:\xff'
561
+ });
562
+
563
  for await (const { value } of stream) {
564
  const user = JSON.parse(value);
565
  if (user.username === username) {
 
570
  } catch (e) {
571
  // Ignore
572
  }
573
+
574
  return null;
575
  }
576
+
577
  function getTotalUsers() {
578
  return usersCache.size;
579
  }
580
+
581
  function getBucketSize() {
582
  let totalSize = 0;
583
 
 
602
  walkDir(DATA_DIR);
603
  return totalSize;
604
  }
605
+
606
  function isSpaceFull() {
607
  const totalUsers = getTotalUsers();
608
  const bucketSize = getBucketSize();
609
+ const globalRpsFull = globalRateLimiter.getCurrentCount() >= MAX_RPS;
610
+ const cpuOverloaded = getCurrentCPUPercentage() >= 98;
611
 
612
+ return totalUsers >= MAX_USERS ||
613
+ bucketSize >= MAX_BUCKET_SIZE ||
614
+ globalRpsFull ||
615
+ cpuOverloaded;
616
  }
617
+
618
  // ============ ULTRA FAST BATCH PROCESSING ============
619
  function scheduleBatchProcess() {
620
  if (batchTimer) return;
 
621
  batchTimer = setImmediate(async () => {
622
  batchTimer = null;
623
  await flushBatchToRedis();
624
  });
625
  }
626
+
627
  async function flushBatchToRedis() {
628
  if (batchBuffer.length === 0 || processingLock) return;
629
 
 
659
  }
660
  }
661
  }
662
+
663
  async function processFromRedis() {
664
  if (!redis) return;
665
 
 
696
  console.error(`Worker ${process.pid}: Redis processing error:`, e.message);
697
  }
698
  }
699
+
700
  async function processRequestsBatch(requests) {
701
  const startTime = Date.now();
702
 
 
728
 
729
  const elapsed = Date.now() - startTime;
730
  console.log(`Worker ${process.pid}: Processed ${requests.length} requests in ${elapsed}ms (${Math.round(requests.length / (elapsed / 1000))} req/sec)`);
731
+
732
+ // Check and update size.txt after processing signups
733
+ if (groups.signup.length > 0) {
734
+ await checkAndUpdateFullStatus();
735
+ }
736
  }
737
+
738
  async function processSignupBatch(requests) {
739
  if (requests.length === 0) return;
740
 
 
778
  usersCache.set(id, user);
779
  }
780
  }
781
+
782
  async function processLoginBatch(requests) {
783
  if (requests.length === 0) return;
784
 
785
  const batch = db.batch();
 
786
  for (const req of requests) {
787
  const user = usersCache.get(req.user_id);
788
  if (user) {
 
790
  batch.put(`user:${req.user_id}`, JSON.stringify(user));
791
  }
792
  }
 
793
  await batch.write();
794
  }
795
+
796
  async function processLogoutBatch(requests) {
797
  if (requests.length === 0) return;
798
 
799
  const batch = db.batch();
 
800
  for (const req of requests) {
801
  const user = usersCache.get(req.user_id);
802
  if (user) {
 
804
  batch.put(`user:${req.user_id}`, JSON.stringify(user));
805
  }
806
  }
 
807
  await batch.write();
808
  }
809
+
810
  async function processUpdateProfileBatch(requests) {
811
  if (requests.length === 0) return;
812
 
813
  const batch = db.batch();
 
814
  for (const req of requests) {
815
  const user = usersCache.get(req.user_id);
816
  if (user) {
 
839
  batch.put(`user:${req.user_id}`, JSON.stringify(user));
840
  }
841
  }
 
842
  await batch.write();
843
  }
844
+
845
  async function processUploadPhotoBatch(requests) {
846
  if (requests.length === 0) return;
847
 
848
  const batch = db.batch();
 
849
  for (const req of requests) {
850
  const user = usersCache.get(req.user_id);
851
  if (user && req.pic_buffer) {
 
870
  batch.put(`user:${req.user_id}`, JSON.stringify(user));
871
  }
872
  }
 
873
  await batch.write();
874
  }
875
+
876
  async function processForgotPasswordBatch(requests) {
877
  if (requests.length === 0) return;
878
 
879
  const batch = db.batch();
 
880
  for (const req of requests) {
881
  const user = usersCache.get(req.user_id);
882
  if (user) {
 
884
  batch.put(`user:${req.user_id}`, JSON.stringify(user));
885
  }
886
  }
 
887
  await batch.write();
888
  }
889
+
890
  // Add request to buffer
891
  function addRequest(userId, username, action, data, picBuffer = null) {
892
  const request = {
 
907
 
908
  return request.id;
909
  }
910
+
911
  // ============ FASTIFY SETUP ============
912
  async function setupFastify() {
913
+ await fastify.register(cors, {
914
+ origin: '*',
915
+ credentials: true,
916
+ methods: ['*'],
917
+ allowedHeaders: ['*']
918
  });
919
 
920
  await fastify.register(multipart, {
921
+ limits: {
922
+ fileSize: 5 * 1024 * 1024
923
+ }
924
  });
925
 
926
  await fastify.register(fastifyStatic, {
 
929
  decorateReply: false,
930
  maxAge: 86400000
931
  });
932
+
933
  // Rate limiting middleware
934
  fastify.addHook('onRequest', async (request, reply) => {
935
+ const cpuUsage = getCurrentCPUPercentage();
936
+ const totalUsers = getTotalUsers();
937
+
938
+ // Check if CPU is overloaded (98%+) or users limit reached - return space full immediately
939
+ if (cpuUsage >= 98 || totalUsers >= MAX_USERS || getBucketSize() >= MAX_BUCKET_SIZE || getMemoryUsage() >= MAX_RAM_USAGE) {
940
+ await addSpaceToFull(CURRENT_SPACE_NAME);
941
+ const responseData = {
942
+ error: 'space_full',
943
+ message: 'Server at maximum capacity. System resources exhausted.',
944
+ current_global_rps: globalRateLimiter.getCurrentCount(),
945
+ cpu_usage: cpuUsage.toFixed(1),
946
+ users: totalUsers,
947
+ retry_after: 1
948
+ };
949
+ reply.status(503);
950
+ reply.header('Content-Type', 'text/plain');
951
+ return toJsonl(responseData);
952
+ }
953
+
954
+ // Check global rate limit
955
  if (!globalRateLimiter.isAllowed()) {
956
  await addSpaceToFull(CURRENT_SPACE_NAME);
957
  const responseData = {
958
  error: 'space_full',
959
+ message: `Server at maximum capacity. Global rate limit (${MAX_RPS} req/sec) reached.`,
960
  current_global_rps: globalRateLimiter.getCurrentCount(),
961
  retry_after: 1
962
  };
 
969
  if (!rateLimiter.isAllowed(clientIp)) {
970
  const responseData = {
971
  error: 'rate_limit_exceeded',
972
+ message: `Per-IP rate limit exceeded. Max ${MAX_RPS} requests per second.`,
973
  retry_after: 1
974
  };
975
  reply.status(429);
 
977
  return toJsonl(responseData);
978
  }
979
  });
980
+
981
  // ============ ROUTES ============
982
  fastify.get('/', async (request, reply) => {
983
  const spaceFull = isSpaceFull();
984
  const fullSpaces = await getFullSpaces();
985
  const emptySpaces = SPACE_NAMES.filter(s => !fullSpaces.includes(s));
986
+ const cpuUsage = getCurrentCPUPercentage();
987
+ const sizeSpaces = await getSizeSpaces();
988
 
989
  const responseData = {
990
  message: 'Velost Auth API - Ultra Fast',
 
993
  space_name: CURRENT_SPACE_NAME,
994
  hash_type: 'SHA256',
995
  rate_limits: {
996
+ global_rps: `${MAX_RPS} requests/second`,
997
+ per_ip_rps: `${MAX_RPS} requests/second`,
998
  current_global_rps: globalRateLimiter.getCurrentCount()
999
  },
1000
  storage: {
 
1010
  buffer_size: batchBuffer.length,
1011
  batch_size: BATCH_SIZE,
1012
  processing: 'ULTRA_FAST_BATCH',
1013
+ worker_pid: process.pid,
1014
+ cpu_usage_percent: cpuUsage.toFixed(1)
1015
  },
1016
  space_status: {
1017
  is_full: spaceFull,
1018
  full_spaces: fullSpaces,
1019
  empty_spaces: emptySpaces,
1020
+ size_spaces: sizeSpaces,
1021
  all_spaces: SPACE_NAMES
1022
  },
1023
  image_processing: {
 
1031
  reply.header('Content-Type', 'text/plain');
1032
  return toJsonl(responseData);
1033
  });
1034
+
1035
  fastify.get('/status', async (request, reply) => {
1036
  const spaceFull = isSpaceFull();
1037
  await checkAndUpdateFullStatus();
1038
  const fullSpaces = await getFullSpaces();
1039
  const emptySpaces = SPACE_NAMES.filter(s => !fullSpaces.includes(s));
1040
+ const sizeSpaces = await getSizeSpaces();
1041
+ const cpuUsage = getCurrentCPUPercentage();
1042
+ const totalUsers = getTotalUsers();
1043
 
1044
  const responseData = {
1045
  worker_pid: process.pid,
 
1047
  is_full: spaceFull,
1048
  rate_limits: {
1049
  global_rps_current: globalRateLimiter.getCurrentCount(),
1050
+ global_rps_max: MAX_RPS,
1051
+ per_ip_rps_max: MAX_RPS
1052
  },
1053
  storage: {
1054
  type: redis ? 'RocksDB + Redis' : 'RocksDB',
 
1060
  ram: {
1061
  max_gb: 7,
1062
  current_mb: Math.round(getMemoryUsage() / (1024 * 1024) * 100) / 100,
1063
+ users_in_memory: totalUsers,
1064
  buffer_size: batchBuffer.length
1065
  },
1066
+ cpu: {
1067
+ usage_percent: cpuUsage.toFixed(1),
1068
+ is_overloaded: cpuUsage >= 98
1069
+ },
1070
  users: {
1071
+ current: totalUsers,
1072
  max: MAX_USERS,
1073
+ remaining: MAX_USERS - totalUsers,
1074
+ percent_full: MAX_USERS > 0 ? `${((totalUsers / MAX_USERS) * 100).toFixed(2)}%` : '0%',
1075
+ size_limit_30000_reached: totalUsers >= MAX_USERS_SIZE_LIMIT
1076
  },
1077
  full_spaces: fullSpaces,
1078
  empty_spaces: emptySpaces,
1079
+ size_spaces: sizeSpaces,
1080
  full_file_content: await fsp.readFile(FULL_FILE, 'utf8').catch(() => ''),
1081
+ size_file_content: await fsp.readFile(SIZE_FILE, 'utf8').catch(() => ''),
1082
  timestamp: new Date().toISOString()
1083
  };
1084
 
1085
  reply.header('Content-Type', 'text/plain');
1086
  return toJsonl(responseData);
1087
  });
1088
+
1089
  fastify.get('/health', async (request, reply) => {
1090
+ const cpuUsage = getCurrentCPUPercentage();
1091
  const responseData = {
1092
  worker_pid: process.pid,
1093
  status: 'healthy',
 
1097
  max_ram_gb: 7,
1098
  bucket_size: formatSize(getBucketSize()),
1099
  buffer_size: batchBuffer.length,
1100
+ cpu_usage_percent: cpuUsage.toFixed(1),
1101
  timestamp: new Date().toISOString()
1102
  };
1103
 
1104
  reply.header('Content-Type', 'text/plain');
1105
  return toJsonl(responseData);
1106
  });
1107
+
1108
  fastify.post('/signup', async (request, reply) => {
1109
  if (getTotalUsers() >= MAX_USERS) {
1110
  reply.status(507);
 
1167
  reply.header('Content-Type', 'text/plain');
1168
  return toJsonl(responseData);
1169
  });
1170
+
1171
  fastify.post('/login', async (request, reply) => {
1172
  const { username, password } = request.body || {};
1173
 
 
1217
  reply.header('Content-Type', 'text/plain');
1218
  return toJsonl(responseData);
1219
  });
1220
+
1221
  fastify.post('/logout', async (request, reply) => {
1222
  const { id } = request.body || {};
1223
 
 
1244
  reply.header('Content-Type', 'text/plain');
1245
  return toJsonl(responseData);
1246
  });
1247
+
1248
  fastify.put('/updateprofiledetails', async (request, reply) => {
1249
  const { id, ...data } = request.body || {};
1250
 
 
1289
  reply.header('Content-Type', 'text/plain');
1290
  return toJsonl(responseData);
1291
  });
1292
+
1293
  fastify.post('/uploadphoto', async (request, reply) => {
1294
  if (getBucketSize() >= MAX_BUCKET_SIZE) {
1295
  reply.status(507);
 
1323
  }
1324
 
1325
  const originalSizeKb = fileBuffer.length / 1024;
1326
+
1327
  addRequest(id, '', 'upload_photo', { original_size_kb: originalSizeKb }, fileBuffer);
1328
 
1329
  const responseData = {
 
1344
  return { detail: 'Upload failed' };
1345
  }
1346
  });
1347
+
1348
  fastify.get('/getuser', async (request, reply) => {
1349
  const { id } = request.query || {};
1350
 
 
1382
  reply.header('Content-Type', 'text/plain');
1383
  return toJsonl(responseData);
1384
  });
1385
+
1386
  fastify.get('/users/count', async (request, reply) => {
1387
  reply.header('Content-Type', 'text/plain');
1388
+ return toJsonl({
1389
+ worker_pid: process.pid,
1390
+ count: getTotalUsers()
1391
+ });
1392
  });
1393
+
1394
  fastify.get('/users', async (request, reply) => {
1395
  if (usersCache.size === 0) {
1396
  reply.header('Content-Type', 'text/plain');
 
1399
 
1400
  const stream = new Readable({
1401
  read() {
1402
+ this.push(toJsonl({
1403
+ worker_pid: process.pid,
1404
+ total: usersCache.size
1405
+ }));
1406
+
1407
  for (const user of usersCache.values()) {
1408
  this.push(toJsonl({
1409
  id: user.id,
 
1422
  last_profile_updated: safeGet(user.last_profile_updated)
1423
  }));
1424
  }
1425
+
1426
  this.push(null);
1427
  }
1428
  });
 
1430
  reply.header('Content-Type', 'text/plain');
1431
  return stream;
1432
  });
1433
+
1434
  fastify.get('/spaces', async (request, reply) => {
1435
  const fullSpaces = await getFullSpaces();
1436
  const emptySpaces = SPACE_NAMES.filter(s => !fullSpaces.includes(s));
1437
+ const sizeSpaces = await getSizeSpaces();
1438
 
1439
  reply.header('Content-Type', 'text/plain');
1440
  return toJsonl({
 
1442
  all_spaces: SPACE_NAMES,
1443
  full_spaces: fullSpaces,
1444
  empty_spaces: emptySpaces,
1445
+ size_spaces: sizeSpaces,
1446
  current_space: CURRENT_SPACE_NAME,
1447
  timestamp: new Date().toISOString()
1448
  });
1449
  });
1450
+
1451
  fastify.get('/buffer-status', async (request, reply) => {
1452
  let redisSize = 0;
1453
  if (redis) {
 
1458
  }
1459
  }
1460
 
1461
+ const cpuUsage = getCurrentCPUPercentage();
1462
+
1463
  reply.header('Content-Type', 'text/plain');
1464
  return toJsonl({
1465
  worker_pid: process.pid,
 
1468
  batch_size: BATCH_SIZE,
1469
  processing: batchBuffer.length > 0 ? 'active' : 'idle',
1470
  ram_usage_mb: Math.round(getMemoryUsage() / (1024 * 1024) * 100) / 100,
1471
+ cpu_usage_percent: cpuUsage.toFixed(1),
1472
  timestamp: new Date().toISOString()
1473
  });
1474
  });
1475
+
1476
  fastify.post('/forgotpassword', async (request, reply) => {
1477
  const { username, email, fing_key, new_password } = request.body || {};
1478
 
 
1532
  reply.header('Content-Type', 'text/plain');
1533
  return toJsonl(responseData);
1534
  });
1535
+
1536
  return fastify;
1537
  }
1538
+
1539
  // ============ STARTUP ============
1540
  async function start() {
1541
  try {
 
1558
  console.log(`Worker ${process.pid}: Loading users into memory...`);
1559
  await loadUsersToMemory();
1560
 
1561
+ console.log(`Worker ${process.pid}: Setting up full.txt and size.txt...`);
1562
  await checkAndUpdateFullStatus();
1563
 
1564
  console.log(`Worker ${process.pid}: Setting up Fastify...`);
 
1573
  }, 50); // Check every 50ms
1574
 
1575
  const port = process.env.PORT || 7860;
 
1576
  // CRITICAL: Bind to 0.0.0.0 for Hugging Face Spaces
1577
  await fastify.listen({ port, host: '0.0.0.0' });
1578
 
 
1583
  console.log(`Worker ${process.pid}: ๐Ÿ” Hash: SHA256 (HASH env: ${HASH.substring(0, 8)}...)`);
1584
  console.log(`Worker ${process.pid}: ๐Ÿ–ผ๏ธ Image format: WebP, max ${MAX_PHOTO_SIZE_KB}KB`);
1585
  console.log(`Worker ${process.pid}: ๐Ÿ“ Space: ${CURRENT_SPACE_NAME}`);
1586
+ console.log(`Worker ${process.pid}: ๐Ÿ“ˆ Max RPS: ${MAX_RPS} req/sec`);
1587
+ console.log(`Worker ${process.pid}: ๐Ÿ‘ฅ Max Users: ${MAX_USERS} (size.txt at ${MAX_USERS_SIZE_LIMIT})`);
1588
  } catch (err) {
1589
  console.error(`Worker ${process.pid}: Error during startup:`, err);
 
1590
  console.error(`Worker ${process.pid}: Stack trace:`, err.stack);
1591
  process.exit(1);
1592
  }
1593
  }
1594
+
1595
  // Handle worker shutdown
1596
  process.on('SIGTERM', async () => {
1597
  console.log(`Worker ${process.pid}: SIGTERM received. Shutting down...`);
 
1602
  if (db) await db.close();
1603
  process.exit(0);
1604
  });
1605
+
1606
  process.on('SIGINT', async () => {
1607
  console.log(`Worker ${process.pid}: SIGINT received. Shutting down...`);
1608
  await flushBatchToRedis();
 
1612
  if (db) await db.close();
1613
  process.exit(0);
1614
  });
1615
+
1616
  // Handle uncaught exceptions
1617
  process.on('uncaughtException', (err) => {
1618
  console.error(`Worker ${process.pid}: Uncaught exception:`, err);
1619
  console.error(`Worker ${process.pid}: Stack trace:`, err.stack);
1620
  // Don't exit, try to continue
1621
  });
1622
+
1623
  process.on('unhandledRejection', (reason, promise) => {
1624
  console.error(`Worker ${process.pid}: Unhandled rejection at:`, promise, 'reason:', reason);
1625
  // Don't exit, try to continue
1626
  });
1627
+
1628
  // Start worker
1629
  start().catch(err => {
1630
  console.error(`Worker ${process.pid}: Failed to start:`, err);