Skip to content

Commit

Permalink
Remove the need for node
Browse files Browse the repository at this point in the history
  • Loading branch information
MotorTruck1221 committed Mar 17, 2024
1 parent e5a047e commit eabe08e
Show file tree
Hide file tree
Showing 20 changed files with 89 additions and 225 deletions.
12 changes: 12 additions & 0 deletions cli/cli.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,18 @@
$database = ENV['DB_DATABASE'] || settings['database']['dbname'].to_s

class RubyCLI < Thor
desc "start", "Start the server"
option :node, :type => :boolean
def start
if options[:node]
puts "Starting with node server...".red
system("node nodeJS/server.js --node-port=9294 &")
system("bundle exec puma -e production -q")
else
puts "Starting the server...".red
system("bundle exec puma -e production -q")
end
end
desc "create", "Create a new user"
def create
puts "Creating a new user...".red
Expand Down
32 changes: 2 additions & 30 deletions config/puma.rb
Original file line number Diff line number Diff line change
@@ -1,59 +1,31 @@
require 'etc'
require 'os'
require 'colorize'
# get the ruby Implementation

if OS.windows?
puts "You are using Windows. Not multi-threading...".colorize(:red)
puts "Starting Server...".colorize(:green)
rubyPort = 9292
rubyPort = ARGV[ARGV.index('-p') + 1] || ARGV[ARGV.index('--port') + 1] if ARGV.include?('-p') || ARGV.include?('--port')
if ENV['RACK_ENV'] == 'production'
system("node node-server/server.js --ruby-port=#{rubyPort} --node-port=9293 &")
else
system("node node-server/server-dev.js --ruby-port=#{rubyPort} --node-port=9293 &")
end
elsif ENV['WP'] != nil
workers ENV['WP'].to_i
before_fork do
puts "The amount of proccesses is: #{ENV['WP']}".colorize(:green)
puts "Master Process ID: #{Process.pid}".colorize(:green)
puts "Starting Server...".colorize(:green)
rubyPort = 9292
cpuCount = Etc.nprocessors
rubyPort = ARGV[ARGV.index('-p') + 1] || ARGV[ARGV.index('--port') + 1] if ARGV.include?('-p') || ARGV.include?('--port')
if ENV['RACK_ENV'] == 'production'
system("node node-server/server.js --ruby-port=#{rubyPort} --node-port=9293 &")
else
system("node node-server/server-dev.js --ruby-port=#{rubyPort} --node-port=9293 &")
end
end
else
if RUBY_ENGINE != 'jruby' && RUBY_ENGINE != 'truffleruby'
workers Etc.nprocessors
before_fork do
puts "Master Process ID: #{Process.pid}".colorize(:green)
puts "Starting Server...".colorize(:green)
rubyPort = 9292
cpuCount = Etc.nprocessors
rubyPort = ARGV[ARGV.index('-p') + 1] || ARGV[ARGV.index('--port') + 1] if ARGV.include?('-p') || ARGV.include?('--port')
if ENV['RACK_ENV'] == 'production'
system("node node-server/server.js --ruby-port=#{rubyPort} --node-port=9293 &")
else
system("node node-server/server-dev.js --ruby-port=#{rubyPort} --node-port=9293 &")
end
end
else
puts "You are using JRuby or TruffleRuby. Not using workers...".colorize(:red)
puts "Starting Server...".colorize(:green)
rubyPort = 9292
rubyPort = ARGV[ARGV.index('-p') + 1] || ARGV[ARGV.index('--port') + 1] if ARGV.include?('-p') || ARGV.include?('--port')
if ENV['RACK_ENV'] == 'production'
system("node node-server/server.js --ruby-port=#{rubyPort} --node-port=9293 &")
else
system("node node-server/server-dev.js --ruby-port=#{rubyPort} --node-port=9293 &")
end
end
end

preload_app!
port ENV['PORT'] || 9292
port ENV['PORT'] || 9293
6 changes: 3 additions & 3 deletions docker/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ RUN cp config/settings.example.yml config/settings.yml
VOLUME /usr/src/app/config/
# Run the app
EXPOSE 9293
CMD ["pnpm", "start"]
CMD ["pnpm", "start", "--node"]

