Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
ovstinga authored Dec 20, 2024
0 parents commit 4687b49
Show file tree
Hide file tree
Showing 14 changed files with 421 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .githooks/pre-commit
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#!/bin/sh
cargo fmt --check && cargo clippy -- -D warnings
21 changes: 21 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
name: CI

on:
push:
branches:
- "**"

jobs:
Tests:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Toolchain
uses: actions-rust-lang/setup-rust-toolchain@v1
- name: Build cache
uses: Swatinem/rust-cache@v2
- name: Test
run: cargo test
- name: Lints
run: ./.githooks/pre-commit
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/target
Cargo.lock
11 changes: 11 additions & 0 deletions .rqst.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
title = "Async Rust"
author = "cognitive-engineering-lab"
repo = "rqst-async"

[[stages]]
label = "01-async-await"
name = "Async and Await"

[[stages]]
label = "02-spawn"
name = "Spawning Futures"
1 change: 1 addition & 0 deletions .rustfmt.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
tab_spaces = 4
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[workspace]
members = ["crates/*"]
resolver = "2"
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 Cognitive Engineering Lab

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# ChatABC

**Chat** using **A**sync, **B**ecause we **C**an.

## Usage

```
cargo run
```

Open <http://localhost:3000/> in your browser.

## Contributing

Before committing, install the our Git hooks:

```
git config --local core.hooksPath .githooks
```
8 changes: 8 additions & 0 deletions crates/miniserve/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[package]
name = "miniserve"
version = "0.1.0"
edition = "2021"

[dependencies]
http = "1.1.0"
httparse = "1.9.4"
86 changes: 86 additions & 0 deletions crates/miniserve/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
#![warn(clippy::pedantic)]

use std::{
collections::HashMap,
io::{self},
net::{TcpListener, TcpStream},
sync::Arc,
thread,
};

/// Re-export for library clients.
pub use http;

/// Implementation details for HTTP.
mod protocol;

/// A request from a client, either a GET or a POST with a body.
#[derive(Debug, Clone)]
pub enum Request {
Get,
Post(String),
}

/// Content to give to a client, either HTML or JSON.
#[derive(Debug, Clone)]
pub enum Content {
Html(String),
Json(String),
}

/// Response to give to a client, either content or a status code for a failure (e.g. 404).
pub type Response = Result<Content, http::StatusCode>;

/// Trait alias for functions that can handle requests and return responses.
pub trait Handler: Fn(Request) -> Response + Send + Sync + 'static {}

impl<F> Handler for F where F: Fn(Request) -> Response + Send + Sync + 'static {}

/// The main server data structure.
#[derive(Default)]
pub struct Server {
/// Map from a route path (e.g., "/foo") to a handler function for that route.
routes: HashMap<String, Box<dyn Handler>>,
}

impl Server {
/// Creates a server with no routes.
#[must_use]
pub fn new() -> Self {
Server {
routes: HashMap::new(),
}
}

/// Adds a new route to the server.
#[must_use]
pub fn route<H: Handler>(mut self, route: impl Into<String>, handler: H) -> Self {
self.routes.insert(route.into(), Box::new(handler));
self
}

/// Runs the server by listening for connections and returning responses.
///
/// This function should never return.
///
/// # Panics
///
/// Panics if `127.0.0.1:3000` is not available.
pub fn run(self) {
let listener =
TcpListener::bind("127.0.0.1:3000").expect("Failed to connect to 127.0.0.1:3000");
let this = Arc::new(self);
for stream in listener.incoming().flatten() {
let this_ref = Arc::clone(&this);
thread::spawn(move || {
let _ = this_ref.handle(&stream);
});
}
}

fn handle(&self, stream: &TcpStream) -> io::Result<()> {
protocol::handle(stream, |route, request| {
self.routes.get(route).map(move |handler| handler(request))
})
}
}
152 changes: 152 additions & 0 deletions crates/miniserve/src/protocol.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
//! Implementation details for HTTP.
//!
//! You should not need to deal with this module.
use std::{
io::{self, BufRead, BufReader, BufWriter, Write},
net::{Shutdown, TcpStream},
};

use http::StatusCode;

