Skip to content

Commit

Permalink
feat: add HTTP -> TCP proxy example
Browse files Browse the repository at this point in the history
Signed-off-by: Roman Volosatovs <[email protected]>
  • Loading branch information
rvolosatovs committed Dec 31, 2024
1 parent 12125e9 commit feea21d
Show file tree
Hide file tree
Showing 9 changed files with 150 additions and 1 deletion.
16 changes: 16 additions & 0 deletions Cargo.lock

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

3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,10 @@ clap = { version = "4", default-features = false }
criterion = { version = "0.5", default-features = false }
futures = { version = "0.3", default-features = false }
heck = { version = "0.5", default-features = false }
http = { version = "1", default-features = false }
humantime = { version = "2.1", default-features = false }
hyper = { version = "1", default-features = false }
hyper-util = { version = "0.1", default-features = false }
nuid = { version = "0.5", default-features = false }
pin-project-lite = { version = "0.2", default-features = false }
prettyplease = { version = "0.2.25", default-features = false }
Expand Down
29 changes: 29 additions & 0 deletions examples/rust/hello-http-tcp-proxy/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
[package]
name = "hello-http-tcp-proxy"
version = "0.1.0"
authors.workspace = true
categories.workspace = true
edition.workspace = true
homepage.workspace = true
license.workspace = true
repository.workspace = true

[dependencies]
anyhow = { workspace = true }
clap = { workspace = true, features = [
"color",
"derive",
"error-context",
"help",
"std",
"suggestions",
"usage",
] }
http = { workspace = true }
hyper = { workspace = true }
hyper-util = { workspace = true, features = ["http1", "http2", "server", "tokio"] }
tokio = { workspace = true, features = ["rt-multi-thread"] }
tracing = { workspace = true }
tracing-subscriber = { workspace = true, features = ["ansi", "fmt"] }
wit-bindgen-wrpc = { workspace = true }
wrpc-transport = { workspace = true, features = ["net"] }
78 changes: 78 additions & 0 deletions examples/rust/hello-http-tcp-proxy/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
use std::sync::Arc;

use anyhow::Context as _;
use clap::Parser;
use hyper_util::rt::{TokioExecutor, TokioIo};
use tokio::net::TcpListener;
use tracing::{error, info};

mod bindings {
wit_bindgen_wrpc::generate!({
with: {
"wrpc-examples:hello/handler": generate
}
});
}

#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct Args {
/// Address to serve `wrpc-examples:hello/handler.hello` on
#[arg(default_value = "[::1]:8080")]
ingress: String,

/// Address to invoke `wrpc-examples:hello/handler.hello` on
#[arg(default_value = "[::1]:7761")]
egress: String,
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
tracing_subscriber::fmt().init();

let Args { egress, ingress } = Args::parse();
let wrpc = wrpc_transport::tcp::Client::from(egress);
let wrpc = Arc::new(wrpc);

let svc = hyper::service::service_fn(move |req| {
let wrpc = Arc::clone(&wrpc);
async move {
let (http::request::Parts { method, uri, .. }, _) = req.into_parts();
match (method.as_str(), uri.path_and_query().map(|pq| pq.as_str())) {
("GET", Some("/hello")) => {
match bindings::wrpc_examples::hello::handler::hello(wrpc.as_ref(), ())
.await
.context("failed to invoke `wrpc-examples.hello/handler.hello`")
{
Ok(hello) => Ok(http::Response::new(format!(r#""{hello}""#))),
Err(err) => Err(format!("{err:#}")),
}
}
(method, Some(path)) => {
Err(format!("method `{method}` not supported for path `{path}`"))
}
(method, None) => Err(format!("method `{method}` not supported")),
}
}
});
let srv = hyper_util::server::conn::auto::Builder::new(TokioExecutor::new());
let socket = TcpListener::bind(&ingress)
.await
.with_context(|| format!("failed to bind on {ingress}"))?;
loop {
let stream = match socket.accept().await {
Ok((stream, addr)) => {
info!(?addr, "accepted HTTP connection");
stream
}
Err(err) => {
error!(?err, "failed to accept HTTP endpoint connection");
continue;
}
};
let svc = svc.clone();
if let Err(err) = srv.serve_connection(TokioIo::new(stream), svc).await {
error!(?err, "failed to serve HTTP endpoint connection");
}
}
}
4 changes: 4 additions & 0 deletions examples/rust/hello-http-tcp-proxy/wit/deps.lock
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[hello]
path = "../../../wit/hello"
sha256 = "3680bb734f3fa9f7325674142a2a9b558efd34ea2cb2df7ccb651ad869078d27"
sha512 = "688fdae594dc43bd65bd15ea66b77a8f97cb4bc1c3629719e91d6c1391c66f7c8c6517d096f686cca996188f64f075c4ccb0d70a40097ce76b8b4bcc71dc7506"
1 change: 1 addition & 0 deletions examples/rust/hello-http-tcp-proxy/wit/deps.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
hello = "../../../wit/hello"
13 changes: 13 additions & 0 deletions examples/rust/hello-http-tcp-proxy/wit/deps/hello/hello.wit
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package wrpc-examples:hello;

interface handler {
hello: func() -> string;
}

world client {
import handler;
}

world server {
export handler;
}
5 changes: 5 additions & 0 deletions examples/rust/hello-http-tcp-proxy/wit/world.wit
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package wrpc-examples:hello-rust-client;

world client {
include wrpc-examples:hello/client;
}
2 changes: 1 addition & 1 deletion examples/rust/hello-tcp-client/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ async fn main() -> anyhow::Result<()> {
tracing_subscriber::fmt().init();

let Args { addr } = Args::parse();
let wrpc = wrpc_transport::tcp::Client::from(addr);
let wrpc = wrpc_transport::tcp::Client::from(&addr);
let hello = bindings::wrpc_examples::hello::handler::hello(&wrpc, ())
.await
.context("failed to invoke `wrpc-examples.hello/handler.hello`")?;
Expand Down

0 comments on commit feea21d

Please sign in to comment.