Skip to content

Commit

Permalink
feat: serve worker.js as static file
Browse files Browse the repository at this point in the history
  • Loading branch information
DefiCake committed Nov 29, 2023
1 parent 8372c06 commit 603c435
Show file tree
Hide file tree
Showing 7 changed files with 146 additions and 25 deletions.
25 changes: 25 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ serde = { version = "1.0", features = ["derive"] }
serde_json = { version = "1.0" }
tokio = { version = "1.0", features = ["full"] }
tower = { version = "0.4", features = ["buffer", "limit", "load-shed", "util", "timeout"] }
tower-http = { version = "0.2.5", features = ["cors", "trace", "set-header"] }
tower-http = { version = "0.2.5", features = ["cors", "trace", "set-header", "fs"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] }

Expand Down
8 changes: 6 additions & 2 deletions build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,14 @@ use std::{env, fs, path::Path};

fn main() {
let out_dir = env::var("OUT_DIR").unwrap();
let dest_path = Path::new(&out_dir).join("index.html");
let html_dest_path = Path::new(&out_dir).join("index.html");
let page = include_bytes!("./static/index.html");
let minified = minify_html::minify(page, &Cfg::spec_compliant());
fs::write(dest_path, minified).expect("failed to save minified index page");
fs::write(html_dest_path, minified).expect("failed to save minified index page");

let worker_dest_path = Path::new(&out_dir).join("worker.js");
let worker_script = include_bytes!("./static/worker.js");
fs::write(worker_dest_path, worker_script).expect("failed to save worker script");

println!("cargo:rerun-if-changed=static");
}
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ pub async fn start_server(
HeaderValue::from_static("public, max-age=3600, immutable"),
)),
)
.nest("/worker.js", routes::serve_worker())
.route("/health", get(health))
.route("/dispense", get(routes::dispense_info))
.route(
Expand Down
22 changes: 19 additions & 3 deletions src/routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use crate::{
};
use axum::{
response::{Html, IntoResponse, Response},
Extension, Json,
Extension, Json, routing::{get_service, MethodRouter},
};

use fuel_core_client::client::FuelClient;
Expand All @@ -24,12 +24,13 @@ use reqwest::StatusCode;
use secrecy::ExposeSecret;
use serde_json::json;
use std::sync::Arc;
use std::time::Duration;
use std::{
collections::BTreeMap,
io,
str::FromStr,
time::{SystemTime, UNIX_EPOCH},
time::{Duration, SystemTime, UNIX_EPOCH},
};
use tower_http::services::ServeFile;
use tracing::{error, info};

// The amount to fetch the biggest input of the faucet.
Expand Down Expand Up @@ -58,6 +59,21 @@ pub fn render_page(public_node_url: String, captcha_key: Option<String>) -> Stri
handlebars.render("index", &data).unwrap()
}

#[memoize::memoize]
pub fn serve_worker() -> MethodRouter {
let template = concat!(env!("OUT_DIR"), "/worker.js");

async fn handle_error(_err: io::Error) -> impl IntoResponse {
dbg!(_err);
(StatusCode::INTERNAL_SERVER_ERROR, "Could not serve worker.js")
}
dbg!(template);
get_service(
ServeFile::new(template)
).handle_error(handle_error)
}


pub async fn main(Extension(config): Extension<SharedConfig>) -> Html<String> {
let public_node_url = config.public_node_url.clone();
let captcha_key = config.captcha_key.clone();
Expand Down
48 changes: 29 additions & 19 deletions static/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -264,27 +264,37 @@ <h2 class="response-title">Test Ether sent to the wallet</h2>
}

function give_me_coins(form) {
const data = {
address: form["address"].value,
captcha: "",
};

if (hasCaptcha()) {
data.captcha = form["g-recaptcha-response"].value;
}
let w = new Worker('./worker.js');

let xhr = new XMLHttpRequest();
xhr.open("POST", "/dispense");
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onload = () =>
handle_response(data.address)(JSON.parse(xhr.responseText));
xhr.onetimeout = () => handle_error("Connection to the server timed out");
xhr.onerror = () => handle_error("Connection to the server failed");
xhr.send(JSON.stringify(data));

document.getElementById("response-failure").innerText = "";
showWaiting();
w.onmessage = function(event){
var reply = parseInt(event.data);
console.log(reply);
};
w.postMessage("5");


// const data = {
// address: form["address"].value,
// captcha: "",
// };

// if (hasCaptcha()) {
// data.captcha = form["g-recaptcha-response"].value;
// }

// let xhr = new XMLHttpRequest();
// xhr.open("POST", "/dispense");
// xhr.setRequestHeader("Accept", "application/json");
// xhr.setRequestHeader("Content-Type", "application/json");
// xhr.onload = () =>
// handle_response(data.address)(JSON.parse(xhr.responseText));
// xhr.onetimeout = () => handle_error("Connection to the server timed out");
// xhr.onerror = () => handle_error("Connection to the server failed");
// xhr.send(JSON.stringify(data));

// document.getElementById("response-failure").innerText = "";
// showWaiting();
}

function handle_response(address) {
Expand Down
65 changes: 65 additions & 0 deletions static/worker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
var num;
var isPrime = false;
var firstMessagePostCompleted = false;
onmessage = function(ev) {
num = parseInt(ev.data);
let temp = num;
if((temp <= 1) || (isNaN(temp))){
this.setTimeout(() => {
//this.postMessage("<b>" + temp + "</b>");
this.postMessage("<b>Primes are integers greater than one with no positive divisors besides one and itself. Please enter a number >= 2.</br>Reload to continue...</b>");
}, 300);
firstMessagePostCompleted = true;
}
else if(temp == 2){
isPrime = true;
this.setTimeout(() => {
this.postMessage(temp);
}, 500);
firstMessagePostCompleted = true;
}
else if(!firstMessagePostCompleted && !isPrime){
let ctr = 0;
temp += 1;
for(let i = 2; i<=Math.sqrt(temp); i++){
if(temp % i == 0){
ctr++;
break;
}
}
if(ctr > 0){
this.setTimeout(() => {
//this.postMessage("<b>" + temp + "</b>");
this.postMessage(temp);
}, 500);
firstMessagePostCompleted = true;
}
else{
isPrime = true;
}
}
else if(firstMessagePostCompleted && !isPrime){
let ctr = 0;
for(let i = 2; i<=Math.sqrt(temp); i++){
if(temp % i == 0){
ctr++;
break;
}
}
if(ctr > 0){
this.setTimeout(() => {
//this.postMessage("<b>" + temp + "</b>");
this.postMessage(temp);
}, 500);
}
else{
isPrime = true;
}
}
else if(firstMessagePostCompleted && isPrime){
this.setTimeout(() => {
//this.postMessage("<b>" + temp + "</b>");
this.postMessage("The next prime number after your input is : " + "<b>" + temp + "</b></br>End of program.</br>------------------------------------------------------------------------------------------------------------------------------");
}, 300);
}
}

0 comments on commit 603c435

Please sign in to comment.