Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Network test #57

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions packages/winterjs-proxy/app.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
kind: wasmer.io/App.v0
name: wasmer-tests-winterjs-proxy-worker
owner: wasmer-tests
package: wasmer-tests/[email protected]
cli_args:
- /src/index.js
debug: false
27 changes: 27 additions & 0 deletions packages/winterjs-proxy/src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@

// Handler function.
// Receives a request and returns a response.
async function handleRequest(ev) {
const request = ev.request;

const url = new URL(request.url);
const path = url.pathname.slice(1);

let res;
try {
console.log('sending fetch request', {url: path});
res = await fetch(path);
console.log('response', {url: res.url, status: res.status});
} catch (err) {
res = new Response(JSON.stringify({ error: err.message }), {
status: 500,
});
}

return res;
}

// Register the listener that handles incoming requests.
addEventListener("fetch", (event) => {
event.respondWith(handleRequest(event));
});
19 changes: 19 additions & 0 deletions packages/winterjs-proxy/wasmer.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
[package]
name = "wasmer-tests/winterjs-proxy"
version = "0.1.0"
description = "wasmer-tests/winterjs-proxy js worker"

[dependencies]
"wasmer/winterjs" = "*"

[fs]
"/src" = "./src"

[[command]]
name = "script"
module = "wasmer/winterjs:winterjs"
runner = "https://webc.org/runner/wasi"

