-
-
Notifications
You must be signed in to change notification settings - Fork 18
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
client breaking: add initial version of client handlers #449
Draft
jbr
wants to merge
1
commit into
0.3.x
Choose a base branch
from
client-handler-initial
base: 0.3.x
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,183 @@ | ||
use blocking::Unblock; | ||
use clap::Parser; | ||
use std::{ | ||
io::{ErrorKind, IsTerminal}, | ||
path::PathBuf, | ||
str::FromStr, | ||
}; | ||
use trillium::{Body, Method}; | ||
use trillium_client::{Client, Conn, Error, FollowRedirects}; | ||
use trillium_native_tls::NativeTlsConfig; | ||
use trillium_rustls::RustlsConfig; | ||
use trillium_smol::ClientConfig; | ||
use url::{self, Url}; | ||
|
||
pub fn main() { | ||
ClientCli::parse().run() | ||
} | ||
|
||
#[derive(Parser, Debug)] | ||
pub struct ClientCli { | ||
#[arg(value_parser = parse_method_case_insensitive)] | ||
method: Method, | ||
|
||
#[arg(value_parser = parse_url)] | ||
url: Url, | ||
|
||
/// provide a file system path to a file to use as the request body | ||
/// | ||
/// alternatively, you can use an operating system pipe to pass a file in | ||
/// | ||
/// three equivalent examples: | ||
/// | ||
/// trillium client post http://httpbin.org/anything -f ./body.json | ||
/// trillium client post http://httpbin.org/anything < ./body.json | ||
/// cat ./body.json | trillium client post http://httpbin.org/anything | ||
#[arg(short, long, verbatim_doc_comment)] | ||
file: Option<PathBuf>, | ||
|
||
/// provide a request body on the command line | ||
/// | ||
/// example: | ||
/// trillium client post http://httpbin.org/post -b '{"hello": "world"}' | ||
#[arg(short, long, verbatim_doc_comment)] | ||
body: Option<String>, | ||
|
||
/// provide headers in the form -h KEY1=VALUE1 KEY2=VALUE2 | ||
/// | ||
/// example: | ||
/// trillium client get http://httpbin.org/headers -H Accept=application/json Authorization="Basic u:p" | ||
#[arg(short = 'H', long, value_parser = parse_header, verbatim_doc_comment)] | ||
headers: Vec<(String, String)>, | ||
|
||
/// tls implementation. options: rustls, native-tls, none | ||
/// | ||
/// requests to https:// urls with `none` will fail | ||
#[arg(short, long, default_value = "rustls", verbatim_doc_comment)] | ||
tls: TlsType, | ||
|
||
/// set the log level. add more flags for more verbosity | ||
/// | ||
/// example: | ||
/// trillium client get https://www.google.com -vvv # `trace` verbosity level | ||
#[command(flatten)] | ||
verbose: clap_verbosity_flag::Verbosity, | ||
} | ||
|
||
impl ClientCli { | ||
async fn build(&self) -> Conn { | ||
let client = match self.tls { | ||
TlsType::None => Client::new(ClientConfig::default()), | ||
TlsType::Rustls => Client::new(RustlsConfig::<ClientConfig>::default()), | ||
TlsType::NativeTls => Client::new(NativeTlsConfig::<ClientConfig>::default()), | ||
}; | ||
|
||
let client = client | ||
.with_handler(FollowRedirects::new()) | ||
.with_default_pool(); | ||
|
||
let mut conn = client.build_conn(self.method, self.url.clone()); | ||
for (name, value) in &self.headers { | ||
conn.request_headers().append(name.clone(), value.clone()); | ||
} | ||
|
||
if let Some(path) = &self.file { | ||
let metadata = async_fs::metadata(path) | ||
.await | ||
.unwrap_or_else(|e| panic!("could not read file {:?} ({})", path, e)); | ||
|
||
let file = async_fs::File::open(path) | ||
.await | ||
.unwrap_or_else(|e| panic!("could not read file {:?} ({})", path, e)); | ||
|
||
conn.with_body(Body::new_streaming(file, Some(metadata.len()))) | ||
} else if let Some(body) = &self.body { | ||
conn.with_body(body.clone()) | ||
} else if !std::io::stdin().is_terminal() { | ||
conn.with_body(Body::new_streaming(Unblock::new(std::io::stdin()), None)) | ||
} else { | ||
conn | ||
} | ||
} | ||
|
||
pub fn run(self) { | ||
trillium_smol::async_global_executor::block_on(async move { | ||
env_logger::Builder::new() | ||
.filter_module("trillium_client", self.verbose.log_level_filter()) | ||
.init(); | ||
|
||
let mut conn = self.build().await; | ||
|
||
if let Err(e) = (&mut conn).await { | ||
match e { | ||
Error::Io(io) if io.kind() == ErrorKind::ConnectionRefused => { | ||
log::error!("could not reach {}", self.url) | ||
} | ||
|
||
_ => log::error!("protocol error:\n\n{}", e), | ||
} | ||
|
||
return; | ||
} | ||
|
||
if std::io::stdout().is_terminal() { | ||
let body = conn.response_body().read_string().await.unwrap(); | ||
|
||
let _request_headers_as_string = format!("{:#?}", conn.request_headers()); | ||
let headers = conn.response_headers(); | ||
let _response_headers_as_string = format!("{:#?}", headers); | ||
let _status_string = conn.status().unwrap().to_string(); | ||
println!("{conn:#?}"); | ||
println!("{body}"); | ||
} else { | ||
futures_lite::io::copy( | ||
&mut conn.response_body(), | ||
&mut Unblock::new(std::io::stdout()), | ||
) | ||
.await | ||
.unwrap(); | ||
} | ||
}); | ||
} | ||
} | ||
|
||
#[derive(clap::ValueEnum, Debug, Eq, PartialEq, Clone)] | ||
enum TlsType { | ||
None, | ||
Rustls, | ||
NativeTls, | ||
} | ||
|
||
fn parse_method_case_insensitive(src: &str) -> Result<Method, String> { | ||
src.to_uppercase() | ||
.parse() | ||
.map_err(|_| format!("unrecognized method {}", src)) | ||
} | ||
|
||
fn parse_url(src: &str) -> Result<Url, url::ParseError> { | ||
if src.starts_with("http") { | ||
src.parse() | ||
} else { | ||
format!("http://{}", src).parse() | ||
} | ||
} | ||
|
||
impl FromStr for TlsType { | ||
type Err = String; | ||
|
||
fn from_str(s: &str) -> Result<Self, Self::Err> { | ||
match &*s.to_ascii_lowercase() { | ||
"none" => Ok(Self::None), | ||
"rustls" => Ok(Self::Rustls), | ||
"native" | "native-tls" => Ok(Self::NativeTls), | ||
_ => Err(format!("unrecognized tls {}", s)), | ||
} | ||
} | ||
} | ||
|
||
fn parse_header(s: &str) -> Result<(String, String), String> { | ||
let pos = s | ||
.find('=') | ||
.ok_or_else(|| format!("invalid KEY=value: no `=` found in `{}`", s))?; | ||
Ok((String::from(&s[..pos]), String::from(&s[pos + 1..]))) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Please consider making
cookies
not be enabled by default. Based on previous experience withtide
, once crates in the ecosystem start depending ontrillium-client
, it's really hard to get all of them usingdefault-features = false
, even though many won't need this.I know that trillium is going for a "just works" API, but having to enable a feature flag to get a more featureful client doesn't seem like too much to ask here.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That's a really useful bit of feedback! My initial inclination was for each client handler be their own crate to make totally clear that it doesn't depend on any private state, but convinced myself to limit the proliferation of tiny
trillium-client-*
crates. I think I may have overcorrected in the other direction. I'll change them to opt-in instead of opt-out before release, or possibly even go for the trillium-client-cookies, trillium-client-follow-redirects, trillium-client-cache cratesThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@jbr Perhaps a middle ground might make sense: a single
trillium-client-handlers
crate for all the handlers that don't add dependencies, and either a separate crate or feature flag (or both with re-export) for handlers that do add dependencies. That should reduce proliferation.