Skip to content

Commit

Permalink
Http server (#6)
Browse files Browse the repository at this point in the history
* added a basic server using the waki

Signed-off-by: Dipankar Das <65275144+dipankardas011@users.noreply.github.com>

* added a new http server

Signed-off-by: Dipankar Das <65275144+dipankardas011@users.noreply.github.com>

* updated the docs

Signed-off-by: Dipankar Das <65275144+dipankardas011@users.noreply.github.com>

---------

Signed-off-by: Dipankar Das <65275144+dipankardas011@users.noreply.github.com>
  • Loading branch information
dipankardas011 authored Jul 8, 2024
1 parent b70c958 commit bb81898
Show file tree
Hide file tree
Showing 5 changed files with 163 additions and 37 deletions.
8 changes: 4 additions & 4 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -110,10 +110,6 @@ build: build_httpclient build_crypto build_openai build_watttime build_github_ap
run_gen_pass:
wasmtime run -S cli -S http composed.wasm -n password-gen -o crypto

.PHONY: run_demo
run_demo:
wasmtime run -S cli -S http --env OPENAI_API_KEY="ABCD1234" --dir=. composed.wasm -n dipankar --op demo

.PHONY: run_get_latest_release
run_get_latest_release:
wasmtime run -S http composed.wasm -n dipankar --op githubapi
Expand All @@ -126,6 +122,10 @@ run_openai:
run_green:
wasmtime run -S http --dir=. composed.wasm -n dipankar --op green

.PHONY: run_server
run_server:
wasmtime serve -O pooling-allocator=n -S cli -S http --dir=. composed.wasm

.PHONY: clean
clean:
rm -vrf \
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ make run_**
```mermaid
graph TD;
cli(["`CLI Written **Rust**`"])-->crypto(["`Crypto Written **Python**`"]);
cli-->webserver(["`HTTP webserver Written **Rust** present inside the cli`"]);
cli-->githubapi(["`Githubapi Written **Python**`"]);
cli-->openai(["`OpenAI LLM Written **Python**`"]);
cli-->watt(["`Watt_time client Written **Python**`"]);
Expand Down
1 change: 1 addition & 0 deletions cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ wit-bindgen-rt = { version = "0.26.0", features = ["bitflags"] }
tokio = { version = "1.38.0", features = ["sync","macros","io-util","rt","time"] }
anyhow = "1.0.86"
ansi_term = "0.12"
waki = "0.3.0"

[profile.release]
codegen-units = 1
Expand Down
174 changes: 143 additions & 31 deletions cli/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
#[allow(warnings)]
mod bindings;

use std::env;
use clap::Parser;
use std::fs;
use std::time::{Duration, SystemTime};
Expand All @@ -12,24 +11,72 @@ use bindings::dipankardas011::{
openai::llm,
watttime,
};
use waki::{handler, ErrorCode, Request, Response};
use anyhow::Result;
use ansi_term;
use ansi_term::Colour::{Cyan, Black, Red, Green, Blue, Yellow};
use ansi_term::Colour::{Cyan, Red, Green, Blue, Yellow};

const FILE_PATH: &str = "README.md";
const OP_CRYPTO: &str = "crypto";
const OP_GITHUBAPI: &str = "githubapi";
const OP_OPENAI: &str = "openai";
const OP_GREEN: &str = "green";
const OP_DEMO: &str = "demo";
const INDEX_HTML: &str = r#"
<!DOCTYPE html>
<html>
<head>
<title>WASI Server</title>
<style>
body {
text-align: center;
}
table {
margin-left: auto;
margin-right: auto;
}
</style>
</head>
<body>
<h1>Welcome to WASI Server</h1>
<p>Thanks for running it</p>
<p>Created in collobration with Dipankar, Joel, and others</p>
<table>
<tr>
<th>Method</th>
<th>Endpoint</th>
<th>Description</th>
</tr>
<tr>
<td>GET</td>
<td>/healthz</td>
<td>Health Check</td>
</tr>
<tr>
<td>GET</td>
<td>/</td>
<td>Home Page</td>
</tr>
<tr>
<td>PUT</td>
<td>/get-lazy?seconds={integer}</td>
<td>Get Lazy</td>
</tr>
<tr>
<td>GET</td>
<td>/**</td>
<td>Serve as a reverse Proxy</td>
</tr>
</table>
</body>
</html>
"#;

#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
struct CommandToPerform {
#[arg(short = 'n', long = "name")]
name: String,

#[arg(short='o', long="op", value_parser=[OP_CRYPTO, OP_GITHUBAPI, OP_DEMO, OP_OPENAI, OP_GREEN], default_value_t=OP_DEMO.to_string())]
#[arg(short='o', long="op", value_parser=[OP_CRYPTO, OP_GITHUBAPI, OP_OPENAI, OP_GREEN])]
operation: String,
}

Expand All @@ -41,13 +88,104 @@ async fn hh(name: &str) {
);
}


#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<()> {

let args = CommandToPerform::parse();

hh(&args.name).await;

#[handler]
fn hello(req: Request) -> Result<Response, ErrorCode> {
println!("client_request: {:?} {:?}", req.method(), req.url());
match (req.method(), req.path()) {
(waki::Method::Get, "/healthz") => {
println!("Health Check");
Response::builder()
.status_code(200)
.headers([("Content-Type", "text/plain"), ("Server", "WASI@v0.2")])
.body(
"Server is READY".as_bytes(),
)
.build()
}

(waki::Method::Get, "/") => {
Response::builder()
.status_code(200)
.headers([("Content-Type", "text/html"), ("Server", "WASI@v0.2")])
.body(
INDEX_HTML.as_bytes(),
)
.build()
}


(waki::Method::Put, "/get-lazy") => {
let query = req.query();
let now = SystemTime::now();
let sleep_duration = match query.get("seconds") {
Some(s) => s.parse::<u64>().unwrap_or(1),
None => 1,
};
sleep(Duration::new(sleep_duration, 0));
if let Err(e) = now.elapsed() {
return Response::builder()
.body(
format!(
"Error: {e:?}"
).as_bytes(),
)
.build();
}

Response::builder()
.body(
format!(
"Thanks for making server lazy for, {}s!",
query.get("seconds").unwrap_or(&"1".to_string())
)
.as_bytes(),
)
.build()
}

(waki::Method::Get, _) => {
let file_loc = req.path();

println!("{}", Blue.paint(format!("In file {:?}", file_loc)));

match fs::read_to_string(file_loc) {
Ok(contents) => {
Response::builder()
.status_code(200)
.headers([("Content-Type", "text/plain"), ("Server", "WASI@v0.2")])
.body(
format!("reverseproxy\n====\n{}",contents).as_bytes(),
)
.build()
}
Err(e) => {
Response::builder()
.status_code(404)
.body(
format!(
"Error: {e:?}"
).as_bytes(),
)
.build()
}
}
}

_ => Response::builder()
.status_code(404)
.body("Not Found".as_bytes())
.build()
}
}

match args.operation.as_str() {
OP_GREEN => {
println!("{}", Cyan.paint("> Enter [1] register [2] get region code based on curr loc [3] get forecast based on current loc [4] get current CO2 MOER index"));
Expand Down Expand Up @@ -216,32 +354,6 @@ async fn main() -> Result<()> {
}

}
OP_DEMO => {
println!("{}", Black.paint(format!("Your Name: {}, Op: {}", args.name, args.operation)));

for (key, value) in env::vars() {
println!("{}", Black.paint(format!("{key} : {value}")));
}

println!("{}", Blue.paint(format!("In file {FILE_PATH}")));

let contents =
fs::read_to_string(FILE_PATH).expect("Should have been able to read the file");

println!("Content upto 50 chars: \n-----\n{}\n-----\n", &contents[..50]);

let now = SystemTime::now();

sleep(Duration::new(2, 0));
match now.elapsed() {
Ok(elapsed) => {
println!("{}", Black.paint(format!("Sleeped for {}s", elapsed.as_secs())));
}
Err(e) => {
eprintln!("{}", Red.bold().paint(format!("Error: {e:?}")));
}
}
}
_ => eprintln!("{}", Red.bold().paint("Invalid Operation choosen"))
}

Expand Down
16 changes: 14 additions & 2 deletions goals.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,5 +63,17 @@ Integrate the above two goals [3](#goal-3) [4](#goal-4) [5](#goal-5)

https://docs.watttime.org/

> [!IMPORTANT]
> Finally deploy using these in a docker container and runtimeclass in K8s

## Goal 8

- [x] Achieved?

- use wasi:http server

## Goal 9

- [ ] Achieved?

replace all the waki http client and server with the wasi http implementation

> drawbacks are so much low level control, but its fun ;)

0 comments on commit bb81898

Please sign in to comment.