Skip to content

Commit

Permalink
tmp: fix build script (maybe?)
Browse files Browse the repository at this point in the history
  • Loading branch information
René Perschon committed Nov 11, 2023
1 parent 0ff9ec5 commit a819e3e
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 66 deletions.
10 changes: 7 additions & 3 deletions fhttp-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@ readme = "../README.asciidoc"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
reqwest = { version = "0.11.8", features = ["rustls-tls", "blocking", "multipart"] }
reqwest = { version = "0.11.8", features = [
"rustls-tls",
"blocking",
"multipart",
] }
# this fixes a compilation error only encountered when running cargo publish
# https://github.com/seanmonstar/reqwest/issues/971#issuecomment-654402354
hyper-tls = "0.4.3"
Expand All @@ -30,12 +34,12 @@ rand = "0.7.3"
apply = "0.3.0"
pest = "2.1.3"
pest_derive = "2.1.0"
deno_core = "0.95.0"
deno_core = "0.228.0"
anyhow = "1.0"
itertools = "0.10"

[build-dependencies]
deno_core = "0.95.0"
deno_core = "0.228.0"

[dev-dependencies]
indoc = "1.0.3"
Expand Down
18 changes: 5 additions & 13 deletions fhttp-core/build.rs
Original file line number Diff line number Diff line change
@@ -1,29 +1,21 @@
use std::env;
use std::path::PathBuf;

use deno_core::{JsRuntime, RuntimeOptions};
use deno_core::{extension, JsRuntimeForSnapshot, RuntimeOptions};

