✨ server bundle

This commit is contained in:
Flam3rboy
2021-08-13 12:58:18 +02:00
parent 7a2711de71
commit 0802d5e6a8
14 changed files with 2997 additions and 219 deletions
+2750
View File
File diff suppressed because it is too large Load Diff
+42
View File
@@ -0,0 +1,42 @@
{
"name": "@fosscord/server",
"version": "1.0.0",
"description": "",
"main": "src/start.js",
"scripts": {
"linkInstall": "npm run --prefix ../util/ link && npm run --prefix ../api/ link && npm run --prefix ../cdn/ link && npm run --prefix ../gateway/ link",
"postinstall": "npm run linkInstall && npm link @fosscord/util && npm link @fosscord/api && npm link @fosscord/gateway && npm link @fosscord/cdn",
"build": "tsc -b .",
"start": "npm run build && node dist/start.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/fosscord/fosscord-api.git"
},
"keywords": [],
"author": "Fosscord",
"license": "AGPLV3",
"bugs": {
"url": "https://github.com/fosscord/fosscord-api/issues"
},
"homepage": "https://github.com/fosscord/fosscord-api#readme",
"devDependencies": {
"@types/async-exit-hook": "^2.0.0",
"@types/express": "^4.17.13",
"@types/node": "^16.6.1",
"@types/node-os-utils": "^1.2.0",
"typescript": "^4.3.5"
},
"dependencies": {
"@fosscord/api": "file:../api",
"@fosscord/cdn": "file:../cdn",
"@fosscord/gateway": "file:../gateway",
"@fosscord/util": "file:../util",
"async-exit-hook": "^2.0.1",
"express": "^4.17.1",
"link": "^0.1.5",
"mongodb-memory-server-global-4.4": "^7.3.6",
"node-os-utils": "^1.3.5"
}
}
+33
View File
@@ -0,0 +1,33 @@
process.on("unhandledRejection", console.error);
process.on("uncaughtException", console.error);
import http from "http";
import { FosscordServer as APIServer } from "@fosscord/api";
import { Server as GatewayServer } from "@fosscord/gateway";
import { CDNServer } from "@fosscord/cdn/";
import express from "express";
import { Config } from "../../util/dist";
const app = express();
const server = http.createServer();
const port = Number(process.env.PORT) || 8080;
const production = true;
server.on("request", app);
// @ts-ignore
const api = new APIServer({ server, port, production, app });
// @ts-ignore
const cdn = new CDNServer({ server, port, production, app });
// @ts-ignore
const gateway = new GatewayServer({ server, port, production });
async function main() {
await api.start();
await cdn.start();
await gateway.start();
if (!Config.get().gateway.endpoint) await Config.set({ gateway: { endpoint: `ws://localhost:${port}` } });
if (!Config.get().cdn.endpoint) await Config.set({ cdn: { endpoint: `http://localhost:${port}` } });
}
main().catch(console.error);
+74
View File
@@ -0,0 +1,74 @@
import fs from "fs";
import { MongoMemoryServer } from "mongodb-memory-server-global-4.4";
import path from "path";
import cluster from "cluster";
import os from "os";
import osu from "node-os-utils";
import exitHook from "async-exit-hook";
const cores = Number(process.env.threads) || 1 || os.cpus().length;
if (cluster.isMaster && !process.env.masterStarted) {
const dbPath = path.join(__dirname, "..", "..", "db");
const dbName = "fosscord";
const storageEngine = "wiredTiger";
const port = 27020;
const ip = "127.0.0.1";
var mongod: MongoMemoryServer;
fs.mkdirSync(dbPath, { recursive: true });
exitHook((callback: any) => {
(async () => {
console.log(`Stopping MongoDB ...`);
await mongod.stop();
console.log(`Stopped MongoDB`);
callback();
})();
});
process.env.masterStarted = "true";
setInterval(async () => {
const [cpuUsed, memory, network] = await Promise.all([osu.cpu.usage(), osu.mem.info(), osu.netstat.inOut()]);
if (typeof network === "object") {
console.log(`Network: in ${network.total.inputMb}mb | out ${network.total.outputMb}mb`);
}
console.log(
`[CPU] ${cpuUsed.toFixed(2)}% | [Memory] ${memory.usedMemMb.toFixed(0)}mb/${memory.totalMemMb.toFixed(0)}mb`
);
}, 1000 * 60);
(async () => {
console.log(`[Database] starting ...`);
mongod = new MongoMemoryServer({
instance: {
port,
ip,
dbName,
dbPath,
storageEngine,
auth: false, // by default `mongod` is started with '--noauth', start `mongod` with '--auth'
},
});
await mongod.start();
process.env.MONGO_URL = mongod.getUri(dbName);
console.log(`[CPU] ${osu.cpu.model()} Cores x${osu.cpu.count()}`);
console.log(`[System] ${await osu.os.oos()} ${os.arch()}`);
console.log(`[Database] started`);
console.log(`[Process] running with pid: ${process.pid}`);
// Fork workers.
for (let i = 0; i < cores; i++) {
cluster.fork();
}
cluster.on("exit", (worker: any, code: any, signal: any) => {
console.log(`[Worker] died with pid: ${worker.process.pid} , restarting ...`);
cluster.fork();
});
})();
} else {
require("./Server.js");
}
+68
View File
@@ -0,0 +1,68 @@
{
"include": ["src/**/*.ts"],
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "ESNext" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */,
"module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */,
"lib": ["ES2020"] /* Specify library files to be included in the compilation. */,
"allowJs": true /* Allow javascript files to be compiled. */,
"checkJs": true /* Report errors in .js files. */,
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
"declaration": true /* Generates corresponding '.d.ts' file. */,
"declarationMap": false /* Generates a sourcemap for each corresponding '.d.ts' file. */,
"sourceMap": true /* Generates corresponding '.map' file. */,
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./dist/" /* Redirect output structure to the directory. */,
"rootDir": "./src/" /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */,
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true /* Enable all strict type-checking options. */,
"noImplicitAny": true /* Raise error on expressions and declarations with an implied 'any' type. */,
"strictNullChecks": true /* Enable strict null checks. */,
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
"strictPropertyInitialization": false /* Enable strict checking of property initialization in classes. */,
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
"alwaysStrict": true /* Parse in strict mode and emit "use strict" for each source file. */,
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
"types": ["node"] /* Type declaration files to be included in compilation. */,
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"skipLibCheck": true /* Skip type checking of declaration files. */,
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
}
}