FROM node:latest as jruby
WORKDIR /usr/src/app
Expand All @@ -40,7 +40,7 @@ RUN cp config/settings.example.yml config/settings.yml
VOLUME /usr/src/app/config/
# Run the app
EXPOSE 9293
CMD ["pnpm", "start"]
CMD ["pnpm", "start", "--node"]

FROM ghcr.io/graalvm/truffleruby-community:23.1.2-debian as truffleruby
WORKDIR /usr/src/app
Expand All @@ -59,4 +59,4 @@ RUN cp config/settings.example.yml config/settings.yml
VOLUME /usr/src/app/config/
# Run the app
EXPOSE 9293
CMD ["pnpm", "start"]
CMD ["pnpm", "start", "--node"]
25 changes: 22 additions & 3 deletions main.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
logging = false
end
set :logging, logging
set :show_exceptions, logging
set :show_exceptions, logging
set :components, File.join(settings.root, 'src', 'views', 'components')
cookie_options = {
:key => 'UserAllowed',
Expand All @@ -34,6 +34,7 @@
:secure => true,
:httponly => true
}

#Validate the YML file
validateYML()
#Validate the ENV variables
Expand Down Expand Up @@ -83,15 +84,33 @@

mime_type :wasm, 'application/wasm'

latestRelease = getLatestRelease()

# Other routes
get '/rubyHealth/?' do
return "OK"
get '/health/?' do
return { status: "ok" }.to_json
end

get '/:unlock?' do
erb :index, :layout => :"layouts/index"
end

get '/version/?' do
return { version: latestRelease }.to_json
end

use Rack::ReverseProxy do
reverse_proxy /^\/gms(\/.*)$/, 'https://rawcdn.githack.com/$1'
end

get '/search/:q?' do
content_type :json
query = params[:q]
resp = HTTParty.get("https://search.brave.com/api/suggest?q=#{query}&format=json")
return resp.body
end


#Auth to login to the site
post '/auth' do
if Settings.corlink.enabled == "true" && Settings.private == "false"
Expand Down
108 changes: 0 additions & 108 deletions node-server/server-dev.js

This file was deleted.

8 changes: 0 additions & 8 deletions node-server/version.js

This file was deleted.

3 changes: 2 additions & 1 deletion node-server/compile.js → nodeJS/compile.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,5 @@ async function compile() {
}
await logger(compileSCSS(), 'Compiling SCSS');
}
export default compile;
compile();
//export default compile;
46 changes: 4 additions & 42 deletions node-server/server.js → nodeJS/server.js
Original file line number Diff line number Diff line change
@@ -1,36 +1,25 @@
import Fastify from 'fastify';
import fastifyMiddie from '@fastify/middie';
import fastifyHttpProxy from '@fastify/http-proxy';
import { fileURLToPath } from 'node:url';
import { createBareServer } from '@tomphttp/bare-server-node';
import createRammerhead from "rammerhead/src/server/index.js";
import { createServer } from 'http';
import fs from 'fs'
import YAML from 'yaml';
import path from 'path';
const __dirname = path.resolve();
const settings = YAML.parse(fs.readFileSync(path.join(__dirname, '/config/settings.yml'), 'utf8'));
import chalk from 'chalk';
import compile from './compile.js';
import getLatestRelease from './version.js';
import wisp from 'wisp-server-node';
import fastifyCaching from '@fastify/caching';
let rubyPort = process.argv.find((arg) => arg.startsWith('--ruby-port')).split('=')[1] || 9292;
let nodePort = process.argv.find((arg) => arg.startsWith('--node-port')).split('=')[1] || 9293;

