Skip to content

Commit

Permalink
feat(js-poc): pass request info to js function
Browse files Browse the repository at this point in the history
  • Loading branch information
matthias-wright committed Apr 23, 2024
1 parent 8bbb3c3 commit 6ab2b9b
Show file tree
Hide file tree
Showing 5 changed files with 52 additions and 14 deletions.
1 change: 0 additions & 1 deletion core/handshake/src/transports/http/handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,6 @@ pub async fn handler<P: ExecutorProviderInterface>(
TransportDetail::HttpRequest {
method,
uri: extract_url(&path, uri),
// TODO
header: headers
.into_iter()
.filter_map(|(name, val)| {
Expand Down
1 change: 1 addition & 0 deletions services/js-poc/examples/js-poc-client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ async fn main() -> anyhow::Result<()> {
origin,
uri,
path: None,
headers: None,
param,
})
.expect("failed to encode request")
Expand Down
52 changes: 40 additions & 12 deletions services/js-poc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,8 @@ async fn handle_connection(
let TransportDetail::HttpRequest { uri, .. } = &connection.header.transport_detail else {
unreachable!()
};
let request = extract_request(uri, &body).context("Could not parse request")?;
let request = extract_request(uri, &body, &connection.header.transport_detail)
.context("Could not parse request")?;
handle_request(&mut connection, &tx, request).await?;
} else {
while let Some(payload) = connection.read_payload().await {
Expand All @@ -95,10 +96,13 @@ async fn handle_request(
tx: &UnboundedSender<IsolateHandle>,
request: Request,
) -> anyhow::Result<()> {
let req_params = serde_json::to_value(&request)?;

let Request {
origin,
uri,
path,
headers: _,
param,
} = request;

Expand Down Expand Up @@ -184,7 +188,10 @@ async fn handle_request(
tx.send(runtime.deno.v8_isolate().thread_safe_handle())
.context("Failed to send the IsolateHandle to main thread.")?;

let res = match runtime.exec(location, source, param).await {
let res = match runtime
.exec(location, source, param, Some(req_params))
.await
{
Ok(Some(res)) => res,
Ok(None) => {
connection
Expand Down Expand Up @@ -266,7 +273,7 @@ async fn handle_request(
Ok(())
}

fn extract_request(url: &Url, body: &[u8]) -> Option<Request> {
fn extract_request(url: &Url, body: &[u8], detail: &TransportDetail) -> Option<Request> {
let mut segments = url.path_segments()?;
let seg1 = segments.next()?;
let seg2 = segments.next()?;
Expand Down Expand Up @@ -305,10 +312,17 @@ fn extract_request(url: &Url, body: &[u8]) -> Option<Request> {
Some(serde_json::from_slice::<serde_json::Value>(body).ok()?)
};

let headers = if let TransportDetail::HttpRequest { header, .. } = &detail {
Some(header.clone())
} else {
None
};

Some(Request {
origin,
uri: seg2.to_string(),
path: Some(path),
headers,
param,
})
}
Expand All @@ -323,69 +337,79 @@ mod tests {
serde_json::to_vec(&value).unwrap()
}

#[test]
fn test_extract_request() {
#[tokio::test]
async fn test_extract_request() {
assert_eq!(
extract_request(
&Url::parse("http://fleek/blake3/content-hash/").unwrap(),
&[]
&[],
&TransportDetail::Other,
),
Some(Request {
origin: Origin::Blake3,
uri: "content-hash".to_string(),
path: Some("/".to_string()),
headers: None,
param: None,
})
);

assert_eq!(
extract_request(
&Url::parse("http://fleek/blake3/content-hash/a").unwrap(),
&[]
&[],
&TransportDetail::Other,
),
Some(Request {
origin: Origin::Blake3,
uri: "content-hash".to_string(),
path: Some("/a".to_string()),
headers: None,
param: None,
})
);

assert_eq!(
extract_request(
&Url::parse("http://fleek/blake3/content-hash/a/b").unwrap(),
&[]
&[],
&TransportDetail::Other,
),
Some(Request {
origin: Origin::Blake3,
uri: "content-hash".to_string(),
path: Some("/a/b".to_string()),
headers: None,
param: None,
})
);

assert_eq!(
extract_request(
&Url::parse("http://fleek/blake3/content-hash/a/b?a=4").unwrap(),
&[]
&[],
&TransportDetail::Other,
),
Some(Request {
origin: Origin::Blake3,
uri: "content-hash".to_string(),
path: Some("/a/b?a=4".to_string()),
headers: None,
param: None,
})
);

assert_eq!(
extract_request(
&Url::parse("http://fleek/blake3/content-hash/a/b?a=4#hello").unwrap(),
&[]
&[],
&TransportDetail::Other,
),
Some(Request {
origin: Origin::Blake3,
uri: "content-hash".to_string(),
path: Some("/a/b?a=4#hello".to_string()),
headers: None,
param: None,
})
);
Expand All @@ -396,12 +420,14 @@ mod tests {
"http://fleek/blake3/content-hash/a/b?a=4&param=%7B%22a%22%3A%204%7D#hello"
)
.unwrap(),
&[]
&[],
&TransportDetail::Other,
),
Some(Request {
origin: Origin::Blake3,
uri: "content-hash".to_string(),
path: Some("/a/b?a=4&param=%7B%22a%22%3A%204%7D#hello".to_string()),
headers: None,
param: Some(json!({"a": 4})),
})
);
Expand All @@ -412,12 +438,14 @@ mod tests {
"http://fleek/blake3/content-hash/a/b?a=4&param=%7B%22a%22%3A%204%7D#hello"
)
.unwrap(),
&body(json!({"hello": 5}))
&body(json!({"hello": 5})),
&TransportDetail::Other,
),
Some(Request {
origin: Origin::Blake3,
uri: "content-hash".to_string(),
path: Some("/a/b?a=4&param=%7B%22a%22%3A%204%7D#hello".to_string()),
headers: None,
param: Some(json!({"hello": 5})),
})
);
Expand Down
8 changes: 7 additions & 1 deletion services/js-poc/src/runtime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,7 @@ impl Runtime {
url: Url,
source: String,
param: Option<serde_json::Value>,
req_params: Option<serde_json::Value>,
) -> anyhow::Result<Option<Global<Value>>> {
let id = self
.deno
Expand Down Expand Up @@ -184,10 +185,15 @@ impl Runtime {
} else {
v8::undefined(scope).into()
};
let req_params = if let Some(req_params) = req_params {
serde_v8::to_v8(scope, req_params)?
} else {
v8::undefined(scope).into()
};
let undefined = v8::undefined(scope);

// call function and move response into a global ref
let Some(res) = main_fn.call(scope, undefined.into(), &[param]) else {
let Some(res) = main_fn.call(scope, undefined.into(), &[param, req_params]) else {
return Ok(None);
};
Ok(Some(Global::new(scope, res)))
Expand Down
4 changes: 4 additions & 0 deletions services/js-poc/src/stream.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::collections::HashMap;

use fn_sdk::api::Origin as ApiOrigin;
use serde::{Deserialize, Serialize};

Expand All @@ -12,6 +14,8 @@ pub struct Request {
pub uri: String,
/// Optional path to provide as the window location
pub path: Option<String>,
/// Headers from the http request
pub headers: Option<HashMap<String, String>>,
/// Parameter to pass to the script's main function
#[serde(skip_serializing_if = "Option::is_none")]
pub param: Option<serde_json::Value>,
Expand Down

0 comments on commit 6ab2b9b

Please sign in to comment.