pub fn stringify_response(response: http::Response<Vec<u8>>) -> Vec<u8> {
let (parts, body) = response.into_parts();

let mut buf = Vec::with_capacity(body.len() + 256);
buf.extend_from_slice(b"HTTP/1.1 ");
buf.extend(parts.status.as_str().as_bytes());
if let Some(reason) = parts.status.canonical_reason() {
buf.extend_from_slice(b" ");
buf.extend(reason.as_bytes());
}

buf.extend_from_slice(b"\r\n");

for (name, value) in parts.headers {
if let Some(name) = name {
buf.extend(name.as_str().as_bytes());
buf.extend_from_slice(b": ");
}
buf.extend(value.as_bytes());
buf.extend_from_slice(b"\r\n");
}

buf.extend_from_slice(b"\r\n");
buf.extend(body);

buf
}

#[allow(clippy::result_large_err)]
fn parse_request(src: &[u8]) -> Result<Option<http::Request<Vec<u8>>>, http::Response<Vec<u8>>> {
let mut headers = [httparse::EMPTY_HEADER; 64];
let mut parsed_req = httparse::Request::new(&mut headers);
let Ok(status) = parsed_req.parse(src) else {
return Err(make_response(
StatusCode::BAD_REQUEST,
"Failed to parse request",
));
};
let amt = match status {
httparse::Status::Complete(amt) => amt,
httparse::Status::Partial => return Ok(None),
};

let Ok(method) = http::Method::try_from(parsed_req.method.unwrap()) else {
return Err(make_response(
StatusCode::BAD_REQUEST,
"Failed to parse request",
));
};

let data = &src[amt..];

let mut builder = http::Request::builder()
.method(method)
.version(http::Version::HTTP_11)
.uri(parsed_req.path.unwrap());
for header in parsed_req.headers {
builder = builder.header(header.name, header.value);
}

Ok(Some(builder.body(data.to_vec()).unwrap()))
}

fn make_response(status: http::StatusCode, explanation: &str) -> http::Response<Vec<u8>> {
http::Response::builder()
.status(status)
.body(explanation.as_bytes().to_vec())
.unwrap()
}

fn generate_response(
req: http::Request<Vec<u8>>,
callback: impl Fn(&str, crate::Request) -> Option<crate::Response>,
) -> http::Response<Vec<u8>> {
let (parts, body) = req.into_parts();
let request = match parts.method {
http::Method::GET => crate::Request::Get,
http::Method::POST => crate::Request::Post(String::from_utf8(body).unwrap()),
_ => return make_response(StatusCode::METHOD_NOT_ALLOWED, "Not implemented"),
};

let Some(response_res) = callback(parts.uri.path(), request) else {
return make_response(StatusCode::NOT_FOUND, "No valid route");
};

match response_res {
Ok(content) => {
let (body, ty) = match content {
crate::Content::Html(body) => (body, "text/html"),
crate::Content::Json(body) => (body, "application/json"),
};
http::Response::builder()
.header("Content-Type", ty)
.header("Content-Length", body.len())
.body(body.into_bytes())
.unwrap()
}
Err(status) => make_response(status, "Handler failed"),
}
}

pub fn handle(
stream: &TcpStream,
callback: impl Fn(&str, crate::Request) -> Option<crate::Response>,
) -> io::Result<()> {
let mut reader = BufReader::new(stream.try_clone()?);
let mut writer = BufWriter::new(stream.try_clone()?);

loop {
let req = loop {
let buf = reader.fill_buf()?;
if buf.is_empty() {
stream.shutdown(Shutdown::Both)?;
return Ok(());
}

match parse_request(buf) {
Ok(None) => continue,
Ok(Some(req)) => {
let amt = buf.len();
reader.consume(amt);
break Ok(req);
}
Err(resp) => {
let amt = buf.len();
reader.consume(amt);
break Err(resp);
}
}
};

let resp = match req {
Ok(req) => generate_response(req, &callback),
Err(resp) => resp,
};

let buf = stringify_response(resp);
writer.write_all(&buf)?;
writer.flush()?;
}
}
7 changes: 7 additions & 0 deletions crates/server/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[package]
name = "server"
version = "0.1.0"
edition = "2021"

[dependencies]
miniserve = { path = "../miniserve" }
Loading

0 comments on commit 4687b49

Please sign in to comment.