Skip to content

Commit cb7b856

Browse files
committed
update micro_http documentation
Signed-off-by: George Pisaltu <gpl@amazon.com>
1 parent 6cbf2d3 commit cb7b856

File tree

3 files changed

+98
-6
lines changed

3 files changed

+98
-6
lines changed

micro_http/src/connection.rs

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,11 @@ impl<T: Read + Write> HttpConnection<T> {
7171
/// Tries to read new bytes from the stream and automatically update the request.
7272
/// Meant to be used only with non-blocking streams and an `EPOLL` structure.
7373
/// Should be called whenever an `EPOLLIN` event is signaled.
74+
///
75+
/// # Errors
76+
/// `StreamError` is returned when an IO operation fails.
77+
/// `ConnectionClosed` is returned when a client prematurely closes the connection.
78+
/// `ParseError` is returned when a parsing operation fails.
7479
pub fn try_read(&mut self) -> Result<(), ConnectionError> {
7580
// Read some bytes from the stream, which will be appended to what is already
7681
// present in the buffer from a previous call of `try_read`. There are already
@@ -293,6 +298,12 @@ impl<T: Read + Write> HttpConnection<T> {
293298
/// Tries to write the first available response to the provided stream.
294299
/// Meant to be used only with non-blocking streams and an `EPOLL` structure.
295300
/// Should be called whenever an `EPOLLOUT` event is signaled.
301+
///
302+
/// # Errors
303+
/// `StreamError` is returned when an IO operation fails.
304+
/// `ConnectionClosed` is returned when trying to write on a closed connection.
305+
/// `InvalidWrite` is returned when trying to write on a connection with an
306+
/// empty outgoing buffer.
296307
pub fn try_write(&mut self) -> Result<(), ConnectionError> {
297308
if self.response_buffer.is_none() {
298309
if let Some(response) = self.response_queue.pop_front() {
@@ -365,12 +376,13 @@ impl<T: Read + Write> HttpConnection<T> {
365376
self.read_cursor = end_cursor - line_start_index;
366377
}
367378

368-
/// Returns the first parsed request in the queue.
379+
/// Returns the first parsed request in the queue or `None` if the queue
380+
/// is empty.
369381
pub fn pop_parsed_request(&mut self) -> Option<Request> {
370382
self.parsed_requests.pop_front()
371383
}
372384

373-
/// Returns true if there are bytes waiting to be written into the stream.
385+
/// Returns `true` if there are bytes waiting to be written into the stream.
374386
pub fn pending_write(&self) -> bool {
375387
self.response_buffer.is_some() || !self.response_queue.is_empty()
376388
}

micro_http/src/lib.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,11 +56,12 @@
5656
//! ## Example for creating an HTTP Response
5757
//! ```
5858
//! extern crate micro_http;
59-
//! use micro_http::{Body, Response, StatusCode, Version};
59+
//! use micro_http::{Body, Response, StatusCode, Version, MediaType};
6060
//!
6161
//! let mut response = Response::new(Version::Http10, StatusCode::OK);
6262
//! let body = String::from("This is a test");
6363
//! response.set_body(Body::new(body.clone()));
64+
//! response.set_content_type(MediaType::PlainText);
6465
//!
6566
//! assert!(response.status() == StatusCode::OK);
6667
//! assert_eq!(response.body().unwrap(), Body::new(body));

micro_http/src/server.rs

Lines changed: 82 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ pub struct ServerRequest {
3232
}
3333

3434
impl ServerRequest {
35-
/// Creates a new `RequestWithID` object from an existing `Request`,
35+
/// Creates a new `ServerRequest` object from an existing `Request`,
3636
/// adding an identification token.
3737
pub fn new(request: Request, id: u64) -> Self {
3838
ServerRequest { request, id }
@@ -43,7 +43,10 @@ impl ServerRequest {
4343
&self.request
4444
}
4545

46-
/// Docs needed.
46+
/// Calls the function provided on the inner request to obtain the response.
47+
/// The response is then wrapped in a `ServerResponse`.
48+
///
49+
/// Returns a `ServerResponse` ready for yielding to the server
4750
pub fn process<F>(&self, callable: F) -> ServerResponse
4851
where
4952
F: Fn(&Request) -> Response,
@@ -246,6 +249,12 @@ pub struct HttpServer {
246249

247250
impl HttpServer {
248251
/// Constructor for `HttpServer`.
252+
///
253+
/// Returns the newly formed `HttpServer`.
254+
///
255+
/// # Errors
256+
/// Returns an `IOError` when binding or `epoll::create` fails.
257+
///
249258
pub fn new<P: AsRef<Path>>(path_to_socket: P) -> Result<Self> {
250259
let socket = UnixListener::bind(path_to_socket).map_err(ServerError::IOError)?;
251260
let epoll_fd = epoll::create(true).map_err(ServerError::IOError)?;
@@ -273,6 +282,13 @@ impl HttpServer {
273282
///
274283
/// Returns a collection of complete and valid requests to be processed by the user
275284
/// of the server. Once processed, responses should be sent using `enqueue_responses()`.
285+
///
286+
/// # Errors
287+
/// `IOError` is returned when `read`, `write` or `epoll::ctl` operations fail.
288+
/// `ServerFull` is returned when a client is trying to connect to the server, but
289+
/// full capacity has already been reached.
290+
/// `InvalidWrite` is returned when the server attempted to perform a write operation
291+
/// on a connection on which it is not possible.
276292
pub fn incoming(&mut self) -> Result<Vec<ServerRequest>> {
277293
let mut parsed_requests: Vec<ServerRequest> = vec![];
278294
let mut events = vec![epoll::Event::new(epoll::Events::empty(), 0); MAX_CONNECTIONS];
@@ -353,12 +369,69 @@ impl HttpServer {
353369
Ok(parsed_requests)
354370
}
355371

372+
/// The file descriptor of the `epoll` structure can enable the server to become
373+
/// a non-blocking structure in an application.
374+
///
356375
/// Returns the file descriptor of the server's internal `epoll` structure.
376+
///
377+
/// # Example
378+
///
379+
/// ## Non-blocking server
380+
/// ```
381+
/// extern crate epoll;
382+
///
383+
/// use micro_http::{HttpServer, Response, StatusCode};
384+
///
385+
/// // Create our epoll manager.
386+
/// let epoll_fd = epoll::create(true).unwrap();
387+
///
388+
/// let path_to_socket = "/tmp/epoll_example.sock";
389+
/// std::fs::remove_file(path_to_socket).unwrap_or_default();
390+
///
391+
/// // Start the server.
392+
/// let mut server = HttpServer::new(path_to_socket).unwrap();
393+
/// server.start_server().unwrap();
394+
///
395+
/// // Add our server to the `epoll` manager.
396+
/// epoll::ctl(
397+
/// epoll_fd,
398+
/// epoll::ControlOptions::EPOLL_CTL_ADD,
399+
/// server.epoll_fd(),
400+
/// epoll::Event::new(epoll::Events::EPOLLIN, 1234u64),
401+
/// ).unwrap();
402+
///
403+
/// // Connect a client to the server so it doesn't block in our example.
404+
/// let mut socket = std::os::unix::net::UnixStream::connect(path_to_socket).unwrap();
405+
///
406+
/// // Control loop of the application.
407+
/// let mut events = Vec::with_capacity(10);
408+
/// loop {
409+
/// let num_ev = epoll::wait(epoll_fd, -1, events.as_mut_slice());
410+
/// for event in events {
411+
/// match event.data {
412+
/// // The server notification.
413+
/// 1234 => {
414+
/// let request = server.incoming();
415+
/// // Process...
416+
/// },
417+
/// // Other `epoll` notifications.
418+
/// _ => {
419+
/// // Do other computation.
420+
/// },
421+
/// }
422+
/// }
423+
/// // Break this example loop.
424+
/// break;
425+
/// }
426+
/// ```
357427
pub fn epoll_fd(&self) -> RawFd {
358428
self.epoll_fd
359429
}
360430

361431
/// Enqueues the provided responses in the outgoing connection.
432+
///
433+
/// # Errors
434+
/// `IOError` is returned when an `epoll::ctl` operation fails.
362435
pub fn enqueue_responses(&mut self, responses: Vec<ServerResponse>) -> Result<()> {
363436
for response in responses {
364437
self.respond(response)?;
@@ -367,7 +440,10 @@ impl HttpServer {
367440
Ok(())
368441
}
369442

370-
/// Docs needed.
443+
/// Adds the provided response to the outgoing buffer in the corresponding connection.
444+
///
445+
/// # Errors
446+
/// `IOError` is returned when an `epoll::ctl` operation fails.
371447
pub fn respond(&mut self, response: ServerResponse) -> Result<()> {
372448
if let Some(client_connection) = self.connections.get_mut(&(response.id as i32)) {
373449
// If the connection was incoming before we enqueue the response, we change its
@@ -382,6 +458,9 @@ impl HttpServer {
382458
}
383459

384460
/// Accepts a new incoming connection and adds it to the `epoll` notification structure.
461+
///
462+
/// # Errors
463+
/// `IOError` is returned when an `epoll::ctl` operation fails.
385464
fn handle_new_connection(&mut self) -> Result<()> {
386465
if self.connections.len() == MAX_CONNECTIONS {
387466
// If we want a replacement policy for connections

0 commit comments

Comments
 (0)