Skip to content

Commit 0d4fc94

Browse files
committed
feat: serve worker.js as static file
1 parent ab542c9 commit 0d4fc94

File tree

7 files changed

+145
-24
lines changed

7 files changed

+145
-24
lines changed

Cargo.lock

Lines changed: 25 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ serde = { version = "1.0", features = ["derive"] }
2626
serde_json = { version = "1.0" }
2727
tokio = { version = "1.0", features = ["full"] }
2828
tower = { version = "0.4", features = ["buffer", "limit", "load-shed", "util", "timeout"] }
29-
tower-http = { version = "0.2.5", features = ["cors", "trace", "set-header"] }
29+
tower-http = { version = "0.2.5", features = ["cors", "trace", "set-header", "fs"] }
3030
tracing = "0.1"
3131
tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] }
3232

build.rs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,14 @@ use std::{env, fs, path::Path};
33

44
fn main() {
55
let out_dir = env::var("OUT_DIR").unwrap();
6-
let dest_path = Path::new(&out_dir).join("index.html");
6+
let html_dest_path = Path::new(&out_dir).join("index.html");
77
let page = include_bytes!("./static/index.html");
88
let minified = minify_html::minify(page, &Cfg::spec_compliant());
9-
fs::write(dest_path, minified).expect("failed to save minified index page");
9+
fs::write(html_dest_path, minified).expect("failed to save minified index page");
10+
11+
let worker_dest_path = Path::new(&out_dir).join("worker.js");
12+
let worker_script = include_bytes!("./static/worker.js");
13+
fs::write(worker_dest_path, worker_script).expect("failed to save worker script");
1014

1115
println!("cargo:rerun-if-changed=static");
1216
}

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,7 @@ pub async fn start_server(
150150
HeaderValue::from_static("public, max-age=3600, immutable"),
151151
)),
152152
)
153+
.nest("/worker.js", routes::serve_worker())
153154
.route("/health", get(health))
154155
.route("/dispense", get(routes::dispense_info))
155156
.route(

src/routes.rs

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use crate::{
44
};
55
use axum::{
66
response::{Html, IntoResponse, Response},
7-
Extension, Json,
7+
Extension, Json, routing::{get_service, MethodRouter},
88
};
99

1010
use fuel_tx::{TransactionFee, UniqueIdentifier, UtxoId};
@@ -24,12 +24,13 @@ use handlebars::Handlebars;
2424
use reqwest::StatusCode;
2525
use secrecy::ExposeSecret;
2626
use serde_json::json;
27-
use std::time::Duration;
27+
use std::{time::Duration, io};
2828
use std::{
2929
collections::BTreeMap,
3030
str::FromStr,
3131
time::{SystemTime, UNIX_EPOCH},
3232
};
33+
use tower_http::services::ServeFile;
3334
use tracing::{error, info};
3435

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

62+
#[memoize::memoize]
63+
pub fn serve_worker() -> MethodRouter {
64+
let template = concat!(env!("OUT_DIR"), "/worker.js");
65+
66+
async fn handle_error(_err: io::Error) -> impl IntoResponse {
67+
dbg!(_err);
68+
(StatusCode::INTERNAL_SERVER_ERROR, "Could not serve worker.js")
69+
}
70+
dbg!(template);
71+
get_service(
72+
ServeFile::new(template)
73+
).handle_error(handle_error)
74+
}
75+
76+
6177
pub async fn main(Extension(config): Extension<SharedConfig>) -> Html<String> {
6278
let public_node_url = config.public_node_url.clone();
6379
let captcha_key = config.captcha_key.clone();

static/index.html

Lines changed: 29 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -264,27 +264,37 @@ <h2 class="response-title">Test Ether sent to the wallet</h2>
264264
}
265265

266266
function give_me_coins(form) {
267-
const data = {
268-
address: form["address"].value,
269-
captcha: "",
270-
};
271267

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

276-
let xhr = new XMLHttpRequest();
277-
xhr.open("POST", "/dispense");
278-
xhr.setRequestHeader("Accept", "application/json");
279-
xhr.setRequestHeader("Content-Type", "application/json");
280-
xhr.onload = () =>
281-
handle_response(data.address)(JSON.parse(xhr.responseText));
282-
xhr.onetimeout = () => handle_error("Connection to the server timed out");
283-
xhr.onerror = () => handle_error("Connection to the server failed");
284-
xhr.send(JSON.stringify(data));
285-
286-
document.getElementById("response-failure").innerText = "";
287-
showWaiting();
270+
w.onmessage = function(event){
271+
var reply = parseInt(event.data);
272+
console.log(reply);
273+
};
274+
w.postMessage("5");
275+
276+
277+
// const data = {
278+
// address: form["address"].value,
279+
// captcha: "",
280+
// };
281+
282+
// if (hasCaptcha()) {
283+
// data.captcha = form["g-recaptcha-response"].value;
284+
// }
285+
286+
// let xhr = new XMLHttpRequest();
287+
// xhr.open("POST", "/dispense");
288+
// xhr.setRequestHeader("Accept", "application/json");
289+
// xhr.setRequestHeader("Content-Type", "application/json");
290+
// xhr.onload = () =>
291+
// handle_response(data.address)(JSON.parse(xhr.responseText));
292+
// xhr.onetimeout = () => handle_error("Connection to the server timed out");
293+
// xhr.onerror = () => handle_error("Connection to the server failed");
294+
// xhr.send(JSON.stringify(data));
295+
296+
// document.getElementById("response-failure").innerText = "";
297+
// showWaiting();
288298
}
289299

290300
function handle_response(address) {

static/worker.js

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
var num;
2+
var isPrime = false;
3+
var firstMessagePostCompleted = false;
4+
onmessage = function(ev) {
5+
num = parseInt(ev.data);
6+
let temp = num;
7+
if((temp <= 1) || (isNaN(temp))){
8+
this.setTimeout(() => {
9+
//this.postMessage("<b>" + temp + "</b>");
10+
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>");
11+
}, 300);
12+
firstMessagePostCompleted = true;
13+
}
14+
else if(temp == 2){
15+
isPrime = true;
16+
this.setTimeout(() => {
17+
this.postMessage(temp);
18+
}, 500);
19+
firstMessagePostCompleted = true;
20+
}
21+
else if(!firstMessagePostCompleted && !isPrime){
22+
let ctr = 0;
23+
temp += 1;
24+
for(let i = 2; i<=Math.sqrt(temp); i++){
25+
if(temp % i == 0){
26+
ctr++;
27+
break;
28+
}
29+
}
30+
if(ctr > 0){
31+
this.setTimeout(() => {
32+
//this.postMessage("<b>" + temp + "</b>");
33+
this.postMessage(temp);
34+
}, 500);
35+
firstMessagePostCompleted = true;
36+
}
37+
else{
38+
isPrime = true;
39+
}
40+
}
41+
else if(firstMessagePostCompleted && !isPrime){
42+
let ctr = 0;
43+
for(let i = 2; i<=Math.sqrt(temp); i++){
44+
if(temp % i == 0){
45+
ctr++;
46+
break;
47+
}
48+
}
49+
if(ctr > 0){
50+
this.setTimeout(() => {
51+
//this.postMessage("<b>" + temp + "</b>");
52+
this.postMessage(temp);
53+
}, 500);
54+
}
55+
else{
56+
isPrime = true;
57+
}
58+
}
59+
else if(firstMessagePostCompleted && isPrime){
60+
this.setTimeout(() => {
61+
//this.postMessage("<b>" + temp + "</b>");
62+
this.postMessage("The next prime number after your input is : " + "<b>" + temp + "</b></br>End of program.</br>------------------------------------------------------------------------------------------------------------------------------");
63+
}, 300);
64+
}
65+
}

0 commit comments

Comments
 (0)