Coder Social home page Coder Social logo

viz's Introduction

Viz

Fast, robust, flexible, lightweight web framework for Rust

Features

  • Safety #![forbid(unsafe_code)]

  • Lightweight

  • Robust Routing

  • Handy Extractors

  • Simple + Flexible Handler & Middleware

  • Supports Tower Service

Hello Viz

use std::net::SocketAddr;
use tokio::net::TcpListener;
use viz::{serve, Request, Result, Router};

async fn index(_: Request) -> Result<&'static str> {
    Ok("Hello, Viz!")
}

#[tokio::main]
async fn main() -> Result<()> {
    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
    let listener = TcpListener::bind(addr).await?;
    println!("listening on http://{addr}");

    let app = Router::new().get("/", index);

    if let Err(e) = serve(listener, app).await {
        println!("{e}");
    }

    Ok(())
}

More examples can be found here.

Get started

Open Viz.rs, select language or version.

License

This project is licensed under the MIT license.

Author

viz's People

Contributors

baiyuetribe avatar fundon avatar kijewski avatar liangdi avatar m1212e avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

viz's Issues

no `serve` in the root

use std::{net::SocketAddr, sync::Arc};
use tokio::net::TcpListener;
use viz::{serve, Request, Result, Router, Tree};

async fn index(_: Request) -> Result<&'static str> {
    Ok("Hello, World!")
}

#[tokio::main]
async fn main() -> Result<()> {
    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
    let listener = TcpListener::bind(addr).await?;
    println!("listening on http://{addr}");

    let app = Router::new().get("/", index);
    let tree = Arc::new(Tree::from(app));

    loop {
        let (stream, addr) = listener.accept().await?;
        let tree = tree.clone();
        tokio::task::spawn(serve(stream, tree, Some(addr)));
    }
}

The hello-word above won't run. error[E0432]: unresolved import viz::serve

RUSTSEC-2021-0059: `aesni` has been merged into the `aes` crate

aesni has been merged into the aes crate

Details
Status unmaintained
Package aesni
Version 0.10.0
URL RustCrypto/block-ciphers#200
Date 2021-04-29

Please use the aes crate going forward. The new repository location is at:

<https://github.com/RustCrypto/block-ciphers/tree/master/aes>

AES-NI is now autodetected at runtime on i686/x86-64 platforms.
If AES-NI is not present, the aes crate will fallback to a constant-time
portable software implementation.

To prevent this fallback (and have absence of AES-NI result in an illegal
instruction crash instead), continue to pass the same RUSTFLAGS which were
previously required for the aesni crate to compile:

RUSTFLAGS=-Ctarget-feature=+aes,+ssse3

See advisory page for additional details.

Is it possible to use state elsewhere?

The following code works fine,

pub type Counter = Arc<Mutex<u32>>; 
async fn demo(mut req: Request) -> Result<Response> {
    let State(counter) = req.extract::<State<Counter>>().await?;
    let mut counter = counter.lock().unwrap();
    *counter += 1;
    Ok(Response::text(format!("Hello, World!{}", counter)))
}

but it's an exception when it's called from somewhere else

// no args
async fn demo() {
    let mut req = Request::builder().body(IncomingBody::Empty).unwrap();
    let State(counter) = req.extract::<State<Counter>>().await.unwrap();
    let mut counter = counter.lock().unwrap();
    *counter += 1;
    println!("Hello, World!{}", counter)
}

erros:
missing state type alloc::sync::Arc<std::sync::mutex::Mutex<u32>>

Tests

use cargo llvm-cov --html to improve coverage

Related to: #62

Methods of `request` that fetch its body don't respect custom limits

minimal example below (this goes for .json(), .text() and .bytes() I think)

Cargo.toml
[package]
name = "viz-limits"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
tokio = { version = "1.24.2", features = ["rt", "macros", "rt-multi-thread"] }
viz = { version = "0.4.4", features = ["limits", "json"] }
src/main.rs
use std::net::{Ipv4Addr, SocketAddr};

use viz::Result;
use viz::middleware::limits;
use viz::{ Router, Server, ServiceMaker};
use viz::{Request, RequestExt};


pub async fn echo(mut req: Request) -> viz::Result<String> {
    Ok(format!("len: {}", req.text().await?.len()))
}

