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