[command.annotations.wasi]
env = ["JS_PATH=/src/index.js"]
main-args = ["/src/index.js"]
15 changes: 3 additions & 12 deletions watest/src/tests/app_flow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,7 @@ use crate::util::{
#[ignore]
#[test_log::test(tokio::test)]
async fn test_cli_app_create_static_site_and_update_multiple_times() {
let name = format!(
"t-{}",
uuid::Uuid::new_v4().to_string().replace("-", "")
);
let name = format!("t-{}", uuid::Uuid::new_v4().to_string().replace("-", ""));
let namespace = test_namespace();

// Create static site app.
Expand Down Expand Up @@ -136,10 +133,7 @@ async fn test_cli_app_create_static_site_and_update_multiple_times() {
/// ensure it stops working.
#[test_log::test(tokio::test)]
async fn test_cli_app_create_and_delete() {
let name = format!(
"t-{}",
uuid::Uuid::new_v4().to_string().replace("-", "")
);
let name = format!("t-{}", uuid::Uuid::new_v4().to_string().replace("-", ""));
let namespace = test_namespace();

// Create static site app.
Expand Down Expand Up @@ -549,10 +543,7 @@ print("\r")
// version.
#[test_log::test(tokio::test)]
async fn test_deploy_app_with_outdated_wasmer_toml_package_version() {
let name = format!(
"o-{}",
uuid::Uuid::new_v4().to_string().replace("-", "")
);
let name = format!("o-{}", uuid::Uuid::new_v4().to_string().replace("-", ""));
let namespace = test_namespace();
let dir = build_clean_test_app_dir(&name);

Expand Down
4 changes: 3 additions & 1 deletion watest/src/tests/app_logging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ use crate::util::{
#[ignore]
#[test_log::test(tokio::test)]
async fn test_python_logging() {
mirror_package_prod_to_local("wasmer", "python").await.unwrap();
mirror_package_prod_to_local("wasmer", "python")
.await
.unwrap();

let name = "wasmer-test-logging-python".to_string();
let namespace = test_namespace();
Expand Down
5 changes: 1 addition & 4 deletions watest/src/tests/app_templates.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,7 @@ async fn test_cli_app_create_winterjs() {
.await
.unwrap();

let name = format!(
"t-{}",
uuid::Uuid::new_v4().to_string().replace("-", "")
);
let name = format!("t-{}", uuid::Uuid::new_v4().to_string().replace("-", ""));
let namespace = test_namespace();

// Create static site app.
Expand Down
2 changes: 1 addition & 1 deletion watest/src/tests/complex_load.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ async fn create_app(name: String) {
));
thread::sleep(Duration::from_secs(5));
if app_response.status().is_success() {
return
return;
}
}
panic!("App {} is not ready", app_hostname);
Expand Down
1 change: 1 addition & 0 deletions watest/src/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ pub mod app_flow;
pub mod app_logging;
pub mod app_templates;
pub mod complex_load;
pub mod networking;
156 changes: 156 additions & 0 deletions watest/src/tests/networking.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
use crate::util::{
api_client, build_clean_test_app_dir, http_client, mirror_package_prod_to_local,
test_namespace, wait_app_latest_version, CommandExt,
};

/// Test that an app can make http requests to both ipv4 and ipv6 servers.
#[test_log::test(tokio::test)]
async fn test_winterjs_http_proxy_ipv4_v6() {
mirror_package_prod_to_local("wasmer", "winterjs")
.await
.unwrap();

let name = "wasmer-test-winterjs-proxy-netw".to_string();
let namespace = test_namespace();

let dir = build_clean_test_app_dir(&name);

let pkgtoml = format!(
r#"
[package]
name = "{namespace}/{name}"
version = "0.1.0"
description = "wasmer-tests/winterjs-proxy js worker"

[dependencies]
"wasmer/winterjs" = "*"

[fs]
"/src" = "./src"

[[command]]
name = "script"
module = "wasmer/winterjs:winterjs"
runner = "https://webc.org/runner/wasi"

[command.annotations.wasi]
env = ["JS_PATH=/src/index.js"]
main-args = ["/src/index.js"]
"#
);

let appyaml = format!(
r#"
---
kind: wasmer.io/App.v0
name: {name}
owner: {namespace}
package: {namespace}/{name}
cli_args:
- /src/index.js
domains:
- {name}.wasmer.app
debug: false
"#
);

let js = r#"
// Handler function.
// Receives a request and returns a response.
async function handleRequest(ev) {
const request = ev.request;

const url = new URL(request.url);
const path = url.pathname.slice(1);
if (path === '/') {
return new Response(JSON.stringify({message: "need to provide a url in the path"}));
}

let res;
try {
console.log('sending fetch request', {url: path});
res = await fetch(path);
console.log('response', {url: res.url, status: res.status});
} catch (err) {
res = new Response(JSON.stringify({ error: err.message }), {
status: 500,
});
}

return res;
}

// Register the listener that handles incoming requests.
addEventListener("fetch", (event) => {
event.respondWith(handleRequest(event));
});
"#;

let srcdir = dir.join("src");
fs_err::create_dir_all(&srcdir).expect("Failed to create src dir");

fs_err::write(dir.join("wasmer.toml"), pkgtoml).expect("Failed to write to wasmer.toml");
fs_err::write(dir.join("app.yaml"), appyaml).expect("Failed to write to app.yaml");
fs_err::write(srcdir.join("index.js"), js).expect("Failed to write to index.js");

// Deploy the app.
std::process::Command::new("wasmer")
.args(&[
"deploy",
"--no-wait",
"--publish-package",
"--path",
dir.to_str().unwrap(),
])
.status_success()
.expect("Failed to invoke 'wasmer deploy'");

// Query the app.

let api = api_client();

let app = wasmer_api::query::get_app(&api, namespace.clone(), name.clone())
.await
.expect("could not query app")
.expect("queried app is None");

let client = http_client();
wait_app_latest_version(&client, &app)
.await
.expect("Failed to wait for app latest version");

tracing::debug!("app deployed, sending request");

let mut url = app
.url
.parse::<url::Url>()
.expect("Failed to parse app URL");

// test v4
url.set_path("http://v4.ipv6test.app/");
let res = crate::util::build_app_request_get(&client, &app, url.clone())
.send()
.await
.expect("Failed to send request")
.error_for_status()
.expect("Failed to get response");
let body = res.text().await.expect("Failed to get response body");
// Should have returned a valid ipv4 address.
let _ip = body
.parse::<std::net::Ipv4Addr>()
.expect("body did not contain a valid ip address");

// Test v6
url.set_path("http://v6.ipv6test.app/");
let res = crate::util::build_app_request_get(&client, &app, url.clone())
.send()
.await
.expect("Failed to send request")
.error_for_status()
.expect("Failed to get response");
let body = res.text().await.expect("Failed to get response body");
// Should have returned a valid ipv6 address.
let _ip = body
.parse::<std::net::Ipv6Addr>()
.expect("body did not contain a valid ip address");
}
45 changes: 43 additions & 2 deletions watest/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,11 +87,13 @@ pub async fn wait_app_latest_version(

let start = std::time::Instant::now();
loop {
if start.elapsed() > std::time::Duration::from_secs(240) {
if start.elapsed() > std::time::Duration::from_secs(360) {
bail!("Timed out waiting for app to be available");
}

let url = format!("http://{}-wasmer-tests.wasmer.app", app.name).parse().unwrap();
let url = format!("http://{}-wasmer-tests.wasmer.app", app.name)
.parse()
.unwrap();
tracing::info!(app.name);
let req = build_app_request_get(client, app, url);
tracing::debug!(?req, "Sending request to app to check version");
Expand Down Expand Up @@ -297,6 +299,45 @@ pub async fn mirror_package(
}
}

/// Ensure a package in a given directory is published.
pub async fn ensure_package_in_dir(path: &Path) -> Result<(), anyhow::Error> {
// Load the version from wasmer.toml.
let toml_path = path.join("wasmer.toml");
let toml_raw = fs_err::read_to_string(&toml_path).context("Failed to read wasmer.toml")?;
let toml = toml::from_str::<toml::Value>(&toml_raw).context("Failed to parse wasmer.toml")?;
let pkg = toml
.get("package")
.and_then(|p| p.as_table())
.context("Failed to get package from wasmer.toml")?;
let version = pkg
.get("version")
.and_then(|v| v.as_str())
.context("Failed to get version from wasmer.toml")?;
let full_name = pkg
.get("name")
.and_then(|n| n.as_str())
.context("Failed to get name from wasmer.toml")?;

// Load the package from the registry.
let api = api_client();
let pkg_opt =
wasmer_api::query::get_package_version(&api, full_name.to_string(), version.to_string())
.await?;

if pkg_opt.is_none() {
tracing::info!(package=%full_name, %version, "package not found in registry, publishing...");
std::process::Command::new("wasmer")
.args(&["publish", "--no-validate"])
.current_dir(path)
.status_success()
.context("Failed to publish package")?;
} else {
tracing::info!(package=%full_name, %version, "package version already exists in registry");
}

Ok(())
}

pub trait CommandExt {
/// Run the command and return an error if the result status is not 0.
fn status_success(&mut self) -> Result<(), std::io::Error>;
Expand Down
Loading