Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Xitca Web
https://github.com/hfqr/xitca-web
Admin
A HTTP library and web framework written in 100% safe Rust with zero-copy
...
Tokens:
270,016
Snippets:
1,805
Trust Score:
7.3
License:
Apache-2.0
Update:
2 weeks ago
Context
Chat
Benchmark
56
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Run Standard Source: https://github.com/hfqr/xitca-web/blob/main/examples/auth/README.md Start the server normally. The server will listen on http://localhost:8080. ```bash cargo run ``` -------------------------------- ### Run with Auto-Reload Source: https://github.com/hfqr/xitca-web/blob/main/examples/auth/README.md Start the server with auto-reload using cargo-watch. Requires cargo-watch to be installed. ```bash cargo watch -x run ``` -------------------------------- ### Clone the Repository Source: https://github.com/hfqr/xitca-web/blob/main/examples/auth/README.md Clone the example repository and navigate into the project directory. ```bash git clone https://github.com/your-username/your-repo-name.git cd your-repo-name ``` -------------------------------- ### Compile project on Unix Source: https://github.com/hfqr/xitca-web/blob/main/examples/wasi/README.md Compiles the project for wasm32-wasip1-threads on Unix with tokio_unstable flag. ```bash RUSTFLAGS="--cfg tokio_unstable" cargo build --release --target wasm32-wasip1-threads ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/hfqr/xitca-web/blob/main/examples/auth/README.md Create a .env file with the database credentials. The DATABASE_URL must point to a running PostgreSQL instance. ```env DATABASE_URL=postgres://username:password@localhost:5432/your_database_name ``` -------------------------------- ### Quick Start: connect, execute, prepare, bind, and query with xitca_postgres Source: https://github.com/hfqr/xitca-web/blob/main/postgres/README.md Connects to a PostgreSQL database, spawns the driver as a tokio task, executes raw SQL, prepares statements with type parameters, binds values, and queries rows. Requires a running PostgreSQL server at postgres://postgres:postgres@localhost:5432. The example uses tokio's #[tokio::main] and demonstrates both static and dynamic binding, row parsing by index and name, and raw SQL querying. ```rust use std::future::IntoFuture; use xitca_postgres::{iter::AsyncLendingIterator, types::Type, Execute, Postgres, Statement}; #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { // connect to database and spawn driver as tokio task. let (cli, drv) = Postgres::new("postgres://postgres:postgres@localhost:5432") .connect() .await?; tokio::spawn(drv.into_future()); // execute raw sql queries with client type. multiple sql queries are separated by ; "CREATE TEMPORARY TABLE foo (id SERIAL, name TEXT); INSERT INTO foo (name) VALUES ('alice'), ('bob'), ('charlie');" .execute(&cli) .await?; // prepare statement with type parameters. multiple params can be annotate as $1, $2 .. $n inside sql string as // it's value identifier. // // following the sql query is a slice of potential postgres type for each param in the same order. the types are // optional and if not provided types will be inferred from database. // // in this case we declare for $1 param's value has to be TEXT type. it's according Rust type can be String/&str // or other types that can represent a text string let stmt = Statement::named("INSERT INTO foo (name) VALUES ($1)", &[Type::TEXT]).execute(&cli).await?; // bind the prepared statement to parameter values. the value's Rust type representation must match the postgres // Type we declared. // execute the bind and return number of rows affected by the sql query on success. let rows_affected = stmt.bind(["david"]).execute(&cli).await?; assert_eq!(rows_affected, 1); // prepare another statement with type parameters. // // in this case we declare for $1 param's value has to be INT4 type. it's according Rust type representation is i32 // and $2 is TEXT type mentioned before. let stmt = Statement::named( "SELECT id, name FROM foo WHERE id = $1 AND name = $2", &[Type::INT4, Type::TEXT], ) .execute(&cli) .await?; // bind the prepared statement to parameter values it declared. // when parameters are different Rust types it's suggested to use dynamic binding as following // query with the bind and get an async streaming for database rows on success let mut stream = stmt.bind_dyn(&[&1i32, &"alice"]).query(&cli).await?; // use async iterator to visit rows let row = stream.try_next().await?.ok_or("no row found")?; // parse column value from row to rust types let id = row.get::<i32>(0); // column's numeric index can be used for slicing the row and parse column. assert_eq!(id, 1); let name = row.get::<&str>("name"); // column's string name index can be used for parsing too. assert_eq!(name, "alice"); // when all rows are visited the stream would yield Ok(None) to indicate it has ended. assert!(stream.try_next().await?.is_none()); // like execute method. query can be used with raw sql string. let mut stream = "SELECT id, name FROM foo WHERE name = 'david'".query(&cli).await?; let row = stream.try_next().await?.ok_or("no row found")?; // unlike query with prepared statement. raw sql query would return rows that can only be parsed to Rust string types. let id = row.get(0).ok_or("no id found")?; assert_eq!(id, "4"); let name = row.get("name").ok_or("no name found")?; assert_eq!(name, "david"); Ok(()) } ``` -------------------------------- ### Compile project on Windows Source: https://github.com/hfqr/xitca-web/blob/main/examples/wasi/README.md Compiles the project for wasm32-wasip1-threads on Windows with tokio_unstable flag. ```commandline set RUSTFLAGS=--cfg tokio_unstable cargo build --release --target wasm32-wasip1-threads ``` -------------------------------- ### Catch-all matching example for nested routers Source: https://github.com/hfqr/xitca-web/blob/main/router/CHANGES.md Shows how to use `/*` catch-all matching to nest routers. A scoped router matches relative paths `/` and `/login`, then is inserted into a root router with prefix `/users/*`. The example asserts that `/users/` and `/users/login` match. ```rust // a scoped router match against relative path of / and /login let mut router_scope = xitca_router::Router::new(); router_scope.insert("/", true); router_scope.insert("/login", true); // add scoped router to root router where /users is used as // prefix let mut router = xitca_router::Router::new(); router.insert("/users/*", router_scope); // handling /users as prefix and / and /login as suffix assert!(m.at("/users/").is_ok()); assert!(m.at("/users/login").is_ok()); ``` -------------------------------- ### Rust main.rs example for Xitca-web Source: https://github.com/hfqr/xitca-web/blob/main/README.md Add this code to your main.rs file to create a basic Xitca-web application that serves a 'Hello world!!' message at localhost:8080. Requires Rust 1.98 or above. ```rust use xitca_web::{handler::handler_service, middleware::Logger, route::get, App}; async fn index() -> &'static str { "Hello world!!" } fn main() -> std::io::Result<()> { App::new() .at("/", get(handler_service(index))) .enclosed(Logger::new()) .serve() .bind("localhost:8080")? .run() .wait() } ``` -------------------------------- ### Create users Table Source: https://github.com/hfqr/xitca-web/blob/main/examples/auth/README.md SQL to create the required users table with id, name, email, and password columns. ```sql CREATE TABLE users ( id TEXT PRIMARY KEY, name TEXT NOT NULL, email TEXT UNIQUE NOT NULL, password TEXT NOT NULL ); ``` -------------------------------- ### Pipeline query with ExecuteMut and Execute traits Source: https://github.com/hfqr/xitca-web/blob/main/postgres/CHANGES.md Shows how to use Pipeline with the new ExecuteMut and Execute traits after removing pipeline::Pipeline::query. Prepares a statement, adds queries to the pipeline, then starts the pipeline query. ```rust use xitca_postgres::Execute; // prepare statement and create a pipeline let stmt = Statement::named("SELECT 1", &[]).execute(&client).await?; let mut pipe = Pipeline::new(); // use ExecuteMut trait to add query to pipeline use xitca_postgres::ExecuteMut; stmt.query_mut(&mut pipe)?; stmt.query_mut(&mut pipe)?; // use Execute trait to start pipeline query let pipe_stream = pipe.query(&client)?; ``` -------------------------------- ### App::with_state delayed state attachment example Source: https://github.com/hfqr/xitca-web/blob/main/web/CHANGES.md Shows delayed state attachment using App::with_state and modular configuration with NestApp. The example demonstrates flexible application state construction. ```rust // delayed state attachment: App::new().at("/", ...).enclosed(...).with_state(996); // modular application configuration before attaching state: use xitca_web::NestApp; fn configure(app: NestApp<String>) -> NestApp<String> { app.at("/", ...) } let mut app = App::new(); app = configure(app); app.with_state(String::from("996")); ``` -------------------------------- ### Run compiled wasm file with wasmtime Source: https://github.com/hfqr/xitca-web/blob/main/examples/wasi/README.md Runs the compiled wasm file using wasmtime with threads, preview2, and tcplisten options. ```commandline wasmtime run -W threads=y -S threads=y,preview2=n,tcplisten=127.0.0.1:8080 --env FD_COUNT=3 ../target/wasm32-wasip1-threads/release/xitca-web-wasi.wasm ``` -------------------------------- ### Add wasm32-wasip1-threads target Source: https://github.com/hfqr/xitca-web/blob/main/examples/wasi/README.md Adds the wasm32-wasip1-threads target platform to the Rust compiler. ```commandline rustup target add wasm32-wasip1-threads ``` -------------------------------- ### Cargo.toml dependency for Xitca-web Source: https://github.com/hfqr/xitca-web/blob/main/README.md Add this dependency to your Cargo.toml file to enable the logger feature required by the example. The version is specified as '*'. ```toml xitca-web = { version = "*" , features = ["logger"]} ``` -------------------------------- ### Reading and consuming data from a byte stream with fill_buf and consume Source: https://github.com/hfqr/xitca-web/blob/main/tokio-uring/DESIGN.md Byte streams manage their internal buffers and implement AsyncBufRead. The caller waits for the buffer to fill, reads the data, then marks it consumed. This example shows reading bytes from a stream and consuming them. ```rust // `fill_buf()` is provided by `AsyncBufRead` let data: &[u8] = my_stream.fill_buf().await?; println!("Got {} bytes", data.len()); // Consume the data my_stream.consume(data.len()); ``` -------------------------------- ### Register Request Payload Source: https://github.com/hfqr/xitca-web/blob/main/examples/auth/README.md JSON payload for the /register endpoint. Includes name, email, and password fields. ```json { "name": "John Doe", "email": "john@example.com", "password": "securepassword123" } ``` -------------------------------- ### Await accept operation on io-uring backed resource Source: https://github.com/hfqr/xitca-web/blob/main/tokio-uring/DESIGN.md Operations on io-uring backed resources return futures that are awaited to get the operation result. The runtime submits the operation to the kernel via the submission queue and returns the result via the completion queue. ```rust let socket = my_listener.accept().await?; ``` -------------------------------- ### IoBuf slice API Source: https://github.com/hfqr/xitca-web/blob/main/tokio-uring/DESIGN.md Defines the Slice type and the slice method on IoBuf, allowing read/write on sub-ranges. The example shows writing a sub-slice of a buffer to a file. ```rust pub struct Slice { buf: IoBuf, begin: usize, end: usize, } impl IoBuf { fn slice(self, range: impl ops::RangeBounds<usize>) -> Slice { .. } } // Write a sub-slice of a buffer my_file.write(my_io_buf.slice(10..20)).await ``` -------------------------------- ### Zero-copy piping between two byte streams using take_read_buf and place_write_buf Source: https://github.com/hfqr/xitca-web/blob/main/tokio-uring/DESIGN.md Byte streams submit read operations using the default buffer pool. Additional methods take and place buffers to support zero-copy piping between two streams. This example moves a buffer from one stream to another and flushes. ```rust my_tcp_stream.fill_buf().await?; let buf: IoBuf = my_tcp_stream.take_read_buf(); // Mutate `buf` if needed here. my_other_stream.place_write_buf(buf); my_other_stream.flush().await?; ``` -------------------------------- ### Trait-based read API example Source: https://github.com/hfqr/xitca-web/blob/main/tokio-uring/DESIGN.md Illustrates a potential future read API that takes T: AsMut<[u8]> for the buffer argument, with a custom buffer type implementing AsMut. The read function takes ownership of the buffer, but pointers become invalid if the value moves. ```rust async fn read<T: AsMut<[u8]>>(&self, dst: T) { ... } struct MyUnstableBuf { mem: [u8; 10], } impl AsMut<[u8]> for MyUnstableBuf { fn as_mut(&mut self) -> &mut [u8] { &mut self.mem[..] } } ``` -------------------------------- ### Read and write with buffer ownership (tokio-uring File) Source: https://github.com/hfqr/xitca-web/blob/main/tokio-uring/DESIGN.md Shows positional read/write on a File using buf::Slice and BufResult. The caller allocates the buffer and passes ownership to the kernel; the buffer is returned on completion. The example reads 1024 bytes at offset 0, then writes 512 bytes at offset 1024. ```rust use tokio_uring::buf; /// The result of an operation that includes a buffer. The buffer must /// be returned to the caller when the operation completes successfully /// or fails. /// /// This is implemented as a new type to implement std::ops::Try once /// the trait is stabilized. type BufResult<T> = (std::io::Result<T>, buf::Slice); // Positional read and write function definitions impl File { async fn read_at(&self, buf: buf::Slice, pos: u64) -> BufResult<usize>; async fn write_at(&self, buf: buf::Slice, pos: u64) -> BufResult<usize>; } /// The caller allocates a buffer let buf = buf::IoBuf::with_capacity(4096); // Read the first 1024 bytes of the file, when `std::ops::Try` is // stable, the `?` can be applied directly on the `BufResult` type. let BufResult(res, buf) = file.read_at(0, buf.slice(0..1024)).await; // Check the result. res?; // Write some data back to the file. let BufResult(res, _) = file.write_at(1024, buf.slice(0..512)).await; res?; ``` -------------------------------- ### Reading into a slice with uninitialized memory Source: https://github.com/hfqr/xitca-web/blob/main/tokio-uring/DESIGN.md Shows that a slice's end may go past the buffer's length but not capacity, enabling reads to uninitialized memory. The example reads from a file into a slice and asserts the length and capacity after the read. ```rust // The buffer's memory is uninitialized let mut buf = IoBuf::with_capacity(4096); let slice = buf.slice(0..100); assert_eq!(slice.len(), 0); assert_eq!(slice.capacity(), 100); // Read data from a file into the buffer let BufResult(res, slice) = my_file.read_at(slice, 0); assert_eq!(slice.len(), 100); assert_eq!(slice.capacity(), 100); ``` -------------------------------- ### Concurrent read and write streams on a File with separate cursors Source: https://github.com/hfqr/xitca-web/blob/main/tokio-uring/DESIGN.md The File type does not expose a byte stream directly; instead, the caller requests read and write streams, each maintaining its own cursor. This example reads from one stream and writes to another, leaving the file unchanged. ```rust let read_stream = my_file.read_stream(); let write_stream = my_file.write_stream(); read_stream.fill_buf().await? let buf: IoBuf = read_stream.take_read_buf(); write_stream.place_write_buf(buf); write_stream.flush().await?; // Because `read_stream` and `write_stream` maintain separate // cursors, `my_file` is unchanged at the end of this example. ``` -------------------------------- ### query_blocking Source: https://github.com/hfqr/xitca-web/blob/main/postgres/README.md Executes a SQL query using the blocking API and returns a stream of rows. The stream can be iterated to access each row, and each row can be parsed using the get method. ```APIDOC ## query_blocking ### Description Executes a SQL query using the blocking API and returns a stream of rows. The stream can be iterated to access each row, and each row can be parsed using the get method. ### Method Blocking execution ### Parameters - **query** (string) - Required - The SQL query to execute. ### Response - **stream** - A stream of rows. ### Request Example ```rust let stream = "SELECT 1".query_blocking(client)?; ``` ### Response Example ```rust for item in stream { let row = item?; let one = row.get(0).expect("database must return 1"); assert_eq!(one, "1"); } ``` ``` -------------------------------- ### Cancel an in-flight accept operation with tokio::select! Source: https://github.com/hfqr/xitca-web/blob/main/tokio-uring/DESIGN.md Operation futures provide an asynchronous cancel function. This example shows cancelling an in-flight accept after a timeout, handling both graceful cancellation and the case where the operation completed before cancellation. ```rust let accept = tcp_listener.accept(); tokio::select! { (tcp_stream, addr) = &mut accept => { ... } _ = tokio::time::sleep(Duration::from_millis(100)) => { // Accept timed out, cancel the in-flight accept. match accept.cancel().await { Ok(_) => { ... } // operation canceled gracefully Err(Completed(tcp_stream, addr)) => { // The operation completed between the timeout // and cancellation request. } Err(_) => { ... } } } } ``` -------------------------------- ### Scoped application state with App::with_state Source: https://github.com/hfqr/xitca-web/blob/main/web/CHANGES.md Added in 0.6.0, this example shows how scoped state overrides global state for a specific route. The handler receives the scoped isize state instead of the global usize state. ```rust App::new() .with_state(996usize) // global state is usize .at( "/foo" App::new() .with_state(996isize) // scoped state is isize .at("/bar", handler_service(handler)) ) // handler function would receive isize as typed state. overriding the global app state of usize async fn handler(StateRef(state): StateRef<'_, isize>) -> .. { assert_eq!(*state, 996isize) } ``` -------------------------------- ### Use derive macro with postgres-derive for custom types Source: https://github.com/hfqr/xitca-web/blob/main/postgres/README.md Add postgres-derive to Cargo dependencies to enable derive macro support. This example defines a custom type Worker, creates a pg_temp type, and binds a Worker value to a statement. ```rust // add postgres-derive to Cargo dependency to enable derive macro support. use postgres_derive::ToSql; // implement derive macro to custom type #[derive(ToSql, Debug)] struct Worker { id: i32, wage: i32, } async fn derive_macro(cli: Client) -> Result<(), Error> { // create custom type "CREATE TYPE pg_temp.\"Worker\" AS (id INT, wage INT);".execute(&cli).await?; // prepare statement with custom type let stmt = Statement::named("SELECT $1::Worker", &[]).execute(&cli).await?; // bind statement to custom type and execute. this works because the derive macro // added necessary trait implement that make Worker type can be encoded and used // as custom type we just created. stmt.bind([&Worker { id: 9527, wage: 0}]).execute(&cli).await?; Ok(()) } ``` -------------------------------- ### Use extended types with postgres-types and uuid Source: https://github.com/hfqr/xitca-web/blob/main/postgres/README.md Add postgres-types with feature "with-uuid-1" to Cargo dependencies to enable UUID type support. This example prepares a statement with the UUID type and binds a default UUID value. ```rust // add postgres-types = { .., features = ["with-uuid-1"] } to Cargo dependency to enable uuid type support. use postgres_types::Type; use uuid::Uuid; use xitca_postgres::{Client, Error, Execute, Statement}; // an example of using extended type support rust-postgres offers through postgres-types crate async fn bind_ext(cli: Client) -> Result<(), Error> { // prepare statement and query with Uuid type let stmt = Statement::named("SELECT * FROM users WHERE id = $1", &[Type::UUID]).execute(&cli).await?; let stream = stmt.bind([Uuid::default()]).query(&cli).await?; Ok(()) } ``` -------------------------------- ### Error upcasting with error::Error::upcast Source: https://github.com/hfqr/xitca-web/blob/main/web/CHANGES.md Introduced in 0.6.0, this method enables error trait upcasting without nightly Rust. The example shows upcasting to a trait object of std::error::Error and downcasting to a concrete type. ```rust fn handle_error<C>(err: Error<C>) { // upcast to trait object of std::error::Error let err_obj = err.upcast(); // try to downcast object to concrete type if let Some(..) = err_obj.downcast_ref::<Foo>() { ... } } ``` -------------------------------- ### Use Redirect, Html, Json as standalone route services Source: https://github.com/hfqr/xitca-web/blob/main/web/CHANGES.md In xitca-web 0.3.0, the handler types Redirect, Html, and Json can be used directly as route services without wrapping in a handler function. The example shows an App with routes for a redirect, an HTML response, and a JSON response. ```rust App::new() .at("/", Redirect::see_other("/index.html")) .at("/index.html", get(Html("<h1>Hello,World!</h1>"))) .at("/hello.json", Json("{\"hello\":\"world!\"}")); ``` -------------------------------- ### BorrowState trait for sub-typed state borrowing Source: https://github.com/hfqr/xitca-web/blob/main/web/CHANGES.md Added in 0.6.0, this example shows implementing BorrowState to borrow a String from a custom State type and using it as typed state in a handler. The handler asserts the borrowed value equals "996". ```rust use xitca_web::handler::state::{BorrowState, StateRef}; // arbitrary state type struct State { field: String } // impl trait for borrowing String type from State impl BorrowState<String> for State { fn borrow(&self) -> &String { &self.field } } // handler function use &String as typed state. async fn handler(StateRef(state): StateRef<'_, String>) -> String { assert_eq!(state, "996"); state.into() } App::new().with_state(State { field: String::from("996") }).at("/foo", handler_service(handler)); ``` -------------------------------- ### Create buffer pool and provide to runtime (tokio-uring) Source: https://github.com/hfqr/xitca-web/blob/main/tokio-uring/DESIGN.md Builds a BufferPool with 256 buffers of 16,384 bytes, creates the runtime, and provides the pool to the kernel via rt.provide_buffers. The pool token is then used in read_at_prepared inside block_on. Ownership of the pool passes to the kernel. ```rust // Allocate a buffer pool let my_pool = BufferPool::builder() .buffer_size(16_384) .num_buffers(256) .build(); // Create the runtime let mut rt = tokio_uring::runtime::Runtime::new()?; // Provide the buffer pool to the kernel. This passes // ownership of the pool to the kernel. let pool_token = rt.provide_buffers(my_pool)?; rt.block_on(async { // ... let buf = file.read_at_prepared(0, 1024, pool_token).await?; }); ``` -------------------------------- ### Initialize tokio-uring runtime in main Source: https://github.com/hfqr/xitca-web/blob/main/tokio-uring/DESIGN.md Creates a tokio-uring runtime and runs an asynchronous block with block_on. The runtime can drive both io-uring specific resources and Tokio resources. ```rust fn main() { let rt = tokio_uring::runtime::Runtime::new().unwrap(); rt.block_on(async { // The rest of the application comes here. }); } ``` -------------------------------- ### Read with buffer pool and drop to reuse (tokio-uring) Source: https://github.com/hfqr/xitca-web/blob/main/tokio-uring/DESIGN.md Uses read_at_prepared with a DefaultPool to draw a buffer from the kernel pool. After writing, dropping the buffer signals the kernel that the buffer may be reused. The comment indicates the buffer is returned to the kernel on drop. ```rust // ... let buf = file.read_at_prepared(0, 1024, DefaultPool).await?; // Write some data back to the file. let BufResult(res, buf) = file.write_at(1024, buf.slice(0..512)).await; res?; // Dropping the buffer lets the kernel know the buffer may // be reused. drop(buf); ``` -------------------------------- ### Acquiring an IoBuf Source: https://github.com/hfqr/xitca-web/blob/main/tokio-uring/DESIGN.md Shows two ways to acquire an IoBuf: individually heap-allocated via with_capacity or checked-out from a pool. The pool checkout returns a Result that may error if the pool is empty. ```rust // Individually heap-allocated let my_buf = IoBuf::with_capacity(4096); // Checked-out from a pool match my_buffer_pool.checkout() { Ok(io_buf) => ..., Err(e) => panic!("buffer pool empty"), } ``` -------------------------------- ### Bind parameters to statement before query Source: https://github.com/hfqr/xitca-web/blob/main/postgres/CHANGES.md Shows the required pattern for queries with parameter values: prepare a statement with types, bind values, then query. ```rust use xitca_postgres::Execute; // prepare a statement. let stmt = Statement::named("SELECT * FROM users WHERE id = $1 AND age = $2", &[Type::INT4, Type::INT4]).execute(&client).await?; // bind statement to typed value and start query let stream = stmt.bind([9527, 42]).query(&client).await?; ``` -------------------------------- ### Typical accept loop pattern Source: https://github.com/hfqr/xitca-web/blob/main/tokio-uring/DESIGN.md Pseudocode for a typical accept loop that spawns a task per connection. Moving the task to another worker thread can delay reading already-buffered request data due to cross-thread synchronization. ```rust loop { let (socket, _) = listener.accept().await?; spawn(async move { let request = read_request(&socket).await; let response = process(request).await; write_response(response, &socket).await; }); } ``` -------------------------------- ### Serve static files with ServeDir Source: https://github.com/hfqr/xitca-web/blob/main/http-file/README.md Use ServeDir::new to create a directory service and serve requests asynchronously. Requires the http and futures crates for HTTP types and async streaming. ```rust use http::Request; use http_file::ServeDir; async fn serve(req: &Request<()>) { let dir = ServeDir::new("sample"); let res = dir.serve(&req).await; } ``` -------------------------------- ### Runtime context requirement for tokio-uring resources Source: https://github.com/hfqr/xitca-web/blob/main/tokio-uring/DESIGN.md Shows that binding a TcpListener does not require the runtime, but using it (e.g., accept) must happen inside the runtime context. Attempting to use a tokio-uring resource outside the runtime results in a panic. ```rust use tokio_uring::runtime::Runtime; use tokio_uring::net::TcpListener; fn main() { // Binding a TcpListener does not require access to the runtime. let listener = TcpListener::bind("0.0.0.0:1234".parse().unwrap()); let rt = Runtime::new().unwrap(); rt.block_on(async { // This works, as `block_on` sets the thread-local variable. let _ = listener.accept().await; }); // BOOM: panics because called outside of the runtime futures::future::block_on(async { let _ = listener.accept().await; }); } ``` -------------------------------- ### Distribute accept operations across runtime threads Source: https://github.com/hfqr/xitca-web/blob/main/tokio-uring/DESIGN.md Pseudocode for balancing load across isolated runtime threads by submitting accept operations for the same listener concurrently on all threads, with workers backing off when overloaded. The listener is wrapped in Arc and each thread waits for capacity before accepting. ```rust let listener = Arc::new(TcpListener::bind(...)); spawn_on_each_thread(async { loop { // Wait for this worker to have capacity. This // ensures there are a minimum number of workers // in the runtime that are flagged as with capacity // to avoid total starvation. current_worker::wait_for_capacity().await; let socket = listener.accept().await; spawn(async move { ... }); } }) ``` -------------------------------- ### IoUringDriver and Operation structs with State and Lifecycle enums Source: https://github.com/hfqr/xitca-web/blob/main/tokio-uring/DESIGN.md Defines the core data structures for the tokio-uring runtime. The IoUringDriver stores in-flight operations in a slab and holds the io-uring queues. Operation holds resources referenced by the kernel and a lifecycle tracking submission, waiting, ignoring, or completion. State enumerates operation types such as read, write, accept, and close. Completion stores the kernel result and flags. ```rust struct IoUringDriver { // Storage for state referenced by in-flight operations in_flight_operations: Slab<Operation>, // The io-uring submission and completion queues. queues: IoUringQueues, } struct Operation { // Resources referenced by the kernel, this must stay // available until the operation completes. state: State, lifecycle: Lifecycle, } enum State { // An in-flight read operation, `None` when reading into // a kernel-owned buffer pool Read { buffer: Option<buf::Slice> }, Write { buffer: buf::Slice }, // Accept a TCP socket Accept { ... } Close { ... } // ... other operations } enum Lifecycle { /// The operation has been submitted to uring and is currently in-flight Submitted, /// The submitter is waiting for the completion of the operation Waiting(Waker), /// The submitter no longer has interest in the operation result. Ignored, /// The operation has completed. The completion result is stored. Completed(Completion), } // Completion result returned from the kernel via the completion queue struct Completion { result: io::Result<u32>, flags: u32, } ``` -------------------------------- ### Add tokio-uring dependency in Cargo.toml Source: https://github.com/hfqr/xitca-web/blob/main/tokio-uring/DESIGN.md Declares the tokio-uring crate as a dependency with version 0.1 in a Cargo.toml file. ```toml [dependencies] tokio-uring = "0.1" ``` -------------------------------- ### Execute trait family usage with named statement and raw SQL Source: https://github.com/hfqr/xitca-web/blob/main/postgres/CHANGES.md Shows the new Execute trait API after removing prepare/query/execute methods. Includes creating a named statement, querying with it, querying raw SQL strings, executing raw SQL, and executing a SQL file. ```rust use xitca_postgres::{Client, Execute, RowSimpleStream, RowStream, Statement}; // create a named statement and execute it. on success returns a prepared statement let stmt: StatementGuarded<'_, Client> = Statement::named("SELECT 1").execute(&client).await?; // query with the prepared statement. on success returns an async row stream. let stream: RowStream<'_> = stmt.query(&client).await?; // query with raw string sql. let stream: RowSimpleStream<'_> = "SELECT 1; SELECT 1".query(&client).await?; // execute raw string sql. let row_affected: u64 = "SELECT 1; SELECT 1".execute(&client).await?; // execute sql file. let row_affected: u64 = std::path::Path::new("./foo.sql").execute(&client).await?; ``` -------------------------------- ### Rate limiting HTTP requests with http_rate Source: https://github.com/hfqr/xitca-web/blob/main/http-rate/README.md Shows how to use the http_rate crate to limit requests to 1 per second. Constructs a Quota and RateLimit, then checks each request's headers and client address. On success, extends the response with rate-limit headers; on failure, formats the error and extends the error response. ```rust use std::net::SocketAddr; use http::{Request, Response}; use http_rate::{Quota, RateLimit}; // a quota limiting request to 1 per second. let quota = Quota::per_second(1); // construct rate limiter with given quota. let limiter = RateLimit::new(quota); fn request(lim: &RateLimit, req: &Request<()>, addr: SocketAddr) -> Response<()> { // rate limiter needs request header map and client socket addr. match lim.rate_limit(req.headers(), &addr) { // client still have quota left. Ok(snap) => { // rate limiter guarded logic can be executed here. // in this case a dummy response is constructed. let mut res = Response::new(()); // snapshot return from rate_limit method can be used to extend // rate-limit related headers to response. snap.extend_response(&mut res); res } // client ran out of quota. Err(e) => { // logic not guarded by rate limiter can be executed here. // in this case a dummy response is constructed. let mut res = Response::new(()); // error return from rate_limit method can be used to extend rate-limit // related headers and status code to error response. e.extend_response(&mut res); // error can be formatted. println!("{e:?}"); println!("{e}"); // error can be boxed as std::error::Error trait object. let _ = Box::new(e) as Box<dyn std::error::Error + Send + Sync>; res } } } ``` -------------------------------- ### Router nesting with PathGen and RouteObject Source: https://github.com/hfqr/xitca-web/blob/main/http/CHANGES.md Shows two valid routing patterns enabled by PathGen and RouteObject: nested Router::new() calls and a flattened path with '/api/v2'. Both use fn_service(..) as the handler. ```rust // this pattern is now valid Router::new() .insert("/api", Router::new() .insert("/v2", Router::new().insert("/login", fn_service(..))) ); // this pattern is also valid Router::new().insert("/api/v2", Router::new().insert("/login", fn_service(..))); ``` -------------------------------- ### Bind parameters to unnamed statement Source: https://github.com/hfqr/xitca-web/blob/main/postgres/CHANGES.md Shows that unnamed statements must bind value parameters before querying. ```rust let stmt = Statement::unnamed("SELECT * FROM users WHERE id = $1", &[Type::INT4]); let row_stream = stmt.bind([9527]).query(&client).await?; ``` -------------------------------- ### Query without parameters using Statement alone Source: https://github.com/hfqr/xitca-web/blob/main/postgres/CHANGES.md Shows that statements without value parameters can be queried directly without binding. ```rust use xitca_postgres::Execute; // prepare a statement. let stmt = Statement::named("SELECT * FROM users", &[]).execute(&client).await?; // statement have no value params and can be used for query. let stream = stmt.query(&client).await?; ``` -------------------------------- ### Read cancellation and re-read on TcpStream Source: https://github.com/hfqr/xitca-web/blob/main/tokio-uring/DESIGN.md Shows the challenge of drop-to-cancel semantics with stateful reads: the first read is canceled and a second read is issued. The kernel may have already completed the first read, risking data loss if the completion is dropped. ```rust let buf = IoBuf::with_capacity(4096); // This read will be canceled. select! { _ = my_tcp_stream.read(buf.slice(..)) => unreachable!(), _ = future::ready(()) => {} } let buf = IoBuf::with_capacity(4096); let (res, buf) = my_tcp_stream.read(buf.slice(..)).await; ``` -------------------------------- ### Synchronous API: execute_blocking and query_blocking Source: https://github.com/hfqr/xitca-web/blob/main/postgres/README.md Use xitca_postgres::Client outside of tokio async runtime with blocking API. Executes a SQL query and iterates over streaming rows, asserting the returned value is "1". ```rust use xitca_postgres::{Client, Error, ExecuteBlocking}; fn query(client: &Client) -> Result<(), Error> { // execute sql query with blocking api "SELECT 1".execute_blocking(client)?; let stream = "SELECT 1".query_blocking(client)?; // use iterator to visit streaming rows for item in stream { let row = item?; let one = row.get(0).expect("database must return 1"); assert_eq!(one, "1"); } Ok(()) } ``` -------------------------------- ### Zero Copy Row Parse: get_zc and FromSqlExt Source: https://github.com/hfqr/xitca-web/blob/main/postgres/README.md Row data is stored as atomic reference counted byte buffer, enabling cheap slicing and zero copy parsing. Shows parsing to Bytes and BytesStr, and implementing FromSqlExt for custom types. ```rust use std::ops::Range; use xitca_io::bytes::{Bytes, BytesStr}; use xitca_postgres::{row::Row, types::Type, FromSqlExt}; fn parse(row: Row<'_>) { // parse column foo to Bytes. it's a reference counted byte slice. // can be roughly seen as Arc<[u8]>. let bytes: Bytes = row.get_zc("foo"); // parse column bar to BytesStr. it's a reference counted slice but for String. // can be roughly seen as Arc<str>. let str: BytesStr = row.get_zc("bar"); // implement FromSqlExt trait for your own type for extended zero copy parsing. struct Baz; // please see doc for implementation detail impl<'a> FromSqlExt<'a> for Baz { fn from_sql_ext( ty: &Type, (range, buf): (&Range<usize>, &'a Bytes) ) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> { Ok(Baz) } fn accepts_ext(ty: &Type) -> bool { true } } // any type implement FromSqlExt trait will be parsable by get_zc API. let foo: Baz = row.get_zc("baz"); } ``` -------------------------------- ### execute_blocking Source: https://github.com/hfqr/xitca-web/blob/main/postgres/README.md Executes a SQL query using the blocking API of xitca_postgres::Client. This method runs outside of the tokio async runtime and returns a Result indicating success or failure. ```APIDOC ## execute_blocking ### Description Executes a SQL query using the blocking API of xitca_postgres::Client. This method runs outside of the tokio async runtime and returns a Result indicating success or failure. ### Method Blocking execution ### Parameters - **query** (string) - Required - The SQL query to execute. ### Response - **Result<(), Error>** - Success or error. ### Request Example ```rust "SELECT 1".execute_blocking(client)?; ``` ``` -------------------------------- ### Explicit asynchronous close for TcpStream Source: https://github.com/hfqr/xitca-web/blob/main/tokio-uring/DESIGN.md Provides an explicit asynchronous close method on resource types to avoid blocking the runtime or closing in the background. The resource must still tolerate being dropped without explicit close, in which case tokio-uring closes it in the background and emits a warning via tracing. ```rust impl TcpStream { async fn close(self) { ... } } my_tcp_stream.close().await; ``` -------------------------------- ### Timeout an accept operation with .timeout() Source: https://github.com/hfqr/xitca-web/blob/main/tokio-uring/DESIGN.md In practice, operation timeouts deserve a dedicated API to handle the boilerplate. The cancel and timeout functions are inherent methods on operation future types. ```rust let (tcp_stream, addr) = tcp_listener .accept() .timeout(Duration::from_millis(100)) .await? ``` -------------------------------- ### IoBuf type definition Source: https://github.com/hfqr/xitca-web/blob/main/tokio-uring/DESIGN.md Defines the IoBuf type with an internal Kind enum that is either vector-backed or buffer pool backed. The buffer must remain alive and pinned during operations. ```rust pub struct IoBuf { kind: Kind, } enum Kind { /// A vector-backed buffer Vec(Vec<u8>), /// Buffer pool backed buffer. The pool is managed by io-uring. Provided(ProvidedBuf), } ``` -------------------------------- ### CustomError Service impl with WebContext and error::Request Source: https://github.com/hfqr/xitca-web/blob/main/web/CHANGES.md Shows the required pattern for error types that need application state after the Error type lost its generic parameter. The WebContext must use the exact type `xitca_web::error::Request<'r>` and `request_ref::<String>()` performs runtime type casting, returning `Some(app_state)` when the requested type matches the application's state. ```rust struct CustomError; // Debug, Display, Error and From impl are ignored there as they don't need change. // assuming app state is needed in error impl. the WebContext has to be written in the exact following type impl<'r> Service<WebContext<'r, xitca_web::error::Request<'r>>> for CustomError { type Response = WebResponse; type Error = Infallible; async fn call(&self, ctx: xitca_web::error::Request<'r>>) -> Result<Self::Response, Self::Error> { // xitca_web::error::Request::request_ref method is able do runtime type casting. and when the type requested // is the same as application's state it will return Some(app_state). if let Some(state) = ctx.state().request_ref::<String>() { } } } ``` -------------------------------- ### AsyncBody from async generator (Rust 2024 edition) Source: https://github.com/hfqr/xitca-web/blob/main/web/CHANGES.md Uses the nightly `async_iterator` feature to bridge `futures::Stream` and `std::async_iter::AsyncIterator`. Requires the `nightly` crate feature and Rust 2024 edition. ```rust let body = AsyncBody::from(async gen { for _ in 0..1 { yield Ok::<_, Infallible>("async generator"); } }) ``` -------------------------------- ### CustomError with #[error_impl] macro using concrete Request type Source: https://github.com/hfqr/xitca-web/blob/main/web/CHANGES.md Shows the updated `codegen::error_impl` macro usage after the Error type change. The impl method must receive `error::Request` as the WebContext type parameter, using concrete types instead of generics. ```rust struct CustomError; #[error_impl] impl CustomError { // remove generic types and use concrete type. async fn call(&self, ctx: WebContext<'_, Request<'_>>) -> WebResponse { } } ``` -------------------------------- ### get_zc Source: https://github.com/hfqr/xitca-web/blob/main/postgres/README.md Retrieves a column value from a row using zero-copy parsing. The method returns a reference-counted byte slice or string, and can be used with any type that implements the FromSqlExt trait. ```APIDOC ## get_zc ### Description Retrieves a column value from a row using zero-copy parsing. The method returns a reference-counted byte slice or string, and can be used with any type that implements the FromSqlExt trait. ### Method Zero-copy row parsing ### Parameters - **column** (string) - Required - The name of the column to retrieve. ### Response - **Bytes** - Reference-counted byte slice. - **BytesStr** - Reference-counted string slice. - **T** - Any type implementing FromSqlExt. ### Request Example ```rust let bytes: Bytes = row.get_zc("foo"); let str: BytesStr = row.get_zc("bar"); let foo: Baz = row.get_zc("baz"); ``` ```