From 7f41933763357119125b8ac388e957ad1c98a4ab Mon Sep 17 00:00:00 2001 From: Flam3rboy <34555296+Flam3rboy@users.noreply.github.com> Date: Sun, 10 Oct 2021 11:02:25 +0200 Subject: :sparkles: changed and fixed compiler --- bundle/scripts/build.js | 112 ++++++---------------------------------------- bundle/scripts/install.js | 14 ++++++ 2 files changed, 28 insertions(+), 98 deletions(-) create mode 100644 bundle/scripts/install.js (limited to 'bundle/scripts') diff --git a/bundle/scripts/build.js b/bundle/scripts/build.js index 4266942f..2a82ec57 100644 --- a/bundle/scripts/build.js +++ b/bundle/scripts/build.js @@ -1,103 +1,19 @@ -const { spawn } = require("child_process"); +const { execSync } = require("child_process"); const path = require("path"); -const fs = require("fs"); -const { performance } = require("perf_hooks"); +const fse = require("fs-extra"); -let parts = "api,cdn,gateway,bundle".split(","); -const tscBin = path.join(__dirname, "..", "..", "util", "node_modules", "typescript", "bin", "tsc"); -const swcBin = path.join(__dirname, "..", "..", "util", "node_modules", "@swc", "cli", "bin", "swc"); +const api = path.join(__dirname, "..", "..", "api"); +const dist = path.join(__dirname, "..", "dist"); -// because npm run is slow we directly get the build script of the package.json script +fse.copySync(path.join(api, "assets"), path.join(dist, "api", "assets")); +fse.copySync(path.join(api, "client_test"), path.join(dist, "api", "client_test")); +fse.copySync(path.join(api, "locales"), path.join(dist, "api", "locales")); -function buildPackage(dir) { - const element = path.basename(dir); - - return require("esbuild").build({ - entryPoints: walk(path.join(dir, "src")), - bundle: false, - outdir: path.join(dir, "dist"), - target: "es2021", - // plugins don't really work because bundle is false - keepNames: false, - tsconfig: path.join(dir, "tsconfig.json"), - }); -} - -const importPart = /import (\* as )?(({[^}]+})|(\w+)) from ("[.\w-/@q]+")/g; -const importMod = /import ("[\w-/@q.]+")/g; -const exportDefault = /export default/g; -const exportAllAs = /export \* from (".+")/g; -const exportMod = /export ({[\w, ]+})/g; -const exportConst = /export (const|var|let) (\w+)/g; -const exportPart = /export ((async )?\w+) (\w+)/g; - -// resolves tsconfig paths + rewrites es6 imports/exports to require (because esbuild/swc doesn't work properly) -function transpileFiles() { - for (const part of ["gateway", "api", "cdn", "bundle"]) { - const files = walk(path.join(__dirname, "..", "..", part, "dist")); - for (const file of files) { - let content = fs.readFileSync(file, { encoding: "utf8" }); - content = content - .replace( - new RegExp(`@fosscord/${part}`), - path.relative(file, path.join(__dirname, "..", "..", part, "dist")).slice(3) - ) - .replace(importPart, `const $2 = require($5)`) - .replace(importMod, `require($1)`) - .replace(exportDefault, `module.exports =`) - .replace(exportAllAs, `module.exports = {...(module.exports)||{}, ...require($1)}`) - .replace(exportMod, "module.exports = $1") - .replace(exportConst, `let $2 = {};\nmodule.exports.$2 = $2`) - .replace(exportPart, `module.exports.$3 = $1 $3`); - fs.writeFileSync(file, content); - } - } -} - -function util() { - // const child = spawn("node", `${swcBin} src --out-dir dist --sync`.split(" "), { - const child = spawn("node", `${tscBin} -b .`.split(" "), { - cwd: path.join(__dirname, "..", "..", "util"), - env: process.env, +console.log( + execSync("node " + path.join(__dirname, "..", "node_modules", "typescript", "lib", "tsc.js") + " -p .", { + cwd: path.join(__dirname, ".."), shell: true, - }); - function log(data) { - console.log(`[util] ` + data.toString().slice(0, -1)); - } - child.stdout.on("data", log); - child.stderr.on("data", log); - child.on("error", (err) => console.error("util", err)); - return child; -} - -const start = performance.now(); - -async function main() { - console.log("[Build] starting ..."); - util(); - await Promise.all(parts.map((part) => buildPackage(path.join(__dirname, "..", "..", part)))); - transpileFiles(); -} - -main(); - -process.on("exit", () => { - console.log("[Build] took " + Math.round(performance.now() - start) + "ms"); -}); - -function walk(dir) { - var results = []; - var list = fs.readdirSync(dir); - list.forEach(function (file) { - file = path.join(dir, file); - var stat = fs.statSync(file); - if (stat && stat.isDirectory()) { - /* Recurse into a subdirectory */ - results = results.concat(walk(file)); - } else if (file.endsWith(".ts") || file.endsWith(".js")) { - /* Is a file */ - results.push(file); - } - }); - return results; -} + env: process.env, + encoding: "utf8", + }) +); diff --git a/bundle/scripts/install.js b/bundle/scripts/install.js new file mode 100644 index 00000000..3008b4c5 --- /dev/null +++ b/bundle/scripts/install.js @@ -0,0 +1,14 @@ +const path = require("path"); +const fs = require("fs"); +const parts = ["api", "util", "cdn", "gateway"]; + +const bundle = require("../package.json"); + +for (const part of parts) { + const { devDependencies, dependencies } = require(path.join("..", "..", part, "package.json")); + bundle.devDependencies = { ...bundle.devDependencies, ...devDependencies }; + bundle.dependencies = { ...bundle.dependencies, ...dependencies }; + delete bundle.dependencies["@fosscord/util"]; +} + +fs.writeFileSync(path.join(__dirname, "..", "package.json"), JSON.stringify(bundle, null, "\t"), { encoding: "utf8" }); -- cgit 1.5.1 From 4722dd5d978e39b203c4ded9c56697467b9f7ece Mon Sep 17 00:00:00 2001 From: Flam3rboy <34555296+Flam3rboy@users.noreply.github.com> Date: Sun, 10 Oct 2021 12:35:46 +0200 Subject: :bug: fix tsc compiler --- api/src/Server.ts | 3 ++- bundle/scripts/build.js | 36 +++++++++++++++++++++++++----------- bundle/tsconfig.json | 21 ++++++--------------- cdn/src/Server.ts | 14 ++++++++++---- util/src/util/TraverseDirectory.ts | 10 ++++++++++ util/src/util/index.ts | 1 + 6 files changed, 54 insertions(+), 31 deletions(-) create mode 100644 util/src/util/TraverseDirectory.ts (limited to 'bundle/scripts') diff --git a/api/src/Server.ts b/api/src/Server.ts index 19e3d245..1f11a295 100644 --- a/api/src/Server.ts +++ b/api/src/Server.ts @@ -11,6 +11,7 @@ import TestClient from "./middlewares/TestClient"; import { initTranslation } from "./middlewares/Translation"; import morgan from "morgan"; import { initInstance } from "./util/Instance"; +import { registerRoutes } from "@fosscord/util"; export interface FosscordServerOptions extends ServerOptions {} @@ -72,7 +73,7 @@ export class FosscordServer extends Server { await initRateLimits(api); await initTranslation(api); - this.routes = await this.registerRoutes(path.join(__dirname, "routes", "/")); + this.routes = await registerRoutes(this, path.join(__dirname, "routes", "/")); api.use("*", (error: any, req: Request, res: Response, next: NextFunction) => { if (error) return next(error); diff --git a/bundle/scripts/build.js b/bundle/scripts/build.js index 2a82ec57..69111c88 100644 --- a/bundle/scripts/build.js +++ b/bundle/scripts/build.js @@ -2,18 +2,32 @@ const { execSync } = require("child_process"); const path = require("path"); const fse = require("fs-extra"); -const api = path.join(__dirname, "..", "..", "api"); -const dist = path.join(__dirname, "..", "dist"); +fse.copySync(path.join(__dirname, "..", "..", "api", "assets"), path.join(__dirname, "..", "dist", "api", "assets")); +fse.copySync( + path.join(__dirname, "..", "..", "api", "client_test"), + path.join(__dirname, "..", "dist", "api", "client_test") +); +fse.copySync(path.join(__dirname, "..", "..", "api", "locales"), path.join(__dirname, "..", "dist", "api", "locales")); +fse.copySync(path.join(__dirname, "..", "..", "api", "src"), path.join(__dirname, "..", "dist", "api", "src")); +fse.copySync(path.join(__dirname, "..", "..", "util", "src"), path.join(__dirname, "..", "dist", "util", "src")); +fse.copySync(path.join(__dirname, "..", "..", "cdn", "src"), path.join(__dirname, "..", "dist", "cdn", "src")); +fse.copySync(path.join(__dirname, "..", "..", "gateway", "src"), path.join(__dirname, "..", "dist", "gateway", "src")); +fse.copySync(path.join(__dirname, "..", "..", "bundle", "src"), path.join(__dirname, "..", "dist", "bundle", "src")); -fse.copySync(path.join(api, "assets"), path.join(dist, "api", "assets")); -fse.copySync(path.join(api, "client_test"), path.join(dist, "api", "client_test")); -fse.copySync(path.join(api, "locales"), path.join(dist, "api", "locales")); +console.log("Copying src files done"); +console.log("Compiling src files ..."); console.log( - execSync("node " + path.join(__dirname, "..", "node_modules", "typescript", "lib", "tsc.js") + " -p .", { - cwd: path.join(__dirname, ".."), - shell: true, - env: process.env, - encoding: "utf8", - }) + execSync( + "node " + + path.join(__dirname, "..", "node_modules", "typescript", "lib", "tsc.js") + + " -p " + + path.join(__dirname, ".."), + { + cwd: path.join(__dirname, ".."), + shell: true, + env: process.env, + encoding: "utf8", + } + ) ); diff --git a/bundle/tsconfig.json b/bundle/tsconfig.json index 1b2949da..4e8db342 100644 --- a/bundle/tsconfig.json +++ b/bundle/tsconfig.json @@ -1,16 +1,11 @@ { - "include": [ - "../api/src/**/*.ts", - "../gateway/src/**/*.ts", - "../cdn/src/**/*.ts", - "../util/src/**/*.ts", - "src/**/*.ts" - ], + "include": ["dist/**/*.ts"], + "exclude": [], "compilerOptions": { /* Visit https://aka.ms/tsconfig.json to read more about this file */ /* Basic Options */ - "incremental": true /* Enable incremental compilation */, + "incremental": false /* Enable incremental compilation */, "target": "ES6" /* 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": ["ES2021"] /* Specify library files to be included in the compilation. */, @@ -22,7 +17,7 @@ "sourceMap": false /* Generates corresponding '.map' file. */, // "outFile": "./", /* Concatenate and emit output to single file. */ "outDir": "./dist/" /* Redirect output structure to the directory. */, - "rootDir": "../" /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */, + "rootDir": "./dist/" /* 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. */ @@ -73,16 +68,12 @@ "emitDecoratorMetadata": true, "experimentalDecorators": true, "resolveJsonModule": true, - "baseUrl": "..", + "baseUrl": "./dist/", "paths": { "@fosscord/api": ["api/src/index"], - "@fosscord/api/*": ["api/src/*"], "@fosscord/gateway": ["gateway/src/index"], - "@fosscord/gateway/*": ["gateway/src/*"], "@fosscord/cdn": ["cdn/src/index"], - "@fosscord/cdn/*": ["cdn/src/*"], - "@fosscord/util": ["util/src/index"], - "@fosscord/util/*": ["util/src/*"] + "@fosscord/util": ["util/src/index"] }, "plugins": [{ "transform": "@zerollup/ts-transform-paths" }] } diff --git a/cdn/src/Server.ts b/cdn/src/Server.ts index 590eda6f..cac34a80 100644 --- a/cdn/src/Server.ts +++ b/cdn/src/Server.ts @@ -1,5 +1,5 @@ import { Server, ServerOptions } from "lambert-server"; -import { Config, initDatabase } from "@fosscord/util"; +import { Config, initDatabase, registerRoutes } from "@fosscord/util"; import path from "path"; import avatarsRoute from "./routes/avatars"; import bodyParser from "body-parser"; @@ -23,13 +23,19 @@ export class CDNServer extends Server { "Content-security-policy", "default-src * data: blob: filesystem: about: ws: wss: 'unsafe-inline' 'unsafe-eval'; script-src * data: blob: 'unsafe-inline' 'unsafe-eval'; connect-src * data: blob: 'unsafe-inline'; img-src * data: blob: 'unsafe-inline'; frame-src * data: blob: ; style-src * data: blob: 'unsafe-inline'; font-src * data: blob: 'unsafe-inline';" ); - res.set("Access-Control-Allow-Headers", req.header("Access-Control-Request-Headers") || "*"); - res.set("Access-Control-Allow-Methods", req.header("Access-Control-Request-Methods") || "*"); + res.set( + "Access-Control-Allow-Headers", + req.header("Access-Control-Request-Headers") || "*" + ); + res.set( + "Access-Control-Allow-Methods", + req.header("Access-Control-Request-Methods") || "*" + ); next(); }); this.app.use(bodyParser.json({ inflate: true, limit: "10mb" })); - await this.registerRoutes(path.join(__dirname, "routes/")); + await registerRoutes(this, path.join(__dirname, "routes/")); this.app.use("/icons/", avatarsRoute); this.log("verbose", "[Server] Route /icons registered"); diff --git a/util/src/util/TraverseDirectory.ts b/util/src/util/TraverseDirectory.ts new file mode 100644 index 00000000..275b7dcc --- /dev/null +++ b/util/src/util/TraverseDirectory.ts @@ -0,0 +1,10 @@ +import { Server, traverseDirectory } from "lambert-server"; + +const DEFAULT_FILTER = /^([^\.].*)(? Date: Sun, 10 Oct 2021 17:55:48 +0200 Subject: Fix duplicate key --- api/assets/schemas.json | 2 +- api/src/routes/guilds/#guild_id/vanity-url.ts | 9 +++------ api/src/routes/invites/index.ts | 1 - bundle/scripts/build.js | 27 +++++++++++++++++++++------ util/src/entities/Guild.ts | 8 -------- util/src/entities/Invite.ts | 3 +++ 6 files changed, 28 insertions(+), 22 deletions(-) (limited to 'bundle/scripts') diff --git a/api/assets/schemas.json b/api/assets/schemas.json index 4f1ab9a8..a12925e0 100644 --- a/api/assets/schemas.json +++ b/api/assets/schemas.json @@ -4744,7 +4744,7 @@ "type": "string" }, "permissions": { - "type": "bigint" + "type": "array" }, "color": { "type": "integer" diff --git a/api/src/routes/guilds/#guild_id/vanity-url.ts b/api/src/routes/guilds/#guild_id/vanity-url.ts index 7f2cea9e..061b317c 100644 --- a/api/src/routes/guilds/#guild_id/vanity-url.ts +++ b/api/src/routes/guilds/#guild_id/vanity-url.ts @@ -10,10 +10,10 @@ const InviteRegex = /\W/g; router.get("/", route({ permission: "MANAGE_GUILD" }), async (req: Request, res: Response) => { const { guild_id } = req.params; - const guild = await Guild.findOneOrFail({ where: { id: guild_id }, relations: ["vanity_url"] }); - if (!guild.vanity_url) return res.json({ code: null }); + const invite = await Invite.findOne({ where: {guild_id: guild_id, vanity_url: true} }); + if (!invite) return res.json({ code: null }); - return res.json({ code: guild.vanity_url_code, uses: guild.vanity_url.uses }); + return res.json({ code: invite.code, uses: invite.uses }); }); export interface VanityUrlSchema { @@ -33,12 +33,9 @@ router.patch("/", route({ body: "VanityUrlSchema", permission: "MANAGE_GUILD" }) const invite = await Invite.findOne({ code }); if (invite) throw new HTTPError("Invite already exists"); - const guild = await Guild.findOneOrFail({ id: guild_id }); const { id } = await Channel.findOneOrFail({ guild_id, type: ChannelType.GUILD_TEXT }); Promise.all([ - Guild.update({ id: guild_id }, { vanity_url_code: code }), - Invite.delete({ code: guild.vanity_url_code }), new Invite({ code: code, uses: 0, diff --git a/api/src/routes/invites/index.ts b/api/src/routes/invites/index.ts index 0fcf7c86..185311bc 100644 --- a/api/src/routes/invites/index.ts +++ b/api/src/routes/invites/index.ts @@ -33,7 +33,6 @@ router.delete("/:code", route({}), async (req: Request, res: Response) => { await Promise.all([ Invite.delete({ code }), - Guild.update({ vanity_url_code: code }, { vanity_url_code: undefined }), emitEvent({ event: "INVITE_DELETE", guild_id: guild_id, diff --git a/bundle/scripts/build.js b/bundle/scripts/build.js index 69111c88..a9798eff 100644 --- a/bundle/scripts/build.js +++ b/bundle/scripts/build.js @@ -1,6 +1,22 @@ const { execSync } = require("child_process"); const path = require("path"); const fse = require("fs-extra"); +const { getSystemErrorMap } = require("util"); +const { argv } = require("process"); + +const dirs = ["api", "util", "cdn", "gateway", "bundle"]; + +const verbose = argv.includes("verbose") || argv.includes("v"); + +if(argv.includes("clean")){ + dirs.forEach(a=>{ + var d = "../"+a+"/dist"; + if(fse.existsSync(d)) { + fse.rmSync(d,{recursive: true}); + if(verbose) console.log(`Deleted ${d}!`); + } + }); +} fse.copySync(path.join(__dirname, "..", "..", "api", "assets"), path.join(__dirname, "..", "dist", "api", "assets")); fse.copySync( @@ -8,13 +24,12 @@ fse.copySync( path.join(__dirname, "..", "dist", "api", "client_test") ); fse.copySync(path.join(__dirname, "..", "..", "api", "locales"), path.join(__dirname, "..", "dist", "api", "locales")); -fse.copySync(path.join(__dirname, "..", "..", "api", "src"), path.join(__dirname, "..", "dist", "api", "src")); -fse.copySync(path.join(__dirname, "..", "..", "util", "src"), path.join(__dirname, "..", "dist", "util", "src")); -fse.copySync(path.join(__dirname, "..", "..", "cdn", "src"), path.join(__dirname, "..", "dist", "cdn", "src")); -fse.copySync(path.join(__dirname, "..", "..", "gateway", "src"), path.join(__dirname, "..", "dist", "gateway", "src")); -fse.copySync(path.join(__dirname, "..", "..", "bundle", "src"), path.join(__dirname, "..", "dist", "bundle", "src")); +dirs.forEach(a=>{ + fse.copySync("../"+a+"/src", "dist/"+a+"/src"); + if(verbose) console.log(`Copied ${"../"+a+"/dist"} -> ${"dist/"+a+"/src"}!`); +}); -console.log("Copying src files done"); +console.log("Copying src files done"); console.log("Compiling src files ..."); console.log( diff --git a/util/src/entities/Guild.ts b/util/src/entities/Guild.ts index 35595191..157f0921 100644 --- a/util/src/entities/Guild.ts +++ b/util/src/entities/Guild.ts @@ -257,14 +257,6 @@ export class Guild extends BaseClass { @Column({ nullable: true }) unavailable?: boolean; - @Column({ nullable: true }) - @RelationId((guild: Guild) => guild.vanity_url) - vanity_url_code?: string; - - @JoinColumn({ name: "vanity_url_code" }) - @ManyToOne(() => Invite) - vanity_url?: Invite; - @Column({ nullable: true }) verification_level?: number; diff --git a/util/src/entities/Invite.ts b/util/src/entities/Invite.ts index 82556fab..d6b8f2f8 100644 --- a/util/src/entities/Invite.ts +++ b/util/src/entities/Invite.ts @@ -71,6 +71,9 @@ export class Invite extends BaseClass { @Column({ nullable: true }) target_user_type?: number; + @Column({ nullable: true}) + vanity_url?: boolean; + static async joinGuild(user_id: string, code: string) { const invite = await Invite.findOneOrFail({ code }); if (invite.uses++ >= invite.max_uses && invite.max_uses !== 0) await Invite.delete({ code }); -- cgit 1.5.1 From 5d20c6246f299a3e71cbe862094cb37e2498d429 Mon Sep 17 00:00:00 2001 From: Maddy Date: Mon, 11 Oct 2021 18:16:22 +1100 Subject: npm run build on Windows with usernames containing space fails, fixed by wrapping tscBin in quotes --- bundle/scripts/build.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'bundle/scripts') diff --git a/bundle/scripts/build.js b/bundle/scripts/build.js index 05cf37ce..d7bd23d9 100644 --- a/bundle/scripts/build.js +++ b/bundle/scripts/build.js @@ -56,7 +56,7 @@ function transpileFiles() { function util() { // const child = spawn("node", `${swcBin} src --out-dir dist --sync`.split(" "), { - const child = spawn("node", `${tscBin} -b .`.split(" "), { + const child = spawn("node", `\"${tscBin}\" -b .`.split(" "), { cwd: path.join(__dirname, "..", "..", "util"), env: process.env, shell: true, -- cgit 1.5.1 From 72a25042994d7c6d63816cd2637ef93f3b3ee01d Mon Sep 17 00:00:00 2001 From: Maddy Date: Tue, 12 Oct 2021 16:14:37 +1100 Subject: npm run build on Windows with usernames containing spaces fails, fixed by escaping tsc.js location in node_modules --- bundle/scripts/build.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'bundle/scripts') diff --git a/bundle/scripts/build.js b/bundle/scripts/build.js index a9798eff..e8eb24b8 100644 --- a/bundle/scripts/build.js +++ b/bundle/scripts/build.js @@ -34,9 +34,9 @@ console.log("Compiling src files ..."); console.log( execSync( - "node " + + "node \"" + path.join(__dirname, "..", "node_modules", "typescript", "lib", "tsc.js") + - " -p " + + "\" -p " + path.join(__dirname, ".."), { cwd: path.join(__dirname, ".."), -- cgit 1.5.1 From 222767591e1a059fbc5327ee0d7fc8bb6b793398 Mon Sep 17 00:00:00 2001 From: Maddy Date: Tue, 12 Oct 2021 17:05:24 +1100 Subject: ...actually fix windows usernames breaking npm run setup ( I forgot to quote second argument :/ ) --- bundle/scripts/build.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'bundle/scripts') diff --git a/bundle/scripts/build.js b/bundle/scripts/build.js index e8eb24b8..dfbaec15 100644 --- a/bundle/scripts/build.js +++ b/bundle/scripts/build.js @@ -36,8 +36,8 @@ console.log( execSync( "node \"" + path.join(__dirname, "..", "node_modules", "typescript", "lib", "tsc.js") + - "\" -p " + - path.join(__dirname, ".."), + "\" -p \"" + + path.join(__dirname, "..") + "\"", { cwd: path.join(__dirname, ".."), shell: true, -- cgit 1.5.1 From 270ad5ee385a55f2160cbf76471aa8d4052c2a89 Mon Sep 17 00:00:00 2001 From: Flam3rboy <34555296+Flam3rboy@users.noreply.github.com> Date: Tue, 12 Oct 2021 21:52:35 +0200 Subject: :zap: benchmark tests --- bundle/scripts/benchmark/connections.js | 58 +++++++++++++++++++++++++++++++++ bundle/scripts/benchmark/index.js | 4 +++ bundle/scripts/benchmark/messages.js | 1 + 3 files changed, 63 insertions(+) create mode 100644 bundle/scripts/benchmark/connections.js create mode 100644 bundle/scripts/benchmark/index.js create mode 100644 bundle/scripts/benchmark/messages.js (limited to 'bundle/scripts') diff --git a/bundle/scripts/benchmark/connections.js b/bundle/scripts/benchmark/connections.js new file mode 100644 index 00000000..efc1bcb6 --- /dev/null +++ b/bundle/scripts/benchmark/connections.js @@ -0,0 +1,58 @@ +const cluster = require("cluster"); +const WebSocket = require("ws"); +const endpoint = process.env.GATEWAY || "ws://localhost:3001"; +const connections = Number(process.env.CONNECTIONS) || 50; +const threads = Number(process.env.THREADS) || require("os").cpus().length || 1; +const token = process.env.TOKEN; + +if (!token) { + console.error("TOKEN env var missing"); + process.exit(); +} + +if (cluster.isMaster) { + for (let i = 0; i < threads; i++) { + cluster.fork(); + } + + cluster.on("exit", (worker, code, signal) => { + console.log(`worker ${worker.process.pid} died`); + }); +} else { + for (let i = 0; i < connections; i++) { + connect(); + } +} + +function connect() { + const client = new WebSocket(endpoint); + client.on("message", (data) => { + data = JSON.parse(data); + + switch (data.op) { + case 10: + client.interval = setInterval(() => { + client.send(JSON.stringify({ op: 1 })); + }, data.d.heartbeat_interval); + + client.send( + JSON.stringify({ + op: 2, + d: { + token, + properties: {}, + }, + }) + ); + + break; + } + }); + client.once("close", (code, reason) => { + clearInterval(client.interval); + connect(); + }); + client.on("error", (err) => { + // console.log(err); + }); +} diff --git a/bundle/scripts/benchmark/index.js b/bundle/scripts/benchmark/index.js new file mode 100644 index 00000000..37ac5633 --- /dev/null +++ b/bundle/scripts/benchmark/index.js @@ -0,0 +1,4 @@ +require("dotenv").config(); + +require("./connections"); +require("./messages"); diff --git a/bundle/scripts/benchmark/messages.js b/bundle/scripts/benchmark/messages.js new file mode 100644 index 00000000..70b786d1 --- /dev/null +++ b/bundle/scripts/benchmark/messages.js @@ -0,0 +1 @@ +// TODO -- cgit 1.5.1 From 64f4fe0591b267b8da85607070e51cf7bfb767cc Mon Sep 17 00:00:00 2001 From: Flam3rboy <34555296+Flam3rboy@users.noreply.github.com> Date: Sun, 17 Oct 2021 00:40:26 +0200 Subject: :zap: added benchmark --- bundle/scripts/benchmark/connections.js | 1 + bundle/scripts/benchmark/messages.js | 1 - bundle/scripts/benchmark/users.js | 25 +++++++++++++++++++++++++ 3 files changed, 26 insertions(+), 1 deletion(-) delete mode 100644 bundle/scripts/benchmark/messages.js create mode 100644 bundle/scripts/benchmark/users.js (limited to 'bundle/scripts') diff --git a/bundle/scripts/benchmark/connections.js b/bundle/scripts/benchmark/connections.js index efc1bcb6..2a4125b4 100644 --- a/bundle/scripts/benchmark/connections.js +++ b/bundle/scripts/benchmark/connections.js @@ -1,3 +1,4 @@ +require("dotenv").config(); const cluster = require("cluster"); const WebSocket = require("ws"); const endpoint = process.env.GATEWAY || "ws://localhost:3001"; diff --git a/bundle/scripts/benchmark/messages.js b/bundle/scripts/benchmark/messages.js deleted file mode 100644 index 70b786d1..00000000 --- a/bundle/scripts/benchmark/messages.js +++ /dev/null @@ -1 +0,0 @@ -// TODO diff --git a/bundle/scripts/benchmark/users.js b/bundle/scripts/benchmark/users.js new file mode 100644 index 00000000..bce67bf4 --- /dev/null +++ b/bundle/scripts/benchmark/users.js @@ -0,0 +1,25 @@ +require("dotenv").config(); +const fetch = require("node-fetch"); +const count = Number(process.env.COUNT) || 50; +const endpoint = process.env.API || "http://localhost:3001"; + +async function main() { + for (let i = 0; i < count; i++) { + fetch(`${endpoint}/api/auth/register`, { + method: "POST", + body: JSON.stringify({ + fingerprint: `${i}.wR8vi8lGlFBJerErO9LG5NViJFw`, + username: `test${i}`, + invite: null, + consent: true, + date_of_birth: "2000-01-01", + gift_code_sku_id: null, + captcha_key: null, + }), + headers: { "content-type": "application/json" }, + }); + console.log(i); + } +} + +main(); -- cgit 1.5.1