Skip to content

Commit

Permalink
build(examples): Update examples and dev-deps to hyper 1
Browse files Browse the repository at this point in the history
Signed-off-by: Jens Reidel <[email protected]>
  • Loading branch information
Gelbpunkt committed Jan 12, 2024
1 parent 2965414 commit defa55d
Show file tree
Hide file tree
Showing 5 changed files with 60 additions and 38 deletions.
4 changes: 3 additions & 1 deletion examples/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ anyhow = { default-features = false, features = ["std"], version = "1" }
ed25519-dalek = "2"
futures-util = { default-features = false, version = "0.3" }
hex = "0.4"
hyper = { features = ["client", "server", "http2", "runtime"], version = "0.14" }
http-body-util = "0.1"
hyper = { features = ["server"], version = "1" }
hyper-util = { features = ["http1", "client-legacy"], version = "0.1" }
log = { default-features = false, version = "0.4" }
once_cell = "1.4"
serde = { version = "1", features = ["derive"] }
Expand Down
13 changes: 10 additions & 3 deletions examples/gateway-queue-http.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
use hyper::client::{Client, HttpConnector};
use http_body_util::Empty;
use hyper::body::Bytes;
use hyper_util::{
client::legacy::{connect::HttpConnector, Client},
rt::TokioExecutor,
};
use std::env;
use tokio::sync::oneshot;
use twilight_gateway::{queue::Queue, ConfigBuilder, Intents, Shard, ShardId};

#[derive(Debug)]
struct HttpQueue(Client<HttpConnector>);
struct HttpQueue(Client<HttpConnector, Empty<Bytes>>);