fn main() {
let fhttp_extension = deno_core::Extension::builder()
.js(deno_core::include_js_files!(
prefix "fhttp",
"src/postprocessing/bootstrap.js",
))
.build();
extension!(fhttp, js = ["src/postprocessing/bootstrap.js"]);

let out_dir = PathBuf::from(env::var_os("OUT_DIR").unwrap());
let snapshot_path = out_dir.join("FHTTP_SNAPSHOT.bin");
let options = RuntimeOptions {
will_snapshot: true,
extensions: vec![
fhttp_extension,
],
extensions: vec![fhttp::init_ops_and_esm()],
..Default::default()
};
let mut isolate = JsRuntime::new(options);
let isolate = JsRuntimeForSnapshot::new(options);

let snapshot = isolate.snapshot();
let snapshot_slice: &[u8] = &*snapshot;
let snapshot_slice: &[u8] = &snapshot;
println!("Snapshot size: {}", snapshot_slice.len());
std::fs::write(&snapshot_path, snapshot_slice).unwrap();
println!("Snapshot written to: {} ", snapshot_path.display());
Expand Down
104 changes: 54 additions & 50 deletions fhttp-core/src/postprocessing/response_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ use std::fmt::Debug;
use anyhow::{Context, Result};
use deno_core::{RuntimeOptions, Snapshot};

static FHTTP_SNAPSHOT: &[u8] =
include_bytes!(concat!(env!("OUT_DIR"), "/FHTTP_SNAPSHOT.bin"));
static FHTTP_SNAPSHOT: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/FHTTP_SNAPSHOT.bin"));

#[derive(Debug, Eq, PartialEq, Clone)]
pub enum ResponseHandler {
Expand All @@ -27,22 +26,17 @@ impl ResponseHandler {
}
}

fn process_body_json(
json_path: &str,
body: &str
) -> Result<String> {
fn process_body_json(json_path: &str, body: &str) -> Result<String> {
use jsonpath::Selector;
use serde_json::Value;

let value: Value = serde_json::from_str(body)
.with_context(|| format!(
"failed to parse response body as json\nBody was '{}'",
body
))?;
.with_context(|| format!("failed to parse response body as json\nBody was '{}'", body))?;

let mut selector = Selector::new();
let json_path_results = selector
.str_path(json_path).unwrap()
.str_path(json_path)
.unwrap()
.value(&value)
.select()
.unwrap();
Expand All @@ -53,7 +47,7 @@ fn process_body_json(

match result {
Value::String(string) => Ok(string),
_ => Ok(serde_json::to_string(&result).unwrap())
_ => Ok(serde_json::to_string(&result).unwrap()),
}
}

Expand All @@ -63,33 +57,31 @@ fn process_body_deno(
headers: &HashMap<&str, &str>,
body: &str,
) -> Result<String> {
use deno_core::op_sync;
use deno_core::JsRuntime;
use std::cell::Cell;
use std::rc::Rc;

let result: Rc<Cell<String>> = Rc::new(Cell::new(body.to_string()));
let runtime_options = RuntimeOptions {
startup_snapshot: Some(Snapshot::Static(FHTTP_SNAPSHOT)),

..RuntimeOptions::default()
};
let mut runtime = JsRuntime::new(runtime_options);

let result_ref = result.clone();
runtime.register_op(
"op_set_result",
op_sync(move |_state, result: String, _: ()| {
result_ref.set(result);
Ok(())
}),
);
runtime.sync_ops_cache();
// let result_ref = result.clone();
// runtime.register_op(
// "op_set_result",
// op_sync(move |_state, result: String, _: ()| {
// result_ref.set(result);
// Ok(())
// }),
// );
// runtime.sync_ops_cache();

let program = prepare_deno_code(program, status, headers, body);

runtime
.execute_script("", &program)
.unwrap();
runtime.execute_script("", program.into()).unwrap();

Ok(result.take())
}
Expand All @@ -100,14 +92,15 @@ fn prepare_deno_code(
headers: &HashMap<&str, &str>,
body: &str,
) -> String {
let header_lines = headers.iter()
.map(|(name, value)|
let header_lines = headers
.iter()
.map(|(name, value)| {
format!(
" '{}': '{}'",
name.replace("'", "\\'"),
value.replace("'", "\\'")
name.replace('\'', "\\'"),
value.replace('"', "\\'")
)
)
})
.collect::<Vec<_>>()
.join(",\n");

Expand All @@ -122,7 +115,7 @@ fn prepare_deno_code(
{program}
"#,
status = status,
body = &body.replace("'", "\\'"),
body = &body.replace('\'', "\\'"),
headers = &header_lines,
program = &program,
)
Expand All @@ -136,7 +129,8 @@ mod json_tests {

#[test]
fn should_apply_the_jsonpath_expression() {
let body = indoc!("
let body = indoc!(
"
{
\"a\": {
\"b\": {
Expand All @@ -145,25 +139,32 @@ mod json_tests {
\"c\": \"failure\"
}
}
");
let handler = ResponseHandler::Json { json_path: "$.a.b.c".into() };
"
);
let handler = ResponseHandler::Json {
json_path: "$.a.b.c".into(),
};
let result = handler.process_body(200, &HashMap::new(), body);

assert_ok!(result, String::from("success"));
}

#[test]
fn should_convert_numbers_to_string() {
let body = indoc!("
let body = indoc!(
"
{
\"a\": {
\"b\": {
\"c\": 3.141
}
}
}
");
let handler = ResponseHandler::Json { json_path: "$.a.b.c".into() };
"
);
let handler = ResponseHandler::Json {
json_path: "$.a.b.c".into(),
};
let result = handler.process_body(200, &HashMap::new(), body);

assert_ok!(result, String::from("3.141"));
Expand All @@ -179,7 +180,9 @@ mod deno_tests {
#[test]
fn should_default_to_response_body_as_result() {
let body = "this is the response body";
let handler = ResponseHandler::Deno { program: String::new() };
let handler = ResponseHandler::Deno {
program: String::new(),
};
let result = handler.process_body(200, &HashMap::new(), body);

assert_ok!(result, String::from("this is the response body"));
Expand All @@ -191,7 +194,8 @@ mod deno_tests {
let handler = ResponseHandler::Deno {
program: r#"
setResult(body.toUpperCase());
"#.into()
"#
.into(),
};
let result = handler.process_body(200, &HashMap::new(), body);

Expand All @@ -201,14 +205,15 @@ mod deno_tests {
#[test]
fn should_have_access_to_result_headers() {
let body = "this is the response body";
let headers = hashmap!{
let headers = hashmap! {
"content-type" => "application/json",
"accept" => "application/json,application/xml"
};
let handler = ResponseHandler::Deno {
program: r#"
setResult(headers['accept']);
"#.into()
"#
.into(),
};
let result = handler.process_body(200, &headers, body);

Expand All @@ -218,13 +223,11 @@ mod deno_tests {
#[test]
fn should_escape_headers() {
let body = "this is the response body";
let headers = hashmap!{
let headers = hashmap! {
"content'type" => "appli'cation",
};
let handler = ResponseHandler::Deno {
program: r#"
setResult(headers['content\'type']);
"#.into()
program: "setResult(headers['content\'type']);".into(),
};
let result = handler.process_body(200, &headers, body);

Expand All @@ -234,11 +237,12 @@ mod deno_tests {
#[test]
fn should_escape_body() {
let body = "this is the 'response' body";
let headers = hashmap!{};
let headers = hashmap! {};
let handler = ResponseHandler::Deno {
program: r#"
setResult(body);
"#.into()
"#
.into(),
};
let result = handler.process_body(200, &headers, body);

Expand All @@ -248,7 +252,7 @@ mod deno_tests {
#[test]
fn should_have_access_to_status_code() {
let body = "this is the response body";
let headers = hashmap!{};
let headers = hashmap! {};
let handler = ResponseHandler::Deno {
program: r#"
if (status === 404)
Expand All @@ -257,11 +261,11 @@ mod deno_tests {
setResult('ok');
else
setResult('who knows?');
"#.into()
"#
.into(),
};
let result = handler.process_body(200, &headers, body);

assert_ok!(result, String::from("ok"));
}

}

0 comments on commit a819e3e

Please sign in to comment.