#[tokio::main]
async fn main() -> Result<()> {
    let addr = SocketAddr::from((Ipv4Addr::new(127, 0, 0, 1), 3001));
    let ls = viz::types::Limits::new()
        .insert("payload", 1000 * 1024 * 1024)
        .insert("text", 1000 * 1024 * 1024)
        .insert("bytes", 1000 * 1024 * 1024)
        .insert("json", 1000 * 1024 * 1024);

    let endpoint = "/echo";
    let app = Router::new()
        .post(endpoint, echo)
        .with(limits::Config::default().limits(ls));

    println!("Listening on {addr}{endpoint}");
    if let Err(err) = Server::bind(&addr).serve(ServiceMaker::from(app)).await {
        eprintln!("{:?}", err);
    }

    Ok(())
}
/home/user/stuff/viz-limits % python3 -c "print('a'*8193)" > out
/home/user/stuff/viz-limits % curl -vv -d @out http://localhost:3001/echo
*   Trying 127.0.0.1:3001...
* Connected to localhost (127.0.0.1) port 3001 (#0)
> POST /echo HTTP/1.1
> Host: localhost:3001
> User-Agent: curl/7.81.0
> Accept: */*
> Content-Length: 8193
> Content-Type: application/x-www-form-urlencoded
> 
* Mark bundle as not supporting multiuse
< HTTP/1.1 413 Payload Too Large
< content-type: text/plain; charset=utf-8
< content-length: 20
< date: Wed, 08 Feb 2023 01:40:19 GMT
< 
* Connection #0 to host localhost left intact
payload is too large%

Allow returning custom error types in `Result`

Currently it does not work to return a custom error type that implements IntoResponse, it expects the error type to be viz::Error

Example

use std::net::SocketAddr;
use viz::{IntoResponse, Request, Result, Router, Server, ServiceMaker};

#[derive(Debug, thiserror::Error)]
#[error("{message}")]
pub struct MyError {
    message: String,
}

impl IntoResponse for MyError {
    fn into_response(self) -> viz::Response {
        viz::Response::builder()
            .body(viz::Body::from(self.message.to_string()))
            .unwrap()
    }
}

async fn index(_: Request) -> Result<&'static str, MyError> {
    Ok("Hello Viz")
}

#[tokio::main]
async fn main() -> Result<()> {
    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
    println!("listening on {addr}");

    let app = Router::new().get("/", index);

    if let Err(err) = Server::bind(&addr).serve(ServiceMaker::from(app)).await {
        println!("{err}");
    }

    Ok(())
}
error[E0271]: expected `impl Future<Output = Result<&str, MyError>>` to be a future that resolves to `Result<_, Error>`, but it resolves to `Result<&str, MyError>`
   --> src/main.rs:27:38
    |
27  |     let app = Router::new().get("/", index);
    |                             ---      ^^^^^ expected `Result<_, Error>`, found `Result<&str, MyError>`
    |                             |
    |                             required by a bound introduced by this call
    |
    = note: expected enum `Result<_, viz::Error>`
               found enum `Result<&'static str, MyError>`

Version 0.4.17

Dependency Dashboard

This issue provides visibility into Renovate updates and their statuses. Learn more

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.


  • Check this box to trigger a request for Renovate to run again on this repository

Server

Server has been removed in hyper-1.0. So we need it to manage connections and shutdown gracefully.

Refactor Extractors

  1. The mutable request is only needed if the infos needs to be modified, or if the body data needs to be extracted.
  2. Other cases do not require mutable

Three APIs

  • extract(): mut req is needed, e.g. extract body
  • extract_ref(): extract a reference
  • extract_cloned(): extract and clone
  • extract_sync: Most cases do not require async/await

RUSTSEC-2021-0060: `aes-soft` has been merged into the `aes` crate

aes-soft has been merged into the aes crate

Details
Status unmaintained
Package aes-soft
Version 0.6.4
URL RustCrypto/block-ciphers#200
Date 2021-04-29

Please use the aes crate going forward. The new repository location is at:

<https://github.com/RustCrypto/block-ciphers/tree/master/aes>

AES-NI is now autodetected at runtime on i686/x86-64 platforms.
If AES-NI is not present, the aes crate will fallback to a constant-time
portable software implementation.

To force the use of a constant-time portable implementation on these platforms,
even if AES-NI is available, use the new force-soft feature of the aes
crate to disable autodetection.

See advisory page for additional details.

RUSTSEC-2020-0159: Potential segfault in `localtime_r` invocations

Potential segfault in localtime_r invocations

Details
Package chrono
Version 0.4.19
URL chronotope/chrono#499
Date 2020-11-10

Impact

Unix-like operating systems may segfault due to dereferencing a dangling pointer in specific circumstances. This requires an environment variable to be set in a different thread than the affected functions. This may occur without the user's knowledge, notably in a third-party library.

Workarounds

No workarounds are known.

References

See advisory page for additional details.

RUSTSEC-2020-0122: beef::Cow lacks a Sync bound on its Send trait allowing for data races

beef::Cow lacks a Sync bound on its Send trait allowing for data races

Details
Package beef
Version 0.4.4
URL maciejhirsz/beef#37
Date 2020-10-28
Patched versions >=0.5.0

Affected versions of this crate did not have a T: Sync bound in the Send impl for Cow&lt;&#39;_, T, U&gt;. This allows users to create data races by making Cow contain types that are (Send && !Sync) like Cell&lt;_&gt; or RefCell&lt;_&gt;.

Such data races can lead to memory corruption.

The flaw was corrected in commit d1c7658 by adding trait bounds T: Sync and T::Owned: Send to the Send impl for Cow&lt;&#39;_, T, U&gt;.

See advisory page for additional details.

Default for viz::types::State?

would be nice to have Default for State so instead of having this horrible mess:

let state = State::new(Arc::new(AppState::default()));

i could instead have this less horrible mess:

type SharedAppState = State<Arc<AppState>>;
let state = SharedAppState::default();

[BUG]Error while serving HTTP connection: early eof

Reproduce

https://github.com/viz-rs/viz/blob/main/examples/static-files/embed/src/main.rsv
add a.txt file to public dir. this file with some word,size 1kb or more.
cargo run --bin embed
run this demo, then quick request url. It will cause a reboot serve
http://127.0.0.1:3000/static/a.txt

Logs

Error while serving HTTP connection: early eof
Error while serving HTTP connection: early eof

Expectations

This bug should not occur in the main application, as it will cause other connections that are being requested to fail

How good is the web-socket support?

Hi, Viz seems like a very good and a minimal alternative to all others out there. I have a question, is the websocket support fully-featured? How does it compare to something like tokio-tungstenite?

I'd love to use Viz it in a personal project to try it out.

RUSTSEC-2020-0071: Potential segfault in the time crate

Potential segfault in the time crate

Details
Package time
Version 0.1.43
URL time-rs/time#293
Date 2020-11-18
Patched versions >=0.2.23
Unaffected versions =0.2.0,=0.2.1,=0.2.2,=0.2.3,=0.2.4,=0.2.5,=0.2.6

Impact

Unix-like operating systems may segfault due to dereferencing a dangling pointer in specific circumstances. This requires an environment variable to be set in a different thread than the affected functions. This may occur without the user's knowledge, notably in a third-party library.

The affected functions from time 0.2.7 through 0.2.22 are:

  • time::UtcOffset::local_offset_at
  • time::UtcOffset::try_local_offset_at
  • time::UtcOffset::current_local_offset
  • time::UtcOffset::try_current_local_offset
  • time::OffsetDateTime::now_local
  • time::OffsetDateTime::try_now_local

The affected functions in time 0.1 (all versions) are:

  • at
  • at_utc

Non-Unix targets (including Windows and wasm) are unaffected.

Patches

Pending a proper fix, the internal method that determines the local offset has been modified to always return None on the affected operating systems. This has the effect of returning an Err on the try_* methods and UTC on the non-try_* methods.

Users and library authors with time in their dependency tree should perform cargo update, which will pull in the updated, unaffected code.

Users of time 0.1 do not have a patch and should upgrade to an unaffected version: time 0.2.23 or greater or the 0.3. series.

Workarounds

No workarounds are known.

References

time-rs/time#293

See advisory page for additional details.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.