blaze-aura69 commited on
Commit
2fed9d6
·
verified ·
1 Parent(s): d85a422

Update index.js

Browse files
Files changed (1) hide show
  1. index.js +525 -524
index.js CHANGED
@@ -3,156 +3,157 @@ const { Worker: ThreadWorker, isMainThread, parentPort, workerData } = require('
3
 
4
  // ============ DATABASE WORKER THREAD ============
5
  if (!isMainThread) {
6
- const Database = require('better-sqlite3');
7
- const path = require('path');
8
- const fs = require('fs');
9
-
10
- const DATA_DIR = workerData.dataDir || "/data";
11
- if (!fs.existsSync(DATA_DIR)) {
12
- fs.mkdirSync(DATA_DIR, { recursive: true });
13
- }
14
-
15
- const dbPath = path.join(DATA_DIR, 'users.db');
16
- const db = new Database(dbPath);
17
- db.pragma('journal_mode = WAL');
18
- db.pragma('synchronous = OFF');
19
- db.pragma('cache_size = -2000000');
20
- db.pragma('temp_store = MEMORY');
21
- db.pragma('mmap_size = 268435456');
22
-
23
- db.exec(`
24
- CREATE TABLE IF NOT EXISTS users (
25
- id TEXT PRIMARY KEY,
26
- username TEXT UNIQUE NOT NULL,
27
- password_hash TEXT NOT NULL,
28
- name TEXT NOT NULL,
29
- created_at TEXT NOT NULL,
30
- is_login INTEGER DEFAULT 0,
31
- bio TEXT DEFAULT '',
32
- pic_url TEXT DEFAULT '',
33
- date_of_birth TEXT DEFAULT '',
34
- is_profile_public TEXT DEFAULT 'true'
35
- )
36
- `);
37
-
38
- db.exec(`CREATE INDEX IF NOT EXISTS idx_username ON users(username);`);
39
-
40
- const stmts = {
41
- getAllUsers: db.prepare('SELECT * FROM users'),
42
- getUserById: db.prepare('SELECT * FROM users WHERE id = ?'),
43
- getUserByUsername: db.prepare('SELECT * FROM users WHERE username = ?'),
44
- insertUser: db.prepare(`
45
- INSERT INTO users (
46
- id, username, password_hash, name, created_at, is_login,
47
- bio, pic_url, date_of_birth, is_profile_public
48
- ) VALUES (
49
- @id, @username, @password_hash, @name, @created_at, @is_login,
50
- @bio, @pic_url, @date_of_birth, @is_profile_public
51
- )
52
- `),
53
- updateLogin: db.prepare('UPDATE users SET is_login = ? WHERE id = ?'),
54
- updateProfile: db.prepare(`
55
- UPDATE users SET
56
- username = COALESCE(NULLIF(@username, ''), username),
57
- name = COALESCE(NULLIF(@name, ''), name),
58
- bio = COALESCE(NULLIF(@bio, ''), bio),
59
- date_of_birth = COALESCE(NULLIF(@date_of_birth, ''), date_of_birth),
60
- is_profile_public = COALESCE(NULLIF(@is_profile_public, ''), is_profile_public)
61
- WHERE id = @id
62
- `),
63
- updatePhoto: db.prepare('UPDATE users SET pic_url = ? WHERE id = ?'),
64
- getCount: db.prepare('SELECT COUNT(*) as count FROM users')
65
- };
66
-
67
- parentPort.on('message', async (message) => {
68
- const { id, action, data } = message;
69
- try {
70
- let result;
71
- switch (action) {
72
- case 'getAllUsers':
73
- result = stmts.getAllUsers.all();
74
- break;
75
- case 'getUserById':
76
- result = stmts.getUserById.get(data.userId);
77
- break;
78
- case 'getUserByUsername':
79
- result = stmts.getUserByUsername.get(data.username);
80
- break;
81
- case 'insertUser':
82
- stmts.insertUser.run(data.user);
83
- result = { success: true };
84
- break;
85
- case 'updateLogin':
86
- stmts.updateLogin.run(data.isLogin ? 1 : 0, data.userId);
87
- result = { success: true };
88
- break;
89
- case 'updateProfile':
90
- stmts.updateProfile.run({
91
- id: data.userId,
92
- username: data.username || '',
93
- name: data.name || 'Unknown',
94
- bio: data.bio || '',
95
- date_of_birth: data.date_of_birth || '',
96
- is_profile_public: data.is_profile_public || 'true'
97
- });
98
- result = { success: true };
99
- break;
100
- case 'updatePhoto':
101
- stmts.updatePhoto.run(data.picUrl, data.userId);
102
- result = { success: true };
103
- break;
104
- case 'batchOperation':
105
- result = processBatch(data.operations);
106
- break;
107
- case 'getCount':
108
- result = stmts.getCount.get().count;
109
- break;
110
- default:
111
- throw new Error(`Unknown action: ${action}`);
112
- }
113
- parentPort.postMessage({ id, success: true, result });
114
- } catch (error) {
115
- parentPort.postMessage({ id, success: false, error: error.message });
116
  }
117
- });
118
-
119
- function processBatch(operations) {
120
- const transaction = db.transaction(() => {
121
- for (const op of operations) {
122
- switch (op.action) {
123
- case 'signup':
124
- try { stmts.insertUser.run(op.user); } catch (e) {}
125
- break;
126
- case 'login':
127
- stmts.updateLogin.run(1, op.userId);
128
- break;
129
- case 'logout':
130
- stmts.updateLogin.run(0, op.userId);
131
- break;
132
- case 'updateProfile':
133
- stmts.updateProfile.run(op.data);
134
- break;
135
- case 'updatePhoto':
136
- stmts.updatePhoto.run(op.picUrl, op.userId);
137
- break;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
  }
139
- }
140
  });
141
- transaction();
142
- return { processed: operations.length };
143
- }
144
-
145
- return;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
  }
147
 
148
  // ============ MAIN THREAD ============
149
- const fastify = require('fastify')({
150
- logger: false,
151
- bodyLimit: 1048576,
152
- keepAliveTimeout: 61000,
153
- connectionTimeout: 61000,
154
- maxRequestsPerSocket: 0,
155
- requestTimeout: 30000
156
  });
157
 
158
  const cors = require('@fastify/cors');
@@ -164,7 +165,9 @@ const fsp = require('fs').promises;
164
  const path = require('path');
165
 
166
  let sharp;
167
- try { sharp = require('sharp'); } catch (e) {}
 
 
168
 
169
  const MAX_BUCKET_SIZE = 60 * 1024 * 1024 * 1024;
170
  const MAX_USERS = 30000;
@@ -172,7 +175,7 @@ const MAX_PHOTO_SIZE_KB = 20;
172
  const MAX_RPS = 15000;
173
  const BATCH_SIZE = 15000;
174
  const HASH = process.env.HASH || 'v3l0st-d3f4ult-h4sh-k3y-2024!@#$%^&*()';
175
- const SPACE_NAME = process.env.SPACE_NAME || '1';
176
  const MAX_USERNAME_LENGTH = 200;
177
  const MAX_NAME_LENGTH = 200;
178
  const MAX_PASSWORD_LENGTH = 200;
@@ -191,79 +194,81 @@ const FULL_FILE = path.join(STATUS_DIR, "full.txt");
191
  const SIZE_FILE = path.join(STATUS_DIR, "size.txt");
192
 
193
  [DATA_DIR, PHOTOS_DIR, STATUS_DIR].forEach(dir => {
194
- if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
195
  });
196
 
197
  if (!fs.existsSync(FULL_FILE)) fs.writeFileSync(FULL_FILE, '', 'utf8');
198
  if (!fs.existsSync(SIZE_FILE)) fs.writeFileSync(SIZE_FILE, '', 'utf8');
199
 
200
  async function getFullSpaces() {
201
- try {
202
- const content = await fsp.readFile(FULL_FILE, 'utf8');
203
- return content.trim() ? content.trim().split('|') : [];
204
- } catch (e) { return []; }
 
 
205
  }
206
 
207
  async function addSpaceToFull() {
208
- try {
209
- let content = await fsp.readFile(FULL_FILE, 'utf8').catch(() => '');
210
- content = content.trim();
211
- let spaces = content ? content.split('|') : [];
212
- if (!spaces.includes(SPACE_NAME)) {
213
- spaces.push(SPACE_NAME);
214
- await fsp.writeFile(FULL_FILE, spaces.join('|'), 'utf8');
215
- }
216
- } catch (e) {}
217
  }
218
 
219
  async function removeSpaceFromFull() {
220
- try {
221
- let content = await fsp.readFile(FULL_FILE, 'utf8').catch(() => '');
222
- content = content.trim();
223
- let spaces = content ? content.split('|') : [];
224
- const newSpaces = spaces.filter(s => s !== SPACE_NAME);
225
- if (newSpaces.length !== spaces.length) {
226
- await fsp.writeFile(FULL_FILE, newSpaces.join('|'), 'utf8');
227
- }
228
- } catch (e) {}
229
  }
230
 
231
  async function addSpaceToSize() {
232
- try {
233
- let content = await fsp.readFile(SIZE_FILE, 'utf8').catch(() => '');
234
- content = content.trim();
235
- let spaces = content ? content.split('|') : [];
236
- if (!spaces.includes(SPACE_NAME)) {
237
- spaces.push(SPACE_NAME);
238
- await fsp.writeFile(SIZE_FILE, spaces.join('|'), 'utf8');
239
- }
240
- } catch (e) {}
241
  }
242
 
243
  function checkRPSStatus() {
244
- const now = Date.now();
245
- if (now - rpsWindowStart >= 1000) {
246
- if (currentRPS >= MAX_RPS * 0.9 && !isSpaceFull_RPS) {
247
- isSpaceFull_RPS = true;
248
- addSpaceToFull();
249
- } else if (currentRPS < MAX_RPS * 0.7 && isSpaceFull_RPS) {
250
- isSpaceFull_RPS = false;
251
- removeSpaceFromFull();
 
 
 
252
  }
253
- currentRPS = 0;
254
- rpsWindowStart = now;
255
- }
256
  }
257
 
258
  async function checkUserCountStatus() {
259
- try {
260
- const count = await dbRequest('getCount');
261
- if (count >= MAX_USERS && !isSpaceFull_Users) {
262
- isSpaceFull_Users = true;
263
- await addSpaceToSize();
264
- await addSpaceToFull();
265
- }
266
- } catch (e) {}
267
  }
268
 
269
  let dbWorker;
@@ -271,382 +276,378 @@ let dbRequestId = 0;
271
  const dbPromises = new Map();
272
 
273
  function initDBWorker() {
274
- return new Promise((resolve, reject) => {
275
- dbWorker = new ThreadWorker(__filename, { workerData: { dataDir: DATA_DIR } });
276
- dbWorker.on('message', (message) => {
277
- const { id, success, result, error } = message;
278
- const promise = dbPromises.get(id);
279
- if (promise) {
280
- dbPromises.delete(id);
281
- if (success) promise.resolve(result);
282
- else promise.reject(new Error(error));
283
- }
 
 
 
 
 
284
  });
285
- dbWorker.on('error', reject);
286
- dbWorker.on('online', resolve);
287
- });
288
  }
289
 
290
  function dbRequest(action, data = {}) {
291
- return new Promise((resolve, reject) => {
292
- const id = ++dbRequestId;
293
- dbPromises.set(id, { resolve, reject });
294
- dbWorker.postMessage({ id, action, data });
295
- });
296
  }
297
 
298
  class FastRateLimiter {
299
- constructor(maxRequests = 15000, windowMs = 1000) {
300
- this.maxRequests = maxRequests;
301
- this.windowMs = windowMs;
302
- this.requests = 0;
303
- this.windowStart = Date.now();
304
- }
305
-
306
- isAllowed() {
307
- const now = Date.now();
308
- if (now - this.windowStart >= this.windowMs) {
309
- this.requests = 0;
310
- this.windowStart = now;
 
 
 
 
 
311
  }
312
- if (this.requests >= this.maxRequests) return false;
313
- this.requests++;
314
- currentRPS++;
315
- return true;
316
- }
317
  }
318
 
319
  const rateLimiter = new FastRateLimiter(15000, 1000);
320
 
321
  function hashPassword(password) {
322
- return crypto.createHash('sha256').update(HASH + password + HASH).digest('hex');
323
  }
324
 
325
  function verifyPassword(password, hash) {
326
- return hashPassword(password) === hash;
327
  }
328
 
329
  function generateId() {
330
- return crypto.randomBytes(16).toString('base64url').substring(0, 21);
331
  }
332
 
333
  function getBucketSize() {
334
- let totalSize = 0;
335
- try {
336
- const files = fs.readdirSync(PHOTOS_DIR);
337
- for (const file of files) {
338
- try { totalSize += fs.statSync(path.join(PHOTOS_DIR, file)).size; } catch (e) {}
339
- }
340
- try { totalSize += fs.statSync(path.join(DATA_DIR, 'users.db')).size; } catch (e) {}
341
- } catch (e) {}
342
- return totalSize;
 
 
 
 
343
  }
344
 
345
  async function compressToWebp(fileData, maxSizeKb = 20) {
346
- if (!sharp) return fileData;
347
- try {
348
- let image = sharp(fileData);
349
- const metadata = await image.metadata();
350
- const currentSizeKb = fileData.length / 1024;
351
- if (metadata.format === 'webp' && currentSizeKb <= maxSizeKb) return fileData;
352
-
353
- let quality = 80;
354
- let outputBuffer;
355
- while (quality >= 10) {
356
- outputBuffer = await image
357
- .resize(800, 800, { fit: 'inside', withoutEnlargement: true })
358
- .webp({ quality })
359
- .toBuffer();
360
- if (outputBuffer.length / 1024 <= maxSizeKb) break;
361
- quality -= 10;
362
- }
363
-
364
- if (outputBuffer.length / 1024 > maxSizeKb) {
365
- outputBuffer = await image
366
- .resize(400, 400, { fit: 'inside', withoutEnlargement: true })
367
- .webp({ quality: 30 })
368
- .toBuffer();
369
- }
370
- return outputBuffer;
371
- } catch (e) { return fileData; }
372
- }
373
-
374
- async function setupFastify() {
375
- await fastify.register(cors, { origin: '*' });
376
- await fastify.register(multipart, { limits: { fileSize: 5 * 1024 * 1024 } });
377
- await fastify.register(fastifyStatic, { root: PHOTOS_DIR, prefix: '/photos/', maxAge: 86400000 });
378
-
379
- fastify.addHook('onRequest', async (request, reply) => {
380
- if (!rateLimiter.isAllowed()) {
381
- reply.status(503).send({ error: 'rate_limit' });
382
- return;
383
- }
384
- });
385
-
386
- fastify.post('/signup', async (request, reply) => {
387
- const { username, password, name } = request.body || {};
388
- if (!username || !password || !name) {
389
- reply.status(400).send({ detail: 'Missing fields' });
390
- return;
391
- }
392
-
393
- const cleanUsername = username.trim().toLowerCase();
394
- if (cleanUsername.length < 3 || cleanUsername.length > MAX_USERNAME_LENGTH) {
395
- reply.status(400).send({ detail: `Username must be 3-${MAX_USERNAME_LENGTH} chars` });
396
- return;
397
- }
398
- if (password.length < 6 || password.length > MAX_PASSWORD_LENGTH) {
399
- reply.status(400).send({ detail: `Password must be 6-${MAX_PASSWORD_LENGTH} chars` });
400
- return;
401
- }
402
- if (name.trim().length > MAX_NAME_LENGTH) {
403
- reply.status(400).send({ detail: `Name max ${MAX_NAME_LENGTH} chars` });
404
- return;
405
- }
406
-
407
- // Check if username exists directly in DB
408
- const existingUser = await dbRequest('getUserByUsername', { username: cleanUsername });
409
- if (existingUser) {
410
- reply.status(409).send({ detail: 'Username exists' });
411
- return;
412
- }
413
-
414
- const count = await dbRequest('getCount');
415
- if (count >= MAX_USERS) {
416
- reply.status(507).send({ detail: 'Server full' });
417
- return;
418
- }
419
-
420
- const userId = generateId();
421
- const newUser = {
422
- id: userId,
423
- username: cleanUsername,
424
- password_hash: hashPassword(password),
425
- name: name.trim(),
426
- created_at: new Date().toISOString(),
427
- is_login: 0,
428
- bio: '',
429
- pic_url: '',
430
- date_of_birth: '',
431
- is_profile_public: 'true'
432
- };
433
-
434
  try {
435
- await dbRequest('insertUser', { user: newUser });
436
- totalUsers = count + 1;
437
- await checkUserCountStatus();
438
- reply.send({ success: true, user_id: userId, username: cleanUsername });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
439
  } catch (e) {
440
- reply.status(500).send({ detail: 'Signup failed' });
441
  }
442
- });
443
 
444
- fastify.post('/login', async (request, reply) => {
445
- const { username, password } = request.body || {};
446
- if (!username || !password) {
447
- reply.status(400).send({ detail: 'Missing fields' });
448
- return;
449
- }
450
-
451
- const cleanUsername = username.trim().toLowerCase();
452
- const user = await dbRequest('getUserByUsername', { username: cleanUsername });
453
- if (!user) {
454
- reply.status(401).send({ detail: 'Invalid credentials' });
455
- return;
456
- }
457
-
458
- if (!verifyPassword(password, user.password_hash)) {
459
- reply.status(401).send({ detail: 'Invalid credentials' });
460
- return;
461
- }
462
 
463
- await dbRequest('updateLogin', { userId: user.id, isLogin: true });
464
- reply.send({
465
- success: true,
466
- id: user.id,
467
- username: user.username,
468
- name: user.name,
469
- bio: user.bio || '',
470
- pic_url: user.pic_url || '',
471
- date_of_birth: user.date_of_birth || '',
472
- is_profile_public: user.is_profile_public || 'true',
473
- created_at: user.created_at
474
  });
475
- });
476
-
477
- fastify.post('/logout', async (request, reply) => {
478
- const { id } = request.body || {};
479
- if (!id) {
480
- reply.status(400).send({ detail: 'Missing ID' });
481
- return;
482
- }
483
-
484
- const user = await dbRequest('getUserById', { userId: id });
485
- if (!user) {
486
- reply.status(404).send({ detail: 'Not found' });
487
- return;
488
- }
489
 
490
- await dbRequest('updateLogin', { userId: id, isLogin: false });
491
- reply.send({ success: true });
492
- });
493
-
494
- fastify.put('/updateprofiledetails', async (request, reply) => {
495
- const { id, username, ...data } = request.body || {};
496
- if (!id) {
497
- reply.status(400).send({ detail: 'Missing ID' });
498
- return;
499
- }
500
-
501
- const user = await dbRequest('getUserById', { userId: id });
502
- if (!user) {
503
- reply.status(404).send({ detail: 'Not found' });
504
- return;
505
- }
506
-
507
- // Check if new username is provided and validate it
508
- if (username) {
509
- const cleanUsername = username.trim().toLowerCase();
510
- if (cleanUsername.length < 3 || cleanUsername.length > MAX_USERNAME_LENGTH) {
511
- reply.status(400).send({ detail: `Username must be 3-${MAX_USERNAME_LENGTH} chars` });
512
- return;
513
- }
514
-
515
- // Check if the new username is already taken by another user
516
- const existingUser = await dbRequest('getUserByUsername', { username: cleanUsername });
517
- if (existingUser && existingUser.id !== id) {
518
- reply.status(409).send({ detail: 'Username already taken' });
519
- return;
520
- }
521
-
522
- // Add the cleaned username to the update data
523
- data.username = cleanUsername;
524
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
525
 
526
- if (data.name && data.name.length > MAX_NAME_LENGTH) {
527
- reply.status(400).send({ detail: `Name max ${MAX_NAME_LENGTH} chars` });
528
- return;
529
- }
530
- if (data.bio && data.bio.length > MAX_BIO_LENGTH) {
531
- reply.status(400).send({ detail: `Bio max ${MAX_BIO_LENGTH} chars` });
532
- return;
533
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
534
 
535
- // Pass username to the update if provided
536
- await dbRequest('updateProfile', {
537
- userId: id,
538
- username: data.username || '', // Pass the new username or empty string
539
- ...data
 
 
 
 
 
 
 
 
 
 
540
  });
541
- reply.send({ success: true });
542
- });
543
-
544
- fastify.post('/uploadphoto', async (request, reply) => {
545
- if (getBucketSize() >= MAX_BUCKET_SIZE) {
546
- reply.status(507).send({ detail: 'Storage full' });
547
- return;
548
- }
549
 
550
- try {
551
- const data = await request.file();
552
- if (!data || !data.mimetype.startsWith('image/')) {
553
- reply.status(400).send({ detail: 'Invalid image' });
554
- return;
555
- }
556
-
557
- const fileBuffer = await data.toBuffer();
558
- const id = (data.fields && data.fields.id) ? data.fields.id.value : null;
559
- const user = await dbRequest('getUserById', { userId: id });
560
- if (!id || !user) {
561
- reply.status(404).send({ detail: 'Not found' });
562
- return;
563
- }
564
-
565
- const compressed = await compressToWebp(fileBuffer, MAX_PHOTO_SIZE_KB);
566
- const filename = `${id}_${Math.floor(Date.now() / 1000)}.webp`;
567
- await fsp.writeFile(path.join(PHOTOS_DIR, filename), compressed);
568
- await dbRequest('updatePhoto', { userId: id, picUrl: `/photos/${filename}` });
569
- reply.send({ success: true });
570
- } catch (e) {
571
- reply.status(500).send({ detail: 'Failed' });
572
- }
573
- });
574
-
575
- fastify.get('/getuser', async (request, reply) => {
576
- const { id, username } = request.query || {};
577
- let user;
578
- if (username) {
579
- user = await dbRequest('getUserByUsername', { username: username.toLowerCase() });
580
- } else if (id) {
581
- user = await dbRequest('getUserById', { userId: id });
582
- } else {
583
- reply.status(400).send({ detail: 'Missing params' });
584
- return;
585
- }
586
 
587
- if (!user) {
588
- reply.status(404).send({ detail: 'Not found' });
589
- return;
590
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
591
 
592
- reply.send({
593
- id: user.id,
594
- username: user.username,
595
- name: user.name,
596
- bio: user.bio || '',
597
- pic_url: user.pic_url || '',
598
- date_of_birth: user.date_of_birth || '',
599
- is_profile_public: user.is_profile_public || 'true',
600
- created_at: user.created_at,
601
- is_login: Boolean(user.is_login)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
602
  });
603
- });
604
-
605
- fastify.get('/check', async (request, reply) => {
606
- const count = await dbRequest('getCount');
607
- reply.send({
608
- status: 'ok',
609
- count: count,
610
- maxUsers: MAX_USERS,
611
- isFull: count >= MAX_USERS,
612
- spaceName: SPACE_NAME
613
  });
614
- });
615
-
616
- return fastify;
617
  }
618
 
619
  async function start() {
620
- try {
621
- await initDBWorker();
622
- // Get initial count
623
- totalUsers = await dbRequest('getCount');
624
- await setupFastify();
625
-
626
- setInterval(() => { checkRPSStatus(); }, 100);
627
- setInterval(async () => { await checkUserCountStatus(); }, 5000);
628
-
629
- const port = process.env.PORT || 7860;
630
- await fastify.listen({ port, host: '0.0.0.0' });
631
- console.log(`Server running on port ${port}`);
632
- } catch (err) {
633
- console.error('Startup error:', err.message);
634
- process.exit(1);
635
- }
 
 
 
 
 
 
 
636
  }
637
 
638
  process.on('SIGTERM', async () => {
639
- await removeSpaceFromFull();
640
- await fastify.close();
641
- if (dbWorker) await dbWorker.terminate();
642
- process.exit(0);
643
  });
644
 
645
  process.on('SIGINT', async () => {
646
- await removeSpaceFromFull();
647
- await fastify.close();
648
- if (dbWorker) await dbWorker.terminate();
649
- process.exit(0);
650
  });
651
 
652
  start().catch(err => process.exit(1));
 
3
 
4
  // ============ DATABASE WORKER THREAD ============
5
  if (!isMainThread) {
6
+ const Database = require('better-sqlite3');
7
+ const path = require('path');
8
+ const fs = require('fs');
9
+
10
+ const DATA_DIR = workerData.dataDir || "/data";
11
+ if (!fs.existsSync(DATA_DIR)) {
12
+ fs.mkdirSync(DATA_DIR, { recursive: true });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  }
14
+
15
+ const dbPath = path.join(DATA_DIR, 'users.db');
16
+ const db = new Database(dbPath);
17
+
18
+ db.pragma('journal_mode = WAL');
19
+ db.pragma('synchronous = OFF');
20
+ db.pragma('cache_size = -2000000');
21
+ db.pragma('temp_store = MEMORY');
22
+ db.pragma('mmap_size = 268435456');
23
+
24
+ db.exec(`
25
+ CREATE TABLE IF NOT EXISTS users (
26
+ id TEXT PRIMARY KEY,
27
+ username TEXT UNIQUE NOT NULL,
28
+ password_hash TEXT NOT NULL,
29
+ name TEXT NOT NULL,
30
+ created_at TEXT NOT NULL,
31
+ is_login INTEGER DEFAULT 0,
32
+ bio TEXT DEFAULT '',
33
+ pic_url TEXT DEFAULT '',
34
+ date_of_birth TEXT DEFAULT '',
35
+ is_profile_public TEXT DEFAULT 'true'
36
+ )
37
+ `);
38
+
39
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_username ON users(username);`);
40
+
41
+ const stmts = {
42
+ getAllUsers: db.prepare('SELECT * FROM users'),
43
+ getUserById: db.prepare('SELECT * FROM users WHERE id = ?'),
44
+ getUserByUsername: db.prepare('SELECT * FROM users WHERE username = ?'),
45
+ insertUser: db.prepare(`
46
+ INSERT INTO users (
47
+ id, username, password_hash, name, created_at, is_login,
48
+ bio, pic_url, date_of_birth, is_profile_public
49
+ ) VALUES (
50
+ @id, @username, @password_hash, @name, @created_at, @is_login,
51
+ @bio, @pic_url, @date_of_birth, @is_profile_public
52
+ )
53
+ `),
54
+ updateLogin: db.prepare('UPDATE users SET is_login = ? WHERE id = ?'),
55
+ updateProfile: db.prepare(`
56
+ UPDATE users SET
57
+ name = COALESCE(NULLIF(@name, ''), name),
58
+ bio = COALESCE(NULLIF(@bio, ''), bio),
59
+ date_of_birth = COALESCE(NULLIF(@date_of_birth, ''), date_of_birth),
60
+ is_profile_public = COALESCE(NULLIF(@is_profile_public, ''), is_profile_public)
61
+ WHERE id = @id
62
+ `),
63
+ updatePhoto: db.prepare('UPDATE users SET pic_url = ? WHERE id = ?'),
64
+ getCount: db.prepare('SELECT COUNT(*) as count FROM users')
65
+ };
66
+
67
+ parentPort.on('message', async (message) => {
68
+ const { id, action, data } = message;
69
+ try {
70
+ let result;
71
+ switch (action) {
72
+ case 'getAllUsers':
73
+ result = stmts.getAllUsers.all();
74
+ break;
75
+ case 'getUserById':
76
+ result = stmts.getUserById.get(data.userId);
77
+ break;
78
+ case 'getUserByUsername':
79
+ result = stmts.getUserByUsername.get(data.username);
80
+ break;
81
+ case 'insertUser':
82
+ stmts.insertUser.run(data.user);
83
+ result = { success: true };
84
+ break;
85
+ case 'updateLogin':
86
+ stmts.updateLogin.run(data.isLogin ? 1 : 0, data.userId);
87
+ result = { success: true };
88
+ break;
89
+ case 'updateProfile':
90
+ stmts.updateProfile.run({
91
+ id: data.userId,
92
+ name: data.name || 'Unknown',
93
+ bio: data.bio || '',
94
+ date_of_birth: data.date_of_birth || '',
95
+ is_profile_public: data.is_profile_public || 'true'
96
+ });
97
+ result = { success: true };
98
+ break;
99
+ case 'updatePhoto':
100
+ stmts.updatePhoto.run(data.picUrl, data.userId);
101
+ result = { success: true };
102
+ break;
103
+ case 'batchOperation':
104
+ result = processBatch(data.operations);
105
+ break;
106
+ case 'getCount':
107
+ result = stmts.getCount.get().count;
108
+ break;
109
+ default:
110
+ throw new Error(`Unknown action: ${action}`);
111
+ }
112
+ parentPort.postMessage({ id, success: true, result });
113
+ } catch (error) {
114
+ parentPort.postMessage({ id, success: false, error: error.message });
115
  }
 
116
  });
117
+
118
+ function processBatch(operations) {
119
+ const transaction = db.transaction(() => {
120
+ for (const op of operations) {
121
+ switch (op.action) {
122
+ case 'signup':
123
+ try {
124
+ stmts.insertUser.run(op.user);
125
+ } catch (e) {}
126
+ break;
127
+ case 'login':
128
+ stmts.updateLogin.run(1, op.userId);
129
+ break;
130
+ case 'logout':
131
+ stmts.updateLogin.run(0, op.userId);
132
+ break;
133
+ case 'updateProfile':
134
+ stmts.updateProfile.run(op.data);
135
+ break;
136
+ case 'updatePhoto':
137
+ stmts.updatePhoto.run(op.picUrl, op.userId);
138
+ break;
139
+ }
140
+ }
141
+ });
142
+ transaction();
143
+ return { processed: operations.length };
144
+ }
145
+
146
+ return;
147
  }
148
 
149
  // ============ MAIN THREAD ============
150
+ const fastify = require('fastify')({
151
+ logger: false,
152
+ bodyLimit: 1048576,
153
+ keepAliveTimeout: 61000,
154
+ connectionTimeout: 61000,
155
+ maxRequestsPerSocket: 0,
156
+ requestTimeout: 30000
157
  });
158
 
159
  const cors = require('@fastify/cors');
 
165
  const path = require('path');
166
 
167
  let sharp;
168
+ try {
169
+ sharp = require('sharp');
170
+ } catch (e) {}
171
 
172
  const MAX_BUCKET_SIZE = 60 * 1024 * 1024 * 1024;
173
  const MAX_USERS = 30000;
 
175
  const MAX_RPS = 15000;
176
  const BATCH_SIZE = 15000;
177
  const HASH = process.env.HASH || 'v3l0st-d3f4ult-h4sh-k3y-2024!@#$%^&*()';
178
+ const SPACE_NAME = process.env.SPACE_NAME || '2';
179
  const MAX_USERNAME_LENGTH = 200;
180
  const MAX_NAME_LENGTH = 200;
181
  const MAX_PASSWORD_LENGTH = 200;
 
194
  const SIZE_FILE = path.join(STATUS_DIR, "size.txt");
195
 
196
  [DATA_DIR, PHOTOS_DIR, STATUS_DIR].forEach(dir => {
197
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
198
  });
199
 
200
  if (!fs.existsSync(FULL_FILE)) fs.writeFileSync(FULL_FILE, '', 'utf8');
201
  if (!fs.existsSync(SIZE_FILE)) fs.writeFileSync(SIZE_FILE, '', 'utf8');
202
 
203
  async function getFullSpaces() {
204
+ try {
205
+ const content = await fsp.readFile(FULL_FILE, 'utf8');
206
+ return content.trim() ? content.trim().split('|') : [];
207
+ } catch (e) {
208
+ return [];
209
+ }
210
  }
211
 
212
  async function addSpaceToFull() {
213
+ try {
214
+ let content = await fsp.readFile(FULL_FILE, 'utf8').catch(() => '');
215
+ content = content.trim();
216
+ let spaces = content ? content.split('|') : [];
217
+ if (!spaces.includes(SPACE_NAME)) {
218
+ spaces.push(SPACE_NAME);
219
+ await fsp.writeFile(FULL_FILE, spaces.join('|'), 'utf8');
220
+ }
221
+ } catch (e) {}
222
  }
223
 
224
  async function removeSpaceFromFull() {
225
+ try {
226
+ let content = await fsp.readFile(FULL_FILE, 'utf8').catch(() => '');
227
+ content = content.trim();
228
+ let spaces = content ? content.split('|') : [];
229
+ const newSpaces = spaces.filter(s => s !== SPACE_NAME);
230
+ if (newSpaces.length !== spaces.length) {
231
+ await fsp.writeFile(FULL_FILE, newSpaces.join('|'), 'utf8');
232
+ }
233
+ } catch (e) {}
234
  }
235
 
236
  async function addSpaceToSize() {
237
+ try {
238
+ let content = await fsp.readFile(SIZE_FILE, 'utf8').catch(() => '');
239
+ content = content.trim();
240
+ let spaces = content ? content.split('|') : [];
241
+ if (!spaces.includes(SPACE_NAME)) {
242
+ spaces.push(SPACE_NAME);
243
+ await fsp.writeFile(SIZE_FILE, spaces.join('|'), 'utf8');
244
+ }
245
+ } catch (e) {}
246
  }
247
 
248
  function checkRPSStatus() {
249
+ const now = Date.now();
250
+ if (now - rpsWindowStart >= 1000) {
251
+ if (currentRPS >= MAX_RPS * 0.9 && !isSpaceFull_RPS) {
252
+ isSpaceFull_RPS = true;
253
+ addSpaceToFull();
254
+ } else if (currentRPS < MAX_RPS * 0.7 && isSpaceFull_RPS) {
255
+ isSpaceFull_RPS = false;
256
+ removeSpaceFromFull();
257
+ }
258
+ currentRPS = 0;
259
+ rpsWindowStart = now;
260
  }
 
 
 
261
  }
262
 
263
  async function checkUserCountStatus() {
264
+ try {
265
+ const count = await dbRequest('getCount');
266
+ if (count >= MAX_USERS && !isSpaceFull_Users) {
267
+ isSpaceFull_Users = true;
268
+ await addSpaceToSize();
269
+ await addSpaceToFull();
270
+ }
271
+ } catch (e) {}
272
  }
273
 
274
  let dbWorker;
 
276
  const dbPromises = new Map();
277
 
278
  function initDBWorker() {
279
+ return new Promise((resolve, reject) => {
280
+ dbWorker = new ThreadWorker(__filename, {
281
+ workerData: { dataDir: DATA_DIR }
282
+ });
283
+ dbWorker.on('message', (message) => {
284
+ const { id, success, result, error } = message;
285
+ const promise = dbPromises.get(id);
286
+ if (promise) {
287
+ dbPromises.delete(id);
288
+ if (success) promise.resolve(result);
289
+ else promise.reject(new Error(error));
290
+ }
291
+ });
292
+ dbWorker.on('error', reject);
293
+ dbWorker.on('online', resolve);
294
  });
 
 
 
295
  }
296
 
297
  function dbRequest(action, data = {}) {
298
+ return new Promise((resolve, reject) => {
299
+ const id = ++dbRequestId;
300
+ dbPromises.set(id, { resolve, reject });
301
+ dbWorker.postMessage({ id, action, data });
302
+ });
303
  }
304
 
305
  class FastRateLimiter {
306
+ constructor(maxRequests = 15000, windowMs = 1000) {
307
+ this.maxRequests = maxRequests;
308
+ this.windowMs = windowMs;
309
+ this.requests = 0;
310
+ this.windowStart = Date.now();
311
+ }
312
+
313
+ isAllowed() {
314
+ const now = Date.now();
315
+ if (now - this.windowStart >= this.windowMs) {
316
+ this.requests = 0;
317
+ this.windowStart = now;
318
+ }
319
+ if (this.requests >= this.maxRequests) return false;
320
+ this.requests++;
321
+ currentRPS++;
322
+ return true;
323
  }
 
 
 
 
 
324
  }
325
 
326
  const rateLimiter = new FastRateLimiter(15000, 1000);
327
 
328
  function hashPassword(password) {
329
+ return crypto.createHash('sha256').update(HASH + password + HASH).digest('hex');
330
  }
331
 
332
  function verifyPassword(password, hash) {
333
+ return hashPassword(password) === hash;
334
  }
335
 
336
  function generateId() {
337
+ return crypto.randomBytes(16).toString('base64url').substring(0, 21);
338
  }
339
 
340
  function getBucketSize() {
341
+ let totalSize = 0;
342
+ try {
343
+ const files = fs.readdirSync(PHOTOS_DIR);
344
+ for (const file of files) {
345
+ try {
346
+ totalSize += fs.statSync(path.join(PHOTOS_DIR, file)).size;
347
+ } catch (e) {}
348
+ }
349
+ try {
350
+ totalSize += fs.statSync(path.join(DATA_DIR, 'users.db')).size;
351
+ } catch (e) {}
352
+ } catch (e) {}
353
+ return totalSize;
354
  }
355
 
356
  async function compressToWebp(fileData, maxSizeKb = 20) {
357
+ if (!sharp) return fileData;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
358
  try {
359
+ let image = sharp(fileData);
360
+ const metadata = await image.metadata();
361
+ const currentSizeKb = fileData.length / 1024;
362
+ if (metadata.format === 'webp' && currentSizeKb <= maxSizeKb) return fileData;
363
+
364
+ let quality = 80;
365
+ let outputBuffer;
366
+ while (quality >= 10) {
367
+ outputBuffer = await image
368
+ .resize(800, 800, { fit: 'inside', withoutEnlargement: true })
369
+ .webp({ quality })
370
+ .toBuffer();
371
+ if (outputBuffer.length / 1024 <= maxSizeKb) break;
372
+ quality -= 10;
373
+ }
374
+
375
+ if (outputBuffer.length / 1024 > maxSizeKb) {
376
+ outputBuffer = await image
377
+ .resize(400, 400, { fit: 'inside', withoutEnlargement: true })
378
+ .webp({ quality: 30 })
379
+ .toBuffer();
380
+ }
381
+ return outputBuffer;
382
  } catch (e) {
383
+ return fileData;
384
  }
385
+ }
386
 
387
+ async function setupFastify() {
388
+ await fastify.register(cors, { origin: '*' });
389
+ await fastify.register(multipart, { limits: { fileSize: 5 * 1024 * 1024 } });
390
+ await fastify.register(fastifyStatic, { root: PHOTOS_DIR, prefix: '/photos/', maxAge: 86400000 });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
391
 
392
+ fastify.addHook('onRequest', async (request, reply) => {
393
+ if (!rateLimiter.isAllowed()) {
394
+ reply.status(503).send({ error: 'rate_limit' });
395
+ return;
396
+ }
 
 
 
 
 
 
397
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
398
 
399
+ fastify.post('/signup', async (request, reply) => {
400
+ const { username, password, name } = request.body || {};
401
+ if (!username || !password || !name) {
402
+ reply.status(400).send({ detail: 'Missing fields' });
403
+ return;
404
+ }
405
+
406
+ const cleanUsername = username.trim().toLowerCase();
407
+ if (cleanUsername.length < 3 || cleanUsername.length > MAX_USERNAME_LENGTH) {
408
+ reply.status(400).send({ detail: `Username must be 3-${MAX_USERNAME_LENGTH} chars` });
409
+ return;
410
+ }
411
+ if (password.length < 6 || password.length > MAX_PASSWORD_LENGTH) {
412
+ reply.status(400).send({ detail: `Password must be 6-${MAX_PASSWORD_LENGTH} chars` });
413
+ return;
414
+ }
415
+ if (name.trim().length > MAX_NAME_LENGTH) {
416
+ reply.status(400).send({ detail: `Name max ${MAX_NAME_LENGTH} chars` });
417
+ return;
418
+ }
419
+
420
+ // Check if username exists directly in DB
421
+ const existingUser = await dbRequest('getUserByUsername', { username: cleanUsername });
422
+ if (existingUser) {
423
+ reply.status(409).send({ detail: 'Username exists' });
424
+ return;
425
+ }
426
+
427
+ const count = await dbRequest('getCount');
428
+ if (count >= MAX_USERS) {
429
+ reply.status(507).send({ detail: 'Server full' });
430
+ return;
431
+ }
432
+
433
+ const userId = generateId();
434
+ const newUser = {
435
+ id: userId,
436
+ username: cleanUsername,
437
+ password_hash: hashPassword(password),
438
+ name: name.trim(),
439
+ created_at: new Date().toISOString(),
440
+ is_login: 0,
441
+ bio: '',
442
+ pic_url: '',
443
+ date_of_birth: '',
444
+ is_profile_public: 'true'
445
+ };
446
+
447
+ try {
448
+ await dbRequest('insertUser', { user: newUser });
449
+ totalUsers = count + 1;
450
+ await checkUserCountStatus();
451
+ reply.send({ success: true, user_id: userId, username: cleanUsername });
452
+ } catch (e) {
453
+ reply.status(500).send({ detail: 'Signup failed' });
454
+ }
455
+ });
456
 
457
+ fastify.post('/login', async (request, reply) => {
458
+ const { username, password } = request.body || {};
459
+ if (!username || !password) {
460
+ reply.status(400).send({ detail: 'Missing fields' });
461
+ return;
462
+ }
463
+
464
+ const cleanUsername = username.trim().toLowerCase();
465
+ const user = await dbRequest('getUserByUsername', { username: cleanUsername });
466
+
467
+ if (!user) {
468
+ reply.status(401).send({ detail: 'Invalid credentials' });
469
+ return;
470
+ }
471
+
472
+ if (!verifyPassword(password, user.password_hash)) {
473
+ reply.status(401).send({ detail: 'Invalid credentials' });
474
+ return;
475
+ }
476
+
477
+ await dbRequest('updateLogin', { userId: user.id, isLogin: true });
478
+
479
+ reply.send({
480
+ success: true,
481
+ id: user.id,
482
+ username: user.username,
483
+ name: user.name,
484
+ bio: user.bio || '',
485
+ pic_url: user.pic_url || '',
486
+ date_of_birth: user.date_of_birth || '',
487
+ is_profile_public: user.is_profile_public || 'true',
488
+ created_at: user.created_at
489
+ });
490
+ });
491
 
492
+ fastify.post('/logout', async (request, reply) => {
493
+ const { id } = request.body || {};
494
+ if (!id) {
495
+ reply.status(400).send({ detail: 'Missing ID' });
496
+ return;
497
+ }
498
+
499
+ const user = await dbRequest('getUserById', { userId: id });
500
+ if (!user) {
501
+ reply.status(404).send({ detail: 'Not found' });
502
+ return;
503
+ }
504
+
505
+ await dbRequest('updateLogin', { userId: id, isLogin: false });
506
+ reply.send({ success: true });
507
  });
 
 
 
 
 
 
 
 
508
 
509
+ fastify.put('/updateprofiledetails', async (request, reply) => {
510
+ const { id, ...data } = request.body || {};
511
+ if (!id) {
512
+ reply.status(400).send({ detail: 'Missing ID' });
513
+ return;
514
+ }
515
+
516
+ const user = await dbRequest('getUserById', { userId: id });
517
+ if (!user) {
518
+ reply.status(404).send({ detail: 'Not found' });
519
+ return;
520
+ }
521
+
522
+ if (data.name && data.name.length > MAX_NAME_LENGTH) {
523
+ reply.status(400).send({ detail: `Name max ${MAX_NAME_LENGTH} chars` });
524
+ return;
525
+ }
526
+ if (data.bio && data.bio.length > MAX_BIO_LENGTH) {
527
+ reply.status(400).send({ detail: `Bio max ${MAX_BIO_LENGTH} chars` });
528
+ return;
529
+ }
530
+
531
+ await dbRequest('updateProfile', { userId: id, ...data });
532
+ reply.send({ success: true });
533
+ });
 
 
 
 
 
 
 
 
 
 
 
534
 
535
+ fastify.post('/uploadphoto', async (request, reply) => {
536
+ if (getBucketSize() >= MAX_BUCKET_SIZE) {
537
+ reply.status(507).send({ detail: 'Storage full' });
538
+ return;
539
+ }
540
+
541
+ try {
542
+ const data = await request.file();
543
+ if (!data || !data.mimetype.startsWith('image/')) {
544
+ reply.status(400).send({ detail: 'Invalid image' });
545
+ return;
546
+ }
547
+
548
+ const fileBuffer = await data.toBuffer();
549
+ const id = (data.fields && data.fields.id) ? data.fields.id.value : null;
550
+
551
+ const user = await dbRequest('getUserById', { userId: id });
552
+ if (!id || !user) {
553
+ reply.status(404).send({ detail: 'Not found' });
554
+ return;
555
+ }
556
+
557
+ const compressed = await compressToWebp(fileBuffer, MAX_PHOTO_SIZE_KB);
558
+ const filename = `${id}_${Math.floor(Date.now() / 1000)}.webp`;
559
+ await fsp.writeFile(path.join(PHOTOS_DIR, filename), compressed);
560
+
561
+ await dbRequest('updatePhoto', { userId: id, picUrl: `/photos/${filename}` });
562
+ reply.send({ success: true });
563
+ } catch (e) {
564
+ reply.status(500).send({ detail: 'Failed' });
565
+ }
566
+ });
567
 
568
+ fastify.get('/getuser', async (request, reply) => {
569
+ const { id, username } = request.query || {};
570
+ let user;
571
+
572
+ if (username) {
573
+ user = await dbRequest('getUserByUsername', { username: username.toLowerCase() });
574
+ } else if (id) {
575
+ user = await dbRequest('getUserById', { userId: id });
576
+ } else {
577
+ reply.status(400).send({ detail: 'Missing params' });
578
+ return;
579
+ }
580
+
581
+ if (!user) {
582
+ reply.status(404).send({ detail: 'Not found' });
583
+ return;
584
+ }
585
+
586
+ reply.send({
587
+ id: user.id,
588
+ username: user.username,
589
+ name: user.name,
590
+ bio: user.bio || '',
591
+ pic_url: user.pic_url || '',
592
+ date_of_birth: user.date_of_birth || '',
593
+ is_profile_public: user.is_profile_public || 'true',
594
+ created_at: user.created_at,
595
+ is_login: Boolean(user.is_login)
596
+ });
597
  });
598
+
599
+ fastify.get('/check', async (request, reply) => {
600
+ const count = await dbRequest('getCount');
601
+ reply.send({
602
+ status: 'ok',
603
+ count: count,
604
+ maxUsers: MAX_USERS,
605
+ isFull: count >= MAX_USERS,
606
+ spaceName: SPACE_NAME
607
+ });
608
  });
609
+
610
+ return fastify;
 
611
  }
612
 
613
  async function start() {
614
+ try {
615
+ await initDBWorker();
616
+
617
+ // Get initial count
618
+ totalUsers = await dbRequest('getCount');
619
+
620
+ await setupFastify();
621
+
622
+ setInterval(() => {
623
+ checkRPSStatus();
624
+ }, 100);
625
+
626
+ setInterval(async () => {
627
+ await checkUserCountStatus();
628
+ }, 5000);
629
+
630
+ const port = process.env.PORT || 7860;
631
+ await fastify.listen({ port, host: '0.0.0.0' });
632
+ console.log(`Server running on port ${port}`);
633
+ } catch (err) {
634
+ console.error('Startup error:', err.message);
635
+ process.exit(1);
636
+ }
637
  }
638
 
639
  process.on('SIGTERM', async () => {
640
+ await removeSpaceFromFull();
641
+ await fastify.close();
642
+ if (dbWorker) await dbWorker.terminate();
643
+ process.exit(0);
644
  });
645
 
646
  process.on('SIGINT', async () => {
647
+ await removeSpaceFromFull();
648
+ await fastify.close();
649
+ if (dbWorker) await dbWorker.terminate();
650
+ process.exit(0);
651
  });
652
 
653
  start().catch(err => process.exit(1));