1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
use crate::expect::{ExpectBytes, ExpectJson, ExpectString};
use crate::middleware::Middleware;
use crate::{
expect::ResponseExpectation,
http::{
headers::{HeaderName, ToHeaderValues},
Body, Method, Mime, Url,
},
};
use crate::{Client, HttpError, Request, Response, ResponseAsync, Result};
use futures_util::future::BoxFuture;
use http_types::convert::DeserializeOwned;
use serde::Serialize;
use std::{fmt, marker::PhantomData};
/// Request Builder
///
/// Provides an ergonomic way to chain the creation of a request.
/// This is generally accessed as the return value from `Http::{method}()`.
///
/// # Examples
///
/// ```no_run
/// use crux_http::http::{mime::HTML};
/// # enum Event { ReceiveResponse(crux_http::Result<crux_http::Response<Vec<u8>>>) }
/// # struct Capabilities { http: crux_http::Http<Event> }
/// # fn update(caps: &Capabilities) {
/// caps.http
/// .post("https://httpbin.org/post")
/// .body("<html>hi</html>")
/// .header("custom-header", "value")
/// .content_type(HTML)
/// .send(Event::ReceiveResponse)
/// # }
/// ```
#[must_use]
pub struct RequestBuilder<Event, ExpectBody = Vec<u8>> {
/// Holds the state of the request.
req: Option<Request>,
cap_or_client: CapOrClient<Event>,
phantom: PhantomData<fn() -> Event>,
expectation: Box<dyn ResponseExpectation<Body = ExpectBody> + Send>,
}
// Middleware request builders won't have access to the capability, so they get a client
// and therefore can't send events themselves. Normal request builders get direct access
// to the capability itself.
enum CapOrClient<Event> {
Client(Client),
Capability(crate::Http<Event>),
}
impl<Event> RequestBuilder<Event, Vec<u8>> {
pub(crate) fn new(method: Method, url: Url, capability: crate::Http<Event>) -> Self {
Self {
req: Some(Request::new(method, url)),
cap_or_client: CapOrClient::Capability(capability),
phantom: PhantomData,
expectation: Box::new(ExpectBytes),
}
}
}
impl RequestBuilder<(), Vec<u8>> {
pub(crate) fn new_for_middleware(method: Method, url: Url, client: Client) -> Self {
Self {
req: Some(Request::new(method, url)),
cap_or_client: CapOrClient::Client(client),
phantom: PhantomData,
expectation: Box::new(ExpectBytes),
}
}
}
impl<Event, ExpectBody> RequestBuilder<Event, ExpectBody>
where
Event: 'static,
ExpectBody: 'static,
{
/// Sets a header on the request.
///
/// # Examples
///
/// ```no_run
/// # enum Event { ReceiveResponse(crux_http::Result<crux_http::Response<Vec<u8>>>) }
/// # struct Capabilities { http: crux_http::Http<Event> }
/// # fn update(caps: &Capabilities) {
/// caps.http
/// .get("https://httpbin.org/get")
/// .body("<html>hi</html>")
/// .header("header-name", "header-value")
/// .send(Event::ReceiveResponse)
/// # }
/// ```
pub fn header(mut self, key: impl Into<HeaderName>, value: impl ToHeaderValues) -> Self {
self.req.as_mut().unwrap().insert_header(key, value);
self
}
/// Sets the Content-Type header on the request.
///
/// # Examples
///
/// ```no_run
/// # use crux_http::http::mime;
/// # enum Event { ReceiveResponse(crux_http::Result<crux_http::Response<Vec<u8>>>) }
/// # struct Capabilities { http: crux_http::Http<Event> }
/// # fn update(caps: &Capabilities) {
/// caps.http
/// .get("https://httpbin.org/get")
/// .content_type(mime::HTML)
/// .send(Event::ReceiveResponse)
/// # }
/// ```
pub fn content_type(mut self, content_type: impl Into<Mime>) -> Self {
self.req
.as_mut()
.unwrap()
.set_content_type(content_type.into());
self
}
/// Sets the body of the request from any type with implements `Into<Body>`, for example, any type with is `AsyncRead`.
/// # Mime
///
/// The encoding is set to `application/octet-stream`.
///
/// # Examples
///
/// ```no_run
/// # enum Event { ReceiveResponse(crux_http::Result<crux_http::Response<Vec<u8>>>) }
/// # struct Capabilities { http: crux_http::Http<Event> }
/// # fn update(caps: &Capabilities) {
/// use serde_json::json;
/// use crux_http::http::mime;
/// caps.http
/// .post("https://httpbin.org/post")
/// .body(json!({"any": "Into<Body>"}))
/// .content_type(mime::HTML)
/// .send(Event::ReceiveResponse)
/// # }
/// ```
pub fn body(mut self, body: impl Into<Body>) -> Self {
self.req.as_mut().unwrap().set_body(body);
self
}
/// Pass JSON as the request body.
///
/// # Mime
///
/// The encoding is set to `application/json`.
///
/// # Errors
///
/// This method will return an error if the provided data could not be serialized to JSON.
///
/// # Examples
///
/// ```no_run
/// # use serde::{Deserialize, Serialize};
/// # enum Event { ReceiveResponse(crux_http::Result<crux_http::Response<Vec<u8>>>) }
/// # struct Capabilities { http: crux_http::Http<Event> }
/// # fn update(caps: &Capabilities) {
/// #[derive(Deserialize, Serialize)]
/// struct Ip {
/// ip: String
/// }
///
/// let data = &Ip { ip: "129.0.0.1".into() };
/// caps.http
/// .post("https://httpbin.org/post")
/// .body_json(data)
/// .expect("could not serialize body")
/// .send(Event::ReceiveResponse)
/// # }
/// ```
pub fn body_json(self, json: &impl Serialize) -> crate::Result<Self> {
Ok(self.body(Body::from_json(json)?))
}
/// Pass a string as the request body.
///
/// # Mime
///
/// The encoding is set to `text/plain; charset=utf-8`.
///
/// # Examples
///
/// ```no_run
/// # enum Event { ReceiveResponse(crux_http::Result<crux_http::Response<Vec<u8>>>) }
/// # struct Capabilities { http: crux_http::Http<Event> }
/// # fn update(caps: &Capabilities) {
/// caps.http
/// .post("https://httpbin.org/post")
/// .body_string("hello_world".to_string())
/// .send(Event::ReceiveResponse)
/// # }
/// ```
pub fn body_string(self, string: String) -> Self {
self.body(Body::from_string(string))
}
/// Pass bytes as the request body.
///
/// # Mime
///
/// The encoding is set to `application/octet-stream`.
///
/// # Examples
///
/// ```no_run
/// # enum Event { ReceiveResponse(crux_http::Result<crux_http::Response<Vec<u8>>>) }
/// # struct Capabilities { http: crux_http::Http<Event> }
/// # fn update(caps: &Capabilities) {
/// caps.http
/// .post("https://httpbin.org/post")
/// .body_bytes(b"hello_world".to_owned())
/// .send(Event::ReceiveResponse)
/// # }
/// ```
pub fn body_bytes(self, bytes: impl AsRef<[u8]>) -> Self {
self.body(Body::from(bytes.as_ref()))
}
/// Set the URL querystring.
///
/// # Examples
///
/// ```no_run
/// # use serde::{Deserialize, Serialize};
/// # enum Event { ReceiveResponse(crux_http::Result<crux_http::Response<Vec<u8>>>) }
/// # struct Capabilities { http: crux_http::Http<Event> }
/// # fn update(caps: &Capabilities) {
/// #[derive(Serialize, Deserialize)]
/// struct Index {
/// page: u32
/// }
///
/// let query = Index { page: 2 };
/// caps.http
/// .post("https://httpbin.org/post")
/// .query(&query)
/// .expect("could not serialize query string")
/// .send(Event::ReceiveResponse)
/// # }
/// ```
pub fn query(mut self, query: &impl Serialize) -> std::result::Result<Self, HttpError> {
self.req.as_mut().unwrap().set_query(query)?;
Ok(self)
}
/// Push middleware onto a per-request middleware stack.
///
/// **Important**: Setting per-request middleware incurs extra allocations.
/// Creating a `Client` with middleware is recommended.
///
/// Client middleware is run before per-request middleware.
///
/// See the [middleware] submodule for more information on middleware.
///
/// [middleware]: ../middleware/index.html
///
/// # Examples
///
/// ```no_run
/// # enum Event { ReceiveResponse(crux_http::Result<crux_http::Response<Vec<u8>>>) }
/// # struct Capabilities { http: crux_http::Http<Event> }
/// # fn update(caps: &Capabilities) {
///
/// caps.http
/// .get("https://httpbin.org/redirect/2")
/// .middleware(crux_http::middleware::Redirect::default())
/// .send(Event::ReceiveResponse)
/// # }
/// ```
pub fn middleware(mut self, middleware: impl Middleware) -> Self {
self.req.as_mut().unwrap().middleware(middleware);
self
}
/// Return the constructed `Request`.
pub fn build(self) -> Request {
self.req.unwrap()
}
/// Decode a String from the response body prior to dispatching it to the apps `update`
/// function.
///
/// This has no effect when used with the [async API](RequestBuilder::send_async).
///
/// # Examples
///
/// ```no_run
/// # struct Capabilities { http: crux_http::Http<Event> }
/// enum Event { ReceiveResponse(crux_http::Result<crux_http::Response<String>>) }
///
/// # fn update(caps: &Capabilities) {
/// caps.http
/// .post("https://httpbin.org/json")
/// .expect_string()
/// .send(Event::ReceiveResponse)
/// # }
/// ```
pub fn expect_string(self) -> RequestBuilder<Event, String> {
let expectation = Box::<ExpectString>::default();
RequestBuilder {
req: self.req,
cap_or_client: self.cap_or_client,
phantom: PhantomData,
expectation,
}
}
/// Decode a `T` from a JSON response body prior to dispatching it to the apps `update`
/// function.
///
/// This has no effect when used with the [async API](RequestBuilder::send_async).
///
/// # Examples
///
/// ```no_run
/// # use serde::{Deserialize, Serialize};
/// # struct Capabilities { http: crux_http::Http<Event> }
/// #[derive(Deserialize)]
/// struct Response {
/// slideshow: Slideshow
/// }
///
/// #[derive(Deserialize)]
/// struct Slideshow {
/// author: String
/// }
///
/// enum Event { ReceiveResponse(crux_http::Result<crux_http::Response<Slideshow>>) }
///
/// # fn update(caps: &Capabilities) {
/// caps.http
/// .post("https://httpbin.org/json")
/// .expect_json::<Slideshow>()
/// .send(Event::ReceiveResponse)
/// # }
/// ```
pub fn expect_json<T>(self) -> RequestBuilder<Event, T>
where
T: DeserializeOwned + 'static,
{
let expectation = Box::<ExpectJson<T>>::default();
RequestBuilder {
req: self.req,
cap_or_client: self.cap_or_client,
phantom: PhantomData,
expectation,
}
}
/// Sends the constructed `Request` and returns its result as an update `Event`
///
/// When finished, the response will wrapped in an event using `make_event` and
/// dispatched to the app's `update function.
pub fn send<F>(self, make_event: F)
where
F: FnOnce(crate::Result<Response<ExpectBody>>) -> Event + Send + 'static,
{
let CapOrClient::Capability(capability) = self.cap_or_client else {
panic!("Called RequestBuilder::send in a middleware context");
};
let request = self.req;
let ctx = capability.context.clone();
ctx.spawn(async move {
let result = capability.client.send(request.unwrap()).await;
let resp = match result {
Ok(resp) => resp,
Err(e) => {
capability.context.update_app(make_event(Err(e)));
return;
}
};
let resp = Response::<Vec<u8>>::new(resp)
.await
.and_then(|r| self.expectation.decode(r));
capability.context.update_app(make_event(resp));
});
}
/// Sends the constructed `Request` and returns a future that resolves to [`ResponseAsync`].
/// but does not consume it or convert the body to an expected format.
///
/// Note that this is equivalent to calling `.into_future()` on the `RequestBuilder`, which
/// will happen implicitly when calling `.await` on the builder, which does implement
/// [`IntoFuture`](std::future::IntoFuture). Calling `.await` on the builder is recommended.
///
/// Not all code working with futures (such as the `join` macro) works with `IntoFuture` (yet?), so this
/// method is provided as a more discoverable `.into_future` alias, and may be deprecated later.
pub fn send_async(self) -> BoxFuture<'static, Result<ResponseAsync>> {
<Self as std::future::IntoFuture>::into_future(self)
}
}
impl<T, Eb> std::future::IntoFuture for RequestBuilder<T, Eb> {
type Output = Result<ResponseAsync>;
type IntoFuture = BoxFuture<'static, Result<ResponseAsync>>;
/// Sends the constructed `Request` and returns a future that resolves to the response
fn into_future(self) -> Self::IntoFuture {
Box::pin({
let client = match self.cap_or_client {
CapOrClient::Client(c) => c,
CapOrClient::Capability(c) => c.client,
};
async move { client.send(self.req.unwrap()).await }
})
}
}
impl<Ev> fmt::Debug for RequestBuilder<Ev> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.req, f)
}
}
// impl From<RequestBuilder<Ev>> for Request {
// /// Converts a `crux_http::RequestBuilder` to a `crux_http::Request`.
// fn from(builder: RequestBuilder) -> Request {
// builder.build()
// }
// }