impl Queue for HttpQueue {
fn enqueue(&self, id: u32) -> oneshot::Receiver<()> {
Expand Down Expand Up @@ -36,7 +41,9 @@ async fn main() -> anyhow::Result<()> {
let intents = Intents::GUILDS | Intents::GUILD_VOICE_STATES;

let config = ConfigBuilder::new(token, intents)
.queue(HttpQueue(Client::new()))
.queue(HttpQueue(
Client::builder(TokioExecutor::new()).build_http(),
))
.build();

let mut shard = Shard::with_config(ShardId::ONE, config);
Expand Down
16 changes: 9 additions & 7 deletions examples/lavalink-basic-bot.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use hyper::{
client::{Client as HyperClient, HttpConnector},
Body, Request,
use http_body_util::{BodyExt, Full};
use hyper::{body::Bytes, Request};
use hyper_util::{
client::legacy::{connect::HttpConnector, Client as HyperClient},
rt::TokioExecutor,
};
use std::{env, future::Future, net::SocketAddr, str::FromStr, sync::Arc};
use twilight_gateway::{Event, Intents, MessageSender, Shard, ShardId};
Expand All @@ -22,7 +24,7 @@ type State = Arc<StateRef>;
struct StateRef {
http: HttpClient,
lavalink: Lavalink,
hyper: HyperClient<HttpConnector>,
hyper: HyperClient<HttpConnector, Full<Bytes>>,
sender: MessageSender,
standby: Standby,
}
Expand Down Expand Up @@ -62,7 +64,7 @@ async fn main() -> anyhow::Result<()> {
Arc::new(StateRef {
http,
lavalink,
hyper: HyperClient::new(),
hyper: HyperClient::builder(TokioExecutor::new()).build_http(),
sender,
standby: Standby::new(),
}),
Expand Down Expand Up @@ -191,9 +193,9 @@ async fn play(msg: Message, state: State) -> anyhow::Result<()> {
&player.node().config().authorization,
)?
.into_parts();
let req = Request::from_parts(parts, Body::from(body));
let req = Request::from_parts(parts, Full::from(body));
let res = state.hyper.request(req).await?;
let response_bytes = hyper::body::to_bytes(res.into_body()).await?;
let response_bytes = res.collect().await?.to_bytes();

let loaded = serde_json::from_slice::<LoadedTracks>(&response_bytes)?;

Expand Down
63 changes: 37 additions & 26 deletions examples/model-webhook-slash.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
use ed25519_dalek::{Verifier, VerifyingKey, PUBLIC_KEY_LENGTH};
use hex::FromHex;
use http_body_util::{BodyExt, Full};
use hyper::{
body::{Bytes, Incoming},
header::CONTENT_TYPE,
http::StatusCode,
service::{make_service_fn, service_fn},
Body, Method, Request, Response, Server,
server::conn::http1,
service::service_fn,
Method, Request, Response,
};
use hyper_util::rt::TokioIo;
use once_cell::sync::Lazy;
use std::future::Future;
use std::{future::Future, net::SocketAddr};
use tokio::net::TcpListener;
use twilight_model::{
application::interaction::{
application_command::CommandData, Interaction, InteractionData, InteractionType,
Expand All @@ -26,17 +31,17 @@ static PUB_KEY: Lazy<VerifyingKey> = Lazy::new(|| {
/// Responses are made by giving a function that takes a Interaction and returns
/// a InteractionResponse or a error.
async fn interaction_handler<F>(
req: Request<Body>,
req: Request<Incoming>,
f: impl Fn(Box<CommandData>) -> F,
) -> anyhow::Result<Response<Body>>
) -> anyhow::Result<Response<Full<Bytes>>>
where
F: Future<Output = anyhow::Result<InteractionResponse>>,
{
// Check that the method used is a POST, all other methods are not allowed.
if req.method() != Method::POST {
return Ok(Response::builder()
.status(StatusCode::METHOD_NOT_ALLOWED)
.body(Body::empty())?);
.body(Full::default())?);
}

// Check if the path the request is sent to is the root of the domain.
Expand All @@ -46,7 +51,7 @@ where
if req.uri().path() != "/" {
return Ok(Response::builder()
.status(StatusCode::NOT_FOUND)
.body(Body::empty())?);
.body(Full::default())?);
}

// Extract the timestamp header for use later to check the signature.
Expand All @@ -55,7 +60,7 @@ where
} else {
return Ok(Response::builder()
.status(StatusCode::BAD_REQUEST)
.body(Body::empty())?);
.body(Full::default())?);
};

// Extract the signature to check against.
Expand All @@ -68,12 +73,12 @@ where
} else {
return Ok(Response::builder()
.status(StatusCode::BAD_REQUEST)
.body(Body::empty())?);
.body(Full::default())?);
};

// Fetch the whole body of the request as that is needed to check the
// signature against.
let whole_body = hyper::body::to_bytes(req).await?;
let whole_body = req.collect().await?.to_bytes();

// Check if the signature matches and else return a error response.
if PUB_KEY
Expand All @@ -85,7 +90,7 @@ where
{
return Ok(Response::builder()
.status(StatusCode::UNAUTHORIZED)
.body(Body::empty())?);
.body(Full::default())?);
}

// Deserialize the body into a interaction.
Expand Down Expand Up @@ -127,7 +132,7 @@ where
// Unhandled interaction types.
_ => Ok(Response::builder()
.status(StatusCode::BAD_REQUEST)
.body(Body::empty())?),
.body(Full::default())?),
}
}

Expand Down Expand Up @@ -169,18 +174,24 @@ async fn main() -> anyhow::Result<()> {
tracing_subscriber::fmt::init();

// Local address to bind the service to.
let addr = "127.0.0.1:3030".parse().unwrap();

// Make the interaction handler into a service function.
let interaction_service = make_service_fn(|_| async {
Ok::<_, anyhow::Error>(service_fn(|req| interaction_handler(req, handler)))
});

// Construct the server and serve the interaction service.
let server = Server::bind(&addr).serve(interaction_service);

// Start the server.
server.await?;

Ok(())
let addr = SocketAddr::from(([127, 0, 0, 1], 3030));

// Bind the server and serve the interaction service.
let listener = TcpListener::bind(addr).await?;

loop {
let (conn, _) = listener.accept().await?;

tokio::spawn(async move {
if let Err(e) = http1::Builder::new()
.serve_connection(
TokioIo::new(conn),
service_fn(|req| interaction_handler(req, handler)),
)
.await
{
tracing::error!("Error handling HTTP request: {e}");
};
});
}
}
2 changes: 1 addition & 1 deletion twilight-http-ratelimiting/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ tracing = { default-features = false, features = ["std", "attributes"], version

[dev-dependencies]
criterion = { default-features = false, version = "0.4" }
http = { version = "0.2", default-features = false }
http = { version = "1", default-features = false }
static_assertions = { default-features = false, version = "1.1.0" }
tokio = { default-features = false, features = ["macros", "rt-multi-thread"], version = "1.0" }

Expand Down

0 comments on commit defa55d

Please sign in to comment.