diff options
Diffstat (limited to 'bundle/src')
-rw-r--r-- | bundle/src/Server.ts | 99 | ||||
-rw-r--r-- | bundle/src/start.ts | 97 | ||||
-rw-r--r-- | bundle/src/stats.ts | 43 |
3 files changed, 0 insertions, 239 deletions
diff --git a/bundle/src/Server.ts b/bundle/src/Server.ts deleted file mode 100644 index 3ed98b15..00000000 --- a/bundle/src/Server.ts +++ /dev/null @@ -1,99 +0,0 @@ -process.on("unhandledRejection", console.error); -process.on("uncaughtException", console.error); - -import http from "http"; -import * as Api from "@fosscord/api"; -import * as Gateway from "@fosscord/gateway"; -import { CDNServer } from "@fosscord/cdn"; -import express from "express"; -import { green, bold, yellow } from "picocolors"; -import { Config, getOrInitialiseDatabase } from "@fosscord/util"; -import * as Sentry from "@sentry/node"; -import * as Tracing from "@sentry/tracing"; - -const app = express(); -const server = http.createServer(); -const port = Number(process.env.PORT) || 3001; -const production = process.env.NODE_ENV == "development" ? false : true; -server.on("request", app); - -// @ts-ignore -const api = new Api.FosscordServer({ server, port, production, app }); -// @ts-ignore -const cdn = new CDNServer({ server, port, production, app }); -// @ts-ignore -const gateway = new Gateway.Server({ server, port, production }); - -//this is what has been added for the /stop API route -process.on('SIGTERM', () => { - setTimeout(()=>process.exit(0), 3000) - server.close(() => { - console.log("Stop API has been successfully POSTed, SIGTERM sent") - }) -}) -//this is what has been added for the /stop API route - -async function main() { - server.listen(port); - await getOrInitialiseDatabase(); - await Config.init(); - // only set endpointPublic, if not already set - await Config.set({ - cdn: { - endpointClient: "${location.host}", - endpointPrivate: `http://localhost:${port}`, - }, - gateway: { - endpointClient: - '${location.protocol === "https:" ? "wss://" : "ws://"}${location.host}', - endpointPrivate: `ws://localhost:${port}`, - ...(!Config.get().gateway.endpointPublic && { - endpointPublic: `ws://localhost:${port}`, - }), - }, - // regions: { - // default: "fosscord", - // useDefaultAsOptimal: true, - // available: [ - // { - // id: "fosscord", - // name: "Fosscord", - // endpoint: "127.0.0.1:3001", - // vip: false, - // custom: false, - // deprecated: false, - // }, - // ], - // }, - } as any); - - //Sentry - if (Config.get().sentry.enabled) { - console.log( - `[Bundle] ${yellow("You are using Sentry! This may slightly impact performance on large loads!")}` - ); - Sentry.init({ - dsn: Config.get().sentry.endpoint, - integrations: [ - new Sentry.Integrations.Http({ tracing: true }), - new Tracing.Integrations.Express({ app }), - ], - tracesSampleRate: Config.get().sentry.traceSampleRate, - environment: Config.get().sentry.environment - }); - - app.use(Sentry.Handlers.requestHandler()); - app.use(Sentry.Handlers.tracingHandler()); - } - await Promise.all([api.start(), cdn.start(), gateway.start()]); - if (Config.get().sentry.enabled) { - app.use(Sentry.Handlers.errorHandler()); - app.use(function onError(err: any, req: any, res: any, next: any) { - res.statusCode = 500; - res.end(res.sentry + "\n"); - }); - } - console.log(`[Server] ${green(`listening on port ${bold(port)}`)}`); -} - -main().catch(console.error); diff --git a/bundle/src/start.ts b/bundle/src/start.ts deleted file mode 100644 index a20581c3..00000000 --- a/bundle/src/start.ts +++ /dev/null @@ -1,97 +0,0 @@ -// process.env.MONGOMS_DEBUG = "true"; -import "reflect-metadata"; -import cluster, { Worker } from "cluster"; -import os from "os"; -import { red, bold, yellow, cyan } from "picocolors"; -import { initStats } from "./stats"; -import { config } from "dotenv"; -config(); -import { execSync } from "child_process"; - -// TODO: add socket event transmission -let cores = 1; -try { - cores = Number(process.env.THREADS) || os.cpus().length; -} catch { - console.log("[API] Failed to get thread count! Using 1...") -} - -if (cluster.isMaster) { - function getCommitOrFail() { - try { - return execSync("git rev-parse HEAD").toString().trim(); - } catch (e) { - return null; - } - } - const commit = getCommitOrFail(); - - console.log( - bold(` -███████╗ ██████╗ ███████╗███████╗ ██████╗ ██████╗ ██████╗ ██████╗ -██╔════╝██╔═══██╗██╔════╝██╔════╝██╔════╝██╔═══██╗██╔══██╗██╔══██╗ -█████╗ ██║ ██║███████╗███████╗██║ ██║ ██║██████╔╝██║ ██║ -██╔══╝ ██║ ██║╚════██║╚════██║██║ ██║ ██║██╔══██╗██║ ██║ -██║ ╚██████╔╝███████║███████║╚██████╗╚██████╔╝██║ ██║██████╔╝ -╚═╝ ╚═════╝ ╚══════╝╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═════╝ - - fosscord-server | ${yellow( - `Pre-release (${ - commit !== null - ? commit.slice(0, 7) - : "Unknown (Git cannot be found)" - })` - )} - -Commit Hash: ${ - commit !== null - ? `${cyan(commit)} (${yellow(commit.slice(0, 7))})` - : "Unknown (Git cannot be found)" - } -Cores: ${cyan(os.cpus().length)} (Using ${cores} thread(s).) -`) - ); - - if (commit == null) { - console.log(yellow(`Warning: Git is not installed or not in PATH.`)); - } - - initStats(); - - console.log(`[Process] starting with ${cores} threads`); - - if (cores === 1) { - require("./Server"); - } else { - process.env.EVENT_TRANSMISSION = "process"; - - // Fork workers. - for (let i = 0; i < cores; i++) { - // Delay each worker start if using sqlite database to prevent locking it - let delay = process.env.DATABASE?.includes("://") ? 0 : i * 1000; - setTimeout(() => { - cluster.fork(); - console.log(`[Process] worker ${cyan(i)} started.`); - }, delay); - } - - cluster.on("message", (sender: Worker, message: any) => { - for (const id in cluster.workers) { - const worker = cluster.workers[id]; - if (worker === sender || !worker) continue; - worker.send(message); - } - }); - - cluster.on("exit", (worker: any, code: any, signal: any) => { - console.log( - `[Worker] ${red( - `died with PID: ${worker.process.pid} , restarting ...` - )}` - ); - cluster.fork(); - }); - } -} else { - require("./Server"); -} diff --git a/bundle/src/stats.ts b/bundle/src/stats.ts deleted file mode 100644 index 022b2000..00000000 --- a/bundle/src/stats.ts +++ /dev/null @@ -1,43 +0,0 @@ -import os from "os"; -import osu from "node-os-utils"; -import { red } from "picocolors"; - -export function initStats() { - console.log(`[Path] running in ${__dirname}`); - try { - console.log(`[CPU] ${osu.cpu.model()} Cores x${osu.cpu.count()}`); - } - catch { - console.log('[CPU] Failed to get cpu model!') - } - - console.log(`[System] ${os.platform()} ${os.arch()}`); - console.log(`[Process] running with PID: ${process.pid}`); - if (process.getuid && process.getuid() === 0) { - console.warn( - red( - `[Process] Warning fosscord is running as root, this highly discouraged and might expose your system vulnerable to attackers. Please run fosscord as a user without root privileges.` - ) - ); - } - - // TODO: node-os-utils might have a memory leak, more investigation needed - // TODO: doesn't work if spawned with multiple threads - // setInterval(async () => { - // const [cpuUsed, memory, network] = await Promise.all([ - // osu.cpu.usage(), - // osu.mem.info(), - // osu.netstat.inOut(), - // ]); - // let networkUsage = ""; - // if (typeof network === "object") { - // networkUsage = `| [Network]: in ${network.total.inputMb}mb | out ${network.total.outputMb}mb`; - // } - - // console.log( - // `[CPU] ${cpuUsed.toPrecision(3)}% | [Memory] ${Math.round( - // process.memoryUsage().rss / 1024 / 1024 - // )}mb/${memory.totalMemMb.toFixed(0)}mb ${networkUsage}` - // ); - // }, 1000 * 60 * 5); -} |