const latestRelease = await getLatestRelease();
let nodePort = process.argv.find((arg) => arg.startsWith('--node-port')).split('=')[1] || 9294;
const bare = createBareServer('/bare/');
const rh = createRammerhead();
const rammerheadScopes = [ "/rammerhead.js", "/hammerhead.js", "/transport-worker.js", "/task.js", "/iframe-task.js", "/worker-hammerhead.js", "/messaging", "/sessionexists", "/deletesession", "/newsession", "/editsession", "/needpassword", "/syncLocalStorage", "/api/shuffleDict", "/mainport" ];
const rammerheadSession = /^\/[a-z0-9]{32}/;
function shouldRouteRh(req) {
const url = new URL(req.url, "http://0.0.0.0");
return (rammerheadScopes.includes(url.pathname) || rammerheadSession.test(url.pathname));
return (rammerheadScopes.includes("/rammer/" + url.pathname) || rammerheadSession.test("/rammer/" + url.pathname));
}
function routeRhRequest(req, res) { rh.emit("request", req, res) }
function routeRhUpgrade(req, socket, head) { rh.emit("upgrade", req, socket, head) }
console.log(chalk.red('Compiling...'))
compile();

const proxyHandler = (handler, opts) => {
return createServer().on('request', (req, res) => {
Expand Down Expand Up @@ -63,7 +52,7 @@ await app
privacy: fastifyCaching.privacy.NOCACHE
})
.register(fastifyHttpProxy, {
upstream: 'http://localhost:9292',
upstream: 'http://localhost:9293',
prefix: '/',
http2: false,
replyOptions: {
Expand All @@ -74,34 +63,7 @@ await app
}
}
})
.register(fastifyHttpProxy, {
upstream: 'https://rawcdn.githack.com',
prefix: '/gms/',
http2: false,
})
.register(fastifyMiddie)
app.get('/search=:query', async (req, res) => {
const { query } = req.params;
try {
const resp = await fetch(`https://search.brave.com/api/suggest?q=${query}&format=json`).then((res) => res.json());
res.send(resp);
}
catch (err) {
reply.code(500).send({ error: "Internal Server Error" });
}
});
app.get('/version', (req, res) => {
res.send({ version: latestRelease });
});
app.get('/health', async (req, res) => {
let resp = await fetch(`http://localhost:${rubyPort}/rubyHealth`);
if (resp.status === 200) {
res.send({ status: 'ok' });
}
else {
res.send({ status: 'error' });
}
});

app.listen({ port: nodePort, host: '0.0.0.0' });
console.log(chalk.green(`Server listening on port ${chalk.red(nodePort)}`));
console.log(chalk.green(`NodeJS Server listening on port ${chalk.red(nodePort)}`));
9 changes: 5 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,13 @@
"author": "Ruby Network",
"scripts": {
"preinstall": "npx -y only-allow pnpm",
"dev": "bundle exec rerun --ignore 'src/public/css/*' --signal 'TERM' -c -w 5 --no-notify -- puma",
"start": "bundle exec puma -e production",
"dev": "bundle exec rerun --ignore 'src/public/css/*' --ignore 'node_modules/*' --signal 'TERM' -c -w 5 --no-notify -- puma",
"start": "bundle exec ruby cli/cli.rb start",
"install": "pnpm run build && bundle install",
"build:rh": "tsc -p ./rammerhead/tsconfig.json",
"build:epoxytransport": "cd ./epoxytransport/ && npm run build",
"build": "pnpm run build:rh && pnpm run build:epoxytransport",
"build:css": "node ./nodeJS/compile.js",
"build": "pnpm run build:rh && pnpm run build:epoxytransport && pnpm run build:css",
"cli": "bundle exec ruby ./cli/cli.rb"
},
"engines": {
Expand All @@ -31,7 +32,7 @@
"chalk": "^5.3.0",
"fastify": "^4.26.2",
"progress-estimator": "^0.3.1",
"rammerhead": "https://github.com/Ruby-Network/rammerhead/releases/download/v1/rammerhead-2.tgz",
"rammerhead": "https://github.com/Ruby-Network/rammerhead/releases/download/v1.0.5/rammerhead-1.2.41-ruby.1.tgz",
"sass": "^1.71.1",
"terser": "^5.29.2",
"typescript": "^5.4.2",
Expand Down
Loading

0 comments on commit eabe08e

Please sign in to comment.